blob: 6ecdbaeff458d6a6d7a8ad56d5e502f460a9b439 [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 Friedmanff030482011-07-28 21:48:00 +0000134static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
135 switch (Val) {
136 default: return AtomicRMWInst::BAD_BINOP;
137 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
138 case bitc::RMW_ADD: return AtomicRMWInst::Add;
139 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
140 case bitc::RMW_AND: return AtomicRMWInst::And;
141 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
142 case bitc::RMW_OR: return AtomicRMWInst::Or;
143 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
144 case bitc::RMW_MAX: return AtomicRMWInst::Max;
145 case bitc::RMW_MIN: return AtomicRMWInst::Min;
146 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
147 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
148 }
149}
150
Eli Friedman47f35132011-07-25 23:16:38 +0000151static AtomicOrdering GetDecodedOrdering(unsigned Val) {
152 switch (Val) {
153 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
154 case bitc::ORDERING_UNORDERED: return Unordered;
155 case bitc::ORDERING_MONOTONIC: return Monotonic;
156 case bitc::ORDERING_ACQUIRE: return Acquire;
157 case bitc::ORDERING_RELEASE: return Release;
158 case bitc::ORDERING_ACQREL: return AcquireRelease;
159 default: // Map unknown orderings to sequentially-consistent.
160 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
161 }
162}
163
164static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
165 switch (Val) {
166 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
167 default: // Map unknown scopes to cross-thread.
168 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
169 }
170}
171
Gabor Greifefe65362008-05-10 08:32:32 +0000172namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000173namespace {
174 /// @brief A class for maintaining the slot number definition
175 /// as a placeholder for the actual definition for forward constants defs.
176 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000177 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000178 public:
179 // allocate space for exactly one operand
180 void *operator new(size_t s) {
181 return User::operator new(s, 1);
182 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000184 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000185 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000186 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000187
Chris Lattnerea693df2008-08-21 02:34:16 +0000188 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000189 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000190 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000191 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000192 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000194
195
Gabor Greifefe65362008-05-10 08:32:32 +0000196 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000197 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000198 };
199}
200
Chris Lattner46e77402009-03-31 22:55:09 +0000201// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000202template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000203struct OperandTraits<ConstantPlaceHolder> :
204 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000205};
Gabor Greifefe65362008-05-10 08:32:32 +0000206}
207
Chris Lattner46e77402009-03-31 22:55:09 +0000208
209void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
210 if (Idx == size()) {
211 push_back(V);
212 return;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
Chris Lattner46e77402009-03-31 22:55:09 +0000215 if (Idx >= size())
216 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
Chris Lattner46e77402009-03-31 22:55:09 +0000218 WeakVH &OldV = ValuePtrs[Idx];
219 if (OldV == 0) {
220 OldV = V;
221 return;
222 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000223
Chris Lattner46e77402009-03-31 22:55:09 +0000224 // Handle constants and non-constants (e.g. instrs) differently for
225 // efficiency.
226 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227 ResolveConstants.push_back(std::make_pair(PHC, Idx));
228 OldV = V;
229 } else {
230 // If there was a forward reference to this value, replace it.
231 Value *PrevVal = OldV;
232 OldV->replaceAllUsesWith(V);
233 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000234 }
235}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000236
Gabor Greifefe65362008-05-10 08:32:32 +0000237
Chris Lattner522b7b12007-04-24 05:48:56 +0000238Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000239 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000240 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000241 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000242
Chris Lattner46e77402009-03-31 22:55:09 +0000243 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000244 assert(Ty == V->getType() && "Type mismatch in constant table!");
245 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000246 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000247
248 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000249 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000250 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000251 return C;
252}
253
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000254Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000255 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000256 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000257
Chris Lattner46e77402009-03-31 22:55:09 +0000258 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000259 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
260 return V;
261 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000262
Chris Lattner01ff65f2007-05-02 05:16:49 +0000263 // No type specified, must be invalid reference.
264 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000265
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000266 // Create and return a placeholder, which will later be RAUW'd.
267 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000268 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000269 return V;
270}
271
Chris Lattnerea693df2008-08-21 02:34:16 +0000272/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273/// resolves any forward references. The idea behind this is that we sometimes
274/// get constants (such as large arrays) which reference *many* forward ref
275/// constants. Replacing each of these causes a lot of thrashing when
276/// building/reuniquing the constant. Instead of doing this, we look at all the
277/// uses and rewrite all the place holders at once for any constant that uses
278/// a placeholder.
279void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000281 // binary search.
282 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000283
Chris Lattnerea693df2008-08-21 02:34:16 +0000284 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnerea693df2008-08-21 02:34:16 +0000286 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000287 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000288 Constant *Placeholder = ResolveConstants.back().first;
289 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerea693df2008-08-21 02:34:16 +0000291 // Loop over all users of the placeholder, updating them to reference the
292 // new value. If they reference more than one placeholder, update them all
293 // at once.
294 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000295 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000296 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 // If the using object isn't uniqued, just update the operands. This
299 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000300 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000301 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000302 continue;
303 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000304
Chris Lattnerea693df2008-08-21 02:34:16 +0000305 // Otherwise, we have a constant that uses the placeholder. Replace that
306 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000307 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
309 I != E; ++I) {
310 Value *NewOp;
311 if (!isa<ConstantPlaceHolder>(*I)) {
312 // Not a placeholder reference.
313 NewOp = *I;
314 } else if (*I == Placeholder) {
315 // Common case is that it just references this one placeholder.
316 NewOp = RealVal;
317 } else {
318 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000319 ResolveConstantsTy::iterator It =
320 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000321 std::pair<Constant*, unsigned>(cast<Constant>(*I),
322 0));
323 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000324 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 }
326
327 NewOps.push_back(cast<Constant>(NewOp));
328 }
329
330 // Make the new constant.
331 Constant *NewC;
332 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000333 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000334 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000335 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000336 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000337 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000338 } else {
339 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000340 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342
Chris Lattnerea693df2008-08-21 02:34:16 +0000343 UserC->replaceAllUsesWith(NewC);
344 UserC->destroyConstant();
345 NewOps.clear();
346 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000347
Nick Lewyckycb337992009-05-10 20:57:05 +0000348 // Update all ValueHandles, they should be the only users at this point.
349 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 delete Placeholder;
351 }
352}
353
Devang Pateld5ac4042009-08-04 06:00:18 +0000354void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
355 if (Idx == size()) {
356 push_back(V);
357 return;
358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000359
Devang Pateld5ac4042009-08-04 06:00:18 +0000360 if (Idx >= size())
361 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Devang Pateld5ac4042009-08-04 06:00:18 +0000363 WeakVH &OldV = MDValuePtrs[Idx];
364 if (OldV == 0) {
365 OldV = V;
366 return;
367 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000368
Devang Pateld5ac4042009-08-04 06:00:18 +0000369 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000370 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000371 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000372 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000373 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
374 // value for Idx.
375 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000376}
377
378Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
379 if (Idx >= size())
380 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000381
Devang Pateld5ac4042009-08-04 06:00:18 +0000382 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000383 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000384 return V;
385 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000386
Devang Pateld5ac4042009-08-04 06:00:18 +0000387 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000388 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 MDValuePtrs[Idx] = V;
390 return V;
391}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000392
Chris Lattner1afcace2011-07-09 17:41:24 +0000393Type *BitcodeReader::getTypeByID(unsigned ID) {
394 // The type table size is always specified correctly.
395 if (ID >= TypeList.size())
396 return 0;
397
398 if (Type *Ty = TypeList[ID])
399 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401 // If we have a forward reference, the only possible case is when it is to a
402 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000403 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000404}
405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406/// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
407Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
408 if (ID >= TypeList.size())
409 TypeList.resize(ID+1);
410
411 return TypeList[ID];
412}
413
414
Chris Lattner48c85b82007-05-04 03:30:17 +0000415//===----------------------------------------------------------------------===//
416// Functions for parsing blocks from the bitcode file
417//===----------------------------------------------------------------------===//
418
Devang Patel05988662008-09-25 21:00:45 +0000419bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000420 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000421 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000422
Devang Patel19c87462008-09-26 22:53:05 +0000423 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000424 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattner48c85b82007-05-04 03:30:17 +0000426 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000427
Devang Patel05988662008-09-25 21:00:45 +0000428 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 // Read all the records.
431 while (1) {
432 unsigned Code = Stream.ReadCode();
433 if (Code == bitc::END_BLOCK) {
434 if (Stream.ReadBlockEnd())
435 return Error("Error at end of PARAMATTR block");
436 return false;
437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Chris Lattner48c85b82007-05-04 03:30:17 +0000439 if (Code == bitc::ENTER_SUBBLOCK) {
440 // No known subblocks, always skip them.
441 Stream.ReadSubBlockID();
442 if (Stream.SkipBlock())
443 return Error("Malformed block record");
444 continue;
445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000446
Chris Lattner48c85b82007-05-04 03:30:17 +0000447 if (Code == bitc::DEFINE_ABBREV) {
448 Stream.ReadAbbrevRecord();
449 continue;
450 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattner48c85b82007-05-04 03:30:17 +0000452 // Read a record.
453 Record.clear();
454 switch (Stream.ReadRecord(Code, Record)) {
455 default: // Default behavior: ignore.
456 break;
457 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458 if (Record.size() & 1)
459 return Error("Invalid ENTRY record");
460
Chris Lattner9a6cb152008-10-05 18:22:09 +0000461 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000462 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000463 // to index ~0. Index 0 is used for return value attributes but used to be
464 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000465 Attributes RetAttribute = Attribute::None;
466 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000467 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000468 // FIXME: remove in LLVM 3.0
469 // The alignment is stored as a 16-bit raw value from bits 31--16.
470 // We shift the bits above 31 down by 11 bits.
471
472 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473 if (Alignment && !isPowerOf2_32(Alignment))
474 return Error("Alignment is not a power of two.");
475
476 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
477 if (Alignment)
478 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
479 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
480 Record[i+1] = ReconstitutedAttr;
481
Devang Patel19c87462008-09-26 22:53:05 +0000482 if (Record[i] == 0)
483 RetAttribute = Record[i+1];
484 else if (Record[i] == ~0U)
485 FnAttribute = Record[i+1];
486 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000487
488 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
489 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000490
Chris Lattner9a6cb152008-10-05 18:22:09 +0000491 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
492 (RetAttribute & OldRetAttrs) != 0) {
493 if (FnAttribute == Attribute::None) { // add a slot so they get added.
494 Record.push_back(~0U);
495 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000496 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000497
Chris Lattner9a6cb152008-10-05 18:22:09 +0000498 FnAttribute |= RetAttribute & OldRetAttrs;
499 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000500 }
Chris Lattner461edd92008-03-12 02:25:52 +0000501
Devang Patel19c87462008-09-26 22:53:05 +0000502 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000503 if (Record[i] == 0) {
504 if (RetAttribute != Attribute::None)
505 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
506 } else if (Record[i] == ~0U) {
507 if (FnAttribute != Attribute::None)
508 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
509 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000510 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
511 }
Devang Patel19c87462008-09-26 22:53:05 +0000512
513 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000514 Attrs.clear();
515 break;
516 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000517 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000518 }
519}
520
Chris Lattner86697142007-05-01 05:01:34 +0000521bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000522 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 return Error("Malformed block record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000524
525 return ParseTypeTableBody();
526}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000527
Chris Lattner1afcace2011-07-09 17:41:24 +0000528bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000529 if (!TypeList.empty())
530 return Error("Multiple TYPE_BLOCKs found!");
531
532 SmallVector<uint64_t, 64> Record;
533 unsigned NumRecords = 0;
534
Chris Lattner1afcace2011-07-09 17:41:24 +0000535 SmallString<64> TypeName;
536
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000537 // Read all the records for this type table.
538 while (1) {
539 unsigned Code = Stream.ReadCode();
540 if (Code == bitc::END_BLOCK) {
541 if (NumRecords != TypeList.size())
542 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000543 if (Stream.ReadBlockEnd())
544 return Error("Error at end of type table block");
545 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000546 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000547
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 if (Code == bitc::ENTER_SUBBLOCK) {
549 // No known subblocks, always skip them.
550 Stream.ReadSubBlockID();
551 if (Stream.SkipBlock())
552 return Error("Malformed block record");
553 continue;
554 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000555
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000556 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000557 Stream.ReadAbbrevRecord();
558 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000559 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000560
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 // Read a record.
562 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000563 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000564 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000565 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000566 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
567 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
568 // type list. This allows us to reserve space.
569 if (Record.size() < 1)
570 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000571 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000574 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000575 break;
576 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000577 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 break;
579 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000580 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000582 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000583 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000584 break;
585 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000586 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000587 break;
588 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000589 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000590 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000591 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000592 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000593 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000594 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000595 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000596 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000597 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
598 ResultTy = Type::getX86_MMXTy(Context);
599 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000600 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
601 if (Record.size() < 1)
602 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000603
Owen Anderson1d0be152009-08-13 21:58:54 +0000604 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000605 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000606 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000607 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000608 if (Record.size() < 1)
609 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000610 unsigned AddressSpace = 0;
611 if (Record.size() == 2)
612 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000613 ResultTy = getTypeByID(Record[0]);
614 if (ResultTy == 0) return Error("invalid element type in pointer type");
615 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000616 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000617 }
Chad Rosiercde54642011-11-03 00:14:01 +0000618 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000619 // FIXME: attrid is dead, remove it in LLVM 3.0
620 // FUNCTION: [vararg, attrid, retty, paramty x N]
621 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000622 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000623 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000624 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
625 if (Type *T = getTypeByID(Record[i]))
626 ArgTys.push_back(T);
627 else
628 break;
629 }
630
631 ResultTy = getTypeByID(Record[2]);
632 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
633 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000634
Chris Lattner1afcace2011-07-09 17:41:24 +0000635 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000636 break;
637 }
Chad Rosiercde54642011-11-03 00:14:01 +0000638 case bitc::TYPE_CODE_FUNCTION: {
639 // FUNCTION: [vararg, retty, paramty x N]
640 if (Record.size() < 2)
641 return Error("Invalid FUNCTION type record");
642 std::vector<Type*> ArgTys;
643 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
644 if (Type *T = getTypeByID(Record[i]))
645 ArgTys.push_back(T);
646 else
647 break;
648 }
649
650 ResultTy = getTypeByID(Record[1]);
651 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
652 return Error("invalid type in function type");
653
654 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
655 break;
656 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000657 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000658 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000659 return Error("Invalid STRUCT type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000660 std::vector<Type*> EltTys;
661 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
662 if (Type *T = getTypeByID(Record[i]))
663 EltTys.push_back(T);
664 else
665 break;
666 }
667 if (EltTys.size() != Record.size()-1)
668 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000669 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000670 break;
671 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000672 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
673 if (ConvertToString(Record, 0, TypeName))
674 return Error("Invalid STRUCT_NAME record");
675 continue;
676
677 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
678 if (Record.size() < 1)
679 return Error("Invalid STRUCT type record");
680
681 if (NumRecords >= TypeList.size())
682 return Error("invalid TYPE table");
683
684 // Check to see if this was forward referenced, if so fill in the temp.
685 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
686 if (Res) {
687 Res->setName(TypeName);
688 TypeList[NumRecords] = 0;
689 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000690 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000691 TypeName.clear();
692
693 SmallVector<Type*, 8> EltTys;
694 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
695 if (Type *T = getTypeByID(Record[i]))
696 EltTys.push_back(T);
697 else
698 break;
699 }
700 if (EltTys.size() != Record.size()-1)
701 return Error("invalid STRUCT type record");
702 Res->setBody(EltTys, Record[0]);
703 ResultTy = Res;
704 break;
705 }
706 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
707 if (Record.size() != 1)
708 return Error("Invalid OPAQUE type record");
709
710 if (NumRecords >= TypeList.size())
711 return Error("invalid TYPE table");
712
713 // Check to see if this was forward referenced, if so fill in the temp.
714 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
715 if (Res) {
716 Res->setName(TypeName);
717 TypeList[NumRecords] = 0;
718 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000719 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000720 TypeName.clear();
721 ResultTy = Res;
722 break;
723 }
724 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
725 if (Record.size() < 2)
726 return Error("Invalid ARRAY type record");
727 if ((ResultTy = getTypeByID(Record[1])))
728 ResultTy = ArrayType::get(ResultTy, Record[0]);
729 else
730 return Error("Invalid ARRAY type element");
731 break;
732 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
733 if (Record.size() < 2)
734 return Error("Invalid VECTOR type record");
735 if ((ResultTy = getTypeByID(Record[1])))
736 ResultTy = VectorType::get(ResultTy, Record[0]);
737 else
738 return Error("Invalid ARRAY type element");
739 break;
740 }
741
742 if (NumRecords >= TypeList.size())
743 return Error("invalid TYPE table");
744 assert(ResultTy && "Didn't read a type?");
745 assert(TypeList[NumRecords] == 0 && "Already read type?");
746 TypeList[NumRecords++] = ResultTy;
747 }
748}
749
750// FIXME: Remove in LLVM 3.1
751bool BitcodeReader::ParseOldTypeTable() {
752 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
753 return Error("Malformed block record");
754
755 if (!TypeList.empty())
756 return Error("Multiple TYPE_BLOCKs found!");
757
758
759 // While horrible, we have no good ordering of types in the bc file. Just
760 // iteratively parse types out of the bc file in multiple passes until we get
761 // them all. Do this by saving a cursor for the start of the type block.
762 BitstreamCursor StartOfTypeBlockCursor(Stream);
763
764 unsigned NumTypesRead = 0;
765
766 SmallVector<uint64_t, 64> Record;
767RestartScan:
768 unsigned NextTypeID = 0;
769 bool ReadAnyTypes = false;
770
771 // Read all the records for this type table.
772 while (1) {
773 unsigned Code = Stream.ReadCode();
774 if (Code == bitc::END_BLOCK) {
775 if (NextTypeID != TypeList.size())
776 return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD");
777
778 // If we haven't read all of the types yet, iterate again.
779 if (NumTypesRead != TypeList.size()) {
780 // If we didn't successfully read any types in this pass, then we must
781 // have an unhandled forward reference.
782 if (!ReadAnyTypes)
783 return Error("Obsolete bitcode contains unhandled recursive type");
784
785 Stream = StartOfTypeBlockCursor;
786 goto RestartScan;
787 }
788
789 if (Stream.ReadBlockEnd())
790 return Error("Error at end of type table block");
791 return false;
792 }
793
794 if (Code == bitc::ENTER_SUBBLOCK) {
795 // No known subblocks, always skip them.
796 Stream.ReadSubBlockID();
797 if (Stream.SkipBlock())
798 return Error("Malformed block record");
799 continue;
800 }
801
802 if (Code == bitc::DEFINE_ABBREV) {
803 Stream.ReadAbbrevRecord();
804 continue;
805 }
806
807 // Read a record.
808 Record.clear();
809 Type *ResultTy = 0;
810 switch (Stream.ReadRecord(Code, Record)) {
811 default: return Error("unknown type in type table");
812 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
813 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
814 // type list. This allows us to reserve space.
815 if (Record.size() < 1)
816 return Error("Invalid TYPE_CODE_NUMENTRY record");
817 TypeList.resize(Record[0]);
818 continue;
819 case bitc::TYPE_CODE_VOID: // VOID
820 ResultTy = Type::getVoidTy(Context);
821 break;
822 case bitc::TYPE_CODE_FLOAT: // FLOAT
823 ResultTy = Type::getFloatTy(Context);
824 break;
825 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
826 ResultTy = Type::getDoubleTy(Context);
827 break;
828 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
829 ResultTy = Type::getX86_FP80Ty(Context);
830 break;
831 case bitc::TYPE_CODE_FP128: // FP128
832 ResultTy = Type::getFP128Ty(Context);
833 break;
834 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
835 ResultTy = Type::getPPC_FP128Ty(Context);
836 break;
837 case bitc::TYPE_CODE_LABEL: // LABEL
838 ResultTy = Type::getLabelTy(Context);
839 break;
840 case bitc::TYPE_CODE_METADATA: // METADATA
841 ResultTy = Type::getMetadataTy(Context);
842 break;
843 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
844 ResultTy = Type::getX86_MMXTy(Context);
845 break;
846 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
847 if (Record.size() < 1)
848 return Error("Invalid Integer type record");
849 ResultTy = IntegerType::get(Context, Record[0]);
850 break;
851 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
852 if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +0000853 ResultTy = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +0000854 break;
855 case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
856 if (NextTypeID >= TypeList.size()) break;
857 // If we already read it, don't reprocess.
858 if (TypeList[NextTypeID] &&
859 !cast<StructType>(TypeList[NextTypeID])->isOpaque())
860 break;
861
862 // Set a type.
863 if (TypeList[NextTypeID] == 0)
Chris Lattner3ebb6492011-08-12 18:06:37 +0000864 TypeList[NextTypeID] = StructType::create(Context);
Chris Lattner1afcace2011-07-09 17:41:24 +0000865
866 std::vector<Type*> EltTys;
867 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
868 if (Type *Elt = getTypeByIDOrNull(Record[i]))
869 EltTys.push_back(Elt);
870 else
871 break;
872 }
873
874 if (EltTys.size() != Record.size()-1)
875 break; // Not all elements are ready.
876
877 cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
878 ResultTy = TypeList[NextTypeID];
879 TypeList[NextTypeID] = 0;
880 break;
881 }
882 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
883 // [pointee type, address space]
884 if (Record.size() < 1)
885 return Error("Invalid POINTER type record");
886 unsigned AddressSpace = 0;
887 if (Record.size() == 2)
888 AddressSpace = Record[1];
889 if ((ResultTy = getTypeByIDOrNull(Record[0])))
890 ResultTy = PointerType::get(ResultTy, AddressSpace);
891 break;
892 }
Chad Rosiercde54642011-11-03 00:14:01 +0000893 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattner1afcace2011-07-09 17:41:24 +0000894 // FIXME: attrid is dead, remove it in LLVM 3.0
895 // FUNCTION: [vararg, attrid, retty, paramty x N]
896 if (Record.size() < 3)
897 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000898 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000899 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
900 if (Type *Elt = getTypeByIDOrNull(Record[i]))
901 ArgTys.push_back(Elt);
902 else
903 break;
904 }
905 if (ArgTys.size()+3 != Record.size())
906 break; // Something was null.
907 if ((ResultTy = getTypeByIDOrNull(Record[2])))
908 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
909 break;
910 }
Chad Rosiercde54642011-11-03 00:14:01 +0000911 case bitc::TYPE_CODE_FUNCTION: {
912 // FUNCTION: [vararg, retty, paramty x N]
913 if (Record.size() < 2)
914 return Error("Invalid FUNCTION type record");
915 std::vector<Type*> ArgTys;
916 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
917 if (Type *Elt = getTypeByIDOrNull(Record[i]))
918 ArgTys.push_back(Elt);
919 else
920 break;
921 }
922 if (ArgTys.size()+2 != Record.size())
923 break; // Something was null.
924 if ((ResultTy = getTypeByIDOrNull(Record[1])))
925 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
926 break;
927 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000928 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
929 if (Record.size() < 2)
930 return Error("Invalid ARRAY type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000931 if ((ResultTy = getTypeByIDOrNull(Record[1])))
932 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000933 break;
934 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
935 if (Record.size() < 2)
936 return Error("Invalid VECTOR type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000937 if ((ResultTy = getTypeByIDOrNull(Record[1])))
938 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000939 break;
940 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000941
942 if (NextTypeID >= TypeList.size())
943 return Error("invalid TYPE table");
944
945 if (ResultTy && TypeList[NextTypeID] == 0) {
946 ++NumTypesRead;
947 ReadAnyTypes = true;
948
949 TypeList[NextTypeID] = ResultTy;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000951
952 ++NextTypeID;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000953 }
954}
955
956
Chris Lattner1afcace2011-07-09 17:41:24 +0000957bool BitcodeReader::ParseOldTypeSymbolTable() {
958 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000959 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000960
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000961 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000963 // Read all the records for this type table.
964 std::string TypeName;
965 while (1) {
966 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000967 if (Code == bitc::END_BLOCK) {
968 if (Stream.ReadBlockEnd())
969 return Error("Error at end of type symbol table block");
970 return false;
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000973 if (Code == bitc::ENTER_SUBBLOCK) {
974 // No known subblocks, always skip them.
975 Stream.ReadSubBlockID();
976 if (Stream.SkipBlock())
977 return Error("Malformed block record");
978 continue;
979 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000980
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000981 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000982 Stream.ReadAbbrevRecord();
983 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000984 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000985
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000986 // Read a record.
987 Record.clear();
988 switch (Stream.ReadRecord(Code, Record)) {
989 default: // Default behavior: unknown type.
990 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000991 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000992 if (ConvertToString(Record, 1, TypeName))
993 return Error("Invalid TST_ENTRY record");
994 unsigned TypeID = Record[0];
995 if (TypeID >= TypeList.size())
996 return Error("Invalid Type ID in TST_ENTRY record");
997
Chris Lattner1afcace2011-07-09 17:41:24 +0000998 // Only apply the type name to a struct type with no name.
999 if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
Chris Lattner3ebb6492011-08-12 18:06:37 +00001000 if (!STy->isLiteral() && !STy->hasName())
Chris Lattner1afcace2011-07-09 17:41:24 +00001001 STy->setName(TypeName);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001002 TypeName.clear();
1003 break;
1004 }
1005 }
1006}
1007
Chris Lattner86697142007-05-01 05:01:34 +00001008bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001009 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +00001010 return Error("Malformed block record");
1011
1012 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001013
Chris Lattner0b2482a2007-04-23 21:26:05 +00001014 // Read all the records for this value table.
1015 SmallString<128> ValueName;
1016 while (1) {
1017 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001018 if (Code == bitc::END_BLOCK) {
1019 if (Stream.ReadBlockEnd())
1020 return Error("Error at end of value symbol table block");
1021 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001022 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001023 if (Code == bitc::ENTER_SUBBLOCK) {
1024 // No known subblocks, always skip them.
1025 Stream.ReadSubBlockID();
1026 if (Stream.SkipBlock())
1027 return Error("Malformed block record");
1028 continue;
1029 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001030
Chris Lattner0b2482a2007-04-23 21:26:05 +00001031 if (Code == bitc::DEFINE_ABBREV) {
1032 Stream.ReadAbbrevRecord();
1033 continue;
1034 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattner0b2482a2007-04-23 21:26:05 +00001036 // Read a record.
1037 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +00001038 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +00001039 default: // Default behavior: unknown type.
1040 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001041 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +00001042 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +00001043 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +00001044 unsigned ValueID = Record[0];
1045 if (ValueID >= ValueList.size())
1046 return Error("Invalid Value ID in VST_ENTRY record");
1047 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +00001048
Daniel Dunbar3f53fa92009-07-26 00:34:27 +00001049 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +00001050 ValueName.clear();
1051 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +00001052 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +00001053 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +00001054 if (ConvertToString(Record, 1, ValueName))
1055 return Error("Invalid VST_BBENTRY record");
1056 BasicBlock *BB = getBasicBlock(Record[0]);
1057 if (BB == 0)
1058 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001059
Daniel Dunbar3f53fa92009-07-26 00:34:27 +00001060 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +00001061 ValueName.clear();
1062 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001063 }
Reid Spencerc8f8a242007-05-04 01:43:33 +00001064 }
Chris Lattner0b2482a2007-04-23 21:26:05 +00001065 }
1066}
1067
Devang Patele54abc92009-07-22 17:43:22 +00001068bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +00001069 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +00001070
1071 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1072 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001073
Devang Patele54abc92009-07-22 17:43:22 +00001074 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001075
Devang Patele54abc92009-07-22 17:43:22 +00001076 // Read all the records.
1077 while (1) {
1078 unsigned Code = Stream.ReadCode();
1079 if (Code == bitc::END_BLOCK) {
1080 if (Stream.ReadBlockEnd())
1081 return Error("Error at end of PARAMATTR block");
1082 return false;
1083 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001084
Devang Patele54abc92009-07-22 17:43:22 +00001085 if (Code == bitc::ENTER_SUBBLOCK) {
1086 // No known subblocks, always skip them.
1087 Stream.ReadSubBlockID();
1088 if (Stream.SkipBlock())
1089 return Error("Malformed block record");
1090 continue;
1091 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001092
Devang Patele54abc92009-07-22 17:43:22 +00001093 if (Code == bitc::DEFINE_ABBREV) {
1094 Stream.ReadAbbrevRecord();
1095 continue;
1096 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001097
Victor Hernandez24e64df2010-01-10 07:14:18 +00001098 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +00001099 // Read a record.
1100 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +00001101 Code = Stream.ReadRecord(Code, Record);
1102 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +00001103 default: // Default behavior: ignore.
1104 break;
Devang Patelaa993142009-07-29 22:34:41 +00001105 case bitc::METADATA_NAME: {
1106 // Read named of the named metadata.
1107 unsigned NameLength = Record.size();
1108 SmallString<8> Name;
1109 Name.resize(NameLength);
1110 for (unsigned i = 0; i != NameLength; ++i)
1111 Name[i] = Record[i];
1112 Record.clear();
1113 Code = Stream.ReadCode();
1114
Chris Lattner9d61dd92011-06-17 17:50:30 +00001115 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +00001116 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001117 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +00001118
1119 // Read named metadata elements.
1120 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +00001121 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +00001122 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +00001123 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1124 if (MD == 0)
1125 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +00001126 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +00001127 }
Devang Patelaa993142009-07-29 22:34:41 +00001128 break;
1129 }
Chris Lattner9d61dd92011-06-17 17:50:30 +00001130 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +00001131 IsFunctionLocal = true;
1132 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +00001133 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +00001134 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +00001135 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001136
Devang Patel104cf9e2009-07-23 01:07:34 +00001137 unsigned Size = Record.size();
1138 SmallVector<Value*, 8> Elts;
1139 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001140 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +00001141 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001142 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +00001143 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +00001144 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +00001145 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1146 else
1147 Elts.push_back(NULL);
1148 }
Jay Foadec9186b2011-04-21 19:59:31 +00001149 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +00001150 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +00001151 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +00001152 break;
1153 }
Devang Patele54abc92009-07-22 17:43:22 +00001154 case bitc::METADATA_STRING: {
1155 unsigned MDStringLength = Record.size();
1156 SmallString<8> String;
1157 String.resize(MDStringLength);
1158 for (unsigned i = 0; i != MDStringLength; ++i)
1159 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +00001160 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +00001161 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +00001162 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +00001163 break;
1164 }
Devang Patele8e02132009-09-18 19:26:43 +00001165 case bitc::METADATA_KIND: {
1166 unsigned RecordLength = Record.size();
1167 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001168 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +00001169 SmallString<8> Name;
1170 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +00001171 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +00001172 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001173 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +00001174
Chris Lattner08113472009-12-29 09:01:33 +00001175 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +00001176 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1177 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +00001178 break;
1179 }
Devang Patele54abc92009-07-22 17:43:22 +00001180 }
1181 }
1182}
1183
Chris Lattner0eef0802007-04-24 04:04:35 +00001184/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
1185/// the LSB for dense VBR encoding.
1186static uint64_t DecodeSignRotatedValue(uint64_t V) {
1187 if ((V & 1) == 0)
1188 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001189 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +00001190 return -(V >> 1);
1191 // There is no such thing as -0 with integers. "-0" really means MININT.
1192 return 1ULL << 63;
1193}
1194
Chris Lattner07d98b42007-04-26 02:46:40 +00001195/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1196/// values and aliases that we can.
1197bool BitcodeReader::ResolveGlobalAndAliasInits() {
1198 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1199 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001200
Chris Lattner07d98b42007-04-26 02:46:40 +00001201 GlobalInitWorklist.swap(GlobalInits);
1202 AliasInitWorklist.swap(AliasInits);
1203
1204 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +00001205 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +00001206 if (ValID >= ValueList.size()) {
1207 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +00001208 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +00001209 } else {
1210 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1211 GlobalInitWorklist.back().first->setInitializer(C);
1212 else
1213 return Error("Global variable initializer is not a constant!");
1214 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001215 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001216 }
1217
1218 while (!AliasInitWorklist.empty()) {
1219 unsigned ValID = AliasInitWorklist.back().second;
1220 if (ValID >= ValueList.size()) {
1221 AliasInits.push_back(AliasInitWorklist.back());
1222 } else {
1223 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +00001224 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +00001225 else
1226 return Error("Alias initializer is not a constant!");
1227 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001228 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +00001229 }
1230 return false;
1231}
1232
Chris Lattner86697142007-05-01 05:01:34 +00001233bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001234 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001235 return Error("Malformed block record");
1236
1237 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001238
Chris Lattnere16504e2007-04-24 03:30:34 +00001239 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001240 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001241 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001242 while (1) {
1243 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +00001244 if (Code == bitc::END_BLOCK)
1245 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001246
Chris Lattnere16504e2007-04-24 03:30:34 +00001247 if (Code == bitc::ENTER_SUBBLOCK) {
1248 // No known subblocks, always skip them.
1249 Stream.ReadSubBlockID();
1250 if (Stream.SkipBlock())
1251 return Error("Malformed block record");
1252 continue;
1253 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001254
Chris Lattnere16504e2007-04-24 03:30:34 +00001255 if (Code == bitc::DEFINE_ABBREV) {
1256 Stream.ReadAbbrevRecord();
1257 continue;
1258 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattnere16504e2007-04-24 03:30:34 +00001260 // Read a record.
1261 Record.clear();
1262 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001263 unsigned BitCode = Stream.ReadRecord(Code, Record);
1264 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001265 default: // Default behavior: unknown constant
1266 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001267 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001268 break;
1269 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1270 if (Record.empty())
1271 return Error("Malformed CST_SETTYPE record");
1272 if (Record[0] >= TypeList.size())
1273 return Error("Invalid Type ID in CST_SETTYPE record");
1274 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001275 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001276 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001277 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001278 break;
1279 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001280 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001281 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001282 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001283 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001284 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001285 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001286 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001287
Chris Lattner15e6d172007-05-04 19:11:41 +00001288 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +00001289 SmallVector<uint64_t, 8> Words;
1290 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +00001291 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001292 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +00001294 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001295 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001296 break;
1297 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001298 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001299 if (Record.empty())
1300 return Error("Invalid FLOAT record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001301 if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001302 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001303 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001304 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001305 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001306 // Bits are not stored the same way as a normal i80 APInt, compensate.
1307 uint64_t Rearrange[2];
1308 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1309 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001310 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001311 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001312 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001313 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001314 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001315 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001316 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001317 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001318 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001319
Chris Lattner15e6d172007-05-04 19:11:41 +00001320 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1321 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001322 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001323
Chris Lattner15e6d172007-05-04 19:11:41 +00001324 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +00001325 std::vector<Constant*> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001326
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001327 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001328 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001329 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001330 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001331 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1333 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001334 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001335 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001336 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001337 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1338 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001339 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001340 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001341 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001342 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001343 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001344 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001345 break;
1346 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001347 case bitc::CST_CODE_STRING: { // STRING: [values]
1348 if (Record.empty())
1349 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001350
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001351 ArrayType *ATy = cast<ArrayType>(CurTy);
1352 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001354 unsigned Size = Record.size();
1355 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001356 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001357 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001358 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001359 break;
1360 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001361 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1362 if (Record.empty())
1363 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001365 ArrayType *ATy = cast<ArrayType>(CurTy);
1366 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001367
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001368 unsigned Size = Record.size();
1369 std::vector<Constant*> Elts;
1370 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001371 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001372 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001373 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001374 break;
1375 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001376 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1377 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1378 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001379 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001380 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001381 } else {
1382 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1383 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001384 unsigned Flags = 0;
1385 if (Record.size() >= 4) {
1386 if (Opc == Instruction::Add ||
1387 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001388 Opc == Instruction::Mul ||
1389 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001390 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1391 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1392 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1393 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001394 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001395 Opc == Instruction::UDiv ||
1396 Opc == Instruction::LShr ||
1397 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001398 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001399 Flags |= SDivOperator::IsExact;
1400 }
1401 }
1402 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001403 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001404 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001405 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001406 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1407 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1408 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001409 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001410 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001411 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001412 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001413 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001414 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001415 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001416 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001417 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001418 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001419 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001420 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001421 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001422 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001423 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001424 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001425 if (!ElTy) return Error("Invalid CE_GEP record");
1426 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1427 }
Jay Foaddab3d292011-07-21 14:31:17 +00001428 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001429 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1430 BitCode ==
1431 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001432 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001433 }
1434 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1435 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001436 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001437 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001438 ValueList.getConstantFwdRef(Record[1],CurTy),
1439 ValueList.getConstantFwdRef(Record[2],CurTy));
1440 break;
1441 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1442 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001443 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001444 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1445 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1446 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001447 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001448 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001449 break;
1450 }
1451 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001452 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001453 if (Record.size() < 3 || OpTy == 0)
1454 return Error("Invalid CE_INSERTELT record");
1455 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1456 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1457 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001458 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001459 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001460 break;
1461 }
1462 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001463 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001464 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001465 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001466 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1467 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001468 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001469 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001470 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001471 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001472 break;
1473 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001474 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001475 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1476 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001477 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001478 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1479 return Error("Invalid CE_SHUFVEC_EX record");
1480 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1481 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001482 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001483 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001484 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001485 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001486 break;
1487 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001488 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1489 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001490 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001491 if (OpTy == 0) return Error("Invalid CE_CMP record");
1492 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1493 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1494
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001495 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001496 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001497 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001498 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001499 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001500 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001501 case bitc::CST_CODE_INLINEASM: {
1502 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1503 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001504 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001505 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001506 unsigned AsmStrSize = Record[1];
1507 if (2+AsmStrSize >= Record.size())
1508 return Error("Invalid INLINEASM record");
1509 unsigned ConstStrSize = Record[2+AsmStrSize];
1510 if (3+AsmStrSize+ConstStrSize > Record.size())
1511 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001512
Chris Lattner2bce93a2007-05-06 01:58:20 +00001513 for (unsigned i = 0; i != AsmStrSize; ++i)
1514 AsmStr += (char)Record[2+i];
1515 for (unsigned i = 0; i != ConstStrSize; ++i)
1516 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001517 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001518 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001519 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001520 break;
1521 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001522 case bitc::CST_CODE_BLOCKADDRESS:{
1523 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001524 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001525 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1526 Function *Fn =
1527 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1528 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1529
1530 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1531 Type::getInt8Ty(Context),
1532 false, GlobalValue::InternalLinkage,
1533 0, "");
1534 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1535 V = FwdRef;
1536 break;
1537 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001539
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001540 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001541 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001542 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001543
Chris Lattnerea693df2008-08-21 02:34:16 +00001544 if (NextCstNo != ValueList.size())
1545 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001546
Chris Lattnerea693df2008-08-21 02:34:16 +00001547 if (Stream.ReadBlockEnd())
1548 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549
Chris Lattnerea693df2008-08-21 02:34:16 +00001550 // Once all the constants have been read, go through and resolve forward
1551 // references.
1552 ValueList.ResolveConstantForwardRefs();
1553 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001554}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001555
Chris Lattner980e5aa2007-05-01 05:52:21 +00001556/// RememberAndSkipFunctionBody - When we see the block for a function body,
1557/// remember where it is and then skip it. This lets us lazily deserialize the
1558/// functions.
1559bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001560 // Get the function we are talking about.
1561 if (FunctionsWithBodies.empty())
1562 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001563
Chris Lattner48f84872007-05-01 04:59:48 +00001564 Function *Fn = FunctionsWithBodies.back();
1565 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001566
Chris Lattner48f84872007-05-01 04:59:48 +00001567 // Save the current stream state.
1568 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001569 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001570
Chris Lattner48f84872007-05-01 04:59:48 +00001571 // Skip over the function block for now.
1572 if (Stream.SkipBlock())
1573 return Error("Malformed block record");
1574 return false;
1575}
1576
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001577bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001578 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001579 return Error("Malformed block record");
1580
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001581 SmallVector<uint64_t, 64> Record;
1582 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001583 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001584
1585 // Read all the records for this module.
1586 while (!Stream.AtEndOfStream()) {
1587 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001588 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001589 if (Stream.ReadBlockEnd())
1590 return Error("Error at end of module block");
1591
1592 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001593 ResolveGlobalAndAliasInits();
1594 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001595 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001596 if (!FunctionsWithBodies.empty())
1597 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001598
Chandler Carruth69940402007-08-04 01:51:18 +00001599 // Look for intrinsic functions which need to be upgraded at some point
1600 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1601 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001602 Function* NewFn;
1603 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001604 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1605 }
1606
Bill Wendlingde49f362010-09-10 18:51:56 +00001607 // Look for global variables which need to be renamed.
1608 for (Module::global_iterator
1609 GI = TheModule->global_begin(), GE = TheModule->global_end();
1610 GI != GE; ++GI)
1611 UpgradeGlobalVariable(GI);
1612
Chris Lattner980e5aa2007-05-01 05:52:21 +00001613 // Force deallocation of memory for these vectors to favor the client that
1614 // want lazy deserialization.
1615 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1616 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1617 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001618 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001619 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001621 if (Code == bitc::ENTER_SUBBLOCK) {
1622 switch (Stream.ReadSubBlockID()) {
1623 default: // Skip unknown content.
1624 if (Stream.SkipBlock())
1625 return Error("Malformed block record");
1626 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001627 case bitc::BLOCKINFO_BLOCK_ID:
1628 if (Stream.ReadBlockInfoBlock())
1629 return Error("Malformed BlockInfoBlock");
1630 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001631 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001632 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001633 return true;
1634 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001635 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001636 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001637 return true;
1638 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001639 case bitc::TYPE_BLOCK_ID_OLD:
1640 if (ParseOldTypeTable())
1641 return true;
1642 break;
1643 case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
1644 if (ParseOldTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001645 return true;
1646 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001647 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001648 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001649 return true;
1650 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001651 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001652 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001653 return true;
1654 break;
Devang Patele54abc92009-07-22 17:43:22 +00001655 case bitc::METADATA_BLOCK_ID:
1656 if (ParseMetadata())
1657 return true;
1658 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001659 case bitc::FUNCTION_BLOCK_ID:
1660 // If this is the first function body we've seen, reverse the
1661 // FunctionsWithBodies list.
1662 if (!HasReversedFunctionsWithBodies) {
1663 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1664 HasReversedFunctionsWithBodies = true;
1665 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001666
Chris Lattner980e5aa2007-05-01 05:52:21 +00001667 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001668 return true;
1669 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001670 }
1671 continue;
1672 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001673
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001674 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001675 Stream.ReadAbbrevRecord();
1676 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001677 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001678
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001679 // Read a record.
1680 switch (Stream.ReadRecord(Code, Record)) {
1681 default: break; // Default behavior, ignore unknown content.
1682 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1683 if (Record.size() < 1)
1684 return Error("Malformed MODULE_CODE_VERSION");
1685 // Only version #0 is supported so far.
1686 if (Record[0] != 0)
1687 return Error("Unknown bitstream version!");
1688 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001689 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001690 std::string S;
1691 if (ConvertToString(Record, 0, S))
1692 return Error("Invalid MODULE_CODE_TRIPLE record");
1693 TheModule->setTargetTriple(S);
1694 break;
1695 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001696 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001697 std::string S;
1698 if (ConvertToString(Record, 0, S))
1699 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1700 TheModule->setDataLayout(S);
1701 break;
1702 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001703 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001704 std::string S;
1705 if (ConvertToString(Record, 0, S))
1706 return Error("Invalid MODULE_CODE_ASM record");
1707 TheModule->setModuleInlineAsm(S);
1708 break;
1709 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001710 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001711 std::string S;
1712 if (ConvertToString(Record, 0, S))
1713 return Error("Invalid MODULE_CODE_DEPLIB record");
1714 TheModule->addLibrary(S);
1715 break;
1716 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001717 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001718 std::string S;
1719 if (ConvertToString(Record, 0, S))
1720 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1721 SectionTable.push_back(S);
1722 break;
1723 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001724 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001725 std::string S;
1726 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001727 return Error("Invalid MODULE_CODE_GCNAME record");
1728 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001729 break;
1730 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001731 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001732 // linkage, alignment, section, visibility, threadlocal,
1733 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001734 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001735 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001736 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001737 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001738 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001739 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001740 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001741 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001742 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001743
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001744 bool isConstant = Record[1];
1745 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1746 unsigned Alignment = (1 << Record[4]) >> 1;
1747 std::string Section;
1748 if (Record[5]) {
1749 if (Record[5]-1 >= SectionTable.size())
1750 return Error("Invalid section ID");
1751 Section = SectionTable[Record[5]-1];
1752 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001753 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001754 if (Record.size() > 6)
1755 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001756 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001757 if (Record.size() > 7)
1758 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001759
Rafael Espindolabea46262011-01-08 16:42:36 +00001760 bool UnnamedAddr = false;
1761 if (Record.size() > 8)
1762 UnnamedAddr = Record[8];
1763
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001764 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001765 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001766 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001767 NewGV->setAlignment(Alignment);
1768 if (!Section.empty())
1769 NewGV->setSection(Section);
1770 NewGV->setVisibility(Visibility);
1771 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001772 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001773
Chris Lattner0b2482a2007-04-23 21:26:05 +00001774 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001775
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001776 // Remember which value to use for the global initializer.
1777 if (unsigned InitID = Record[2])
1778 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001779 break;
1780 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001781 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001782 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001783 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001784 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001785 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001786 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001787 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001788 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001789 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001790 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001791 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1792 if (!FTy)
1793 return Error("Function not a pointer to function type!");
1794
Gabor Greif051a9502008-04-06 20:25:17 +00001795 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1796 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001797
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001798 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001799 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001800 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001801 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001802
Chris Lattnera9bb7132007-05-08 05:38:01 +00001803 Func->setAlignment((1 << Record[5]) >> 1);
1804 if (Record[6]) {
1805 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001806 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001807 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001808 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001809 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001810 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001811 if (Record[8]-1 > GCTable.size())
1812 return Error("Invalid GC ID");
1813 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001814 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001815 bool UnnamedAddr = false;
1816 if (Record.size() > 9)
1817 UnnamedAddr = Record[9];
1818 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001819 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001820
Chris Lattner48f84872007-05-01 04:59:48 +00001821 // If this is a function with a body, remember the prototype we are
1822 // creating now, so that we can match up the body with them later.
1823 if (!isProto)
1824 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001825 break;
1826 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001827 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001828 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001829 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001830 if (Record.size() < 3)
1831 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001832 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001833 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001834 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001835 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001836
Chris Lattner07d98b42007-04-26 02:46:40 +00001837 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1838 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001839 // Old bitcode files didn't have visibility field.
1840 if (Record.size() > 3)
1841 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001842 ValueList.push_back(NewGA);
1843 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1844 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001845 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001846 /// MODULE_CODE_PURGEVALS: [numvals]
1847 case bitc::MODULE_CODE_PURGEVALS:
1848 // Trim down the value list to the specified size.
1849 if (Record.size() < 1 || Record[0] > ValueList.size())
1850 return Error("Invalid MODULE_PURGEVALS record");
1851 ValueList.shrinkTo(Record[0]);
1852 break;
1853 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001854 Record.clear();
1855 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001857 return Error("Premature end of bitstream");
1858}
1859
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001860bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001861 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001862
Chris Lattnerc453f762007-04-29 07:54:31 +00001863 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001864 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001866 if (Buffer->getBufferSize() & 3) {
1867 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1868 return Error("Invalid bitcode signature");
1869 else
1870 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1871 }
1872
Chris Lattner6fa6a322008-07-09 05:14:23 +00001873 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1874 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001875 if (isBitcodeWrapper(BufPtr, BufEnd))
1876 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001877 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattner962dde32009-04-26 20:59:02 +00001879 StreamFile.init(BufPtr, BufEnd);
1880 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001882 // Sniff for the signature.
1883 if (Stream.Read(8) != 'B' ||
1884 Stream.Read(8) != 'C' ||
1885 Stream.Read(4) != 0x0 ||
1886 Stream.Read(4) != 0xC ||
1887 Stream.Read(4) != 0xE ||
1888 Stream.Read(4) != 0xD)
1889 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001890
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001891 // We expect a number of well-defined blocks, though we don't necessarily
1892 // need to understand them all.
1893 while (!Stream.AtEndOfStream()) {
1894 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001895
Rafael Espindolac9687b32011-05-26 18:59:54 +00001896 if (Code != bitc::ENTER_SUBBLOCK) {
1897
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001898 // The ranlib in xcode 4 will align archive members by appending newlines
1899 // to the end of them. If this file size is a multiple of 4 but not 8, we
1900 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001901 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1902 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1903 Stream.AtEndOfStream())
1904 return false;
1905
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001906 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001907 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001909 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001911 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001912 switch (BlockID) {
1913 case bitc::BLOCKINFO_BLOCK_ID:
1914 if (Stream.ReadBlockInfoBlock())
1915 return Error("Malformed BlockInfoBlock");
1916 break;
1917 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001918 // Reject multiple MODULE_BLOCK's in a single bitstream.
1919 if (TheModule)
1920 return Error("Multiple MODULE_BLOCKs in same stream");
1921 TheModule = M;
1922 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001923 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001924 break;
1925 default:
1926 if (Stream.SkipBlock())
1927 return Error("Malformed block record");
1928 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001929 }
1930 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001931
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001932 return false;
1933}
Chris Lattnerc453f762007-04-29 07:54:31 +00001934
Bill Wendling34711742010-10-06 01:22:42 +00001935bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1936 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1937 return Error("Malformed block record");
1938
1939 SmallVector<uint64_t, 64> Record;
1940
1941 // Read all the records for this module.
1942 while (!Stream.AtEndOfStream()) {
1943 unsigned Code = Stream.ReadCode();
1944 if (Code == bitc::END_BLOCK) {
1945 if (Stream.ReadBlockEnd())
1946 return Error("Error at end of module block");
1947
1948 return false;
1949 }
1950
1951 if (Code == bitc::ENTER_SUBBLOCK) {
1952 switch (Stream.ReadSubBlockID()) {
1953 default: // Skip unknown content.
1954 if (Stream.SkipBlock())
1955 return Error("Malformed block record");
1956 break;
1957 }
1958 continue;
1959 }
1960
1961 if (Code == bitc::DEFINE_ABBREV) {
1962 Stream.ReadAbbrevRecord();
1963 continue;
1964 }
1965
1966 // Read a record.
1967 switch (Stream.ReadRecord(Code, Record)) {
1968 default: break; // Default behavior, ignore unknown content.
1969 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1970 if (Record.size() < 1)
1971 return Error("Malformed MODULE_CODE_VERSION");
1972 // Only version #0 is supported so far.
1973 if (Record[0] != 0)
1974 return Error("Unknown bitstream version!");
1975 break;
1976 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1977 std::string S;
1978 if (ConvertToString(Record, 0, S))
1979 return Error("Invalid MODULE_CODE_TRIPLE record");
1980 Triple = S;
1981 break;
1982 }
1983 }
1984 Record.clear();
1985 }
1986
1987 return Error("Premature end of bitstream");
1988}
1989
1990bool BitcodeReader::ParseTriple(std::string &Triple) {
1991 if (Buffer->getBufferSize() & 3)
1992 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1993
1994 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1995 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1996
1997 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1998 // The magic number is 0x0B17C0DE stored in little endian.
1999 if (isBitcodeWrapper(BufPtr, BufEnd))
2000 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
2001 return Error("Invalid bitcode wrapper header");
2002
2003 StreamFile.init(BufPtr, BufEnd);
2004 Stream.init(StreamFile);
2005
2006 // Sniff for the signature.
2007 if (Stream.Read(8) != 'B' ||
2008 Stream.Read(8) != 'C' ||
2009 Stream.Read(4) != 0x0 ||
2010 Stream.Read(4) != 0xC ||
2011 Stream.Read(4) != 0xE ||
2012 Stream.Read(4) != 0xD)
2013 return Error("Invalid bitcode signature");
2014
2015 // We expect a number of well-defined blocks, though we don't necessarily
2016 // need to understand them all.
2017 while (!Stream.AtEndOfStream()) {
2018 unsigned Code = Stream.ReadCode();
2019
2020 if (Code != bitc::ENTER_SUBBLOCK)
2021 return Error("Invalid record at top-level");
2022
2023 unsigned BlockID = Stream.ReadSubBlockID();
2024
2025 // We only know the MODULE subblock ID.
2026 switch (BlockID) {
2027 case bitc::MODULE_BLOCK_ID:
2028 if (ParseModuleTriple(Triple))
2029 return true;
2030 break;
2031 default:
2032 if (Stream.SkipBlock())
2033 return Error("Malformed block record");
2034 break;
2035 }
2036 }
2037
2038 return false;
2039}
2040
Devang Patele8e02132009-09-18 19:26:43 +00002041/// ParseMetadataAttachment - Parse metadata attachments.
2042bool BitcodeReader::ParseMetadataAttachment() {
2043 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2044 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002045
Devang Patele8e02132009-09-18 19:26:43 +00002046 SmallVector<uint64_t, 64> Record;
2047 while(1) {
2048 unsigned Code = Stream.ReadCode();
2049 if (Code == bitc::END_BLOCK) {
2050 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00002052 break;
2053 }
2054 if (Code == bitc::DEFINE_ABBREV) {
2055 Stream.ReadAbbrevRecord();
2056 continue;
2057 }
2058 // Read a metadata attachment record.
2059 Record.clear();
2060 switch (Stream.ReadRecord(Code, Record)) {
2061 default: // Default behavior: ignore.
2062 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00002063 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00002064 unsigned RecordLength = Record.size();
2065 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00002066 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00002067 Instruction *Inst = InstructionList[Record[0]];
2068 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00002069 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00002070 DenseMap<unsigned, unsigned>::iterator I =
2071 MDKindMap.find(Kind);
2072 if (I == MDKindMap.end())
2073 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002074 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00002075 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00002076 }
2077 break;
2078 }
2079 }
2080 }
2081 return false;
2082}
Chris Lattner48f84872007-05-01 04:59:48 +00002083
Chris Lattner980e5aa2007-05-01 05:52:21 +00002084/// ParseFunctionBody - Lazily parse the specified function body block.
2085bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00002086 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00002087 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002088
Nick Lewycky9a49f152010-02-25 08:30:17 +00002089 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002090 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00002091 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002092
Chris Lattner980e5aa2007-05-01 05:52:21 +00002093 // Add all the function arguments to the value table.
2094 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2095 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002097 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00002098 BasicBlock *CurBB = 0;
2099 unsigned CurBBNo = 0;
2100
Chris Lattnera6245242010-04-03 02:17:50 +00002101 DebugLoc LastLoc;
2102
Chris Lattner980e5aa2007-05-01 05:52:21 +00002103 // Read all the records.
2104 SmallVector<uint64_t, 64> Record;
2105 while (1) {
2106 unsigned Code = Stream.ReadCode();
2107 if (Code == bitc::END_BLOCK) {
2108 if (Stream.ReadBlockEnd())
2109 return Error("Error at end of function block");
2110 break;
2111 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002112
Chris Lattner980e5aa2007-05-01 05:52:21 +00002113 if (Code == bitc::ENTER_SUBBLOCK) {
2114 switch (Stream.ReadSubBlockID()) {
2115 default: // Skip unknown content.
2116 if (Stream.SkipBlock())
2117 return Error("Malformed block record");
2118 break;
2119 case bitc::CONSTANTS_BLOCK_ID:
2120 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002121 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002122 break;
2123 case bitc::VALUE_SYMTAB_BLOCK_ID:
2124 if (ParseValueSymbolTable()) return true;
2125 break;
Devang Patele8e02132009-09-18 19:26:43 +00002126 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002127 if (ParseMetadataAttachment()) return true;
2128 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002129 case bitc::METADATA_BLOCK_ID:
2130 if (ParseMetadata()) return true;
2131 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002132 }
2133 continue;
2134 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002135
Chris Lattner980e5aa2007-05-01 05:52:21 +00002136 if (Code == bitc::DEFINE_ABBREV) {
2137 Stream.ReadAbbrevRecord();
2138 continue;
2139 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Chris Lattner980e5aa2007-05-01 05:52:21 +00002141 // Read a record.
2142 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002143 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00002144 unsigned BitCode = Stream.ReadRecord(Code, Record);
2145 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002146 default: // Default behavior: reject
2147 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002148 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002149 if (Record.size() < 1 || Record[0] == 0)
2150 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002151 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002152 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002153 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002154 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002155 CurBB = FunctionBBs[0];
2156 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00002157
2158 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2159 // This record indicates that the last instruction is at the same
2160 // location as the previous instruction with a location.
2161 I = 0;
2162
2163 // Get the last instruction emitted.
2164 if (CurBB && !CurBB->empty())
2165 I = &CurBB->back();
2166 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2167 !FunctionBBs[CurBBNo-1]->empty())
2168 I = &FunctionBBs[CurBBNo-1]->back();
2169
2170 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2171 I->setDebugLoc(LastLoc);
2172 I = 0;
2173 continue;
2174
Chris Lattner4f6bab92011-06-17 18:17:37 +00002175 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002176 I = 0; // Get the last instruction emitted.
2177 if (CurBB && !CurBB->empty())
2178 I = &CurBB->back();
2179 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2180 !FunctionBBs[CurBBNo-1]->empty())
2181 I = &FunctionBBs[CurBBNo-1]->back();
2182 if (I == 0 || Record.size() < 4)
2183 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2184
2185 unsigned Line = Record[0], Col = Record[1];
2186 unsigned ScopeID = Record[2], IAID = Record[3];
2187
2188 MDNode *Scope = 0, *IA = 0;
2189 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2190 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2191 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2192 I->setDebugLoc(LastLoc);
2193 I = 0;
2194 continue;
2195 }
2196
Chris Lattnerabfbf852007-05-06 00:21:25 +00002197 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2198 unsigned OpNum = 0;
2199 Value *LHS, *RHS;
2200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2201 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002202 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002203 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002204
Dan Gohman1224c382009-07-20 21:19:07 +00002205 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002206 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002207 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002208 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002209 if (OpNum < Record.size()) {
2210 if (Opc == Instruction::Add ||
2211 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002212 Opc == Instruction::Mul ||
2213 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002214 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002215 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002216 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002217 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002218 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002219 Opc == Instruction::UDiv ||
2220 Opc == Instruction::LShr ||
2221 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002222 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002223 cast<BinaryOperator>(I)->setIsExact(true);
2224 }
2225 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002226 break;
2227 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002228 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2229 unsigned OpNum = 0;
2230 Value *Op;
2231 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2232 OpNum+2 != Record.size())
2233 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002234
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002235 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002236 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2237 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002238 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002239 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002240 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002241 break;
2242 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002243 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002244 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002245 unsigned OpNum = 0;
2246 Value *BasePtr;
2247 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002248 return Error("Invalid GEP record");
2249
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002250 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002251 while (OpNum != Record.size()) {
2252 Value *Op;
2253 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002254 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002255 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002256 }
2257
Jay Foada9203102011-07-25 09:48:08 +00002258 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002259 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002260 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002261 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002262 break;
2263 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002265 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2266 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002267 unsigned OpNum = 0;
2268 Value *Agg;
2269 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2270 return Error("Invalid EXTRACTVAL record");
2271
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002272 SmallVector<unsigned, 4> EXTRACTVALIdx;
2273 for (unsigned RecSize = Record.size();
2274 OpNum != RecSize; ++OpNum) {
2275 uint64_t Index = Record[OpNum];
2276 if ((unsigned)Index != Index)
2277 return Error("Invalid EXTRACTVAL index");
2278 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002279 }
2280
Jay Foadfc6d3a42011-07-13 10:26:04 +00002281 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002282 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002283 break;
2284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002286 case bitc::FUNC_CODE_INST_INSERTVAL: {
2287 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002288 unsigned OpNum = 0;
2289 Value *Agg;
2290 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2291 return Error("Invalid INSERTVAL record");
2292 Value *Val;
2293 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2294 return Error("Invalid INSERTVAL record");
2295
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002296 SmallVector<unsigned, 4> INSERTVALIdx;
2297 for (unsigned RecSize = Record.size();
2298 OpNum != RecSize; ++OpNum) {
2299 uint64_t Index = Record[OpNum];
2300 if ((unsigned)Index != Index)
2301 return Error("Invalid INSERTVAL index");
2302 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002303 }
2304
Jay Foadfc6d3a42011-07-13 10:26:04 +00002305 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002306 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002307 break;
2308 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002309
Chris Lattnerabfbf852007-05-06 00:21:25 +00002310 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002311 // obsolete form of select
2312 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002313 unsigned OpNum = 0;
2314 Value *TrueVal, *FalseVal, *Cond;
2315 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2316 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002317 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002318 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002319
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002320 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002321 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002322 break;
2323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002324
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002325 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2326 // new form of select
2327 // handles select i1 or select [N x i1]
2328 unsigned OpNum = 0;
2329 Value *TrueVal, *FalseVal, *Cond;
2330 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2331 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2332 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2333 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002334
2335 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002336 if (VectorType* vector_type =
2337 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002338 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002339 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002340 return Error("Invalid SELECT condition type");
2341 } else {
2342 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002343 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002344 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345 }
2346
Gabor Greif051a9502008-04-06 20:25:17 +00002347 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002348 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002349 break;
2350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002351
Chris Lattner01ff65f2007-05-02 05:16:49 +00002352 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002353 unsigned OpNum = 0;
2354 Value *Vec, *Idx;
2355 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002356 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002357 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002358 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002359 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002360 break;
2361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002362
Chris Lattner01ff65f2007-05-02 05:16:49 +00002363 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002364 unsigned OpNum = 0;
2365 Value *Vec, *Elt, *Idx;
2366 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002367 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002368 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002369 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002370 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002371 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002372 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002373 break;
2374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002375
Chris Lattnerabfbf852007-05-06 00:21:25 +00002376 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2377 unsigned OpNum = 0;
2378 Value *Vec1, *Vec2, *Mask;
2379 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2380 getValue(Record, OpNum, Vec1->getType(), Vec2))
2381 return Error("Invalid SHUFFLEVEC record");
2382
Mon P Wangaeb06d22008-11-10 04:46:22 +00002383 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002384 return Error("Invalid SHUFFLEVEC record");
2385 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002386 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002387 break;
2388 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002389
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002390 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2391 // Old form of ICmp/FCmp returning bool
2392 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2393 // both legal on vectors but had different behaviour.
2394 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2395 // FCmp/ICmp returning bool or vector of bool
2396
Chris Lattner7337ab92007-05-06 00:00:00 +00002397 unsigned OpNum = 0;
2398 Value *LHS, *RHS;
2399 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2400 getValue(Record, OpNum, LHS->getType(), RHS) ||
2401 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002402 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002403
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002404 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002405 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002406 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002407 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002408 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002409 break;
2410 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002411
Chris Lattner231cbcb2007-05-02 04:27:25 +00002412 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002413 {
2414 unsigned Size = Record.size();
2415 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002416 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002417 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002418 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002419 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002420
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002421 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002422 Value *Op = NULL;
2423 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2424 return Error("Invalid RET record");
2425 if (OpNum != Record.size())
2426 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002427
Chris Lattner96a74c52011-06-17 18:09:11 +00002428 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002430 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002431 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002432 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002433 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002434 return Error("Invalid BR record");
2435 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2436 if (TrueDest == 0)
2437 return Error("Invalid BR record");
2438
Devang Patele8e02132009-09-18 19:26:43 +00002439 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002440 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002441 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002442 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002443 else {
2444 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002445 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002446 if (FalseDest == 0 || Cond == 0)
2447 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002448 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002450 }
2451 break;
2452 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002453 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002454 if (Record.size() < 3 || (Record.size() & 1) == 0)
2455 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002456 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002457 Value *Cond = getFnValueByID(Record[1], OpTy);
2458 BasicBlock *Default = getBasicBlock(Record[2]);
2459 if (OpTy == 0 || Cond == 0 || Default == 0)
2460 return Error("Invalid SWITCH record");
2461 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002462 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002463 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002464 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002465 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002466 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2467 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2468 if (CaseVal == 0 || DestBB == 0) {
2469 delete SI;
2470 return Error("Invalid SWITCH record!");
2471 }
2472 SI->addCase(CaseVal, DestBB);
2473 }
2474 I = SI;
2475 break;
2476 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002477 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002478 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002479 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002480 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002481 Value *Address = getFnValueByID(Record[1], OpTy);
2482 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002483 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002484 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002485 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002486 InstructionList.push_back(IBI);
2487 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2488 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2489 IBI->addDestination(DestBB);
2490 } else {
2491 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002492 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002493 }
2494 }
2495 I = IBI;
2496 break;
2497 }
2498
Duncan Sandsdc024672007-11-27 13:23:08 +00002499 case bitc::FUNC_CODE_INST_INVOKE: {
2500 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002501 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002502 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002503 unsigned CCInfo = Record[1];
2504 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2505 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506
Chris Lattnera9bb7132007-05-08 05:38:01 +00002507 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002508 Value *Callee;
2509 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002510 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002511
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002512 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2513 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002514 dyn_cast<FunctionType>(CalleeTy->getElementType());
2515
2516 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002517 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2518 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002519 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002520
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002521 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002522 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2523 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2524 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002525 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002526
Chris Lattner7337ab92007-05-06 00:00:00 +00002527 if (!FTy->isVarArg()) {
2528 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002529 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002530 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002531 // Read type/value pairs for varargs params.
2532 while (OpNum != Record.size()) {
2533 Value *Op;
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2535 return Error("Invalid INVOKE record");
2536 Ops.push_back(Op);
2537 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002538 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002539
Jay Foada3efbb12011-07-15 08:37:34 +00002540 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002541 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002542 cast<InvokeInst>(I)->setCallingConv(
2543 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002544 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002545 break;
2546 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002547 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2548 unsigned Idx = 0;
2549 Value *Val = 0;
2550 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2551 return Error("Invalid RESUME record");
2552 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002553 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002554 break;
2555 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002556 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002557 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002558 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002559 break;
2560 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002561 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002562 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002563 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002564 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002565 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002566 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002567 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002568 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002569
Jay Foad3ecfc862011-03-30 11:28:46 +00002570 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002571 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Chris Lattner15e6d172007-05-04 19:11:41 +00002573 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2574 Value *V = getFnValueByID(Record[1+i], Ty);
2575 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002576 if (!V || !BB) return Error("Invalid PHI record");
2577 PN->addIncoming(V, BB);
2578 }
2579 I = PN;
2580 break;
2581 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002582
Bill Wendlinge6e88262011-08-12 20:24:12 +00002583 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2584 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2585 unsigned Idx = 0;
2586 if (Record.size() < 4)
2587 return Error("Invalid LANDINGPAD record");
2588 Type *Ty = getTypeByID(Record[Idx++]);
2589 if (!Ty) return Error("Invalid LANDINGPAD record");
2590 Value *PersFn = 0;
2591 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2592 return Error("Invalid LANDINGPAD record");
2593
2594 bool IsCleanup = !!Record[Idx++];
2595 unsigned NumClauses = Record[Idx++];
2596 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2597 LP->setCleanup(IsCleanup);
2598 for (unsigned J = 0; J != NumClauses; ++J) {
2599 LandingPadInst::ClauseType CT =
2600 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2601 Value *Val;
2602
2603 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2604 delete LP;
2605 return Error("Invalid LANDINGPAD record");
2606 }
2607
2608 assert((CT != LandingPadInst::Catch ||
2609 !isa<ArrayType>(Val->getType())) &&
2610 "Catch clause has a invalid type!");
2611 assert((CT != LandingPadInst::Filter ||
2612 isa<ArrayType>(Val->getType())) &&
2613 "Filter clause has invalid type!");
2614 LP->addClause(Val);
2615 }
2616
2617 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002618 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002619 break;
2620 }
2621
Chris Lattner96a74c52011-06-17 18:09:11 +00002622 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2623 if (Record.size() != 4)
2624 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002625 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002626 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002627 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002628 Value *Size = getFnValueByID(Record[2], OpTy);
2629 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002630 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002631 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002632 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002633 break;
2634 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002635 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002636 unsigned OpNum = 0;
2637 Value *Op;
2638 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2639 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002640 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002641
Chris Lattner7337ab92007-05-06 00:00:00 +00002642 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002643 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002644 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002645 }
Eli Friedman21006d42011-08-09 23:02:53 +00002646 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2647 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2648 unsigned OpNum = 0;
2649 Value *Op;
2650 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2651 OpNum+4 != Record.size())
2652 return Error("Invalid LOADATOMIC record");
2653
2654
2655 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2656 if (Ordering == NotAtomic || Ordering == Release ||
2657 Ordering == AcquireRelease)
2658 return Error("Invalid LOADATOMIC record");
2659 if (Ordering != NotAtomic && Record[OpNum] == 0)
2660 return Error("Invalid LOADATOMIC record");
2661 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2662
2663 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2664 Ordering, SynchScope);
2665 InstructionList.push_back(I);
2666 break;
2667 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002668 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002669 unsigned OpNum = 0;
2670 Value *Val, *Ptr;
2671 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002672 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002673 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2674 OpNum+2 != Record.size())
2675 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002676
Christopher Lambfe63fb92007-12-11 08:59:05 +00002677 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002678 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002679 break;
2680 }
Eli Friedman21006d42011-08-09 23:02:53 +00002681 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2682 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2683 unsigned OpNum = 0;
2684 Value *Val, *Ptr;
2685 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2686 getValue(Record, OpNum,
2687 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2688 OpNum+4 != Record.size())
2689 return Error("Invalid STOREATOMIC record");
2690
2691 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002692 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002693 Ordering == AcquireRelease)
2694 return Error("Invalid STOREATOMIC record");
2695 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2696 if (Ordering != NotAtomic && Record[OpNum] == 0)
2697 return Error("Invalid STOREATOMIC record");
2698
2699 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2700 Ordering, SynchScope);
2701 InstructionList.push_back(I);
2702 break;
2703 }
Eli Friedmanff030482011-07-28 21:48:00 +00002704 case bitc::FUNC_CODE_INST_CMPXCHG: {
2705 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2706 unsigned OpNum = 0;
2707 Value *Ptr, *Cmp, *New;
2708 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2709 getValue(Record, OpNum,
2710 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2711 getValue(Record, OpNum,
2712 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2713 OpNum+3 != Record.size())
2714 return Error("Invalid CMPXCHG record");
2715 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002716 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002717 return Error("Invalid CMPXCHG record");
2718 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2719 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2720 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2721 InstructionList.push_back(I);
2722 break;
2723 }
2724 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2725 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2726 unsigned OpNum = 0;
2727 Value *Ptr, *Val;
2728 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2729 getValue(Record, OpNum,
2730 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2731 OpNum+4 != Record.size())
2732 return Error("Invalid ATOMICRMW record");
2733 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2734 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2735 Operation > AtomicRMWInst::LAST_BINOP)
2736 return Error("Invalid ATOMICRMW record");
2737 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002738 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002739 return Error("Invalid ATOMICRMW record");
2740 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2741 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2742 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2743 InstructionList.push_back(I);
2744 break;
2745 }
Eli Friedman47f35132011-07-25 23:16:38 +00002746 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2747 if (2 != Record.size())
2748 return Error("Invalid FENCE record");
2749 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2750 if (Ordering == NotAtomic || Ordering == Unordered ||
2751 Ordering == Monotonic)
2752 return Error("Invalid FENCE record");
2753 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2754 I = new FenceInst(Context, Ordering, SynchScope);
2755 InstructionList.push_back(I);
2756 break;
2757 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002758 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002759 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2760 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002761 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002762
Devang Patel05988662008-09-25 21:00:45 +00002763 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002764 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Chris Lattnera9bb7132007-05-08 05:38:01 +00002766 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002767 Value *Callee;
2768 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2769 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002770
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002771 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2772 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002773 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002774 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002775 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Chris Lattner0579f7f2007-05-03 22:04:19 +00002777 SmallVector<Value*, 16> Args;
2778 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002779 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002780 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002781 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002782 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002783 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002784 if (Args.back() == 0) return Error("Invalid CALL record");
2785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002786
Chris Lattner0579f7f2007-05-03 22:04:19 +00002787 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002788 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002789 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002790 return Error("Invalid CALL record");
2791 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002792 while (OpNum != Record.size()) {
2793 Value *Op;
2794 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2795 return Error("Invalid CALL record");
2796 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002797 }
2798 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002799
Jay Foada3efbb12011-07-15 08:37:34 +00002800 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002801 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002802 cast<CallInst>(I)->setCallingConv(
2803 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002804 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002805 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002806 break;
2807 }
2808 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2809 if (Record.size() < 3)
2810 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002811 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002812 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002813 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002814 if (!OpTy || !Op || !ResTy)
2815 return Error("Invalid VAARG record");
2816 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002817 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002818 break;
2819 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002820 }
2821
2822 // Add instruction to end of current BB. If there is no current BB, reject
2823 // this file.
2824 if (CurBB == 0) {
2825 delete I;
2826 return Error("Invalid instruction with no BB");
2827 }
2828 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002829
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002830 // If this was a terminator instruction, move to the next block.
2831 if (isa<TerminatorInst>(I)) {
2832 ++CurBBNo;
2833 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2834 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002835
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002836 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002837 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002838 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002839 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002840
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002841 // Check the function list for unresolved values.
2842 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2843 if (A->getParent() == 0) {
2844 // We found at least one unresolved value. Nuke them all to avoid leaks.
2845 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002846 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002847 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002848 delete A;
2849 }
2850 }
Chris Lattner35a04702007-05-04 03:50:29 +00002851 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002852 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002853 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002854
Dan Gohman064ff3e2010-08-25 20:23:38 +00002855 // FIXME: Check for unresolved forward-declared metadata references
2856 // and clean up leaks.
2857
Chris Lattner50b136d2009-10-28 05:53:48 +00002858 // See if anything took the address of blocks in this function. If so,
2859 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002860 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2861 BlockAddrFwdRefs.find(F);
2862 if (BAFRI != BlockAddrFwdRefs.end()) {
2863 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2864 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2865 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002866 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002867 return Error("Invalid blockaddress block #");
2868
2869 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002870 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002871 FwdRef->eraseFromParent();
2872 }
2873
2874 BlockAddrFwdRefs.erase(BAFRI);
2875 }
2876
Chris Lattner980e5aa2007-05-01 05:52:21 +00002877 // Trim the value list down to the size it was before we parsed this function.
2878 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002879 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002880 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002881 return false;
2882}
2883
Chris Lattnerb348bb82007-05-18 04:02:46 +00002884//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002885// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002886//===----------------------------------------------------------------------===//
2887
2888
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002889bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2890 if (const Function *F = dyn_cast<Function>(GV)) {
2891 return F->isDeclaration() &&
2892 DeferredFunctionInfo.count(const_cast<Function*>(F));
2893 }
2894 return false;
2895}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002896
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002897bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2898 Function *F = dyn_cast<Function>(GV);
2899 // If it's not a function or is already material, ignore the request.
2900 if (!F || !F->isMaterializable()) return false;
2901
2902 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002903 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002904
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002905 // Move the bit stream to the saved position of the deferred function body.
2906 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002907
Chris Lattnerb348bb82007-05-18 04:02:46 +00002908 if (ParseFunctionBody(F)) {
2909 if (ErrInfo) *ErrInfo = ErrorString;
2910 return true;
2911 }
Chandler Carruth69940402007-08-04 01:51:18 +00002912
2913 // Upgrade any old intrinsic calls in the function.
2914 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2915 E = UpgradedIntrinsics.end(); I != E; ++I) {
2916 if (I->first != I->second) {
2917 for (Value::use_iterator UI = I->first->use_begin(),
2918 UE = I->first->use_end(); UI != UE; ) {
2919 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2920 UpgradeIntrinsicCall(CI, I->second);
2921 }
2922 }
2923 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002924
Chris Lattnerb348bb82007-05-18 04:02:46 +00002925 return false;
2926}
2927
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002928bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2929 const Function *F = dyn_cast<Function>(GV);
2930 if (!F || F->isDeclaration())
2931 return false;
2932 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2933}
2934
2935void BitcodeReader::Dematerialize(GlobalValue *GV) {
2936 Function *F = dyn_cast<Function>(GV);
2937 // If this function isn't dematerializable, this is a noop.
2938 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002939 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002940
Chris Lattnerb348bb82007-05-18 04:02:46 +00002941 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002942
Chris Lattnerb348bb82007-05-18 04:02:46 +00002943 // Just forget the function body, we can remat it later.
2944 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002945}
2946
2947
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002948bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2949 assert(M == TheModule &&
2950 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002951 // Iterate over the module, deserializing any functions that are still on
2952 // disk.
2953 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2954 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002955 if (F->isMaterializable() &&
2956 Materialize(F, ErrInfo))
2957 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002958
Daniel Dunbara279bc32009-09-20 02:20:51 +00002959 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2960 // delete the old functions to clean up. We can't do this unless the entire
2961 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002962 // with calls to the old function.
2963 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2964 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2965 if (I->first != I->second) {
2966 for (Value::use_iterator UI = I->first->use_begin(),
2967 UE = I->first->use_end(); UI != UE; ) {
2968 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2969 UpgradeIntrinsicCall(CI, I->second);
2970 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002971 if (!I->first->use_empty())
2972 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002973 I->first->eraseFromParent();
2974 }
2975 }
2976 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002977
Bill Wendlinge9b88cb2011-10-05 07:04:14 +00002978 // Upgrade to new EH scheme. N.B. This will go away in 3.1.
2979 UpgradeExceptionHandling(M);
2980
Devang Patele4b27562009-08-28 23:24:31 +00002981 // Check debug info intrinsics.
2982 CheckDebugInfoIntrinsics(TheModule);
2983
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002984 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002985}
2986
Chris Lattner48f84872007-05-01 04:59:48 +00002987
Chris Lattnerc453f762007-04-29 07:54:31 +00002988//===----------------------------------------------------------------------===//
2989// External interface
2990//===----------------------------------------------------------------------===//
2991
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002992/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002993///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002994Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2995 LLVMContext& Context,
2996 std::string *ErrMsg) {
2997 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002998 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002999 M->setMaterializer(R);
3000 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003001 if (ErrMsg)
3002 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003003
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003004 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003005 return 0;
3006 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003007 // Have the BitcodeReader dtor delete 'Buffer'.
3008 R->setBufferOwned(true);
3009 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003010}
3011
3012/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3013/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003014Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003015 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003016 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3017 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003018
3019 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3020 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003021 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003022
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003023 // Read in the entire module, and destroy the BitcodeReader.
3024 if (M->MaterializeAllPermanently(ErrMsg)) {
3025 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003026 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003027 }
Bill Wendling34711742010-10-06 01:22:42 +00003028
Chris Lattnerc453f762007-04-29 07:54:31 +00003029 return M;
3030}
Bill Wendling34711742010-10-06 01:22:42 +00003031
3032std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3033 LLVMContext& Context,
3034 std::string *ErrMsg) {
3035 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3036 // Don't let the BitcodeReader dtor delete 'Buffer'.
3037 R->setBufferOwned(false);
3038
3039 std::string Triple("");
3040 if (R->ParseTriple(Triple))
3041 if (ErrMsg)
3042 *ErrMsg = R->getErrorString();
3043
3044 delete R;
3045 return Triple;
3046}