blob: 672acd3daec990010e44efc42a29c22f2b03c642 [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
Rafael Espindola47f79bb2012-01-02 07:49:53 +000030void BitcodeReader::materializeForwardReferencedFunctions() {
31 while (!BlockAddrFwdRefs.empty()) {
32 Function *F = BlockAddrFwdRefs.begin()->first;
33 F->Materialize();
34 }
35}
36
Chris Lattnerb348bb82007-05-18 04:02:46 +000037void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000038 if (BufferOwned)
39 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000040 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000041 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000042 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000043 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000044
Devang Patel19c87462008-09-26 22:53:05 +000045 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000046 std::vector<BasicBlock*>().swap(FunctionBBs);
47 std::vector<Function*>().swap(FunctionsWithBodies);
48 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000049 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000050}
51
Chris Lattner48c85b82007-05-04 03:30:17 +000052//===----------------------------------------------------------------------===//
53// Helper functions to implement forward reference resolution, etc.
54//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000055
Chris Lattnercaee0dc2007-04-22 06:23:29 +000056/// ConvertToString - Convert a string from a record into an std::string, return
57/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000058template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000060 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000061 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000062 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000063
Chris Lattner15e6d172007-05-04 19:11:41 +000064 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
65 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000066 return false;
67}
68
69static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
70 switch (Val) {
71 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000072 case 0: return GlobalValue::ExternalLinkage;
73 case 1: return GlobalValue::WeakAnyLinkage;
74 case 2: return GlobalValue::AppendingLinkage;
75 case 3: return GlobalValue::InternalLinkage;
76 case 4: return GlobalValue::LinkOnceAnyLinkage;
77 case 5: return GlobalValue::DLLImportLinkage;
78 case 6: return GlobalValue::DLLExportLinkage;
79 case 7: return GlobalValue::ExternalWeakLinkage;
80 case 8: return GlobalValue::CommonLinkage;
81 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000082 case 10: return GlobalValue::WeakODRLinkage;
83 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000084 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000085 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000086 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000087 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000088 }
89}
90
91static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
92 switch (Val) {
93 default: // Map unknown visibilities to default.
94 case 0: return GlobalValue::DefaultVisibility;
95 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000096 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000097 }
98}
99
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000100static int GetDecodedCastOpcode(unsigned Val) {
101 switch (Val) {
102 default: return -1;
103 case bitc::CAST_TRUNC : return Instruction::Trunc;
104 case bitc::CAST_ZEXT : return Instruction::ZExt;
105 case bitc::CAST_SEXT : return Instruction::SExt;
106 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
107 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
108 case bitc::CAST_UITOFP : return Instruction::UIToFP;
109 case bitc::CAST_SITOFP : return Instruction::SIToFP;
110 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
111 case bitc::CAST_FPEXT : return Instruction::FPExt;
112 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
113 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
114 case bitc::CAST_BITCAST : return Instruction::BitCast;
115 }
116}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000117static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000118 switch (Val) {
119 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000120 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000121 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000122 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000123 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000124 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000125 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000126 case bitc::BINOP_UDIV: return Instruction::UDiv;
127 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000128 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000129 case bitc::BINOP_UREM: return Instruction::URem;
130 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000131 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 case bitc::BINOP_SHL: return Instruction::Shl;
133 case bitc::BINOP_LSHR: return Instruction::LShr;
134 case bitc::BINOP_ASHR: return Instruction::AShr;
135 case bitc::BINOP_AND: return Instruction::And;
136 case bitc::BINOP_OR: return Instruction::Or;
137 case bitc::BINOP_XOR: return Instruction::Xor;
138 }
139}
140
Eli Friedmanff030482011-07-28 21:48:00 +0000141static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
142 switch (Val) {
143 default: return AtomicRMWInst::BAD_BINOP;
144 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
145 case bitc::RMW_ADD: return AtomicRMWInst::Add;
146 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
147 case bitc::RMW_AND: return AtomicRMWInst::And;
148 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
149 case bitc::RMW_OR: return AtomicRMWInst::Or;
150 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
151 case bitc::RMW_MAX: return AtomicRMWInst::Max;
152 case bitc::RMW_MIN: return AtomicRMWInst::Min;
153 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
154 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
155 }
156}
157
Eli Friedman47f35132011-07-25 23:16:38 +0000158static AtomicOrdering GetDecodedOrdering(unsigned Val) {
159 switch (Val) {
160 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
161 case bitc::ORDERING_UNORDERED: return Unordered;
162 case bitc::ORDERING_MONOTONIC: return Monotonic;
163 case bitc::ORDERING_ACQUIRE: return Acquire;
164 case bitc::ORDERING_RELEASE: return Release;
165 case bitc::ORDERING_ACQREL: return AcquireRelease;
166 default: // Map unknown orderings to sequentially-consistent.
167 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
168 }
169}
170
171static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
172 switch (Val) {
173 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
174 default: // Map unknown scopes to cross-thread.
175 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
176 }
177}
178
Gabor Greifefe65362008-05-10 08:32:32 +0000179namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000180namespace {
181 /// @brief A class for maintaining the slot number definition
182 /// as a placeholder for the actual definition for forward constants defs.
183 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000184 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000185 public:
186 // allocate space for exactly one operand
187 void *operator new(size_t s) {
188 return User::operator new(s, 1);
189 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000190 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000191 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000192 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000194
Chris Lattnerea693df2008-08-21 02:34:16 +0000195 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000196 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000197 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000198 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000199 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000201
202
Gabor Greifefe65362008-05-10 08:32:32 +0000203 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000204 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000205 };
206}
207
Chris Lattner46e77402009-03-31 22:55:09 +0000208// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000209template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000210struct OperandTraits<ConstantPlaceHolder> :
211 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000212};
Gabor Greifefe65362008-05-10 08:32:32 +0000213}
214
Chris Lattner46e77402009-03-31 22:55:09 +0000215
216void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
217 if (Idx == size()) {
218 push_back(V);
219 return;
220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000221
Chris Lattner46e77402009-03-31 22:55:09 +0000222 if (Idx >= size())
223 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000224
Chris Lattner46e77402009-03-31 22:55:09 +0000225 WeakVH &OldV = ValuePtrs[Idx];
226 if (OldV == 0) {
227 OldV = V;
228 return;
229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattner46e77402009-03-31 22:55:09 +0000231 // Handle constants and non-constants (e.g. instrs) differently for
232 // efficiency.
233 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
234 ResolveConstants.push_back(std::make_pair(PHC, Idx));
235 OldV = V;
236 } else {
237 // If there was a forward reference to this value, replace it.
238 Value *PrevVal = OldV;
239 OldV->replaceAllUsesWith(V);
240 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000241 }
242}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Gabor Greifefe65362008-05-10 08:32:32 +0000244
Chris Lattner522b7b12007-04-24 05:48:56 +0000245Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000246 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000247 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000248 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000249
Chris Lattner46e77402009-03-31 22:55:09 +0000250 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000251 assert(Ty == V->getType() && "Type mismatch in constant table!");
252 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000253 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000254
255 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000256 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000257 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000258 return C;
259}
260
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000262 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000263 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000264
Chris Lattner46e77402009-03-31 22:55:09 +0000265 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000266 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
267 return V;
268 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000269
Chris Lattner01ff65f2007-05-02 05:16:49 +0000270 // No type specified, must be invalid reference.
271 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000272
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000273 // Create and return a placeholder, which will later be RAUW'd.
274 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000275 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000276 return V;
277}
278
Chris Lattnerea693df2008-08-21 02:34:16 +0000279/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
280/// resolves any forward references. The idea behind this is that we sometimes
281/// get constants (such as large arrays) which reference *many* forward ref
282/// constants. Replacing each of these causes a lot of thrashing when
283/// building/reuniquing the constant. Instead of doing this, we look at all the
284/// uses and rewrite all the place holders at once for any constant that uses
285/// a placeholder.
286void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000288 // binary search.
289 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerea693df2008-08-21 02:34:16 +0000291 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000294 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000295 Constant *Placeholder = ResolveConstants.back().first;
296 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 // Loop over all users of the placeholder, updating them to reference the
299 // new value. If they reference more than one placeholder, update them all
300 // at once.
301 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000302 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000303 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000304
Chris Lattnerea693df2008-08-21 02:34:16 +0000305 // If the using object isn't uniqued, just update the operands. This
306 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000307 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000308 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 continue;
310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000311
Chris Lattnerea693df2008-08-21 02:34:16 +0000312 // Otherwise, we have a constant that uses the placeholder. Replace that
313 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000314 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000315 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
316 I != E; ++I) {
317 Value *NewOp;
318 if (!isa<ConstantPlaceHolder>(*I)) {
319 // Not a placeholder reference.
320 NewOp = *I;
321 } else if (*I == Placeholder) {
322 // Common case is that it just references this one placeholder.
323 NewOp = RealVal;
324 } else {
325 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000326 ResolveConstantsTy::iterator It =
327 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 std::pair<Constant*, unsigned>(cast<Constant>(*I),
329 0));
330 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000331 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000332 }
333
334 NewOps.push_back(cast<Constant>(NewOp));
335 }
336
337 // Make the new constant.
338 Constant *NewC;
339 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000340 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000342 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000343 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000344 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000345 } else {
346 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000347 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000349
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 UserC->replaceAllUsesWith(NewC);
351 UserC->destroyConstant();
352 NewOps.clear();
353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Nick Lewyckycb337992009-05-10 20:57:05 +0000355 // Update all ValueHandles, they should be the only users at this point.
356 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000357 delete Placeholder;
358 }
359}
360
Devang Pateld5ac4042009-08-04 06:00:18 +0000361void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
362 if (Idx == size()) {
363 push_back(V);
364 return;
365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000366
Devang Pateld5ac4042009-08-04 06:00:18 +0000367 if (Idx >= size())
368 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000369
Devang Pateld5ac4042009-08-04 06:00:18 +0000370 WeakVH &OldV = MDValuePtrs[Idx];
371 if (OldV == 0) {
372 OldV = V;
373 return;
374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000375
Devang Pateld5ac4042009-08-04 06:00:18 +0000376 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000377 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000378 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000379 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000380 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
381 // value for Idx.
382 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000383}
384
385Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
386 if (Idx >= size())
387 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000390 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 return V;
392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000395 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 MDValuePtrs[Idx] = V;
397 return V;
398}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000399
Chris Lattner1afcace2011-07-09 17:41:24 +0000400Type *BitcodeReader::getTypeByID(unsigned ID) {
401 // The type table size is always specified correctly.
402 if (ID >= TypeList.size())
403 return 0;
404
405 if (Type *Ty = TypeList[ID])
406 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000407
Chris Lattner1afcace2011-07-09 17:41:24 +0000408 // If we have a forward reference, the only possible case is when it is to a
409 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000410 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000411}
412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413
Chris Lattner48c85b82007-05-04 03:30:17 +0000414//===----------------------------------------------------------------------===//
415// Functions for parsing blocks from the bitcode file
416//===----------------------------------------------------------------------===//
417
Devang Patel05988662008-09-25 21:00:45 +0000418bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000419 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000420 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000421
Devang Patel19c87462008-09-26 22:53:05 +0000422 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000423 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000424
Chris Lattner48c85b82007-05-04 03:30:17 +0000425 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000426
Devang Patel05988662008-09-25 21:00:45 +0000427 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000428
Chris Lattner48c85b82007-05-04 03:30:17 +0000429 // Read all the records.
430 while (1) {
431 unsigned Code = Stream.ReadCode();
432 if (Code == bitc::END_BLOCK) {
433 if (Stream.ReadBlockEnd())
434 return Error("Error at end of PARAMATTR block");
435 return false;
436 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 if (Code == bitc::ENTER_SUBBLOCK) {
439 // No known subblocks, always skip them.
440 Stream.ReadSubBlockID();
441 if (Stream.SkipBlock())
442 return Error("Malformed block record");
443 continue;
444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000445
Chris Lattner48c85b82007-05-04 03:30:17 +0000446 if (Code == bitc::DEFINE_ABBREV) {
447 Stream.ReadAbbrevRecord();
448 continue;
449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 // Read a record.
452 Record.clear();
453 switch (Stream.ReadRecord(Code, Record)) {
454 default: // Default behavior: ignore.
455 break;
456 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
457 if (Record.size() & 1)
458 return Error("Invalid ENTRY record");
459
Chris Lattner9a6cb152008-10-05 18:22:09 +0000460 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000461 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000462 // to index ~0. Index 0 is used for return value attributes but used to be
463 // used for function attributes.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000464 Attributes RetAttribute;
465 Attributes FnAttribute;
Chris Lattner48c85b82007-05-04 03:30:17 +0000466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000467 // FIXME: remove in LLVM 3.0
468 // The alignment is stored as a 16-bit raw value from bits 31--16.
469 // We shift the bits above 31 down by 11 bits.
470
471 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
472 if (Alignment && !isPowerOf2_32(Alignment))
473 return Error("Alignment is not a power of two.");
474
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000475 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000476 if (Alignment)
477 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000478 ReconstitutedAttr |=
479 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000480
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000481 Record[i+1] = ReconstitutedAttr.Raw();
Devang Patel19c87462008-09-26 22:53:05 +0000482 if (Record[i] == 0)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000483 RetAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000484 else if (Record[i] == ~0U)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000485 FnAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000486 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000487
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000488 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
Chris Lattner9a6cb152008-10-05 18:22:09 +0000489 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 &&
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000492 (RetAttribute & OldRetAttrs)) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000493 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));
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000509 } else if (Attributes(Record[i+1]) != Attribute::None)
510 Attrs.push_back(AttributeWithIndex::get(Record[i],
511 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000512 }
Devang Patel19c87462008-09-26 22:53:05 +0000513
514 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000515 Attrs.clear();
516 break;
517 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000518 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000519 }
520}
521
Chris Lattner86697142007-05-01 05:01:34 +0000522bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000523 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000524 return Error("Malformed block record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000525
526 return ParseTypeTableBody();
527}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000528
Chris Lattner1afcace2011-07-09 17:41:24 +0000529bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000530 if (!TypeList.empty())
531 return Error("Multiple TYPE_BLOCKs found!");
532
533 SmallVector<uint64_t, 64> Record;
534 unsigned NumRecords = 0;
535
Chris Lattner1afcace2011-07-09 17:41:24 +0000536 SmallString<64> TypeName;
537
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 // Read all the records for this type table.
539 while (1) {
540 unsigned Code = Stream.ReadCode();
541 if (Code == bitc::END_BLOCK) {
542 if (NumRecords != TypeList.size())
543 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000544 if (Stream.ReadBlockEnd())
545 return Error("Error at end of type table block");
546 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000548
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 if (Code == bitc::ENTER_SUBBLOCK) {
550 // No known subblocks, always skip them.
551 Stream.ReadSubBlockID();
552 if (Stream.SkipBlock())
553 return Error("Malformed block record");
554 continue;
555 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000556
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000557 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000558 Stream.ReadAbbrevRecord();
559 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000560 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000561
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000562 // Read a record.
563 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000564 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000565 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000566 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
568 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
569 // type list. This allows us to reserve space.
570 if (Record.size() < 1)
571 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000572 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000576 break;
Dan Gohmance163392011-12-17 00:04:22 +0000577 case bitc::TYPE_CODE_HALF: // HALF
578 ResultTy = Type::getHalfTy(Context);
579 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000581 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000582 break;
583 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000584 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000586 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000587 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000588 break;
589 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000590 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000591 break;
592 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000593 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000594 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000595 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000596 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000597 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000598 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000599 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000600 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000601 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
602 ResultTy = Type::getX86_MMXTy(Context);
603 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000604 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
605 if (Record.size() < 1)
606 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000607
Owen Anderson1d0be152009-08-13 21:58:54 +0000608 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000609 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000610 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000611 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000612 if (Record.size() < 1)
613 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000614 unsigned AddressSpace = 0;
615 if (Record.size() == 2)
616 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000617 ResultTy = getTypeByID(Record[0]);
618 if (ResultTy == 0) return Error("invalid element type in pointer type");
619 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000620 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000621 }
Chad Rosiercde54642011-11-03 00:14:01 +0000622 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000623 // FIXME: attrid is dead, remove it in LLVM 3.0
624 // FUNCTION: [vararg, attrid, retty, paramty x N]
625 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000626 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000627 SmallVector<Type*, 8> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000628 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
629 if (Type *T = getTypeByID(Record[i]))
630 ArgTys.push_back(T);
631 else
632 break;
633 }
634
635 ResultTy = getTypeByID(Record[2]);
636 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
637 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000638
Chris Lattner1afcace2011-07-09 17:41:24 +0000639 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000640 break;
641 }
Chad Rosiercde54642011-11-03 00:14:01 +0000642 case bitc::TYPE_CODE_FUNCTION: {
643 // FUNCTION: [vararg, retty, paramty x N]
644 if (Record.size() < 2)
645 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000646 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000647 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
648 if (Type *T = getTypeByID(Record[i]))
649 ArgTys.push_back(T);
650 else
651 break;
652 }
653
654 ResultTy = getTypeByID(Record[1]);
655 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
656 return Error("invalid type in function type");
657
658 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
659 break;
660 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000661 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000662 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000663 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000664 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000665 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
666 if (Type *T = getTypeByID(Record[i]))
667 EltTys.push_back(T);
668 else
669 break;
670 }
671 if (EltTys.size() != Record.size()-1)
672 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000673 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000674 break;
675 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000676 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
677 if (ConvertToString(Record, 0, TypeName))
678 return Error("Invalid STRUCT_NAME record");
679 continue;
680
681 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
682 if (Record.size() < 1)
683 return Error("Invalid STRUCT type record");
684
685 if (NumRecords >= TypeList.size())
686 return Error("invalid TYPE table");
687
688 // Check to see if this was forward referenced, if so fill in the temp.
689 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
690 if (Res) {
691 Res->setName(TypeName);
692 TypeList[NumRecords] = 0;
693 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000694 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000695 TypeName.clear();
696
697 SmallVector<Type*, 8> EltTys;
698 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
699 if (Type *T = getTypeByID(Record[i]))
700 EltTys.push_back(T);
701 else
702 break;
703 }
704 if (EltTys.size() != Record.size()-1)
705 return Error("invalid STRUCT type record");
706 Res->setBody(EltTys, Record[0]);
707 ResultTy = Res;
708 break;
709 }
710 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
711 if (Record.size() != 1)
712 return Error("Invalid OPAQUE type record");
713
714 if (NumRecords >= TypeList.size())
715 return Error("invalid TYPE table");
716
717 // Check to see if this was forward referenced, if so fill in the temp.
718 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
719 if (Res) {
720 Res->setName(TypeName);
721 TypeList[NumRecords] = 0;
722 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000723 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000724 TypeName.clear();
725 ResultTy = Res;
726 break;
727 }
728 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
729 if (Record.size() < 2)
730 return Error("Invalid ARRAY type record");
731 if ((ResultTy = getTypeByID(Record[1])))
732 ResultTy = ArrayType::get(ResultTy, Record[0]);
733 else
734 return Error("Invalid ARRAY type element");
735 break;
736 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
737 if (Record.size() < 2)
738 return Error("Invalid VECTOR type record");
739 if ((ResultTy = getTypeByID(Record[1])))
740 ResultTy = VectorType::get(ResultTy, Record[0]);
741 else
742 return Error("Invalid ARRAY type element");
743 break;
744 }
745
746 if (NumRecords >= TypeList.size())
747 return Error("invalid TYPE table");
748 assert(ResultTy && "Didn't read a type?");
749 assert(TypeList[NumRecords] == 0 && "Already read type?");
750 TypeList[NumRecords++] = ResultTy;
751 }
752}
753
Chris Lattner86697142007-05-01 05:01:34 +0000754bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000755 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000756 return Error("Malformed block record");
757
758 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattner0b2482a2007-04-23 21:26:05 +0000760 // Read all the records for this value table.
761 SmallString<128> ValueName;
762 while (1) {
763 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000764 if (Code == bitc::END_BLOCK) {
765 if (Stream.ReadBlockEnd())
766 return Error("Error at end of value symbol table block");
767 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000768 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000769 if (Code == bitc::ENTER_SUBBLOCK) {
770 // No known subblocks, always skip them.
771 Stream.ReadSubBlockID();
772 if (Stream.SkipBlock())
773 return Error("Malformed block record");
774 continue;
775 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Chris Lattner0b2482a2007-04-23 21:26:05 +0000777 if (Code == bitc::DEFINE_ABBREV) {
778 Stream.ReadAbbrevRecord();
779 continue;
780 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Chris Lattner0b2482a2007-04-23 21:26:05 +0000782 // Read a record.
783 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000784 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000785 default: // Default behavior: unknown type.
786 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000787 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000788 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000789 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000790 unsigned ValueID = Record[0];
791 if (ValueID >= ValueList.size())
792 return Error("Invalid Value ID in VST_ENTRY record");
793 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000795 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000796 ValueName.clear();
797 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000798 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000799 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000800 if (ConvertToString(Record, 1, ValueName))
801 return Error("Invalid VST_BBENTRY record");
802 BasicBlock *BB = getBasicBlock(Record[0]);
803 if (BB == 0)
804 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000806 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000807 ValueName.clear();
808 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000809 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000810 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000811 }
812}
813
Devang Patele54abc92009-07-22 17:43:22 +0000814bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000815 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000816
817 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
818 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Devang Patele54abc92009-07-22 17:43:22 +0000820 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000821
Devang Patele54abc92009-07-22 17:43:22 +0000822 // Read all the records.
823 while (1) {
824 unsigned Code = Stream.ReadCode();
825 if (Code == bitc::END_BLOCK) {
826 if (Stream.ReadBlockEnd())
827 return Error("Error at end of PARAMATTR block");
828 return false;
829 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000830
Devang Patele54abc92009-07-22 17:43:22 +0000831 if (Code == bitc::ENTER_SUBBLOCK) {
832 // No known subblocks, always skip them.
833 Stream.ReadSubBlockID();
834 if (Stream.SkipBlock())
835 return Error("Malformed block record");
836 continue;
837 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000838
Devang Patele54abc92009-07-22 17:43:22 +0000839 if (Code == bitc::DEFINE_ABBREV) {
840 Stream.ReadAbbrevRecord();
841 continue;
842 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000843
Victor Hernandez24e64df2010-01-10 07:14:18 +0000844 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000845 // Read a record.
846 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000847 Code = Stream.ReadRecord(Code, Record);
848 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000849 default: // Default behavior: ignore.
850 break;
Devang Patelaa993142009-07-29 22:34:41 +0000851 case bitc::METADATA_NAME: {
852 // Read named of the named metadata.
853 unsigned NameLength = Record.size();
854 SmallString<8> Name;
855 Name.resize(NameLength);
856 for (unsigned i = 0; i != NameLength; ++i)
857 Name[i] = Record[i];
858 Record.clear();
859 Code = Stream.ReadCode();
860
Chris Lattner9d61dd92011-06-17 17:50:30 +0000861 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000862 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000863 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000864
865 // Read named metadata elements.
866 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000867 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000868 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000869 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
870 if (MD == 0)
871 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000872 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000873 }
Devang Patelaa993142009-07-29 22:34:41 +0000874 break;
875 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000876 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000877 IsFunctionLocal = true;
878 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000879 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000880 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000881 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000882
Devang Patel104cf9e2009-07-23 01:07:34 +0000883 unsigned Size = Record.size();
884 SmallVector<Value*, 8> Elts;
885 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000886 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000887 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000888 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000889 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000890 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000891 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
892 else
893 Elts.push_back(NULL);
894 }
Jay Foadec9186b2011-04-21 19:59:31 +0000895 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000896 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000897 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000898 break;
899 }
Devang Patele54abc92009-07-22 17:43:22 +0000900 case bitc::METADATA_STRING: {
901 unsigned MDStringLength = Record.size();
902 SmallString<8> String;
903 String.resize(MDStringLength);
904 for (unsigned i = 0; i != MDStringLength; ++i)
905 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000906 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000907 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000908 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000909 break;
910 }
Devang Patele8e02132009-09-18 19:26:43 +0000911 case bitc::METADATA_KIND: {
912 unsigned RecordLength = Record.size();
913 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000914 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000915 SmallString<8> Name;
916 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000917 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000918 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000919 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000920
Chris Lattner08113472009-12-29 09:01:33 +0000921 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000922 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
923 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000924 break;
925 }
Devang Patele54abc92009-07-22 17:43:22 +0000926 }
927 }
928}
929
Chris Lattner0eef0802007-04-24 04:04:35 +0000930/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
931/// the LSB for dense VBR encoding.
932static uint64_t DecodeSignRotatedValue(uint64_t V) {
933 if ((V & 1) == 0)
934 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000935 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000936 return -(V >> 1);
937 // There is no such thing as -0 with integers. "-0" really means MININT.
938 return 1ULL << 63;
939}
940
Chris Lattner07d98b42007-04-26 02:46:40 +0000941/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
942/// values and aliases that we can.
943bool BitcodeReader::ResolveGlobalAndAliasInits() {
944 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
945 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000946
Chris Lattner07d98b42007-04-26 02:46:40 +0000947 GlobalInitWorklist.swap(GlobalInits);
948 AliasInitWorklist.swap(AliasInits);
949
950 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000951 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000952 if (ValID >= ValueList.size()) {
953 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000954 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000955 } else {
956 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
957 GlobalInitWorklist.back().first->setInitializer(C);
958 else
959 return Error("Global variable initializer is not a constant!");
960 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000961 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000962 }
963
964 while (!AliasInitWorklist.empty()) {
965 unsigned ValID = AliasInitWorklist.back().second;
966 if (ValID >= ValueList.size()) {
967 AliasInits.push_back(AliasInitWorklist.back());
968 } else {
969 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000970 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000971 else
972 return Error("Alias initializer is not a constant!");
973 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000974 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000975 }
976 return false;
977}
978
Chris Lattner86697142007-05-01 05:01:34 +0000979bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000980 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000981 return Error("Malformed block record");
982
983 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000984
Chris Lattnere16504e2007-04-24 03:30:34 +0000985 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000986 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000987 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000988 while (1) {
989 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000990 if (Code == bitc::END_BLOCK)
991 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000992
Chris Lattnere16504e2007-04-24 03:30:34 +0000993 if (Code == bitc::ENTER_SUBBLOCK) {
994 // No known subblocks, always skip them.
995 Stream.ReadSubBlockID();
996 if (Stream.SkipBlock())
997 return Error("Malformed block record");
998 continue;
999 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001000
Chris Lattnere16504e2007-04-24 03:30:34 +00001001 if (Code == bitc::DEFINE_ABBREV) {
1002 Stream.ReadAbbrevRecord();
1003 continue;
1004 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001005
Chris Lattnere16504e2007-04-24 03:30:34 +00001006 // Read a record.
1007 Record.clear();
1008 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001009 unsigned BitCode = Stream.ReadRecord(Code, Record);
1010 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001011 default: // Default behavior: unknown constant
1012 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001013 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001014 break;
1015 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1016 if (Record.empty())
1017 return Error("Malformed CST_SETTYPE record");
1018 if (Record[0] >= TypeList.size())
1019 return Error("Invalid Type ID in CST_SETTYPE record");
1020 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001021 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001022 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001023 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001024 break;
1025 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001026 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001027 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001028 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001029 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001030 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001031 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001032 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001033
Chris Lattner15e6d172007-05-04 19:11:41 +00001034 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +00001035 SmallVector<uint64_t, 8> Words;
1036 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +00001037 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001038 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001039 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +00001040 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001041 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001042 break;
1043 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001044 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001045 if (Record.empty())
1046 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001047 if (CurTy->isHalfTy())
1048 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1049 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001050 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001051 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001052 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001053 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001054 // Bits are not stored the same way as a normal i80 APInt, compensate.
1055 uint64_t Rearrange[2];
1056 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1057 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001058 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001059 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001060 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001061 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001062 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001063 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001064 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001065 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001066 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001067
Chris Lattner15e6d172007-05-04 19:11:41 +00001068 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1069 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001070 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001071
Chris Lattner15e6d172007-05-04 19:11:41 +00001072 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001073 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001074
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001075 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001076 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001077 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001078 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001079 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001080 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1081 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001082 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001083 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001084 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001085 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1086 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001087 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001088 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001089 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001090 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001091 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001092 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001093 break;
1094 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001095 case bitc::CST_CODE_STRING: { // STRING: [values]
1096 if (Record.empty())
1097 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001098
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001099 ArrayType *ATy = cast<ArrayType>(CurTy);
1100 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001101
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001102 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001103 SmallVector<Constant*, 16> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001104 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001105 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001106 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001107 break;
1108 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001109 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1110 if (Record.empty())
1111 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001112
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001113 ArrayType *ATy = cast<ArrayType>(CurTy);
1114 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001115
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001116 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001117 SmallVector<Constant*, 16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001118 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001119 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001120 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001121 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001122 break;
1123 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001124 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1125 if (Record.empty())
1126 return Error("Invalid CST_DATA record");
1127
1128 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1129 unsigned Size = Record.size();
1130
1131 if (EltTy->isIntegerTy(8)) {
1132 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1133 if (isa<VectorType>(CurTy))
1134 V = ConstantDataVector::get(Context, Elts);
1135 else
1136 V = ConstantDataArray::get(Context, Elts);
1137 } else if (EltTy->isIntegerTy(16)) {
1138 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1139 if (isa<VectorType>(CurTy))
1140 V = ConstantDataVector::get(Context, Elts);
1141 else
1142 V = ConstantDataArray::get(Context, Elts);
1143 } else if (EltTy->isIntegerTy(32)) {
1144 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1145 if (isa<VectorType>(CurTy))
1146 V = ConstantDataVector::get(Context, Elts);
1147 else
1148 V = ConstantDataArray::get(Context, Elts);
1149 } else if (EltTy->isIntegerTy(64)) {
1150 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1151 if (isa<VectorType>(CurTy))
1152 V = ConstantDataVector::get(Context, Elts);
1153 else
1154 V = ConstantDataArray::get(Context, Elts);
1155 } else if (EltTy->isFloatTy()) {
1156 SmallVector<float, 16> Elts;
1157 for (unsigned i = 0; i != Size; ++i) {
1158 union { uint32_t I; float F; };
1159 I = Record[i];
1160 Elts.push_back(F);
1161 }
1162 if (isa<VectorType>(CurTy))
1163 V = ConstantDataVector::get(Context, Elts);
1164 else
1165 V = ConstantDataArray::get(Context, Elts);
1166 } else if (EltTy->isDoubleTy()) {
1167 SmallVector<double, 16> Elts;
1168 for (unsigned i = 0; i != Size; ++i) {
1169 union { uint64_t I; double F; };
1170 I = Record[i];
1171 Elts.push_back(F);
1172 }
1173 if (isa<VectorType>(CurTy))
1174 V = ConstantDataVector::get(Context, Elts);
1175 else
1176 V = ConstantDataArray::get(Context, Elts);
1177 } else {
1178 return Error("Unknown element type in CE_DATA");
1179 }
1180 break;
1181 }
1182
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001183 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1184 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1185 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001186 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001187 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001188 } else {
1189 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1190 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001191 unsigned Flags = 0;
1192 if (Record.size() >= 4) {
1193 if (Opc == Instruction::Add ||
1194 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001195 Opc == Instruction::Mul ||
1196 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001197 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1198 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1199 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1200 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001201 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001202 Opc == Instruction::UDiv ||
1203 Opc == Instruction::LShr ||
1204 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001205 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001206 Flags |= SDivOperator::IsExact;
1207 }
1208 }
1209 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001210 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001211 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001212 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001213 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1214 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1215 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001216 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001217 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001218 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001219 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001220 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001221 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001222 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001223 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001224 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001225 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001226 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001227 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001228 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001229 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001230 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001231 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001232 if (!ElTy) return Error("Invalid CE_GEP record");
1233 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1234 }
Jay Foaddab3d292011-07-21 14:31:17 +00001235 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001236 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1237 BitCode ==
1238 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001239 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001240 }
1241 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1242 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001243 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001244 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001245 ValueList.getConstantFwdRef(Record[1],CurTy),
1246 ValueList.getConstantFwdRef(Record[2],CurTy));
1247 break;
1248 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1249 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001250 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001251 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1252 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1253 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001254 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001255 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001256 break;
1257 }
1258 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001259 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001260 if (Record.size() < 3 || OpTy == 0)
1261 return Error("Invalid CE_INSERTELT record");
1262 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1263 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1264 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001265 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001266 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001267 break;
1268 }
1269 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001270 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001271 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001272 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001273 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1274 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001275 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001276 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001277 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001278 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001279 break;
1280 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001281 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1283 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001284 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001285 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1286 return Error("Invalid CE_SHUFVEC_EX record");
1287 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1288 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001289 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001290 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001291 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001292 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001293 break;
1294 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001295 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1296 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001297 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001298 if (OpTy == 0) return Error("Invalid CE_CMP record");
1299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1300 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1301
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001302 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001303 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001304 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001305 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001306 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001307 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001308 case bitc::CST_CODE_INLINEASM: {
1309 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1310 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001311 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001312 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001313 unsigned AsmStrSize = Record[1];
1314 if (2+AsmStrSize >= Record.size())
1315 return Error("Invalid INLINEASM record");
1316 unsigned ConstStrSize = Record[2+AsmStrSize];
1317 if (3+AsmStrSize+ConstStrSize > Record.size())
1318 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001319
Chris Lattner2bce93a2007-05-06 01:58:20 +00001320 for (unsigned i = 0; i != AsmStrSize; ++i)
1321 AsmStr += (char)Record[2+i];
1322 for (unsigned i = 0; i != ConstStrSize; ++i)
1323 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001324 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001325 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001326 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001327 break;
1328 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001329 case bitc::CST_CODE_BLOCKADDRESS:{
1330 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001331 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001332 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1333 Function *Fn =
1334 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1335 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1336
1337 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1338 Type::getInt8Ty(Context),
1339 false, GlobalValue::InternalLinkage,
1340 0, "");
1341 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1342 V = FwdRef;
1343 break;
1344 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001345 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001346
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001347 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001348 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001350
Chris Lattnerea693df2008-08-21 02:34:16 +00001351 if (NextCstNo != ValueList.size())
1352 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Chris Lattnerea693df2008-08-21 02:34:16 +00001354 if (Stream.ReadBlockEnd())
1355 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001356
Chris Lattnerea693df2008-08-21 02:34:16 +00001357 // Once all the constants have been read, go through and resolve forward
1358 // references.
1359 ValueList.ResolveConstantForwardRefs();
1360 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001361}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001362
Chad Rosiercbbb0962011-12-07 21:44:12 +00001363bool BitcodeReader::ParseUseLists() {
1364 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1365 return Error("Malformed block record");
1366
1367 SmallVector<uint64_t, 64> Record;
1368
1369 // Read all the records.
1370 while (1) {
1371 unsigned Code = Stream.ReadCode();
1372 if (Code == bitc::END_BLOCK) {
1373 if (Stream.ReadBlockEnd())
1374 return Error("Error at end of use-list table block");
1375 return false;
1376 }
1377
1378 if (Code == bitc::ENTER_SUBBLOCK) {
1379 // No known subblocks, always skip them.
1380 Stream.ReadSubBlockID();
1381 if (Stream.SkipBlock())
1382 return Error("Malformed block record");
1383 continue;
1384 }
1385
1386 if (Code == bitc::DEFINE_ABBREV) {
1387 Stream.ReadAbbrevRecord();
1388 continue;
1389 }
1390
1391 // Read a use list record.
1392 Record.clear();
1393 switch (Stream.ReadRecord(Code, Record)) {
1394 default: // Default behavior: unknown type.
1395 break;
1396 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1397 unsigned RecordLength = Record.size();
1398 if (RecordLength < 1)
1399 return Error ("Invalid UseList reader!");
1400 UseListRecords.push_back(Record);
1401 break;
1402 }
1403 }
1404 }
1405}
1406
Chris Lattner980e5aa2007-05-01 05:52:21 +00001407/// RememberAndSkipFunctionBody - When we see the block for a function body,
1408/// remember where it is and then skip it. This lets us lazily deserialize the
1409/// functions.
1410bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001411 // Get the function we are talking about.
1412 if (FunctionsWithBodies.empty())
1413 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001414
Chris Lattner48f84872007-05-01 04:59:48 +00001415 Function *Fn = FunctionsWithBodies.back();
1416 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001417
Chris Lattner48f84872007-05-01 04:59:48 +00001418 // Save the current stream state.
1419 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001420 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001421
Chris Lattner48f84872007-05-01 04:59:48 +00001422 // Skip over the function block for now.
1423 if (Stream.SkipBlock())
1424 return Error("Malformed block record");
1425 return false;
1426}
1427
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001428bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001429 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001430 return Error("Malformed block record");
1431
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001432 SmallVector<uint64_t, 64> Record;
1433 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001434 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001435
1436 // Read all the records for this module.
1437 while (!Stream.AtEndOfStream()) {
1438 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001439 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001440 if (Stream.ReadBlockEnd())
1441 return Error("Error at end of module block");
1442
1443 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001444 ResolveGlobalAndAliasInits();
1445 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001446 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001447 if (!FunctionsWithBodies.empty())
1448 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001449
Chandler Carruth69940402007-08-04 01:51:18 +00001450 // Look for intrinsic functions which need to be upgraded at some point
1451 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1452 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001453 Function* NewFn;
1454 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001455 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1456 }
1457
Bill Wendlingde49f362010-09-10 18:51:56 +00001458 // Look for global variables which need to be renamed.
1459 for (Module::global_iterator
1460 GI = TheModule->global_begin(), GE = TheModule->global_end();
1461 GI != GE; ++GI)
1462 UpgradeGlobalVariable(GI);
1463
Chris Lattner980e5aa2007-05-01 05:52:21 +00001464 // Force deallocation of memory for these vectors to favor the client that
1465 // want lazy deserialization.
1466 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1467 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1468 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001469 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001470 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001471
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001472 if (Code == bitc::ENTER_SUBBLOCK) {
1473 switch (Stream.ReadSubBlockID()) {
1474 default: // Skip unknown content.
1475 if (Stream.SkipBlock())
1476 return Error("Malformed block record");
1477 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001478 case bitc::BLOCKINFO_BLOCK_ID:
1479 if (Stream.ReadBlockInfoBlock())
1480 return Error("Malformed BlockInfoBlock");
1481 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001482 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001483 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001484 return true;
1485 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001486 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001487 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001488 return true;
1489 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001490 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001491 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001492 return true;
1493 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001494 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001495 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001496 return true;
1497 break;
Devang Patele54abc92009-07-22 17:43:22 +00001498 case bitc::METADATA_BLOCK_ID:
1499 if (ParseMetadata())
1500 return true;
1501 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001502 case bitc::FUNCTION_BLOCK_ID:
1503 // If this is the first function body we've seen, reverse the
1504 // FunctionsWithBodies list.
1505 if (!HasReversedFunctionsWithBodies) {
1506 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1507 HasReversedFunctionsWithBodies = true;
1508 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001509
Chris Lattner980e5aa2007-05-01 05:52:21 +00001510 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001511 return true;
1512 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001513 case bitc::USELIST_BLOCK_ID:
1514 if (ParseUseLists())
1515 return true;
1516 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001517 }
1518 continue;
1519 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001520
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001521 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001522 Stream.ReadAbbrevRecord();
1523 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001524 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001525
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001526 // Read a record.
1527 switch (Stream.ReadRecord(Code, Record)) {
1528 default: break; // Default behavior, ignore unknown content.
1529 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1530 if (Record.size() < 1)
1531 return Error("Malformed MODULE_CODE_VERSION");
1532 // Only version #0 is supported so far.
1533 if (Record[0] != 0)
1534 return Error("Unknown bitstream version!");
1535 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001536 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001537 std::string S;
1538 if (ConvertToString(Record, 0, S))
1539 return Error("Invalid MODULE_CODE_TRIPLE record");
1540 TheModule->setTargetTriple(S);
1541 break;
1542 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001543 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001544 std::string S;
1545 if (ConvertToString(Record, 0, S))
1546 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1547 TheModule->setDataLayout(S);
1548 break;
1549 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001550 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001551 std::string S;
1552 if (ConvertToString(Record, 0, S))
1553 return Error("Invalid MODULE_CODE_ASM record");
1554 TheModule->setModuleInlineAsm(S);
1555 break;
1556 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001557 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001558 std::string S;
1559 if (ConvertToString(Record, 0, S))
1560 return Error("Invalid MODULE_CODE_DEPLIB record");
1561 TheModule->addLibrary(S);
1562 break;
1563 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001564 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001565 std::string S;
1566 if (ConvertToString(Record, 0, S))
1567 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1568 SectionTable.push_back(S);
1569 break;
1570 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001571 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001572 std::string S;
1573 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001574 return Error("Invalid MODULE_CODE_GCNAME record");
1575 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001576 break;
1577 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001578 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001579 // linkage, alignment, section, visibility, threadlocal,
1580 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001581 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001582 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001583 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001584 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001585 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001586 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001587 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001588 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001589 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001590
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001591 bool isConstant = Record[1];
1592 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1593 unsigned Alignment = (1 << Record[4]) >> 1;
1594 std::string Section;
1595 if (Record[5]) {
1596 if (Record[5]-1 >= SectionTable.size())
1597 return Error("Invalid section ID");
1598 Section = SectionTable[Record[5]-1];
1599 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001600 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001601 if (Record.size() > 6)
1602 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001603 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001604 if (Record.size() > 7)
1605 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001606
Rafael Espindolabea46262011-01-08 16:42:36 +00001607 bool UnnamedAddr = false;
1608 if (Record.size() > 8)
1609 UnnamedAddr = Record[8];
1610
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001611 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001612 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001613 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001614 NewGV->setAlignment(Alignment);
1615 if (!Section.empty())
1616 NewGV->setSection(Section);
1617 NewGV->setVisibility(Visibility);
1618 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001619 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620
Chris Lattner0b2482a2007-04-23 21:26:05 +00001621 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001623 // Remember which value to use for the global initializer.
1624 if (unsigned InitID = Record[2])
1625 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001626 break;
1627 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001628 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001629 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001630 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001631 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001632 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001633 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001634 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001635 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001636 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001637 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001638 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1639 if (!FTy)
1640 return Error("Function not a pointer to function type!");
1641
Gabor Greif051a9502008-04-06 20:25:17 +00001642 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1643 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001644
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001645 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001646 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001647 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001648 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001649
Chris Lattnera9bb7132007-05-08 05:38:01 +00001650 Func->setAlignment((1 << Record[5]) >> 1);
1651 if (Record[6]) {
1652 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001653 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001654 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001655 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001656 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001657 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001658 if (Record[8]-1 > GCTable.size())
1659 return Error("Invalid GC ID");
1660 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001661 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001662 bool UnnamedAddr = false;
1663 if (Record.size() > 9)
1664 UnnamedAddr = Record[9];
1665 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001666 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattner48f84872007-05-01 04:59:48 +00001668 // If this is a function with a body, remember the prototype we are
1669 // creating now, so that we can match up the body with them later.
1670 if (!isProto)
1671 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001672 break;
1673 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001674 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001675 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001676 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001677 if (Record.size() < 3)
1678 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001679 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001680 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001681 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001682 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001683
Chris Lattner07d98b42007-04-26 02:46:40 +00001684 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1685 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001686 // Old bitcode files didn't have visibility field.
1687 if (Record.size() > 3)
1688 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001689 ValueList.push_back(NewGA);
1690 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1691 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001692 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001693 /// MODULE_CODE_PURGEVALS: [numvals]
1694 case bitc::MODULE_CODE_PURGEVALS:
1695 // Trim down the value list to the specified size.
1696 if (Record.size() < 1 || Record[0] > ValueList.size())
1697 return Error("Invalid MODULE_PURGEVALS record");
1698 ValueList.shrinkTo(Record[0]);
1699 break;
1700 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001701 Record.clear();
1702 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001703
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001704 return Error("Premature end of bitstream");
1705}
1706
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001707bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001708 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Chris Lattnerc453f762007-04-29 07:54:31 +00001710 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001711 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001713 if (Buffer->getBufferSize() & 3) {
1714 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1715 return Error("Invalid bitcode signature");
1716 else
1717 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1718 }
1719
Chris Lattner6fa6a322008-07-09 05:14:23 +00001720 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1721 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001722 if (isBitcodeWrapper(BufPtr, BufEnd))
1723 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001724 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001725
Chris Lattner962dde32009-04-26 20:59:02 +00001726 StreamFile.init(BufPtr, BufEnd);
1727 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001728
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001729 // Sniff for the signature.
1730 if (Stream.Read(8) != 'B' ||
1731 Stream.Read(8) != 'C' ||
1732 Stream.Read(4) != 0x0 ||
1733 Stream.Read(4) != 0xC ||
1734 Stream.Read(4) != 0xE ||
1735 Stream.Read(4) != 0xD)
1736 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001737
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001738 // We expect a number of well-defined blocks, though we don't necessarily
1739 // need to understand them all.
1740 while (!Stream.AtEndOfStream()) {
1741 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Rafael Espindolac9687b32011-05-26 18:59:54 +00001743 if (Code != bitc::ENTER_SUBBLOCK) {
1744
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001745 // The ranlib in xcode 4 will align archive members by appending newlines
1746 // to the end of them. If this file size is a multiple of 4 but not 8, we
1747 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001748 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1749 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1750 Stream.AtEndOfStream())
1751 return false;
1752
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001753 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001754 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001755
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001756 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001757
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001758 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001759 switch (BlockID) {
1760 case bitc::BLOCKINFO_BLOCK_ID:
1761 if (Stream.ReadBlockInfoBlock())
1762 return Error("Malformed BlockInfoBlock");
1763 break;
1764 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001765 // Reject multiple MODULE_BLOCK's in a single bitstream.
1766 if (TheModule)
1767 return Error("Multiple MODULE_BLOCKs in same stream");
1768 TheModule = M;
1769 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001770 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001771 break;
1772 default:
1773 if (Stream.SkipBlock())
1774 return Error("Malformed block record");
1775 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001776 }
1777 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001779 return false;
1780}
Chris Lattnerc453f762007-04-29 07:54:31 +00001781
Bill Wendling34711742010-10-06 01:22:42 +00001782bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1783 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1784 return Error("Malformed block record");
1785
1786 SmallVector<uint64_t, 64> Record;
1787
1788 // Read all the records for this module.
1789 while (!Stream.AtEndOfStream()) {
1790 unsigned Code = Stream.ReadCode();
1791 if (Code == bitc::END_BLOCK) {
1792 if (Stream.ReadBlockEnd())
1793 return Error("Error at end of module block");
1794
1795 return false;
1796 }
1797
1798 if (Code == bitc::ENTER_SUBBLOCK) {
1799 switch (Stream.ReadSubBlockID()) {
1800 default: // Skip unknown content.
1801 if (Stream.SkipBlock())
1802 return Error("Malformed block record");
1803 break;
1804 }
1805 continue;
1806 }
1807
1808 if (Code == bitc::DEFINE_ABBREV) {
1809 Stream.ReadAbbrevRecord();
1810 continue;
1811 }
1812
1813 // Read a record.
1814 switch (Stream.ReadRecord(Code, Record)) {
1815 default: break; // Default behavior, ignore unknown content.
1816 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1817 if (Record.size() < 1)
1818 return Error("Malformed MODULE_CODE_VERSION");
1819 // Only version #0 is supported so far.
1820 if (Record[0] != 0)
1821 return Error("Unknown bitstream version!");
1822 break;
1823 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1824 std::string S;
1825 if (ConvertToString(Record, 0, S))
1826 return Error("Invalid MODULE_CODE_TRIPLE record");
1827 Triple = S;
1828 break;
1829 }
1830 }
1831 Record.clear();
1832 }
1833
1834 return Error("Premature end of bitstream");
1835}
1836
1837bool BitcodeReader::ParseTriple(std::string &Triple) {
1838 if (Buffer->getBufferSize() & 3)
1839 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1840
1841 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1842 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1843
1844 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1845 // The magic number is 0x0B17C0DE stored in little endian.
1846 if (isBitcodeWrapper(BufPtr, BufEnd))
1847 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1848 return Error("Invalid bitcode wrapper header");
1849
1850 StreamFile.init(BufPtr, BufEnd);
1851 Stream.init(StreamFile);
1852
1853 // Sniff for the signature.
1854 if (Stream.Read(8) != 'B' ||
1855 Stream.Read(8) != 'C' ||
1856 Stream.Read(4) != 0x0 ||
1857 Stream.Read(4) != 0xC ||
1858 Stream.Read(4) != 0xE ||
1859 Stream.Read(4) != 0xD)
1860 return Error("Invalid bitcode signature");
1861
1862 // We expect a number of well-defined blocks, though we don't necessarily
1863 // need to understand them all.
1864 while (!Stream.AtEndOfStream()) {
1865 unsigned Code = Stream.ReadCode();
1866
1867 if (Code != bitc::ENTER_SUBBLOCK)
1868 return Error("Invalid record at top-level");
1869
1870 unsigned BlockID = Stream.ReadSubBlockID();
1871
1872 // We only know the MODULE subblock ID.
1873 switch (BlockID) {
1874 case bitc::MODULE_BLOCK_ID:
1875 if (ParseModuleTriple(Triple))
1876 return true;
1877 break;
1878 default:
1879 if (Stream.SkipBlock())
1880 return Error("Malformed block record");
1881 break;
1882 }
1883 }
1884
1885 return false;
1886}
1887
Devang Patele8e02132009-09-18 19:26:43 +00001888/// ParseMetadataAttachment - Parse metadata attachments.
1889bool BitcodeReader::ParseMetadataAttachment() {
1890 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1891 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Devang Patele8e02132009-09-18 19:26:43 +00001893 SmallVector<uint64_t, 64> Record;
1894 while(1) {
1895 unsigned Code = Stream.ReadCode();
1896 if (Code == bitc::END_BLOCK) {
1897 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001899 break;
1900 }
1901 if (Code == bitc::DEFINE_ABBREV) {
1902 Stream.ReadAbbrevRecord();
1903 continue;
1904 }
1905 // Read a metadata attachment record.
1906 Record.clear();
1907 switch (Stream.ReadRecord(Code, Record)) {
1908 default: // Default behavior: ignore.
1909 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001910 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001911 unsigned RecordLength = Record.size();
1912 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001914 Instruction *Inst = InstructionList[Record[0]];
1915 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001916 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001917 DenseMap<unsigned, unsigned>::iterator I =
1918 MDKindMap.find(Kind);
1919 if (I == MDKindMap.end())
1920 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001922 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001923 }
1924 break;
1925 }
1926 }
1927 }
1928 return false;
1929}
Chris Lattner48f84872007-05-01 04:59:48 +00001930
Chris Lattner980e5aa2007-05-01 05:52:21 +00001931/// ParseFunctionBody - Lazily parse the specified function body block.
1932bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001933 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001934 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001935
Nick Lewycky9a49f152010-02-25 08:30:17 +00001936 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001938 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001939
Chris Lattner980e5aa2007-05-01 05:52:21 +00001940 // Add all the function arguments to the value table.
1941 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1942 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001943
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001944 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001945 BasicBlock *CurBB = 0;
1946 unsigned CurBBNo = 0;
1947
Chris Lattnera6245242010-04-03 02:17:50 +00001948 DebugLoc LastLoc;
1949
Chris Lattner980e5aa2007-05-01 05:52:21 +00001950 // Read all the records.
1951 SmallVector<uint64_t, 64> Record;
1952 while (1) {
1953 unsigned Code = Stream.ReadCode();
1954 if (Code == bitc::END_BLOCK) {
1955 if (Stream.ReadBlockEnd())
1956 return Error("Error at end of function block");
1957 break;
1958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001959
Chris Lattner980e5aa2007-05-01 05:52:21 +00001960 if (Code == bitc::ENTER_SUBBLOCK) {
1961 switch (Stream.ReadSubBlockID()) {
1962 default: // Skip unknown content.
1963 if (Stream.SkipBlock())
1964 return Error("Malformed block record");
1965 break;
1966 case bitc::CONSTANTS_BLOCK_ID:
1967 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001968 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001969 break;
1970 case bitc::VALUE_SYMTAB_BLOCK_ID:
1971 if (ParseValueSymbolTable()) return true;
1972 break;
Devang Patele8e02132009-09-18 19:26:43 +00001973 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974 if (ParseMetadataAttachment()) return true;
1975 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001976 case bitc::METADATA_BLOCK_ID:
1977 if (ParseMetadata()) return true;
1978 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001979 }
1980 continue;
1981 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001982
Chris Lattner980e5aa2007-05-01 05:52:21 +00001983 if (Code == bitc::DEFINE_ABBREV) {
1984 Stream.ReadAbbrevRecord();
1985 continue;
1986 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001987
Chris Lattner980e5aa2007-05-01 05:52:21 +00001988 // Read a record.
1989 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001990 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001991 unsigned BitCode = Stream.ReadRecord(Code, Record);
1992 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001993 default: // Default behavior: reject
1994 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001995 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001996 if (Record.size() < 1 || Record[0] == 0)
1997 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001998 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001999 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002000 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002001 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002002 CurBB = FunctionBBs[0];
2003 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00002004
2005 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2006 // This record indicates that the last instruction is at the same
2007 // location as the previous instruction with a location.
2008 I = 0;
2009
2010 // Get the last instruction emitted.
2011 if (CurBB && !CurBB->empty())
2012 I = &CurBB->back();
2013 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2014 !FunctionBBs[CurBBNo-1]->empty())
2015 I = &FunctionBBs[CurBBNo-1]->back();
2016
2017 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2018 I->setDebugLoc(LastLoc);
2019 I = 0;
2020 continue;
2021
Chris Lattner4f6bab92011-06-17 18:17:37 +00002022 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002023 I = 0; // Get the last instruction emitted.
2024 if (CurBB && !CurBB->empty())
2025 I = &CurBB->back();
2026 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2027 !FunctionBBs[CurBBNo-1]->empty())
2028 I = &FunctionBBs[CurBBNo-1]->back();
2029 if (I == 0 || Record.size() < 4)
2030 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2031
2032 unsigned Line = Record[0], Col = Record[1];
2033 unsigned ScopeID = Record[2], IAID = Record[3];
2034
2035 MDNode *Scope = 0, *IA = 0;
2036 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2037 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2038 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2039 I->setDebugLoc(LastLoc);
2040 I = 0;
2041 continue;
2042 }
2043
Chris Lattnerabfbf852007-05-06 00:21:25 +00002044 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2045 unsigned OpNum = 0;
2046 Value *LHS, *RHS;
2047 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2048 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002049 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002050 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Dan Gohman1224c382009-07-20 21:19:07 +00002052 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002053 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002054 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002055 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002056 if (OpNum < Record.size()) {
2057 if (Opc == Instruction::Add ||
2058 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002059 Opc == Instruction::Mul ||
2060 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002061 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002062 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002063 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002064 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002065 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002066 Opc == Instruction::UDiv ||
2067 Opc == Instruction::LShr ||
2068 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002069 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002070 cast<BinaryOperator>(I)->setIsExact(true);
2071 }
2072 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002073 break;
2074 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002075 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2076 unsigned OpNum = 0;
2077 Value *Op;
2078 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2079 OpNum+2 != Record.size())
2080 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002081
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002082 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002083 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2084 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002085 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002087 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002088 break;
2089 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002090 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002091 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002092 unsigned OpNum = 0;
2093 Value *BasePtr;
2094 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002095 return Error("Invalid GEP record");
2096
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002097 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002098 while (OpNum != Record.size()) {
2099 Value *Op;
2100 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002101 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002102 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002103 }
2104
Jay Foada9203102011-07-25 09:48:08 +00002105 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002106 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002107 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002108 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002109 break;
2110 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002111
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002112 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2113 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002114 unsigned OpNum = 0;
2115 Value *Agg;
2116 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2117 return Error("Invalid EXTRACTVAL record");
2118
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002119 SmallVector<unsigned, 4> EXTRACTVALIdx;
2120 for (unsigned RecSize = Record.size();
2121 OpNum != RecSize; ++OpNum) {
2122 uint64_t Index = Record[OpNum];
2123 if ((unsigned)Index != Index)
2124 return Error("Invalid EXTRACTVAL index");
2125 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002126 }
2127
Jay Foadfc6d3a42011-07-13 10:26:04 +00002128 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002129 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002130 break;
2131 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002132
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002133 case bitc::FUNC_CODE_INST_INSERTVAL: {
2134 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002135 unsigned OpNum = 0;
2136 Value *Agg;
2137 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2138 return Error("Invalid INSERTVAL record");
2139 Value *Val;
2140 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2141 return Error("Invalid INSERTVAL record");
2142
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002143 SmallVector<unsigned, 4> INSERTVALIdx;
2144 for (unsigned RecSize = Record.size();
2145 OpNum != RecSize; ++OpNum) {
2146 uint64_t Index = Record[OpNum];
2147 if ((unsigned)Index != Index)
2148 return Error("Invalid INSERTVAL index");
2149 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002150 }
2151
Jay Foadfc6d3a42011-07-13 10:26:04 +00002152 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002153 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002154 break;
2155 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002156
Chris Lattnerabfbf852007-05-06 00:21:25 +00002157 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002158 // obsolete form of select
2159 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002160 unsigned OpNum = 0;
2161 Value *TrueVal, *FalseVal, *Cond;
2162 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2163 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002164 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002165 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002166
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002167 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002168 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002169 break;
2170 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002171
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002172 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2173 // new form of select
2174 // handles select i1 or select [N x i1]
2175 unsigned OpNum = 0;
2176 Value *TrueVal, *FalseVal, *Cond;
2177 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2178 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2179 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2180 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002181
2182 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002183 if (VectorType* vector_type =
2184 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002185 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002187 return Error("Invalid SELECT condition type");
2188 } else {
2189 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002190 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002191 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002192 }
2193
Gabor Greif051a9502008-04-06 20:25:17 +00002194 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002195 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002196 break;
2197 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002198
Chris Lattner01ff65f2007-05-02 05:16:49 +00002199 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002200 unsigned OpNum = 0;
2201 Value *Vec, *Idx;
2202 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002203 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002204 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002205 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002206 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002207 break;
2208 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002209
Chris Lattner01ff65f2007-05-02 05:16:49 +00002210 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002211 unsigned OpNum = 0;
2212 Value *Vec, *Elt, *Idx;
2213 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002214 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002215 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002216 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002217 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002218 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002219 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002220 break;
2221 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002222
Chris Lattnerabfbf852007-05-06 00:21:25 +00002223 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2224 unsigned OpNum = 0;
2225 Value *Vec1, *Vec2, *Mask;
2226 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2227 getValue(Record, OpNum, Vec1->getType(), Vec2))
2228 return Error("Invalid SHUFFLEVEC record");
2229
Mon P Wangaeb06d22008-11-10 04:46:22 +00002230 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002231 return Error("Invalid SHUFFLEVEC record");
2232 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002233 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002234 break;
2235 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002236
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002237 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2238 // Old form of ICmp/FCmp returning bool
2239 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2240 // both legal on vectors but had different behaviour.
2241 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2242 // FCmp/ICmp returning bool or vector of bool
2243
Chris Lattner7337ab92007-05-06 00:00:00 +00002244 unsigned OpNum = 0;
2245 Value *LHS, *RHS;
2246 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2247 getValue(Record, OpNum, LHS->getType(), RHS) ||
2248 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002249 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002251 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002252 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002253 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002254 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002255 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002256 break;
2257 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002258
Chris Lattner231cbcb2007-05-02 04:27:25 +00002259 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002260 {
2261 unsigned Size = Record.size();
2262 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002263 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002264 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002265 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002266 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002267
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002268 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002269 Value *Op = NULL;
2270 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2271 return Error("Invalid RET record");
2272 if (OpNum != Record.size())
2273 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002274
Chris Lattner96a74c52011-06-17 18:09:11 +00002275 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002276 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002277 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002278 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002279 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002280 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002281 return Error("Invalid BR record");
2282 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2283 if (TrueDest == 0)
2284 return Error("Invalid BR record");
2285
Devang Patele8e02132009-09-18 19:26:43 +00002286 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002287 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002288 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002289 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002290 else {
2291 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002292 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002293 if (FalseDest == 0 || Cond == 0)
2294 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002295 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002296 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002297 }
2298 break;
2299 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002300 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002301 if (Record.size() < 3 || (Record.size() & 1) == 0)
2302 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002303 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002304 Value *Cond = getFnValueByID(Record[1], OpTy);
2305 BasicBlock *Default = getBasicBlock(Record[2]);
2306 if (OpTy == 0 || Cond == 0 || Default == 0)
2307 return Error("Invalid SWITCH record");
2308 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002309 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002310 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002311 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002312 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002313 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2314 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2315 if (CaseVal == 0 || DestBB == 0) {
2316 delete SI;
2317 return Error("Invalid SWITCH record!");
2318 }
2319 SI->addCase(CaseVal, DestBB);
2320 }
2321 I = SI;
2322 break;
2323 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002324 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002325 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002326 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002327 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002328 Value *Address = getFnValueByID(Record[1], OpTy);
2329 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002330 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002331 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002332 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002333 InstructionList.push_back(IBI);
2334 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2335 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2336 IBI->addDestination(DestBB);
2337 } else {
2338 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002339 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002340 }
2341 }
2342 I = IBI;
2343 break;
2344 }
2345
Duncan Sandsdc024672007-11-27 13:23:08 +00002346 case bitc::FUNC_CODE_INST_INVOKE: {
2347 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002348 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002349 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002350 unsigned CCInfo = Record[1];
2351 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2352 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002353
Chris Lattnera9bb7132007-05-08 05:38:01 +00002354 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002355 Value *Callee;
2356 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002357 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002358
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002359 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2360 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002361 dyn_cast<FunctionType>(CalleeTy->getElementType());
2362
2363 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002364 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2365 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002366 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002367
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002368 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002369 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2370 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2371 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002372 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002373
Chris Lattner7337ab92007-05-06 00:00:00 +00002374 if (!FTy->isVarArg()) {
2375 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002376 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002377 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002378 // Read type/value pairs for varargs params.
2379 while (OpNum != Record.size()) {
2380 Value *Op;
2381 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2382 return Error("Invalid INVOKE record");
2383 Ops.push_back(Op);
2384 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002385 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002386
Jay Foada3efbb12011-07-15 08:37:34 +00002387 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002388 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002389 cast<InvokeInst>(I)->setCallingConv(
2390 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002391 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002392 break;
2393 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002394 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2395 unsigned Idx = 0;
2396 Value *Val = 0;
2397 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2398 return Error("Invalid RESUME record");
2399 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002400 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002401 break;
2402 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002403 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002404 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002405 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002406 break;
2407 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002408 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002409 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002410 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002411 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002412 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002413 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002414 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002415 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002416
Jay Foad3ecfc862011-03-30 11:28:46 +00002417 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002418 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002419
Chris Lattner15e6d172007-05-04 19:11:41 +00002420 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2421 Value *V = getFnValueByID(Record[1+i], Ty);
2422 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002423 if (!V || !BB) return Error("Invalid PHI record");
2424 PN->addIncoming(V, BB);
2425 }
2426 I = PN;
2427 break;
2428 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429
Bill Wendlinge6e88262011-08-12 20:24:12 +00002430 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2431 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2432 unsigned Idx = 0;
2433 if (Record.size() < 4)
2434 return Error("Invalid LANDINGPAD record");
2435 Type *Ty = getTypeByID(Record[Idx++]);
2436 if (!Ty) return Error("Invalid LANDINGPAD record");
2437 Value *PersFn = 0;
2438 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2439 return Error("Invalid LANDINGPAD record");
2440
2441 bool IsCleanup = !!Record[Idx++];
2442 unsigned NumClauses = Record[Idx++];
2443 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2444 LP->setCleanup(IsCleanup);
2445 for (unsigned J = 0; J != NumClauses; ++J) {
2446 LandingPadInst::ClauseType CT =
2447 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2448 Value *Val;
2449
2450 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2451 delete LP;
2452 return Error("Invalid LANDINGPAD record");
2453 }
2454
2455 assert((CT != LandingPadInst::Catch ||
2456 !isa<ArrayType>(Val->getType())) &&
2457 "Catch clause has a invalid type!");
2458 assert((CT != LandingPadInst::Filter ||
2459 isa<ArrayType>(Val->getType())) &&
2460 "Filter clause has invalid type!");
2461 LP->addClause(Val);
2462 }
2463
2464 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002465 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002466 break;
2467 }
2468
Chris Lattner96a74c52011-06-17 18:09:11 +00002469 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2470 if (Record.size() != 4)
2471 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002472 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002473 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002474 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002475 Value *Size = getFnValueByID(Record[2], OpTy);
2476 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002477 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002478 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002479 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002480 break;
2481 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002482 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002483 unsigned OpNum = 0;
2484 Value *Op;
2485 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2486 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002487 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002488
Chris Lattner7337ab92007-05-06 00:00:00 +00002489 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002490 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002491 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002492 }
Eli Friedman21006d42011-08-09 23:02:53 +00002493 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2494 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2495 unsigned OpNum = 0;
2496 Value *Op;
2497 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2498 OpNum+4 != Record.size())
2499 return Error("Invalid LOADATOMIC record");
2500
2501
2502 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2503 if (Ordering == NotAtomic || Ordering == Release ||
2504 Ordering == AcquireRelease)
2505 return Error("Invalid LOADATOMIC record");
2506 if (Ordering != NotAtomic && Record[OpNum] == 0)
2507 return Error("Invalid LOADATOMIC record");
2508 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2509
2510 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2511 Ordering, SynchScope);
2512 InstructionList.push_back(I);
2513 break;
2514 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002515 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002516 unsigned OpNum = 0;
2517 Value *Val, *Ptr;
2518 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002519 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002520 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2521 OpNum+2 != Record.size())
2522 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002523
Christopher Lambfe63fb92007-12-11 08:59:05 +00002524 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002525 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002526 break;
2527 }
Eli Friedman21006d42011-08-09 23:02:53 +00002528 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2529 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2530 unsigned OpNum = 0;
2531 Value *Val, *Ptr;
2532 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2533 getValue(Record, OpNum,
2534 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2535 OpNum+4 != Record.size())
2536 return Error("Invalid STOREATOMIC record");
2537
2538 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002539 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002540 Ordering == AcquireRelease)
2541 return Error("Invalid STOREATOMIC record");
2542 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2543 if (Ordering != NotAtomic && Record[OpNum] == 0)
2544 return Error("Invalid STOREATOMIC record");
2545
2546 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2547 Ordering, SynchScope);
2548 InstructionList.push_back(I);
2549 break;
2550 }
Eli Friedmanff030482011-07-28 21:48:00 +00002551 case bitc::FUNC_CODE_INST_CMPXCHG: {
2552 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2553 unsigned OpNum = 0;
2554 Value *Ptr, *Cmp, *New;
2555 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2556 getValue(Record, OpNum,
2557 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2558 getValue(Record, OpNum,
2559 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2560 OpNum+3 != Record.size())
2561 return Error("Invalid CMPXCHG record");
2562 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002563 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002564 return Error("Invalid CMPXCHG record");
2565 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2566 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2567 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2568 InstructionList.push_back(I);
2569 break;
2570 }
2571 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2572 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2573 unsigned OpNum = 0;
2574 Value *Ptr, *Val;
2575 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2576 getValue(Record, OpNum,
2577 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2578 OpNum+4 != Record.size())
2579 return Error("Invalid ATOMICRMW record");
2580 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2581 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2582 Operation > AtomicRMWInst::LAST_BINOP)
2583 return Error("Invalid ATOMICRMW record");
2584 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002585 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002586 return Error("Invalid ATOMICRMW record");
2587 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2588 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2589 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2590 InstructionList.push_back(I);
2591 break;
2592 }
Eli Friedman47f35132011-07-25 23:16:38 +00002593 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2594 if (2 != Record.size())
2595 return Error("Invalid FENCE record");
2596 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2597 if (Ordering == NotAtomic || Ordering == Unordered ||
2598 Ordering == Monotonic)
2599 return Error("Invalid FENCE record");
2600 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2601 I = new FenceInst(Context, Ordering, SynchScope);
2602 InstructionList.push_back(I);
2603 break;
2604 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002605 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002606 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2607 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002608 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002609
Devang Patel05988662008-09-25 21:00:45 +00002610 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002611 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002612
Chris Lattnera9bb7132007-05-08 05:38:01 +00002613 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002614 Value *Callee;
2615 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2616 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002617
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002618 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2619 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002620 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002621 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002622 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002623
Chris Lattner0579f7f2007-05-03 22:04:19 +00002624 SmallVector<Value*, 16> Args;
2625 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002626 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002627 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002628 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002629 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002630 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002631 if (Args.back() == 0) return Error("Invalid CALL record");
2632 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002633
Chris Lattner0579f7f2007-05-03 22:04:19 +00002634 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002635 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002636 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002637 return Error("Invalid CALL record");
2638 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002639 while (OpNum != Record.size()) {
2640 Value *Op;
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2642 return Error("Invalid CALL record");
2643 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002644 }
2645 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Jay Foada3efbb12011-07-15 08:37:34 +00002647 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002648 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002649 cast<CallInst>(I)->setCallingConv(
2650 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002651 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002652 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002653 break;
2654 }
2655 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2656 if (Record.size() < 3)
2657 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002658 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002659 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002660 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002661 if (!OpTy || !Op || !ResTy)
2662 return Error("Invalid VAARG record");
2663 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002664 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002665 break;
2666 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002667 }
2668
2669 // Add instruction to end of current BB. If there is no current BB, reject
2670 // this file.
2671 if (CurBB == 0) {
2672 delete I;
2673 return Error("Invalid instruction with no BB");
2674 }
2675 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002676
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002677 // If this was a terminator instruction, move to the next block.
2678 if (isa<TerminatorInst>(I)) {
2679 ++CurBBNo;
2680 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2681 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002682
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002683 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002684 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002685 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002686 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002687
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002688 // Check the function list for unresolved values.
2689 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2690 if (A->getParent() == 0) {
2691 // We found at least one unresolved value. Nuke them all to avoid leaks.
2692 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002693 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002694 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002695 delete A;
2696 }
2697 }
Chris Lattner35a04702007-05-04 03:50:29 +00002698 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002699 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002700 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002701
Dan Gohman064ff3e2010-08-25 20:23:38 +00002702 // FIXME: Check for unresolved forward-declared metadata references
2703 // and clean up leaks.
2704
Chris Lattner50b136d2009-10-28 05:53:48 +00002705 // See if anything took the address of blocks in this function. If so,
2706 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002707 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2708 BlockAddrFwdRefs.find(F);
2709 if (BAFRI != BlockAddrFwdRefs.end()) {
2710 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2711 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2712 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002713 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002714 return Error("Invalid blockaddress block #");
2715
2716 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002717 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002718 FwdRef->eraseFromParent();
2719 }
2720
2721 BlockAddrFwdRefs.erase(BAFRI);
2722 }
2723
Chris Lattner980e5aa2007-05-01 05:52:21 +00002724 // Trim the value list down to the size it was before we parsed this function.
2725 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002726 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002727 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002728 return false;
2729}
2730
Chris Lattnerb348bb82007-05-18 04:02:46 +00002731//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002732// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002733//===----------------------------------------------------------------------===//
2734
2735
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002736bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2737 if (const Function *F = dyn_cast<Function>(GV)) {
2738 return F->isDeclaration() &&
2739 DeferredFunctionInfo.count(const_cast<Function*>(F));
2740 }
2741 return false;
2742}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002744bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2745 Function *F = dyn_cast<Function>(GV);
2746 // If it's not a function or is already material, ignore the request.
2747 if (!F || !F->isMaterializable()) return false;
2748
2749 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002750 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002751
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002752 // Move the bit stream to the saved position of the deferred function body.
2753 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002754
Chris Lattnerb348bb82007-05-18 04:02:46 +00002755 if (ParseFunctionBody(F)) {
2756 if (ErrInfo) *ErrInfo = ErrorString;
2757 return true;
2758 }
Chandler Carruth69940402007-08-04 01:51:18 +00002759
2760 // Upgrade any old intrinsic calls in the function.
2761 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2762 E = UpgradedIntrinsics.end(); I != E; ++I) {
2763 if (I->first != I->second) {
2764 for (Value::use_iterator UI = I->first->use_begin(),
2765 UE = I->first->use_end(); UI != UE; ) {
2766 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2767 UpgradeIntrinsicCall(CI, I->second);
2768 }
2769 }
2770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002771
Chris Lattnerb348bb82007-05-18 04:02:46 +00002772 return false;
2773}
2774
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002775bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2776 const Function *F = dyn_cast<Function>(GV);
2777 if (!F || F->isDeclaration())
2778 return false;
2779 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2780}
2781
2782void BitcodeReader::Dematerialize(GlobalValue *GV) {
2783 Function *F = dyn_cast<Function>(GV);
2784 // If this function isn't dematerializable, this is a noop.
2785 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002786 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002787
Chris Lattnerb348bb82007-05-18 04:02:46 +00002788 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002789
Chris Lattnerb348bb82007-05-18 04:02:46 +00002790 // Just forget the function body, we can remat it later.
2791 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002792}
2793
2794
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002795bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2796 assert(M == TheModule &&
2797 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002798 // Iterate over the module, deserializing any functions that are still on
2799 // disk.
2800 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2801 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002802 if (F->isMaterializable() &&
2803 Materialize(F, ErrInfo))
2804 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002805
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2807 // delete the old functions to clean up. We can't do this unless the entire
2808 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002809 // with calls to the old function.
2810 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2811 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2812 if (I->first != I->second) {
2813 for (Value::use_iterator UI = I->first->use_begin(),
2814 UE = I->first->use_end(); UI != UE; ) {
2815 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2816 UpgradeIntrinsicCall(CI, I->second);
2817 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002818 if (!I->first->use_empty())
2819 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002820 I->first->eraseFromParent();
2821 }
2822 }
2823 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002824
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002825 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002826}
2827
Chris Lattner48f84872007-05-01 04:59:48 +00002828
Chris Lattnerc453f762007-04-29 07:54:31 +00002829//===----------------------------------------------------------------------===//
2830// External interface
2831//===----------------------------------------------------------------------===//
2832
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002833/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002834///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002835Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2836 LLVMContext& Context,
2837 std::string *ErrMsg) {
2838 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002839 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002840 M->setMaterializer(R);
2841 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002842 if (ErrMsg)
2843 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002844
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002845 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002846 return 0;
2847 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002848 // Have the BitcodeReader dtor delete 'Buffer'.
2849 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002850
2851 R->materializeForwardReferencedFunctions();
2852
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002853 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002854}
2855
2856/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2857/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002858Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002859 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002860 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2861 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002862
2863 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2864 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002865 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002866
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002867 // Read in the entire module, and destroy the BitcodeReader.
2868 if (M->MaterializeAllPermanently(ErrMsg)) {
2869 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002870 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002871 }
Bill Wendling34711742010-10-06 01:22:42 +00002872
Chad Rosiercbbb0962011-12-07 21:44:12 +00002873 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2874 // written. We must defer until the Module has been fully materialized.
2875
Chris Lattnerc453f762007-04-29 07:54:31 +00002876 return M;
2877}
Bill Wendling34711742010-10-06 01:22:42 +00002878
2879std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2880 LLVMContext& Context,
2881 std::string *ErrMsg) {
2882 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2883 // Don't let the BitcodeReader dtor delete 'Buffer'.
2884 R->setBufferOwned(false);
2885
2886 std::string Triple("");
2887 if (R->ParseTriple(Triple))
2888 if (ErrMsg)
2889 *ErrMsg = R->getErrorString();
2890
2891 delete R;
2892 return Triple;
2893}