blob: e3990403bd71ba394f22c34965a8743a5cb910fc [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"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Rafael Espindola47f79bb2012-01-02 07:49:53 +000031void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
34 F->Materialize();
35 }
36}
37
Chris Lattnerb348bb82007-05-18 04:02:46 +000038void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000039 if (BufferOwned)
40 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000041 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000042 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000044 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000045
Devang Patel19c87462008-09-26 22:53:05 +000046 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000050 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000051}
52
Chris Lattner48c85b82007-05-04 03:30:17 +000053//===----------------------------------------------------------------------===//
54// Helper functions to implement forward reference resolution, etc.
55//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000056
Chris Lattnercaee0dc2007-04-22 06:23:29 +000057/// ConvertToString - Convert a string from a record into an std::string, return
58/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000059template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000060static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000061 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000062 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000064
Chris Lattner15e6d172007-05-04 19:11:41 +000065 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
66 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return false;
68}
69
70static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
71 switch (Val) {
72 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000073 case 0: return GlobalValue::ExternalLinkage;
74 case 1: return GlobalValue::WeakAnyLinkage;
75 case 2: return GlobalValue::AppendingLinkage;
76 case 3: return GlobalValue::InternalLinkage;
77 case 4: return GlobalValue::LinkOnceAnyLinkage;
78 case 5: return GlobalValue::DLLImportLinkage;
79 case 6: return GlobalValue::DLLExportLinkage;
80 case 7: return GlobalValue::ExternalWeakLinkage;
81 case 8: return GlobalValue::CommonLinkage;
82 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000083 case 10: return GlobalValue::WeakODRLinkage;
84 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000085 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000086 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000087 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000088 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000089 }
90}
91
92static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
93 switch (Val) {
94 default: // Map unknown visibilities to default.
95 case 0: return GlobalValue::DefaultVisibility;
96 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000097 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000098 }
99}
100
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000101static int GetDecodedCastOpcode(unsigned Val) {
102 switch (Val) {
103 default: return -1;
104 case bitc::CAST_TRUNC : return Instruction::Trunc;
105 case bitc::CAST_ZEXT : return Instruction::ZExt;
106 case bitc::CAST_SEXT : return Instruction::SExt;
107 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
108 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
109 case bitc::CAST_UITOFP : return Instruction::UIToFP;
110 case bitc::CAST_SITOFP : return Instruction::SIToFP;
111 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
112 case bitc::CAST_FPEXT : return Instruction::FPExt;
113 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
114 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
115 case bitc::CAST_BITCAST : return Instruction::BitCast;
116 }
117}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000118static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000119 switch (Val) {
120 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000121 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000122 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000123 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000124 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000125 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000126 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000127 case bitc::BINOP_UDIV: return Instruction::UDiv;
128 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000129 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000130 case bitc::BINOP_UREM: return Instruction::URem;
131 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000132 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000133 case bitc::BINOP_SHL: return Instruction::Shl;
134 case bitc::BINOP_LSHR: return Instruction::LShr;
135 case bitc::BINOP_ASHR: return Instruction::AShr;
136 case bitc::BINOP_AND: return Instruction::And;
137 case bitc::BINOP_OR: return Instruction::Or;
138 case bitc::BINOP_XOR: return Instruction::Xor;
139 }
140}
141
Eli Friedmanff030482011-07-28 21:48:00 +0000142static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
143 switch (Val) {
144 default: return AtomicRMWInst::BAD_BINOP;
145 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
146 case bitc::RMW_ADD: return AtomicRMWInst::Add;
147 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
148 case bitc::RMW_AND: return AtomicRMWInst::And;
149 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
150 case bitc::RMW_OR: return AtomicRMWInst::Or;
151 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
152 case bitc::RMW_MAX: return AtomicRMWInst::Max;
153 case bitc::RMW_MIN: return AtomicRMWInst::Min;
154 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
155 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
156 }
157}
158
Eli Friedman47f35132011-07-25 23:16:38 +0000159static AtomicOrdering GetDecodedOrdering(unsigned Val) {
160 switch (Val) {
161 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
162 case bitc::ORDERING_UNORDERED: return Unordered;
163 case bitc::ORDERING_MONOTONIC: return Monotonic;
164 case bitc::ORDERING_ACQUIRE: return Acquire;
165 case bitc::ORDERING_RELEASE: return Release;
166 case bitc::ORDERING_ACQREL: return AcquireRelease;
167 default: // Map unknown orderings to sequentially-consistent.
168 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
169 }
170}
171
172static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
173 switch (Val) {
174 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
175 default: // Map unknown scopes to cross-thread.
176 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
177 }
178}
179
Gabor Greifefe65362008-05-10 08:32:32 +0000180namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000181namespace {
182 /// @brief A class for maintaining the slot number definition
183 /// as a placeholder for the actual definition for forward constants defs.
184 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000185 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000186 public:
187 // allocate space for exactly one operand
188 void *operator new(size_t s) {
189 return User::operator new(s, 1);
190 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000191 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000192 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000193 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000195
Chris Lattnerea693df2008-08-21 02:34:16 +0000196 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000197 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000198 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000199 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000200 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000202
203
Gabor Greifefe65362008-05-10 08:32:32 +0000204 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000205 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000206 };
207}
208
Chris Lattner46e77402009-03-31 22:55:09 +0000209// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000210template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000211struct OperandTraits<ConstantPlaceHolder> :
212 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000213};
Gabor Greifefe65362008-05-10 08:32:32 +0000214}
215
Chris Lattner46e77402009-03-31 22:55:09 +0000216
217void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
218 if (Idx == size()) {
219 push_back(V);
220 return;
221 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000222
Chris Lattner46e77402009-03-31 22:55:09 +0000223 if (Idx >= size())
224 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000225
Chris Lattner46e77402009-03-31 22:55:09 +0000226 WeakVH &OldV = ValuePtrs[Idx];
227 if (OldV == 0) {
228 OldV = V;
229 return;
230 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000231
Chris Lattner46e77402009-03-31 22:55:09 +0000232 // Handle constants and non-constants (e.g. instrs) differently for
233 // efficiency.
234 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
235 ResolveConstants.push_back(std::make_pair(PHC, Idx));
236 OldV = V;
237 } else {
238 // If there was a forward reference to this value, replace it.
239 Value *PrevVal = OldV;
240 OldV->replaceAllUsesWith(V);
241 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000242 }
243}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000244
Gabor Greifefe65362008-05-10 08:32:32 +0000245
Chris Lattner522b7b12007-04-24 05:48:56 +0000246Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000247 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000248 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000249 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000250
Chris Lattner46e77402009-03-31 22:55:09 +0000251 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000252 assert(Ty == V->getType() && "Type mismatch in constant table!");
253 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000254 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000255
256 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000257 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000258 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000259 return C;
260}
261
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000262Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000264 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000265
Chris Lattner46e77402009-03-31 22:55:09 +0000266 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000267 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
268 return V;
269 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000270
Chris Lattner01ff65f2007-05-02 05:16:49 +0000271 // No type specified, must be invalid reference.
272 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000273
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000274 // Create and return a placeholder, which will later be RAUW'd.
275 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000276 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000277 return V;
278}
279
Chris Lattnerea693df2008-08-21 02:34:16 +0000280/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
281/// resolves any forward references. The idea behind this is that we sometimes
282/// get constants (such as large arrays) which reference *many* forward ref
283/// constants. Replacing each of these causes a lot of thrashing when
284/// building/reuniquing the constant. Instead of doing this, we look at all the
285/// uses and rewrite all the place holders at once for any constant that uses
286/// a placeholder.
287void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000288 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000289 // binary search.
290 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000293
Chris Lattnerea693df2008-08-21 02:34:16 +0000294 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000295 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000296 Constant *Placeholder = ResolveConstants.back().first;
297 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000298
Chris Lattnerea693df2008-08-21 02:34:16 +0000299 // Loop over all users of the placeholder, updating them to reference the
300 // new value. If they reference more than one placeholder, update them all
301 // at once.
302 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000303 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000304 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 // If the using object isn't uniqued, just update the operands. This
307 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000308 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000309 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 continue;
311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000312
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 // Otherwise, we have a constant that uses the placeholder. Replace that
314 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000315 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000316 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
317 I != E; ++I) {
318 Value *NewOp;
319 if (!isa<ConstantPlaceHolder>(*I)) {
320 // Not a placeholder reference.
321 NewOp = *I;
322 } else if (*I == Placeholder) {
323 // Common case is that it just references this one placeholder.
324 NewOp = RealVal;
325 } else {
326 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327 ResolveConstantsTy::iterator It =
328 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000329 std::pair<Constant*, unsigned>(cast<Constant>(*I),
330 0));
331 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000332 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 }
334
335 NewOps.push_back(cast<Constant>(NewOp));
336 }
337
338 // Make the new constant.
339 Constant *NewC;
340 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000341 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000342 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000343 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000344 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000345 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000346 } else {
347 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000348 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000349 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000350
Chris Lattnerea693df2008-08-21 02:34:16 +0000351 UserC->replaceAllUsesWith(NewC);
352 UserC->destroyConstant();
353 NewOps.clear();
354 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000355
Nick Lewyckycb337992009-05-10 20:57:05 +0000356 // Update all ValueHandles, they should be the only users at this point.
357 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000358 delete Placeholder;
359 }
360}
361
Devang Pateld5ac4042009-08-04 06:00:18 +0000362void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
363 if (Idx == size()) {
364 push_back(V);
365 return;
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Devang Pateld5ac4042009-08-04 06:00:18 +0000368 if (Idx >= size())
369 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000370
Devang Pateld5ac4042009-08-04 06:00:18 +0000371 WeakVH &OldV = MDValuePtrs[Idx];
372 if (OldV == 0) {
373 OldV = V;
374 return;
375 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000376
Devang Pateld5ac4042009-08-04 06:00:18 +0000377 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000378 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000379 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000380 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000381 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
382 // value for Idx.
383 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000384}
385
386Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
387 if (Idx >= size())
388 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Devang Pateld5ac4042009-08-04 06:00:18 +0000390 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000391 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000392 return V;
393 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000394
Devang Pateld5ac4042009-08-04 06:00:18 +0000395 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000396 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000397 MDValuePtrs[Idx] = V;
398 return V;
399}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401Type *BitcodeReader::getTypeByID(unsigned ID) {
402 // The type table size is always specified correctly.
403 if (ID >= TypeList.size())
404 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406 if (Type *Ty = TypeList[ID])
407 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000408
Chris Lattner1afcace2011-07-09 17:41:24 +0000409 // If we have a forward reference, the only possible case is when it is to a
410 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000411 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412}
413
Chris Lattner1afcace2011-07-09 17:41:24 +0000414
Chris Lattner48c85b82007-05-04 03:30:17 +0000415//===----------------------------------------------------------------------===//
416// Functions for parsing blocks from the bitcode file
417//===----------------------------------------------------------------------===//
418
Devang Patel05988662008-09-25 21:00:45 +0000419bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000420 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000421 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000422
Devang Patel19c87462008-09-26 22:53:05 +0000423 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000424 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattner48c85b82007-05-04 03:30:17 +0000426 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000427
Devang Patel05988662008-09-25 21:00:45 +0000428 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 // Read all the records.
431 while (1) {
432 unsigned Code = Stream.ReadCode();
433 if (Code == bitc::END_BLOCK) {
434 if (Stream.ReadBlockEnd())
435 return Error("Error at end of PARAMATTR block");
436 return false;
437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000438
Chris Lattner48c85b82007-05-04 03:30:17 +0000439 if (Code == bitc::ENTER_SUBBLOCK) {
440 // No known subblocks, always skip them.
441 Stream.ReadSubBlockID();
442 if (Stream.SkipBlock())
443 return Error("Malformed block record");
444 continue;
445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000446
Chris Lattner48c85b82007-05-04 03:30:17 +0000447 if (Code == bitc::DEFINE_ABBREV) {
448 Stream.ReadAbbrevRecord();
449 continue;
450 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000451
Chris Lattner48c85b82007-05-04 03:30:17 +0000452 // Read a record.
453 Record.clear();
454 switch (Stream.ReadRecord(Code, Record)) {
455 default: // Default behavior: ignore.
456 break;
457 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458 if (Record.size() & 1)
459 return Error("Invalid ENTRY record");
460
Chris Lattner9a6cb152008-10-05 18:22:09 +0000461 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000462 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000463 // to index ~0. Index 0 is used for return value attributes but used to be
464 // used for function attributes.
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000465 Attributes RetAttribute;
466 Attributes FnAttribute;
Chris Lattner48c85b82007-05-04 03:30:17 +0000467 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000468 // FIXME: remove in LLVM 3.0
469 // The alignment is stored as a 16-bit raw value from bits 31--16.
470 // We shift the bits above 31 down by 11 bits.
471
472 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473 if (Alignment && !isPowerOf2_32(Alignment))
474 return Error("Alignment is not a power of two.");
475
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000476 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000477 if (Alignment)
478 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000479 ReconstitutedAttr |=
480 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000481
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000482 Record[i+1] = ReconstitutedAttr.Raw();
Devang Patel19c87462008-09-26 22:53:05 +0000483 if (Record[i] == 0)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000484 RetAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000485 else if (Record[i] == ~0U)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 FnAttribute = ReconstitutedAttr;
Devang Patel19c87462008-09-26 22:53:05 +0000487 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000488
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000489 Attributes OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
Chris Lattner9a6cb152008-10-05 18:22:09 +0000490 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000491
Chris Lattner9a6cb152008-10-05 18:22:09 +0000492 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000493 (RetAttribute & OldRetAttrs)) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000494 if (FnAttribute == Attribute::None) { // add a slot so they get added.
495 Record.push_back(~0U);
496 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000497 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000498
Chris Lattner9a6cb152008-10-05 18:22:09 +0000499 FnAttribute |= RetAttribute & OldRetAttrs;
500 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000501 }
Chris Lattner461edd92008-03-12 02:25:52 +0000502
Devang Patel19c87462008-09-26 22:53:05 +0000503 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000504 if (Record[i] == 0) {
505 if (RetAttribute != Attribute::None)
506 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
507 } else if (Record[i] == ~0U) {
508 if (FnAttribute != Attribute::None)
509 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000510 } else if (Attributes(Record[i+1]) != Attribute::None)
511 Attrs.push_back(AttributeWithIndex::get(Record[i],
512 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000513 }
Devang Patel19c87462008-09-26 22:53:05 +0000514
515 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000516 Attrs.clear();
517 break;
518 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000519 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000520 }
521}
522
Chris Lattner86697142007-05-01 05:01:34 +0000523bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000526
Chris Lattner1afcace2011-07-09 17:41:24 +0000527 return ParseTypeTableBody();
528}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000529
Chris Lattner1afcace2011-07-09 17:41:24 +0000530bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 if (!TypeList.empty())
532 return Error("Multiple TYPE_BLOCKs found!");
533
534 SmallVector<uint64_t, 64> Record;
535 unsigned NumRecords = 0;
536
Chris Lattner1afcace2011-07-09 17:41:24 +0000537 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000538
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 // Read all the records for this type table.
540 while (1) {
541 unsigned Code = Stream.ReadCode();
542 if (Code == bitc::END_BLOCK) {
543 if (NumRecords != TypeList.size())
544 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000545 if (Stream.ReadBlockEnd())
546 return Error("Error at end of type table block");
547 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000549
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 if (Code == bitc::ENTER_SUBBLOCK) {
551 // No known subblocks, always skip them.
552 Stream.ReadSubBlockID();
553 if (Stream.SkipBlock())
554 return Error("Malformed block record");
555 continue;
556 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000557
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000558 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000559 Stream.ReadAbbrevRecord();
560 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000562
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000563 // Read a record.
564 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000565 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000566 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000567 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
569 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
570 // type list. This allows us to reserve space.
571 if (Record.size() < 1)
572 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000573 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000575 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000576 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000577 break;
Dan Gohmance163392011-12-17 00:04:22 +0000578 case bitc::TYPE_CODE_HALF: // HALF
579 ResultTy = Type::getHalfTy(Context);
580 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000581 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000582 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 break;
584 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000585 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000586 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000587 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000588 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000589 break;
590 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000591 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000592 break;
593 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000594 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000595 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000597 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000598 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000599 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000600 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000601 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000602 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
603 ResultTy = Type::getX86_MMXTy(Context);
604 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000605 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
606 if (Record.size() < 1)
607 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Owen Anderson1d0be152009-08-13 21:58:54 +0000609 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000610 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000611 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000612 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000613 if (Record.size() < 1)
614 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000615 unsigned AddressSpace = 0;
616 if (Record.size() == 2)
617 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000618 ResultTy = getTypeByID(Record[0]);
619 if (ResultTy == 0) return Error("invalid element type in pointer type");
620 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000621 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000622 }
Chad Rosiercde54642011-11-03 00:14:01 +0000623 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000624 // FIXME: attrid is dead, remove it in LLVM 3.0
625 // FUNCTION: [vararg, attrid, retty, paramty x N]
626 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000627 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000628 SmallVector<Type*, 8> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000629 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
630 if (Type *T = getTypeByID(Record[i]))
631 ArgTys.push_back(T);
632 else
633 break;
634 }
635
636 ResultTy = getTypeByID(Record[2]);
637 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
638 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000639
Chris Lattner1afcace2011-07-09 17:41:24 +0000640 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000641 break;
642 }
Chad Rosiercde54642011-11-03 00:14:01 +0000643 case bitc::TYPE_CODE_FUNCTION: {
644 // FUNCTION: [vararg, retty, paramty x N]
645 if (Record.size() < 2)
646 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000647 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000648 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
649 if (Type *T = getTypeByID(Record[i]))
650 ArgTys.push_back(T);
651 else
652 break;
653 }
654
655 ResultTy = getTypeByID(Record[1]);
656 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
657 return Error("invalid type in function type");
658
659 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
660 break;
661 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000662 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000663 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000664 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000665 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000666 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
667 if (Type *T = getTypeByID(Record[i]))
668 EltTys.push_back(T);
669 else
670 break;
671 }
672 if (EltTys.size() != Record.size()-1)
673 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000674 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000675 break;
676 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000677 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
678 if (ConvertToString(Record, 0, TypeName))
679 return Error("Invalid STRUCT_NAME record");
680 continue;
681
682 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
683 if (Record.size() < 1)
684 return Error("Invalid STRUCT type record");
685
686 if (NumRecords >= TypeList.size())
687 return Error("invalid TYPE table");
688
689 // Check to see if this was forward referenced, if so fill in the temp.
690 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
691 if (Res) {
692 Res->setName(TypeName);
693 TypeList[NumRecords] = 0;
694 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000695 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000696 TypeName.clear();
697
698 SmallVector<Type*, 8> EltTys;
699 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
700 if (Type *T = getTypeByID(Record[i]))
701 EltTys.push_back(T);
702 else
703 break;
704 }
705 if (EltTys.size() != Record.size()-1)
706 return Error("invalid STRUCT type record");
707 Res->setBody(EltTys, Record[0]);
708 ResultTy = Res;
709 break;
710 }
711 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
712 if (Record.size() != 1)
713 return Error("Invalid OPAQUE type record");
714
715 if (NumRecords >= TypeList.size())
716 return Error("invalid TYPE table");
717
718 // Check to see if this was forward referenced, if so fill in the temp.
719 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
720 if (Res) {
721 Res->setName(TypeName);
722 TypeList[NumRecords] = 0;
723 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000724 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000725 TypeName.clear();
726 ResultTy = Res;
727 break;
728 }
729 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
730 if (Record.size() < 2)
731 return Error("Invalid ARRAY type record");
732 if ((ResultTy = getTypeByID(Record[1])))
733 ResultTy = ArrayType::get(ResultTy, Record[0]);
734 else
735 return Error("Invalid ARRAY type element");
736 break;
737 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
738 if (Record.size() < 2)
739 return Error("Invalid VECTOR type record");
740 if ((ResultTy = getTypeByID(Record[1])))
741 ResultTy = VectorType::get(ResultTy, Record[0]);
742 else
743 return Error("Invalid ARRAY type element");
744 break;
745 }
746
747 if (NumRecords >= TypeList.size())
748 return Error("invalid TYPE table");
749 assert(ResultTy && "Didn't read a type?");
750 assert(TypeList[NumRecords] == 0 && "Already read type?");
751 TypeList[NumRecords++] = ResultTy;
752 }
753}
754
Chris Lattner86697142007-05-01 05:01:34 +0000755bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000756 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 return Error("Malformed block record");
758
759 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000760
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 // Read all the records for this value table.
762 SmallString<128> ValueName;
763 while (1) {
764 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000765 if (Code == bitc::END_BLOCK) {
766 if (Stream.ReadBlockEnd())
767 return Error("Error at end of value symbol table block");
768 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000769 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000770 if (Code == bitc::ENTER_SUBBLOCK) {
771 // No known subblocks, always skip them.
772 Stream.ReadSubBlockID();
773 if (Stream.SkipBlock())
774 return Error("Malformed block record");
775 continue;
776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000777
Chris Lattner0b2482a2007-04-23 21:26:05 +0000778 if (Code == bitc::DEFINE_ABBREV) {
779 Stream.ReadAbbrevRecord();
780 continue;
781 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000782
Chris Lattner0b2482a2007-04-23 21:26:05 +0000783 // Read a record.
784 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000785 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000786 default: // Default behavior: unknown type.
787 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000788 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000789 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000790 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000791 unsigned ValueID = Record[0];
792 if (ValueID >= ValueList.size())
793 return Error("Invalid Value ID in VST_ENTRY record");
794 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000796 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000797 ValueName.clear();
798 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000799 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000800 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000801 if (ConvertToString(Record, 1, ValueName))
802 return Error("Invalid VST_BBENTRY record");
803 BasicBlock *BB = getBasicBlock(Record[0]);
804 if (BB == 0)
805 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000807 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000808 ValueName.clear();
809 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000810 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000811 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000812 }
813}
814
Devang Patele54abc92009-07-22 17:43:22 +0000815bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000816 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000817
818 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
819 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000820
Devang Patele54abc92009-07-22 17:43:22 +0000821 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000822
Devang Patele54abc92009-07-22 17:43:22 +0000823 // Read all the records.
824 while (1) {
825 unsigned Code = Stream.ReadCode();
826 if (Code == bitc::END_BLOCK) {
827 if (Stream.ReadBlockEnd())
828 return Error("Error at end of PARAMATTR block");
829 return false;
830 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000831
Devang Patele54abc92009-07-22 17:43:22 +0000832 if (Code == bitc::ENTER_SUBBLOCK) {
833 // No known subblocks, always skip them.
834 Stream.ReadSubBlockID();
835 if (Stream.SkipBlock())
836 return Error("Malformed block record");
837 continue;
838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Devang Patele54abc92009-07-22 17:43:22 +0000840 if (Code == bitc::DEFINE_ABBREV) {
841 Stream.ReadAbbrevRecord();
842 continue;
843 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000844
Victor Hernandez24e64df2010-01-10 07:14:18 +0000845 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000846 // Read a record.
847 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000848 Code = Stream.ReadRecord(Code, Record);
849 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000850 default: // Default behavior: ignore.
851 break;
Devang Patelaa993142009-07-29 22:34:41 +0000852 case bitc::METADATA_NAME: {
853 // Read named of the named metadata.
854 unsigned NameLength = Record.size();
855 SmallString<8> Name;
856 Name.resize(NameLength);
857 for (unsigned i = 0; i != NameLength; ++i)
858 Name[i] = Record[i];
859 Record.clear();
860 Code = Stream.ReadCode();
861
Chris Lattner9d61dd92011-06-17 17:50:30 +0000862 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000863 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000864 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000865
866 // Read named metadata elements.
867 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000868 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000869 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000870 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
871 if (MD == 0)
872 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000873 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000874 }
Devang Patelaa993142009-07-29 22:34:41 +0000875 break;
876 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000877 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000878 IsFunctionLocal = true;
879 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000880 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000881 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000882 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000883
Devang Patel104cf9e2009-07-23 01:07:34 +0000884 unsigned Size = Record.size();
885 SmallVector<Value*, 8> Elts;
886 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000887 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000888 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000889 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000890 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000891 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000892 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
893 else
894 Elts.push_back(NULL);
895 }
Jay Foadec9186b2011-04-21 19:59:31 +0000896 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000897 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000898 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000899 break;
900 }
Devang Patele54abc92009-07-22 17:43:22 +0000901 case bitc::METADATA_STRING: {
902 unsigned MDStringLength = Record.size();
903 SmallString<8> String;
904 String.resize(MDStringLength);
905 for (unsigned i = 0; i != MDStringLength; ++i)
906 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000907 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000908 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000909 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000910 break;
911 }
Devang Patele8e02132009-09-18 19:26:43 +0000912 case bitc::METADATA_KIND: {
913 unsigned RecordLength = Record.size();
914 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000915 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000916 SmallString<8> Name;
917 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000918 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000919 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000920 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000921
Chris Lattner08113472009-12-29 09:01:33 +0000922 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000923 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
924 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000925 break;
926 }
Devang Patele54abc92009-07-22 17:43:22 +0000927 }
928 }
929}
930
Chris Lattner0eef0802007-04-24 04:04:35 +0000931/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
932/// the LSB for dense VBR encoding.
933static uint64_t DecodeSignRotatedValue(uint64_t V) {
934 if ((V & 1) == 0)
935 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000937 return -(V >> 1);
938 // There is no such thing as -0 with integers. "-0" really means MININT.
939 return 1ULL << 63;
940}
941
Chris Lattner07d98b42007-04-26 02:46:40 +0000942/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
943/// values and aliases that we can.
944bool BitcodeReader::ResolveGlobalAndAliasInits() {
945 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
946 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000947
Chris Lattner07d98b42007-04-26 02:46:40 +0000948 GlobalInitWorklist.swap(GlobalInits);
949 AliasInitWorklist.swap(AliasInits);
950
951 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000952 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000953 if (ValID >= ValueList.size()) {
954 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000955 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000956 } else {
957 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
958 GlobalInitWorklist.back().first->setInitializer(C);
959 else
960 return Error("Global variable initializer is not a constant!");
961 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000963 }
964
965 while (!AliasInitWorklist.empty()) {
966 unsigned ValID = AliasInitWorklist.back().second;
967 if (ValID >= ValueList.size()) {
968 AliasInits.push_back(AliasInitWorklist.back());
969 } else {
970 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000971 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000972 else
973 return Error("Alias initializer is not a constant!");
974 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000975 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000976 }
977 return false;
978}
979
Chris Lattner86697142007-05-01 05:01:34 +0000980bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000981 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000982 return Error("Malformed block record");
983
984 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000985
Chris Lattnere16504e2007-04-24 03:30:34 +0000986 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000987 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000988 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000989 while (1) {
990 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000991 if (Code == bitc::END_BLOCK)
992 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000993
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 if (Code == bitc::ENTER_SUBBLOCK) {
995 // No known subblocks, always skip them.
996 Stream.ReadSubBlockID();
997 if (Stream.SkipBlock())
998 return Error("Malformed block record");
999 continue;
1000 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001001
Chris Lattnere16504e2007-04-24 03:30:34 +00001002 if (Code == bitc::DEFINE_ABBREV) {
1003 Stream.ReadAbbrevRecord();
1004 continue;
1005 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001006
Chris Lattnere16504e2007-04-24 03:30:34 +00001007 // Read a record.
1008 Record.clear();
1009 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001010 unsigned BitCode = Stream.ReadRecord(Code, Record);
1011 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001012 default: // Default behavior: unknown constant
1013 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001014 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001015 break;
1016 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1017 if (Record.empty())
1018 return Error("Malformed CST_SETTYPE record");
1019 if (Record[0] >= TypeList.size())
1020 return Error("Invalid Type ID in CST_SETTYPE record");
1021 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001022 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001023 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001024 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001025 break;
1026 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001027 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001028 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001029 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001030 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001031 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001032 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001033 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001034
Chris Lattner15e6d172007-05-04 19:11:41 +00001035 unsigned NumWords = Record.size();
Stepan Dyatkovskiy1f983832012-05-08 08:33:21 +00001036 SmallVector<uint64_t, 8> Words;
1037 Words.resize(NumWords);
1038 for (unsigned i = 0; i != NumWords; ++i)
1039 Words[i] = DecodeSignRotatedValue(Record[i]);
1040 V = ConstantInt::get(Context,
1041 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1042 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001043 break;
1044 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001045 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001046 if (Record.empty())
1047 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001048 if (CurTy->isHalfTy())
1049 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1050 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001051 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001052 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001053 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001054 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001055 // Bits are not stored the same way as a normal i80 APInt, compensate.
1056 uint64_t Rearrange[2];
1057 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1058 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001059 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001060 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001061 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001062 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001063 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001064 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001065 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001066 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001067 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001068
Chris Lattner15e6d172007-05-04 19:11:41 +00001069 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1070 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001071 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001072
Chris Lattner15e6d172007-05-04 19:11:41 +00001073 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001074 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001075
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001076 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001077 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001078 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001079 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001080 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001081 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1082 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001083 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001084 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001085 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001086 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1087 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001088 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001089 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001090 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001091 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001092 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001093 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001094 break;
1095 }
Chris Lattner2237f842012-02-05 02:41:35 +00001096 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001097 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1098 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001099 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001100
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001101 unsigned Size = Record.size();
Chris Lattner2237f842012-02-05 02:41:35 +00001102 SmallString<16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001103 for (unsigned i = 0; i != Size; ++i)
Chris Lattner2237f842012-02-05 02:41:35 +00001104 Elts.push_back(Record[i]);
1105 V = ConstantDataArray::getString(Context, Elts,
1106 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001107 break;
1108 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001109 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1110 if (Record.empty())
1111 return Error("Invalid CST_DATA record");
1112
1113 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1114 unsigned Size = Record.size();
1115
1116 if (EltTy->isIntegerTy(8)) {
1117 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1118 if (isa<VectorType>(CurTy))
1119 V = ConstantDataVector::get(Context, Elts);
1120 else
1121 V = ConstantDataArray::get(Context, Elts);
1122 } else if (EltTy->isIntegerTy(16)) {
1123 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1124 if (isa<VectorType>(CurTy))
1125 V = ConstantDataVector::get(Context, Elts);
1126 else
1127 V = ConstantDataArray::get(Context, Elts);
1128 } else if (EltTy->isIntegerTy(32)) {
1129 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1130 if (isa<VectorType>(CurTy))
1131 V = ConstantDataVector::get(Context, Elts);
1132 else
1133 V = ConstantDataArray::get(Context, Elts);
1134 } else if (EltTy->isIntegerTy(64)) {
1135 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1136 if (isa<VectorType>(CurTy))
1137 V = ConstantDataVector::get(Context, Elts);
1138 else
1139 V = ConstantDataArray::get(Context, Elts);
1140 } else if (EltTy->isFloatTy()) {
1141 SmallVector<float, 16> Elts;
1142 for (unsigned i = 0; i != Size; ++i) {
1143 union { uint32_t I; float F; };
1144 I = Record[i];
1145 Elts.push_back(F);
1146 }
1147 if (isa<VectorType>(CurTy))
1148 V = ConstantDataVector::get(Context, Elts);
1149 else
1150 V = ConstantDataArray::get(Context, Elts);
1151 } else if (EltTy->isDoubleTy()) {
1152 SmallVector<double, 16> Elts;
1153 for (unsigned i = 0; i != Size; ++i) {
1154 union { uint64_t I; double F; };
1155 I = Record[i];
1156 Elts.push_back(F);
1157 }
1158 if (isa<VectorType>(CurTy))
1159 V = ConstantDataVector::get(Context, Elts);
1160 else
1161 V = ConstantDataArray::get(Context, Elts);
1162 } else {
1163 return Error("Unknown element type in CE_DATA");
1164 }
1165 break;
1166 }
1167
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001168 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1169 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1170 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001171 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001172 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001173 } else {
1174 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1175 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001176 unsigned Flags = 0;
1177 if (Record.size() >= 4) {
1178 if (Opc == Instruction::Add ||
1179 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001180 Opc == Instruction::Mul ||
1181 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001182 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1183 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1184 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1185 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001186 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001187 Opc == Instruction::UDiv ||
1188 Opc == Instruction::LShr ||
1189 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001190 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001191 Flags |= SDivOperator::IsExact;
1192 }
1193 }
1194 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001195 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001196 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001197 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001198 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1199 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1200 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001201 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001202 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001203 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001204 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001205 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001206 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001207 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001208 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001209 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001210 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001211 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001213 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001214 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001215 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001216 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001217 if (!ElTy) return Error("Invalid CE_GEP record");
1218 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1219 }
Jay Foaddab3d292011-07-21 14:31:17 +00001220 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001221 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1222 BitCode ==
1223 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001224 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001225 }
1226 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1227 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001228 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001229 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001230 ValueList.getConstantFwdRef(Record[1],CurTy),
1231 ValueList.getConstantFwdRef(Record[2],CurTy));
1232 break;
1233 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1234 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001235 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1237 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1238 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001239 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001240 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001241 break;
1242 }
1243 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001244 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001245 if (Record.size() < 3 || OpTy == 0)
1246 return Error("Invalid CE_INSERTELT record");
1247 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1248 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1249 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001250 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001251 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001252 break;
1253 }
1254 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001255 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001256 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001257 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001258 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1259 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001260 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001261 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001262 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001263 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001264 break;
1265 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001266 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001267 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1268 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001269 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001270 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1271 return Error("Invalid CE_SHUFVEC_EX record");
1272 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1273 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001274 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001275 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001276 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001277 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001278 break;
1279 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001280 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1281 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001283 if (OpTy == 0) return Error("Invalid CE_CMP record");
1284 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1285 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1286
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001287 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001288 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001289 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001290 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001291 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001292 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001293 case bitc::CST_CODE_INLINEASM: {
1294 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1295 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001296 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001297 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001298 unsigned AsmStrSize = Record[1];
1299 if (2+AsmStrSize >= Record.size())
1300 return Error("Invalid INLINEASM record");
1301 unsigned ConstStrSize = Record[2+AsmStrSize];
1302 if (3+AsmStrSize+ConstStrSize > Record.size())
1303 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001304
Chris Lattner2bce93a2007-05-06 01:58:20 +00001305 for (unsigned i = 0; i != AsmStrSize; ++i)
1306 AsmStr += (char)Record[2+i];
1307 for (unsigned i = 0; i != ConstStrSize; ++i)
1308 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001309 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001310 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001311 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001312 break;
1313 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001314 case bitc::CST_CODE_BLOCKADDRESS:{
1315 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001316 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001317 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1318 Function *Fn =
1319 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1320 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1321
1322 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1323 Type::getInt8Ty(Context),
1324 false, GlobalValue::InternalLinkage,
1325 0, "");
1326 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1327 V = FwdRef;
1328 break;
1329 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001330 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001331
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001332 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001333 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001334 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001335
Chris Lattnerea693df2008-08-21 02:34:16 +00001336 if (NextCstNo != ValueList.size())
1337 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001338
Chris Lattnerea693df2008-08-21 02:34:16 +00001339 if (Stream.ReadBlockEnd())
1340 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001341
Chris Lattnerea693df2008-08-21 02:34:16 +00001342 // Once all the constants have been read, go through and resolve forward
1343 // references.
1344 ValueList.ResolveConstantForwardRefs();
1345 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001346}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001347
Chad Rosiercbbb0962011-12-07 21:44:12 +00001348bool BitcodeReader::ParseUseLists() {
1349 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1350 return Error("Malformed block record");
1351
1352 SmallVector<uint64_t, 64> Record;
1353
1354 // Read all the records.
1355 while (1) {
1356 unsigned Code = Stream.ReadCode();
1357 if (Code == bitc::END_BLOCK) {
1358 if (Stream.ReadBlockEnd())
1359 return Error("Error at end of use-list table block");
1360 return false;
1361 }
1362
1363 if (Code == bitc::ENTER_SUBBLOCK) {
1364 // No known subblocks, always skip them.
1365 Stream.ReadSubBlockID();
1366 if (Stream.SkipBlock())
1367 return Error("Malformed block record");
1368 continue;
1369 }
1370
1371 if (Code == bitc::DEFINE_ABBREV) {
1372 Stream.ReadAbbrevRecord();
1373 continue;
1374 }
1375
1376 // Read a use list record.
1377 Record.clear();
1378 switch (Stream.ReadRecord(Code, Record)) {
1379 default: // Default behavior: unknown type.
1380 break;
1381 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1382 unsigned RecordLength = Record.size();
1383 if (RecordLength < 1)
1384 return Error ("Invalid UseList reader!");
1385 UseListRecords.push_back(Record);
1386 break;
1387 }
1388 }
1389 }
1390}
1391
Chris Lattner980e5aa2007-05-01 05:52:21 +00001392/// RememberAndSkipFunctionBody - When we see the block for a function body,
1393/// remember where it is and then skip it. This lets us lazily deserialize the
1394/// functions.
1395bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001396 // Get the function we are talking about.
1397 if (FunctionsWithBodies.empty())
1398 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
Chris Lattner48f84872007-05-01 04:59:48 +00001400 Function *Fn = FunctionsWithBodies.back();
1401 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402
Chris Lattner48f84872007-05-01 04:59:48 +00001403 // Save the current stream state.
1404 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001405 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001406
Chris Lattner48f84872007-05-01 04:59:48 +00001407 // Skip over the function block for now.
1408 if (Stream.SkipBlock())
1409 return Error("Malformed block record");
1410 return false;
1411}
1412
Derek Schuff2ea93872012-02-06 22:30:29 +00001413bool BitcodeReader::GlobalCleanup() {
1414 // Patch the initializers for globals and aliases up.
1415 ResolveGlobalAndAliasInits();
1416 if (!GlobalInits.empty() || !AliasInits.empty())
1417 return Error("Malformed global initializer set");
1418
1419 // Look for intrinsic functions which need to be upgraded at some point
1420 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1421 FI != FE; ++FI) {
1422 Function *NewFn;
1423 if (UpgradeIntrinsicFunction(FI, NewFn))
1424 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1425 }
1426
1427 // Look for global variables which need to be renamed.
1428 for (Module::global_iterator
1429 GI = TheModule->global_begin(), GE = TheModule->global_end();
1430 GI != GE; ++GI)
1431 UpgradeGlobalVariable(GI);
1432 // Force deallocation of memory for these vectors to favor the client that
1433 // want lazy deserialization.
1434 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1435 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1436 return false;
1437}
1438
1439bool BitcodeReader::ParseModule(bool Resume) {
1440 if (Resume)
1441 Stream.JumpToBit(NextUnreadBit);
1442 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001443 return Error("Malformed block record");
1444
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001445 SmallVector<uint64_t, 64> Record;
1446 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001447 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001448
1449 // Read all the records for this module.
1450 while (!Stream.AtEndOfStream()) {
1451 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001452 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001453 if (Stream.ReadBlockEnd())
1454 return Error("Error at end of module block");
1455
Derek Schuff2ea93872012-02-06 22:30:29 +00001456 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001457 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001458
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001459 if (Code == bitc::ENTER_SUBBLOCK) {
1460 switch (Stream.ReadSubBlockID()) {
1461 default: // Skip unknown content.
1462 if (Stream.SkipBlock())
1463 return Error("Malformed block record");
1464 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001465 case bitc::BLOCKINFO_BLOCK_ID:
1466 if (Stream.ReadBlockInfoBlock())
1467 return Error("Malformed BlockInfoBlock");
1468 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001469 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001470 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001471 return true;
1472 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001473 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001474 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001475 return true;
1476 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001477 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001478 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001479 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001480 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001481 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001482 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001483 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001484 return true;
1485 break;
Devang Patele54abc92009-07-22 17:43:22 +00001486 case bitc::METADATA_BLOCK_ID:
1487 if (ParseMetadata())
1488 return true;
1489 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001490 case bitc::FUNCTION_BLOCK_ID:
1491 // If this is the first function body we've seen, reverse the
1492 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001493 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001494 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001495 if (GlobalCleanup())
1496 return true;
1497 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001498 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattner980e5aa2007-05-01 05:52:21 +00001500 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001501 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001502 // For streaming bitcode, suspend parsing when we reach the function
1503 // bodies. Subsequent materialization calls will resume it when
1504 // necessary. For streaming, the function bodies must be at the end of
1505 // the bitcode. If the bitcode file is old, the symbol table will be
1506 // at the end instead and will not have been seen yet. In this case,
1507 // just finish the parse now.
1508 if (LazyStreamer && SeenValueSymbolTable) {
1509 NextUnreadBit = Stream.GetCurrentBitNo();
1510 return false;
1511 }
Chris Lattner48f84872007-05-01 04:59:48 +00001512 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.
Derek Schuff2ea93872012-02-06 22:30:29 +00001670 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001671 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001672 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1673 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001674 break;
1675 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001676 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001677 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001678 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001679 if (Record.size() < 3)
1680 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001681 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001682 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001683 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001684 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Chris Lattner07d98b42007-04-26 02:46:40 +00001686 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1687 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001688 // Old bitcode files didn't have visibility field.
1689 if (Record.size() > 3)
1690 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001691 ValueList.push_back(NewGA);
1692 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1693 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001694 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001695 /// MODULE_CODE_PURGEVALS: [numvals]
1696 case bitc::MODULE_CODE_PURGEVALS:
1697 // Trim down the value list to the specified size.
1698 if (Record.size() < 1 || Record[0] > ValueList.size())
1699 return Error("Invalid MODULE_PURGEVALS record");
1700 ValueList.shrinkTo(Record[0]);
1701 break;
1702 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001703 Record.clear();
1704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001705
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001706 return Error("Premature end of bitstream");
1707}
1708
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001709bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001710 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Derek Schuff2ea93872012-02-06 22:30:29 +00001712 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001713
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001714 // Sniff for the signature.
1715 if (Stream.Read(8) != 'B' ||
1716 Stream.Read(8) != 'C' ||
1717 Stream.Read(4) != 0x0 ||
1718 Stream.Read(4) != 0xC ||
1719 Stream.Read(4) != 0xE ||
1720 Stream.Read(4) != 0xD)
1721 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001722
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001723 // We expect a number of well-defined blocks, though we don't necessarily
1724 // need to understand them all.
1725 while (!Stream.AtEndOfStream()) {
1726 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001727
Rafael Espindolac9687b32011-05-26 18:59:54 +00001728 if (Code != bitc::ENTER_SUBBLOCK) {
1729
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001730 // The ranlib in xcode 4 will align archive members by appending newlines
1731 // to the end of them. If this file size is a multiple of 4 but not 8, we
1732 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001733 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1734 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1735 Stream.AtEndOfStream())
1736 return false;
1737
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001738 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001741 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001742
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001743 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001744 switch (BlockID) {
1745 case bitc::BLOCKINFO_BLOCK_ID:
1746 if (Stream.ReadBlockInfoBlock())
1747 return Error("Malformed BlockInfoBlock");
1748 break;
1749 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001750 // Reject multiple MODULE_BLOCK's in a single bitstream.
1751 if (TheModule)
1752 return Error("Multiple MODULE_BLOCKs in same stream");
1753 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001754 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001755 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001756 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001757 break;
1758 default:
1759 if (Stream.SkipBlock())
1760 return Error("Malformed block record");
1761 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001762 }
1763 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001764
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001765 return false;
1766}
Chris Lattnerc453f762007-04-29 07:54:31 +00001767
Bill Wendling34711742010-10-06 01:22:42 +00001768bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1769 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1770 return Error("Malformed block record");
1771
1772 SmallVector<uint64_t, 64> Record;
1773
1774 // Read all the records for this module.
1775 while (!Stream.AtEndOfStream()) {
1776 unsigned Code = Stream.ReadCode();
1777 if (Code == bitc::END_BLOCK) {
1778 if (Stream.ReadBlockEnd())
1779 return Error("Error at end of module block");
1780
1781 return false;
1782 }
1783
1784 if (Code == bitc::ENTER_SUBBLOCK) {
1785 switch (Stream.ReadSubBlockID()) {
1786 default: // Skip unknown content.
1787 if (Stream.SkipBlock())
1788 return Error("Malformed block record");
1789 break;
1790 }
1791 continue;
1792 }
1793
1794 if (Code == bitc::DEFINE_ABBREV) {
1795 Stream.ReadAbbrevRecord();
1796 continue;
1797 }
1798
1799 // Read a record.
1800 switch (Stream.ReadRecord(Code, Record)) {
1801 default: break; // Default behavior, ignore unknown content.
1802 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1803 if (Record.size() < 1)
1804 return Error("Malformed MODULE_CODE_VERSION");
1805 // Only version #0 is supported so far.
1806 if (Record[0] != 0)
1807 return Error("Unknown bitstream version!");
1808 break;
1809 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1810 std::string S;
1811 if (ConvertToString(Record, 0, S))
1812 return Error("Invalid MODULE_CODE_TRIPLE record");
1813 Triple = S;
1814 break;
1815 }
1816 }
1817 Record.clear();
1818 }
1819
1820 return Error("Premature end of bitstream");
1821}
1822
1823bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001824 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001825
1826 // Sniff for the signature.
1827 if (Stream.Read(8) != 'B' ||
1828 Stream.Read(8) != 'C' ||
1829 Stream.Read(4) != 0x0 ||
1830 Stream.Read(4) != 0xC ||
1831 Stream.Read(4) != 0xE ||
1832 Stream.Read(4) != 0xD)
1833 return Error("Invalid bitcode signature");
1834
1835 // We expect a number of well-defined blocks, though we don't necessarily
1836 // need to understand them all.
1837 while (!Stream.AtEndOfStream()) {
1838 unsigned Code = Stream.ReadCode();
1839
1840 if (Code != bitc::ENTER_SUBBLOCK)
1841 return Error("Invalid record at top-level");
1842
1843 unsigned BlockID = Stream.ReadSubBlockID();
1844
1845 // We only know the MODULE subblock ID.
1846 switch (BlockID) {
1847 case bitc::MODULE_BLOCK_ID:
1848 if (ParseModuleTriple(Triple))
1849 return true;
1850 break;
1851 default:
1852 if (Stream.SkipBlock())
1853 return Error("Malformed block record");
1854 break;
1855 }
1856 }
1857
1858 return false;
1859}
1860
Devang Patele8e02132009-09-18 19:26:43 +00001861/// ParseMetadataAttachment - Parse metadata attachments.
1862bool BitcodeReader::ParseMetadataAttachment() {
1863 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1864 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Devang Patele8e02132009-09-18 19:26:43 +00001866 SmallVector<uint64_t, 64> Record;
1867 while(1) {
1868 unsigned Code = Stream.ReadCode();
1869 if (Code == bitc::END_BLOCK) {
1870 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001872 break;
1873 }
1874 if (Code == bitc::DEFINE_ABBREV) {
1875 Stream.ReadAbbrevRecord();
1876 continue;
1877 }
1878 // Read a metadata attachment record.
1879 Record.clear();
1880 switch (Stream.ReadRecord(Code, Record)) {
1881 default: // Default behavior: ignore.
1882 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001883 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001884 unsigned RecordLength = Record.size();
1885 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001887 Instruction *Inst = InstructionList[Record[0]];
1888 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001889 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001890 DenseMap<unsigned, unsigned>::iterator I =
1891 MDKindMap.find(Kind);
1892 if (I == MDKindMap.end())
1893 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001895 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001896 }
1897 break;
1898 }
1899 }
1900 }
1901 return false;
1902}
Chris Lattner48f84872007-05-01 04:59:48 +00001903
Chris Lattner980e5aa2007-05-01 05:52:21 +00001904/// ParseFunctionBody - Lazily parse the specified function body block.
1905bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001906 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001907 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Nick Lewycky9a49f152010-02-25 08:30:17 +00001909 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001910 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001911 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Chris Lattner980e5aa2007-05-01 05:52:21 +00001913 // Add all the function arguments to the value table.
1914 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1915 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001917 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001918 BasicBlock *CurBB = 0;
1919 unsigned CurBBNo = 0;
1920
Chris Lattnera6245242010-04-03 02:17:50 +00001921 DebugLoc LastLoc;
1922
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 // Read all the records.
1924 SmallVector<uint64_t, 64> Record;
1925 while (1) {
1926 unsigned Code = Stream.ReadCode();
1927 if (Code == bitc::END_BLOCK) {
1928 if (Stream.ReadBlockEnd())
1929 return Error("Error at end of function block");
1930 break;
1931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 if (Code == bitc::ENTER_SUBBLOCK) {
1934 switch (Stream.ReadSubBlockID()) {
1935 default: // Skip unknown content.
1936 if (Stream.SkipBlock())
1937 return Error("Malformed block record");
1938 break;
1939 case bitc::CONSTANTS_BLOCK_ID:
1940 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001941 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001942 break;
1943 case bitc::VALUE_SYMTAB_BLOCK_ID:
1944 if (ParseValueSymbolTable()) return true;
1945 break;
Devang Patele8e02132009-09-18 19:26:43 +00001946 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947 if (ParseMetadataAttachment()) return true;
1948 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001949 case bitc::METADATA_BLOCK_ID:
1950 if (ParseMetadata()) return true;
1951 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001952 }
1953 continue;
1954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattner980e5aa2007-05-01 05:52:21 +00001956 if (Code == bitc::DEFINE_ABBREV) {
1957 Stream.ReadAbbrevRecord();
1958 continue;
1959 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960
Chris Lattner980e5aa2007-05-01 05:52:21 +00001961 // Read a record.
1962 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001963 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001964 unsigned BitCode = Stream.ReadRecord(Code, Record);
1965 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001966 default: // Default behavior: reject
1967 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001968 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001969 if (Record.size() < 1 || Record[0] == 0)
1970 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001972 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001973 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001974 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001975 CurBB = FunctionBBs[0];
1976 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001977
1978 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1979 // This record indicates that the last instruction is at the same
1980 // location as the previous instruction with a location.
1981 I = 0;
1982
1983 // Get the last instruction emitted.
1984 if (CurBB && !CurBB->empty())
1985 I = &CurBB->back();
1986 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1987 !FunctionBBs[CurBBNo-1]->empty())
1988 I = &FunctionBBs[CurBBNo-1]->back();
1989
1990 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1991 I->setDebugLoc(LastLoc);
1992 I = 0;
1993 continue;
1994
Chris Lattner4f6bab92011-06-17 18:17:37 +00001995 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001996 I = 0; // Get the last instruction emitted.
1997 if (CurBB && !CurBB->empty())
1998 I = &CurBB->back();
1999 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000 !FunctionBBs[CurBBNo-1]->empty())
2001 I = &FunctionBBs[CurBBNo-1]->back();
2002 if (I == 0 || Record.size() < 4)
2003 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2004
2005 unsigned Line = Record[0], Col = Record[1];
2006 unsigned ScopeID = Record[2], IAID = Record[3];
2007
2008 MDNode *Scope = 0, *IA = 0;
2009 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2010 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2011 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2012 I->setDebugLoc(LastLoc);
2013 I = 0;
2014 continue;
2015 }
2016
Chris Lattnerabfbf852007-05-06 00:21:25 +00002017 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2018 unsigned OpNum = 0;
2019 Value *LHS, *RHS;
2020 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2021 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002022 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002023 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Dan Gohman1224c382009-07-20 21:19:07 +00002025 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002026 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002027 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002028 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002029 if (OpNum < Record.size()) {
2030 if (Opc == Instruction::Add ||
2031 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002032 Opc == Instruction::Mul ||
2033 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002034 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002035 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002036 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002037 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002038 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002039 Opc == Instruction::UDiv ||
2040 Opc == Instruction::LShr ||
2041 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002042 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002043 cast<BinaryOperator>(I)->setIsExact(true);
2044 }
2045 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002046 break;
2047 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002048 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2049 unsigned OpNum = 0;
2050 Value *Op;
2051 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2052 OpNum+2 != Record.size())
2053 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002055 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002056 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2057 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002058 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002059 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002060 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002061 break;
2062 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002063 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002064 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002065 unsigned OpNum = 0;
2066 Value *BasePtr;
2067 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002068 return Error("Invalid GEP record");
2069
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002070 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002071 while (OpNum != Record.size()) {
2072 Value *Op;
2073 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002074 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002075 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002076 }
2077
Jay Foada9203102011-07-25 09:48:08 +00002078 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002079 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002080 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002081 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002082 break;
2083 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002085 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2086 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002087 unsigned OpNum = 0;
2088 Value *Agg;
2089 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2090 return Error("Invalid EXTRACTVAL record");
2091
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002092 SmallVector<unsigned, 4> EXTRACTVALIdx;
2093 for (unsigned RecSize = Record.size();
2094 OpNum != RecSize; ++OpNum) {
2095 uint64_t Index = Record[OpNum];
2096 if ((unsigned)Index != Index)
2097 return Error("Invalid EXTRACTVAL index");
2098 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002099 }
2100
Jay Foadfc6d3a42011-07-13 10:26:04 +00002101 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002102 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002103 break;
2104 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002105
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002106 case bitc::FUNC_CODE_INST_INSERTVAL: {
2107 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002108 unsigned OpNum = 0;
2109 Value *Agg;
2110 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2111 return Error("Invalid INSERTVAL record");
2112 Value *Val;
2113 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2114 return Error("Invalid INSERTVAL record");
2115
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002116 SmallVector<unsigned, 4> INSERTVALIdx;
2117 for (unsigned RecSize = Record.size();
2118 OpNum != RecSize; ++OpNum) {
2119 uint64_t Index = Record[OpNum];
2120 if ((unsigned)Index != Index)
2121 return Error("Invalid INSERTVAL index");
2122 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002123 }
2124
Jay Foadfc6d3a42011-07-13 10:26:04 +00002125 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002126 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002127 break;
2128 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002129
Chris Lattnerabfbf852007-05-06 00:21:25 +00002130 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002131 // obsolete form of select
2132 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002133 unsigned OpNum = 0;
2134 Value *TrueVal, *FalseVal, *Cond;
2135 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2136 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002137 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002138 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002140 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002141 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002142 break;
2143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002145 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2146 // new form of select
2147 // handles select i1 or select [N x i1]
2148 unsigned OpNum = 0;
2149 Value *TrueVal, *FalseVal, *Cond;
2150 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2151 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2152 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2153 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002154
2155 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002156 if (VectorType* vector_type =
2157 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002158 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002159 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002160 return Error("Invalid SELECT condition type");
2161 } else {
2162 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002164 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002165 }
2166
Gabor Greif051a9502008-04-06 20:25:17 +00002167 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002168 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002169 break;
2170 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002171
Chris Lattner01ff65f2007-05-02 05:16:49 +00002172 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002173 unsigned OpNum = 0;
2174 Value *Vec, *Idx;
2175 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002176 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002177 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002178 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002179 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002180 break;
2181 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002182
Chris Lattner01ff65f2007-05-02 05:16:49 +00002183 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002184 unsigned OpNum = 0;
2185 Value *Vec, *Elt, *Idx;
2186 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002187 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002188 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002189 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002190 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002191 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002192 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002193 break;
2194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002195
Chris Lattnerabfbf852007-05-06 00:21:25 +00002196 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2197 unsigned OpNum = 0;
2198 Value *Vec1, *Vec2, *Mask;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2200 getValue(Record, OpNum, Vec1->getType(), Vec2))
2201 return Error("Invalid SHUFFLEVEC record");
2202
Mon P Wangaeb06d22008-11-10 04:46:22 +00002203 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002204 return Error("Invalid SHUFFLEVEC record");
2205 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002206 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002207 break;
2208 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002209
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002210 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2211 // Old form of ICmp/FCmp returning bool
2212 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2213 // both legal on vectors but had different behaviour.
2214 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2215 // FCmp/ICmp returning bool or vector of bool
2216
Chris Lattner7337ab92007-05-06 00:00:00 +00002217 unsigned OpNum = 0;
2218 Value *LHS, *RHS;
2219 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2220 getValue(Record, OpNum, LHS->getType(), RHS) ||
2221 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002222 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002224 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002225 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002226 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002227 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002228 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002229 break;
2230 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002231
Chris Lattner231cbcb2007-05-02 04:27:25 +00002232 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002233 {
2234 unsigned Size = Record.size();
2235 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002237 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002238 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002239 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002240
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002241 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002242 Value *Op = NULL;
2243 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2244 return Error("Invalid RET record");
2245 if (OpNum != Record.size())
2246 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002247
Chris Lattner96a74c52011-06-17 18:09:11 +00002248 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002250 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002251 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002252 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002253 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002254 return Error("Invalid BR record");
2255 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2256 if (TrueDest == 0)
2257 return Error("Invalid BR record");
2258
Devang Patele8e02132009-09-18 19:26:43 +00002259 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002260 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002261 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002262 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002263 else {
2264 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002265 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002266 if (FalseDest == 0 || Cond == 0)
2267 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002268 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002269 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002270 }
2271 break;
2272 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002273 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002274 if (Record.size() < 3 || (Record.size() & 1) == 0)
2275 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002276 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002277 Value *Cond = getFnValueByID(Record[1], OpTy);
2278 BasicBlock *Default = getBasicBlock(Record[2]);
2279 if (OpTy == 0 || Cond == 0 || Default == 0)
2280 return Error("Invalid SWITCH record");
2281 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002282 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002283 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002284 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002285 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002286 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2287 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2288 if (CaseVal == 0 || DestBB == 0) {
2289 delete SI;
2290 return Error("Invalid SWITCH record!");
2291 }
2292 SI->addCase(CaseVal, DestBB);
2293 }
2294 I = SI;
2295 break;
2296 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002297 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002298 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002299 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002300 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002301 Value *Address = getFnValueByID(Record[1], OpTy);
2302 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002303 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002304 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002305 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002306 InstructionList.push_back(IBI);
2307 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2308 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2309 IBI->addDestination(DestBB);
2310 } else {
2311 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002312 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002313 }
2314 }
2315 I = IBI;
2316 break;
2317 }
2318
Duncan Sandsdc024672007-11-27 13:23:08 +00002319 case bitc::FUNC_CODE_INST_INVOKE: {
2320 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002321 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002322 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002323 unsigned CCInfo = Record[1];
2324 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2325 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326
Chris Lattnera9bb7132007-05-08 05:38:01 +00002327 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002328 Value *Callee;
2329 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002330 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002331
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002332 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2333 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002334 dyn_cast<FunctionType>(CalleeTy->getElementType());
2335
2336 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002337 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2338 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002339 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002340
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002341 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002342 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2343 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2344 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002345 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002346
Chris Lattner7337ab92007-05-06 00:00:00 +00002347 if (!FTy->isVarArg()) {
2348 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002349 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002350 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002351 // Read type/value pairs for varargs params.
2352 while (OpNum != Record.size()) {
2353 Value *Op;
2354 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2355 return Error("Invalid INVOKE record");
2356 Ops.push_back(Op);
2357 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002359
Jay Foada3efbb12011-07-15 08:37:34 +00002360 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002361 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002362 cast<InvokeInst>(I)->setCallingConv(
2363 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002364 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002365 break;
2366 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002367 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2368 unsigned Idx = 0;
2369 Value *Val = 0;
2370 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2371 return Error("Invalid RESUME record");
2372 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002373 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002374 break;
2375 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002376 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002377 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002378 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002379 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002380 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002381 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002382 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002383 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002384 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002385
Jay Foad3ecfc862011-03-30 11:28:46 +00002386 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002387 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Chris Lattner15e6d172007-05-04 19:11:41 +00002389 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2390 Value *V = getFnValueByID(Record[1+i], Ty);
2391 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002392 if (!V || !BB) return Error("Invalid PHI record");
2393 PN->addIncoming(V, BB);
2394 }
2395 I = PN;
2396 break;
2397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002398
Bill Wendlinge6e88262011-08-12 20:24:12 +00002399 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2400 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2401 unsigned Idx = 0;
2402 if (Record.size() < 4)
2403 return Error("Invalid LANDINGPAD record");
2404 Type *Ty = getTypeByID(Record[Idx++]);
2405 if (!Ty) return Error("Invalid LANDINGPAD record");
2406 Value *PersFn = 0;
2407 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2408 return Error("Invalid LANDINGPAD record");
2409
2410 bool IsCleanup = !!Record[Idx++];
2411 unsigned NumClauses = Record[Idx++];
2412 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2413 LP->setCleanup(IsCleanup);
2414 for (unsigned J = 0; J != NumClauses; ++J) {
2415 LandingPadInst::ClauseType CT =
2416 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2417 Value *Val;
2418
2419 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2420 delete LP;
2421 return Error("Invalid LANDINGPAD record");
2422 }
2423
2424 assert((CT != LandingPadInst::Catch ||
2425 !isa<ArrayType>(Val->getType())) &&
2426 "Catch clause has a invalid type!");
2427 assert((CT != LandingPadInst::Filter ||
2428 isa<ArrayType>(Val->getType())) &&
2429 "Filter clause has invalid type!");
2430 LP->addClause(Val);
2431 }
2432
2433 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002434 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002435 break;
2436 }
2437
Chris Lattner96a74c52011-06-17 18:09:11 +00002438 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2439 if (Record.size() != 4)
2440 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002441 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002442 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002443 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002444 Value *Size = getFnValueByID(Record[2], OpTy);
2445 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002446 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002447 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002448 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002449 break;
2450 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002451 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002452 unsigned OpNum = 0;
2453 Value *Op;
2454 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2455 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002456 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002457
Chris Lattner7337ab92007-05-06 00:00:00 +00002458 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002459 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002460 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002461 }
Eli Friedman21006d42011-08-09 23:02:53 +00002462 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2463 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2464 unsigned OpNum = 0;
2465 Value *Op;
2466 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2467 OpNum+4 != Record.size())
2468 return Error("Invalid LOADATOMIC record");
2469
2470
2471 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2472 if (Ordering == NotAtomic || Ordering == Release ||
2473 Ordering == AcquireRelease)
2474 return Error("Invalid LOADATOMIC record");
2475 if (Ordering != NotAtomic && Record[OpNum] == 0)
2476 return Error("Invalid LOADATOMIC record");
2477 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2478
2479 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2480 Ordering, SynchScope);
2481 InstructionList.push_back(I);
2482 break;
2483 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002484 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002485 unsigned OpNum = 0;
2486 Value *Val, *Ptr;
2487 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002488 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002489 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2490 OpNum+2 != Record.size())
2491 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002492
Christopher Lambfe63fb92007-12-11 08:59:05 +00002493 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002494 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002495 break;
2496 }
Eli Friedman21006d42011-08-09 23:02:53 +00002497 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2498 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2499 unsigned OpNum = 0;
2500 Value *Val, *Ptr;
2501 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2502 getValue(Record, OpNum,
2503 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2504 OpNum+4 != Record.size())
2505 return Error("Invalid STOREATOMIC record");
2506
2507 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002508 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002509 Ordering == AcquireRelease)
2510 return Error("Invalid STOREATOMIC record");
2511 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2512 if (Ordering != NotAtomic && Record[OpNum] == 0)
2513 return Error("Invalid STOREATOMIC record");
2514
2515 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2516 Ordering, SynchScope);
2517 InstructionList.push_back(I);
2518 break;
2519 }
Eli Friedmanff030482011-07-28 21:48:00 +00002520 case bitc::FUNC_CODE_INST_CMPXCHG: {
2521 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2522 unsigned OpNum = 0;
2523 Value *Ptr, *Cmp, *New;
2524 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2525 getValue(Record, OpNum,
2526 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2527 getValue(Record, OpNum,
2528 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2529 OpNum+3 != Record.size())
2530 return Error("Invalid CMPXCHG record");
2531 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002532 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002533 return Error("Invalid CMPXCHG record");
2534 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2535 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2536 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2537 InstructionList.push_back(I);
2538 break;
2539 }
2540 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2541 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2542 unsigned OpNum = 0;
2543 Value *Ptr, *Val;
2544 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2545 getValue(Record, OpNum,
2546 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2547 OpNum+4 != Record.size())
2548 return Error("Invalid ATOMICRMW record");
2549 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2550 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2551 Operation > AtomicRMWInst::LAST_BINOP)
2552 return Error("Invalid ATOMICRMW record");
2553 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002554 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002555 return Error("Invalid ATOMICRMW record");
2556 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2557 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2558 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2559 InstructionList.push_back(I);
2560 break;
2561 }
Eli Friedman47f35132011-07-25 23:16:38 +00002562 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2563 if (2 != Record.size())
2564 return Error("Invalid FENCE record");
2565 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2566 if (Ordering == NotAtomic || Ordering == Unordered ||
2567 Ordering == Monotonic)
2568 return Error("Invalid FENCE record");
2569 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2570 I = new FenceInst(Context, Ordering, SynchScope);
2571 InstructionList.push_back(I);
2572 break;
2573 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002574 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002575 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2576 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002577 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002578
Devang Patel05988662008-09-25 21:00:45 +00002579 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002580 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002581
Chris Lattnera9bb7132007-05-08 05:38:01 +00002582 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002583 Value *Callee;
2584 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2585 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002586
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002587 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2588 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002589 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002590 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002591 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002592
Chris Lattner0579f7f2007-05-03 22:04:19 +00002593 SmallVector<Value*, 16> Args;
2594 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002596 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002597 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002598 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002599 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002600 if (Args.back() == 0) return Error("Invalid CALL record");
2601 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002602
Chris Lattner0579f7f2007-05-03 22:04:19 +00002603 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002604 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002605 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002606 return Error("Invalid CALL record");
2607 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002608 while (OpNum != Record.size()) {
2609 Value *Op;
2610 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2611 return Error("Invalid CALL record");
2612 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002613 }
2614 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002615
Jay Foada3efbb12011-07-15 08:37:34 +00002616 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002617 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002618 cast<CallInst>(I)->setCallingConv(
2619 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002620 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002621 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002622 break;
2623 }
2624 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2625 if (Record.size() < 3)
2626 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002627 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002628 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002629 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002630 if (!OpTy || !Op || !ResTy)
2631 return Error("Invalid VAARG record");
2632 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002633 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002634 break;
2635 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002636 }
2637
2638 // Add instruction to end of current BB. If there is no current BB, reject
2639 // this file.
2640 if (CurBB == 0) {
2641 delete I;
2642 return Error("Invalid instruction with no BB");
2643 }
2644 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002645
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002646 // If this was a terminator instruction, move to the next block.
2647 if (isa<TerminatorInst>(I)) {
2648 ++CurBBNo;
2649 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2650 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002651
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002652 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002653 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002654 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002656
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002657 // Check the function list for unresolved values.
2658 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2659 if (A->getParent() == 0) {
2660 // We found at least one unresolved value. Nuke them all to avoid leaks.
2661 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002662 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002663 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002664 delete A;
2665 }
2666 }
Chris Lattner35a04702007-05-04 03:50:29 +00002667 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002668 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002669 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Dan Gohman064ff3e2010-08-25 20:23:38 +00002671 // FIXME: Check for unresolved forward-declared metadata references
2672 // and clean up leaks.
2673
Chris Lattner50b136d2009-10-28 05:53:48 +00002674 // See if anything took the address of blocks in this function. If so,
2675 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002676 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2677 BlockAddrFwdRefs.find(F);
2678 if (BAFRI != BlockAddrFwdRefs.end()) {
2679 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2680 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2681 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002682 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002683 return Error("Invalid blockaddress block #");
2684
2685 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002686 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002687 FwdRef->eraseFromParent();
2688 }
2689
2690 BlockAddrFwdRefs.erase(BAFRI);
2691 }
2692
Chris Lattner980e5aa2007-05-01 05:52:21 +00002693 // Trim the value list down to the size it was before we parsed this function.
2694 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002695 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002696 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002697 return false;
2698}
2699
Derek Schuff2ea93872012-02-06 22:30:29 +00002700/// FindFunctionInStream - Find the function body in the bitcode stream
2701bool BitcodeReader::FindFunctionInStream(Function *F,
2702 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2703 while (DeferredFunctionInfoIterator->second == 0) {
2704 if (Stream.AtEndOfStream())
2705 return Error("Could not find Function in stream");
2706 // ParseModule will parse the next body in the stream and set its
2707 // position in the DeferredFunctionInfo map.
2708 if (ParseModule(true)) return true;
2709 }
2710 return false;
2711}
2712
Chris Lattnerb348bb82007-05-18 04:02:46 +00002713//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002714// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002715//===----------------------------------------------------------------------===//
2716
2717
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002718bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2719 if (const Function *F = dyn_cast<Function>(GV)) {
2720 return F->isDeclaration() &&
2721 DeferredFunctionInfo.count(const_cast<Function*>(F));
2722 }
2723 return false;
2724}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002726bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2727 Function *F = dyn_cast<Function>(GV);
2728 // If it's not a function or is already material, ignore the request.
2729 if (!F || !F->isMaterializable()) return false;
2730
2731 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002732 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002733 // If its position is recorded as 0, its body is somewhere in the stream
2734 // but we haven't seen it yet.
2735 if (DFII->second == 0)
2736 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002737
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002738 // Move the bit stream to the saved position of the deferred function body.
2739 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Chris Lattnerb348bb82007-05-18 04:02:46 +00002741 if (ParseFunctionBody(F)) {
2742 if (ErrInfo) *ErrInfo = ErrorString;
2743 return true;
2744 }
Chandler Carruth69940402007-08-04 01:51:18 +00002745
2746 // Upgrade any old intrinsic calls in the function.
2747 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2748 E = UpgradedIntrinsics.end(); I != E; ++I) {
2749 if (I->first != I->second) {
2750 for (Value::use_iterator UI = I->first->use_begin(),
2751 UE = I->first->use_end(); UI != UE; ) {
2752 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2753 UpgradeIntrinsicCall(CI, I->second);
2754 }
2755 }
2756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002757
Chris Lattnerb348bb82007-05-18 04:02:46 +00002758 return false;
2759}
2760
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002761bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2762 const Function *F = dyn_cast<Function>(GV);
2763 if (!F || F->isDeclaration())
2764 return false;
2765 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2766}
2767
2768void BitcodeReader::Dematerialize(GlobalValue *GV) {
2769 Function *F = dyn_cast<Function>(GV);
2770 // If this function isn't dematerializable, this is a noop.
2771 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002772 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002773
Chris Lattnerb348bb82007-05-18 04:02:46 +00002774 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Chris Lattnerb348bb82007-05-18 04:02:46 +00002776 // Just forget the function body, we can remat it later.
2777 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002778}
2779
2780
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002781bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2782 assert(M == TheModule &&
2783 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002784 // Iterate over the module, deserializing any functions that are still on
2785 // disk.
2786 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2787 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002788 if (F->isMaterializable() &&
2789 Materialize(F, ErrInfo))
2790 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002791
Derek Schuff0ffe6982012-02-29 00:07:09 +00002792 // At this point, if there are any function bodies, the current bit is
2793 // pointing to the END_BLOCK record after them. Now make sure the rest
2794 // of the bits in the module have been read.
2795 if (NextUnreadBit)
2796 ParseModule(true);
2797
Daniel Dunbara279bc32009-09-20 02:20:51 +00002798 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2799 // delete the old functions to clean up. We can't do this unless the entire
2800 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002801 // with calls to the old function.
2802 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2803 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2804 if (I->first != I->second) {
2805 for (Value::use_iterator UI = I->first->use_begin(),
2806 UE = I->first->use_end(); UI != UE; ) {
2807 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2808 UpgradeIntrinsicCall(CI, I->second);
2809 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002810 if (!I->first->use_empty())
2811 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002812 I->first->eraseFromParent();
2813 }
2814 }
2815 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002816
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002817 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002818}
2819
Derek Schuff2ea93872012-02-06 22:30:29 +00002820bool BitcodeReader::InitStream() {
2821 if (LazyStreamer) return InitLazyStream();
2822 return InitStreamFromBuffer();
2823}
2824
2825bool BitcodeReader::InitStreamFromBuffer() {
2826 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2827 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2828
2829 if (Buffer->getBufferSize() & 3) {
2830 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2831 return Error("Invalid bitcode signature");
2832 else
2833 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2834 }
2835
2836 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2837 // The magic number is 0x0B17C0DE stored in little endian.
2838 if (isBitcodeWrapper(BufPtr, BufEnd))
2839 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2840 return Error("Invalid bitcode wrapper header");
2841
2842 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2843 Stream.init(*StreamFile);
2844
2845 return false;
2846}
2847
2848bool BitcodeReader::InitLazyStream() {
2849 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2850 // see it.
2851 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2852 StreamFile.reset(new BitstreamReader(Bytes));
2853 Stream.init(*StreamFile);
2854
2855 unsigned char buf[16];
2856 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2857 return Error("Bitcode stream must be at least 16 bytes in length");
2858
2859 if (!isBitcode(buf, buf + 16))
2860 return Error("Invalid bitcode signature");
2861
2862 if (isBitcodeWrapper(buf, buf + 4)) {
2863 const unsigned char *bitcodeStart = buf;
2864 const unsigned char *bitcodeEnd = buf + 16;
2865 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2866 Bytes->dropLeadingBytes(bitcodeStart - buf);
2867 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2868 }
2869 return false;
2870}
Chris Lattner48f84872007-05-01 04:59:48 +00002871
Chris Lattnerc453f762007-04-29 07:54:31 +00002872//===----------------------------------------------------------------------===//
2873// External interface
2874//===----------------------------------------------------------------------===//
2875
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002876/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002877///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002878Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2879 LLVMContext& Context,
2880 std::string *ErrMsg) {
2881 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002882 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002883 M->setMaterializer(R);
2884 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002885 if (ErrMsg)
2886 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002887
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002888 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002889 return 0;
2890 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002891 // Have the BitcodeReader dtor delete 'Buffer'.
2892 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002893
2894 R->materializeForwardReferencedFunctions();
2895
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002896 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002897}
2898
Derek Schuff2ea93872012-02-06 22:30:29 +00002899
2900Module *llvm::getStreamedBitcodeModule(const std::string &name,
2901 DataStreamer *streamer,
2902 LLVMContext &Context,
2903 std::string *ErrMsg) {
2904 Module *M = new Module(name, Context);
2905 BitcodeReader *R = new BitcodeReader(streamer, Context);
2906 M->setMaterializer(R);
2907 if (R->ParseBitcodeInto(M)) {
2908 if (ErrMsg)
2909 *ErrMsg = R->getErrorString();
2910 delete M; // Also deletes R.
2911 return 0;
2912 }
2913 R->setBufferOwned(false); // no buffer to delete
2914 return M;
2915}
2916
Chris Lattnerc453f762007-04-29 07:54:31 +00002917/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2918/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002919Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002920 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002921 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2922 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002923
2924 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2925 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002926 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002928 // Read in the entire module, and destroy the BitcodeReader.
2929 if (M->MaterializeAllPermanently(ErrMsg)) {
2930 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002931 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002932 }
Bill Wendling34711742010-10-06 01:22:42 +00002933
Chad Rosiercbbb0962011-12-07 21:44:12 +00002934 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2935 // written. We must defer until the Module has been fully materialized.
2936
Chris Lattnerc453f762007-04-29 07:54:31 +00002937 return M;
2938}
Bill Wendling34711742010-10-06 01:22:42 +00002939
2940std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2941 LLVMContext& Context,
2942 std::string *ErrMsg) {
2943 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2944 // Don't let the BitcodeReader dtor delete 'Buffer'.
2945 R->setBufferOwned(false);
2946
2947 std::string Triple("");
2948 if (R->ParseTriple(Triple))
2949 if (ErrMsg)
2950 *ErrMsg = R->getErrorString();
2951
2952 delete R;
2953 return Triple;
2954}