blob: 4387f09997595facc7b672217de29cc837721d02 [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
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
Devang Patel19c87462008-09-26 22:53:05 +000050 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000051 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000054 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000055}
56
Chris Lattner48c85b82007-05-04 03:30:17 +000057//===----------------------------------------------------------------------===//
58// Helper functions to implement forward reference resolution, etc.
59//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000060
Chris Lattnercaee0dc2007-04-22 06:23:29 +000061/// ConvertToString - Convert a string from a record into an std::string, return
62/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000063template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000064static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000065 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000066 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000068
Chris Lattner15e6d172007-05-04 19:11:41 +000069 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000071 return false;
72}
73
74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 switch (Val) {
76 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::DLLImportLinkage;
83 case 6: return GlobalValue::DLLExportLinkage;
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000087 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000089 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000090 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000091 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000092 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000093 }
94}
95
96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97 switch (Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000101 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000102 }
103}
104
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000105static int GetDecodedCastOpcode(unsigned Val) {
106 switch (Val) {
107 default: return -1;
108 case bitc::CAST_TRUNC : return Instruction::Trunc;
109 case bitc::CAST_ZEXT : return Instruction::ZExt;
110 case bitc::CAST_SEXT : return Instruction::SExt;
111 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
112 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
113 case bitc::CAST_UITOFP : return Instruction::UIToFP;
114 case bitc::CAST_SITOFP : return Instruction::SIToFP;
115 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
116 case bitc::CAST_FPEXT : return Instruction::FPExt;
117 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
118 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
119 case bitc::CAST_BITCAST : return Instruction::BitCast;
120 }
121}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000122static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000123 switch (Val) {
124 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000125 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000126 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000127 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000128 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000129 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000130 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000131 case bitc::BINOP_UDIV: return Instruction::UDiv;
132 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000133 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000134 case bitc::BINOP_UREM: return Instruction::URem;
135 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000136 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000137 case bitc::BINOP_SHL: return Instruction::Shl;
138 case bitc::BINOP_LSHR: return Instruction::LShr;
139 case bitc::BINOP_ASHR: return Instruction::AShr;
140 case bitc::BINOP_AND: return Instruction::And;
141 case bitc::BINOP_OR: return Instruction::Or;
142 case bitc::BINOP_XOR: return Instruction::Xor;
143 }
144}
145
Eli Friedmanff030482011-07-28 21:48:00 +0000146static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
147 switch (Val) {
148 default: return AtomicRMWInst::BAD_BINOP;
149 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
150 case bitc::RMW_ADD: return AtomicRMWInst::Add;
151 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
152 case bitc::RMW_AND: return AtomicRMWInst::And;
153 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
154 case bitc::RMW_OR: return AtomicRMWInst::Or;
155 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
156 case bitc::RMW_MAX: return AtomicRMWInst::Max;
157 case bitc::RMW_MIN: return AtomicRMWInst::Min;
158 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
159 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
160 }
161}
162
Eli Friedman47f35132011-07-25 23:16:38 +0000163static AtomicOrdering GetDecodedOrdering(unsigned Val) {
164 switch (Val) {
165 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
166 case bitc::ORDERING_UNORDERED: return Unordered;
167 case bitc::ORDERING_MONOTONIC: return Monotonic;
168 case bitc::ORDERING_ACQUIRE: return Acquire;
169 case bitc::ORDERING_RELEASE: return Release;
170 case bitc::ORDERING_ACQREL: return AcquireRelease;
171 default: // Map unknown orderings to sequentially-consistent.
172 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
173 }
174}
175
176static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
177 switch (Val) {
178 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
179 default: // Map unknown scopes to cross-thread.
180 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
181 }
182}
183
Gabor Greifefe65362008-05-10 08:32:32 +0000184namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000185namespace {
186 /// @brief A class for maintaining the slot number definition
187 /// as a placeholder for the actual definition for forward constants defs.
188 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000189 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000190 public:
191 // allocate space for exactly one operand
192 void *operator new(size_t s) {
193 return User::operator new(s, 1);
194 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000195 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000196 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000197 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000198 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000199
Chris Lattnerea693df2008-08-21 02:34:16 +0000200 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000201 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000202 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000203 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000204 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000206
207
Gabor Greifefe65362008-05-10 08:32:32 +0000208 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000209 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000210 };
211}
212
Chris Lattner46e77402009-03-31 22:55:09 +0000213// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000214template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000215struct OperandTraits<ConstantPlaceHolder> :
216 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000217};
Gabor Greifefe65362008-05-10 08:32:32 +0000218}
219
Chris Lattner46e77402009-03-31 22:55:09 +0000220
221void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
222 if (Idx == size()) {
223 push_back(V);
224 return;
225 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000226
Chris Lattner46e77402009-03-31 22:55:09 +0000227 if (Idx >= size())
228 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000229
Chris Lattner46e77402009-03-31 22:55:09 +0000230 WeakVH &OldV = ValuePtrs[Idx];
231 if (OldV == 0) {
232 OldV = V;
233 return;
234 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000235
Chris Lattner46e77402009-03-31 22:55:09 +0000236 // Handle constants and non-constants (e.g. instrs) differently for
237 // efficiency.
238 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
239 ResolveConstants.push_back(std::make_pair(PHC, Idx));
240 OldV = V;
241 } else {
242 // If there was a forward reference to this value, replace it.
243 Value *PrevVal = OldV;
244 OldV->replaceAllUsesWith(V);
245 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000246 }
247}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000248
Gabor Greifefe65362008-05-10 08:32:32 +0000249
Chris Lattner522b7b12007-04-24 05:48:56 +0000250Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000251 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000252 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000253 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000254
Chris Lattner46e77402009-03-31 22:55:09 +0000255 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000256 assert(Ty == V->getType() && "Type mismatch in constant table!");
257 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000258 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000259
260 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000261 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000262 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000263 return C;
264}
265
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000266Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000267 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000268 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000269
Chris Lattner46e77402009-03-31 22:55:09 +0000270 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000271 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
272 return V;
273 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000274
Chris Lattner01ff65f2007-05-02 05:16:49 +0000275 // No type specified, must be invalid reference.
276 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000278 // Create and return a placeholder, which will later be RAUW'd.
279 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000280 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000281 return V;
282}
283
Chris Lattnerea693df2008-08-21 02:34:16 +0000284/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
285/// resolves any forward references. The idea behind this is that we sometimes
286/// get constants (such as large arrays) which reference *many* forward ref
287/// constants. Replacing each of these causes a lot of thrashing when
288/// building/reuniquing the constant. Instead of doing this, we look at all the
289/// uses and rewrite all the place holders at once for any constant that uses
290/// a placeholder.
291void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 // binary search.
294 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000295
Chris Lattnerea693df2008-08-21 02:34:16 +0000296 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000299 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000300 Constant *Placeholder = ResolveConstants.back().first;
301 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000302
Chris Lattnerea693df2008-08-21 02:34:16 +0000303 // Loop over all users of the placeholder, updating them to reference the
304 // new value. If they reference more than one placeholder, update them all
305 // at once.
306 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000307 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000308 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000309
Chris Lattnerea693df2008-08-21 02:34:16 +0000310 // If the using object isn't uniqued, just update the operands. This
311 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000312 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000313 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000314 continue;
315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000316
Chris Lattnerea693df2008-08-21 02:34:16 +0000317 // Otherwise, we have a constant that uses the placeholder. Replace that
318 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000319 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000320 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
321 I != E; ++I) {
322 Value *NewOp;
323 if (!isa<ConstantPlaceHolder>(*I)) {
324 // Not a placeholder reference.
325 NewOp = *I;
326 } else if (*I == Placeholder) {
327 // Common case is that it just references this one placeholder.
328 NewOp = RealVal;
329 } else {
330 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000331 ResolveConstantsTy::iterator It =
332 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 std::pair<Constant*, unsigned>(cast<Constant>(*I),
334 0));
335 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000336 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000337 }
338
339 NewOps.push_back(cast<Constant>(NewOp));
340 }
341
342 // Make the new constant.
343 Constant *NewC;
344 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000345 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000346 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000347 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000349 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000350 } else {
351 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000352 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Chris Lattnerea693df2008-08-21 02:34:16 +0000355 UserC->replaceAllUsesWith(NewC);
356 UserC->destroyConstant();
357 NewOps.clear();
358 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000359
Nick Lewyckycb337992009-05-10 20:57:05 +0000360 // Update all ValueHandles, they should be the only users at this point.
361 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000362 delete Placeholder;
363 }
364}
365
Devang Pateld5ac4042009-08-04 06:00:18 +0000366void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
367 if (Idx == size()) {
368 push_back(V);
369 return;
370 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000371
Devang Pateld5ac4042009-08-04 06:00:18 +0000372 if (Idx >= size())
373 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000374
Devang Pateld5ac4042009-08-04 06:00:18 +0000375 WeakVH &OldV = MDValuePtrs[Idx];
376 if (OldV == 0) {
377 OldV = V;
378 return;
379 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Devang Pateld5ac4042009-08-04 06:00:18 +0000381 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000382 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000384 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000385 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
386 // value for Idx.
387 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000388}
389
390Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
391 if (Idx >= size())
392 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000395 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 return V;
397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000398
Devang Pateld5ac4042009-08-04 06:00:18 +0000399 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000400 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000401 MDValuePtrs[Idx] = V;
402 return V;
403}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000404
Chris Lattner1afcace2011-07-09 17:41:24 +0000405Type *BitcodeReader::getTypeByID(unsigned ID) {
406 // The type table size is always specified correctly.
407 if (ID >= TypeList.size())
408 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000409
Chris Lattner1afcace2011-07-09 17:41:24 +0000410 if (Type *Ty = TypeList[ID])
411 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413 // If we have a forward reference, the only possible case is when it is to a
414 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000415 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000416}
417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418
Chris Lattner48c85b82007-05-04 03:30:17 +0000419//===----------------------------------------------------------------------===//
420// Functions for parsing blocks from the bitcode file
421//===----------------------------------------------------------------------===//
422
Devang Patel05988662008-09-25 21:00:45 +0000423bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000424 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000425 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000426
Devang Patel19c87462008-09-26 22:53:05 +0000427 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000428 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000431
Devang Patel05988662008-09-25 21:00:45 +0000432 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000433
Chris Lattner48c85b82007-05-04 03:30:17 +0000434 // Read all the records.
435 while (1) {
436 unsigned Code = Stream.ReadCode();
437 if (Code == bitc::END_BLOCK) {
438 if (Stream.ReadBlockEnd())
439 return Error("Error at end of PARAMATTR block");
440 return false;
441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Chris Lattner48c85b82007-05-04 03:30:17 +0000443 if (Code == bitc::ENTER_SUBBLOCK) {
444 // No known subblocks, always skip them.
445 Stream.ReadSubBlockID();
446 if (Stream.SkipBlock())
447 return Error("Malformed block record");
448 continue;
449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 if (Code == bitc::DEFINE_ABBREV) {
452 Stream.ReadAbbrevRecord();
453 continue;
454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000455
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 // Read a record.
457 Record.clear();
458 switch (Stream.ReadRecord(Code, Record)) {
459 default: // Default behavior: ignore.
460 break;
461 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
462 if (Record.size() & 1)
463 return Error("Invalid ENTRY record");
464
Chris Lattner48c85b82007-05-04 03:30:17 +0000465 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000466 // FIXME: remove in LLVM 3.0
467 // The alignment is stored as a 16-bit raw value from bits 31--16.
468 // We shift the bits above 31 down by 11 bits.
469
470 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
471 if (Alignment && !isPowerOf2_32(Alignment))
472 return Error("Alignment is not a power of two.");
473
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000474 Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000475 if (Alignment)
476 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000477 ReconstitutedAttr |=
478 Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000479
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000480 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000481 }
Chris Lattner461edd92008-03-12 02:25:52 +0000482
Devang Patel19c87462008-09-26 22:53:05 +0000483 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nuno Lopes006c7b92012-05-08 17:07:35 +0000484 if (Attributes(Record[i+1]) != Attribute::None)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000485 Attrs.push_back(AttributeWithIndex::get(Record[i],
486 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000487 }
Devang Patel19c87462008-09-26 22:53:05 +0000488
489 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000490 Attrs.clear();
491 break;
492 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000493 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000494 }
495}
496
Chris Lattner86697142007-05-01 05:01:34 +0000497bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000498 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000499 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000500
Chris Lattner1afcace2011-07-09 17:41:24 +0000501 return ParseTypeTableBody();
502}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000503
Chris Lattner1afcace2011-07-09 17:41:24 +0000504bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000505 if (!TypeList.empty())
506 return Error("Multiple TYPE_BLOCKs found!");
507
508 SmallVector<uint64_t, 64> Record;
509 unsigned NumRecords = 0;
510
Chris Lattner1afcace2011-07-09 17:41:24 +0000511 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000512
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000513 // Read all the records for this type table.
514 while (1) {
515 unsigned Code = Stream.ReadCode();
516 if (Code == bitc::END_BLOCK) {
517 if (NumRecords != TypeList.size())
518 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000519 if (Stream.ReadBlockEnd())
520 return Error("Error at end of type table block");
521 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000523
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000524 if (Code == bitc::ENTER_SUBBLOCK) {
525 // No known subblocks, always skip them.
526 Stream.ReadSubBlockID();
527 if (Stream.SkipBlock())
528 return Error("Malformed block record");
529 continue;
530 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000531
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000532 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000533 Stream.ReadAbbrevRecord();
534 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000536
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000537 // Read a record.
538 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000539 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000540 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000541 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000542 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
543 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
544 // type list. This allows us to reserve space.
545 if (Record.size() < 1)
546 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000547 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000550 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000551 break;
Dan Gohmance163392011-12-17 00:04:22 +0000552 case bitc::TYPE_CODE_HALF: // HALF
553 ResultTy = Type::getHalfTy(Context);
554 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000555 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000557 break;
558 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000559 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000560 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000561 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000562 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000563 break;
564 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000565 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000566 break;
567 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000569 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000571 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000573 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000574 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000575 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000576 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
577 ResultTy = Type::getX86_MMXTy(Context);
578 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000579 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
580 if (Record.size() < 1)
581 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000582
Owen Anderson1d0be152009-08-13 21:58:54 +0000583 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000584 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000585 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000586 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000587 if (Record.size() < 1)
588 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000589 unsigned AddressSpace = 0;
590 if (Record.size() == 2)
591 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000592 ResultTy = getTypeByID(Record[0]);
593 if (ResultTy == 0) return Error("invalid element type in pointer type");
594 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000595 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000596 }
Chad Rosiercde54642011-11-03 00:14:01 +0000597 case bitc::TYPE_CODE_FUNCTION: {
598 // FUNCTION: [vararg, retty, paramty x N]
599 if (Record.size() < 2)
600 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000601 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000602 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
603 if (Type *T = getTypeByID(Record[i]))
604 ArgTys.push_back(T);
605 else
606 break;
607 }
608
609 ResultTy = getTypeByID(Record[1]);
610 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
611 return Error("invalid type in function type");
612
613 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
614 break;
615 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000616 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000617 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000618 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000619 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000620 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
621 if (Type *T = getTypeByID(Record[i]))
622 EltTys.push_back(T);
623 else
624 break;
625 }
626 if (EltTys.size() != Record.size()-1)
627 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000628 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000629 break;
630 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000631 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
632 if (ConvertToString(Record, 0, TypeName))
633 return Error("Invalid STRUCT_NAME record");
634 continue;
635
636 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
637 if (Record.size() < 1)
638 return Error("Invalid STRUCT type record");
639
640 if (NumRecords >= TypeList.size())
641 return Error("invalid TYPE table");
642
643 // Check to see if this was forward referenced, if so fill in the temp.
644 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
645 if (Res) {
646 Res->setName(TypeName);
647 TypeList[NumRecords] = 0;
648 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000649 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000650 TypeName.clear();
651
652 SmallVector<Type*, 8> EltTys;
653 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
654 if (Type *T = getTypeByID(Record[i]))
655 EltTys.push_back(T);
656 else
657 break;
658 }
659 if (EltTys.size() != Record.size()-1)
660 return Error("invalid STRUCT type record");
661 Res->setBody(EltTys, Record[0]);
662 ResultTy = Res;
663 break;
664 }
665 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
666 if (Record.size() != 1)
667 return Error("Invalid OPAQUE type record");
668
669 if (NumRecords >= TypeList.size())
670 return Error("invalid TYPE table");
671
672 // Check to see if this was forward referenced, if so fill in the temp.
673 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
674 if (Res) {
675 Res->setName(TypeName);
676 TypeList[NumRecords] = 0;
677 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000678 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000679 TypeName.clear();
680 ResultTy = Res;
681 break;
682 }
683 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
684 if (Record.size() < 2)
685 return Error("Invalid ARRAY type record");
686 if ((ResultTy = getTypeByID(Record[1])))
687 ResultTy = ArrayType::get(ResultTy, Record[0]);
688 else
689 return Error("Invalid ARRAY type element");
690 break;
691 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
692 if (Record.size() < 2)
693 return Error("Invalid VECTOR type record");
694 if ((ResultTy = getTypeByID(Record[1])))
695 ResultTy = VectorType::get(ResultTy, Record[0]);
696 else
697 return Error("Invalid ARRAY type element");
698 break;
699 }
700
701 if (NumRecords >= TypeList.size())
702 return Error("invalid TYPE table");
703 assert(ResultTy && "Didn't read a type?");
704 assert(TypeList[NumRecords] == 0 && "Already read type?");
705 TypeList[NumRecords++] = ResultTy;
706 }
707}
708
Chris Lattner86697142007-05-01 05:01:34 +0000709bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000710 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000711 return Error("Malformed block record");
712
713 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000714
Chris Lattner0b2482a2007-04-23 21:26:05 +0000715 // Read all the records for this value table.
716 SmallString<128> ValueName;
717 while (1) {
718 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000719 if (Code == bitc::END_BLOCK) {
720 if (Stream.ReadBlockEnd())
721 return Error("Error at end of value symbol table block");
722 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000723 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000724 if (Code == bitc::ENTER_SUBBLOCK) {
725 // No known subblocks, always skip them.
726 Stream.ReadSubBlockID();
727 if (Stream.SkipBlock())
728 return Error("Malformed block record");
729 continue;
730 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000731
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 if (Code == bitc::DEFINE_ABBREV) {
733 Stream.ReadAbbrevRecord();
734 continue;
735 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000736
Chris Lattner0b2482a2007-04-23 21:26:05 +0000737 // Read a record.
738 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000739 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000740 default: // Default behavior: unknown type.
741 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000742 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000743 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000744 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000745 unsigned ValueID = Record[0];
746 if (ValueID >= ValueList.size())
747 return Error("Invalid Value ID in VST_ENTRY record");
748 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000749
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000750 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000751 ValueName.clear();
752 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000753 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000754 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000755 if (ConvertToString(Record, 1, ValueName))
756 return Error("Invalid VST_BBENTRY record");
757 BasicBlock *BB = getBasicBlock(Record[0]);
758 if (BB == 0)
759 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000760
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000761 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000762 ValueName.clear();
763 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000765 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000766 }
767}
768
Devang Patele54abc92009-07-22 17:43:22 +0000769bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000770 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000771
772 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
773 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000774
Devang Patele54abc92009-07-22 17:43:22 +0000775 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776
Devang Patele54abc92009-07-22 17:43:22 +0000777 // Read all the records.
778 while (1) {
779 unsigned Code = Stream.ReadCode();
780 if (Code == bitc::END_BLOCK) {
781 if (Stream.ReadBlockEnd())
782 return Error("Error at end of PARAMATTR block");
783 return false;
784 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000785
Devang Patele54abc92009-07-22 17:43:22 +0000786 if (Code == bitc::ENTER_SUBBLOCK) {
787 // No known subblocks, always skip them.
788 Stream.ReadSubBlockID();
789 if (Stream.SkipBlock())
790 return Error("Malformed block record");
791 continue;
792 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Devang Patele54abc92009-07-22 17:43:22 +0000794 if (Code == bitc::DEFINE_ABBREV) {
795 Stream.ReadAbbrevRecord();
796 continue;
797 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Victor Hernandez24e64df2010-01-10 07:14:18 +0000799 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000800 // Read a record.
801 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000802 Code = Stream.ReadRecord(Code, Record);
803 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000804 default: // Default behavior: ignore.
805 break;
Devang Patelaa993142009-07-29 22:34:41 +0000806 case bitc::METADATA_NAME: {
807 // Read named of the named metadata.
808 unsigned NameLength = Record.size();
809 SmallString<8> Name;
810 Name.resize(NameLength);
811 for (unsigned i = 0; i != NameLength; ++i)
812 Name[i] = Record[i];
813 Record.clear();
814 Code = Stream.ReadCode();
815
Chris Lattner9d61dd92011-06-17 17:50:30 +0000816 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000817 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000818 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000819
820 // Read named metadata elements.
821 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000822 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000823 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000824 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
825 if (MD == 0)
826 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000827 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000828 }
Devang Patelaa993142009-07-29 22:34:41 +0000829 break;
830 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000831 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000832 IsFunctionLocal = true;
833 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000834 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000835 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000836 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000837
Devang Patel104cf9e2009-07-23 01:07:34 +0000838 unsigned Size = Record.size();
839 SmallVector<Value*, 8> Elts;
840 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000841 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000842 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000843 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000844 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000845 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000846 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
847 else
848 Elts.push_back(NULL);
849 }
Jay Foadec9186b2011-04-21 19:59:31 +0000850 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000851 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000852 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000853 break;
854 }
Devang Patele54abc92009-07-22 17:43:22 +0000855 case bitc::METADATA_STRING: {
856 unsigned MDStringLength = Record.size();
857 SmallString<8> String;
858 String.resize(MDStringLength);
859 for (unsigned i = 0; i != MDStringLength; ++i)
860 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000861 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000862 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000863 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000864 break;
865 }
Devang Patele8e02132009-09-18 19:26:43 +0000866 case bitc::METADATA_KIND: {
867 unsigned RecordLength = Record.size();
868 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000869 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000870 SmallString<8> Name;
871 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000872 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000873 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000874 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000875
Chris Lattner08113472009-12-29 09:01:33 +0000876 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000877 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
878 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000879 break;
880 }
Devang Patele54abc92009-07-22 17:43:22 +0000881 }
882 }
883}
884
Chris Lattner0eef0802007-04-24 04:04:35 +0000885/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
886/// the LSB for dense VBR encoding.
887static uint64_t DecodeSignRotatedValue(uint64_t V) {
888 if ((V & 1) == 0)
889 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000890 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000891 return -(V >> 1);
892 // There is no such thing as -0 with integers. "-0" really means MININT.
893 return 1ULL << 63;
894}
895
Chris Lattner07d98b42007-04-26 02:46:40 +0000896/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
897/// values and aliases that we can.
898bool BitcodeReader::ResolveGlobalAndAliasInits() {
899 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
900 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000901
Chris Lattner07d98b42007-04-26 02:46:40 +0000902 GlobalInitWorklist.swap(GlobalInits);
903 AliasInitWorklist.swap(AliasInits);
904
905 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000906 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000907 if (ValID >= ValueList.size()) {
908 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000909 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000910 } else {
911 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
912 GlobalInitWorklist.back().first->setInitializer(C);
913 else
914 return Error("Global variable initializer is not a constant!");
915 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000916 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000917 }
918
919 while (!AliasInitWorklist.empty()) {
920 unsigned ValID = AliasInitWorklist.back().second;
921 if (ValID >= ValueList.size()) {
922 AliasInits.push_back(AliasInitWorklist.back());
923 } else {
924 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000925 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 else
927 return Error("Alias initializer is not a constant!");
928 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000929 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000930 }
931 return false;
932}
933
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000934APInt ReadWideAPInt(const uint64_t *Vals, unsigned ActiveWords,
935 unsigned TypeBits) {
936 SmallVector<uint64_t, 8> Words;
937 Words.resize(ActiveWords);
938 for (unsigned i = 0; i != ActiveWords; ++i)
939 Words[i] = DecodeSignRotatedValue(Vals[i]);
940
941 return APInt(TypeBits, Words);
942}
943
Chris Lattner86697142007-05-01 05:01:34 +0000944bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000945 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000946 return Error("Malformed block record");
947
948 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000949
Chris Lattnere16504e2007-04-24 03:30:34 +0000950 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000951 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000952 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 while (1) {
954 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000955 if (Code == bitc::END_BLOCK)
956 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000957
Chris Lattnere16504e2007-04-24 03:30:34 +0000958 if (Code == bitc::ENTER_SUBBLOCK) {
959 // No known subblocks, always skip them.
960 Stream.ReadSubBlockID();
961 if (Stream.SkipBlock())
962 return Error("Malformed block record");
963 continue;
964 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000965
Chris Lattnere16504e2007-04-24 03:30:34 +0000966 if (Code == bitc::DEFINE_ABBREV) {
967 Stream.ReadAbbrevRecord();
968 continue;
969 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000970
Chris Lattnere16504e2007-04-24 03:30:34 +0000971 // Read a record.
972 Record.clear();
973 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000974 unsigned BitCode = Stream.ReadRecord(Code, Record);
975 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000976 default: // Default behavior: unknown constant
977 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000978 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000979 break;
980 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
981 if (Record.empty())
982 return Error("Malformed CST_SETTYPE record");
983 if (Record[0] >= TypeList.size())
984 return Error("Invalid Type ID in CST_SETTYPE record");
985 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000986 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000987 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000988 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000989 break;
990 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000991 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000992 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000993 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000994 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000995 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000996 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000997 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000998
Chris Lattner15e6d172007-05-04 19:11:41 +0000999 unsigned NumWords = Record.size();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001000
1001 APInt VInt = ReadWideAPInt(&Record[0], NumWords,
1002 cast<IntegerType>(CurTy)->getBitWidth());
1003 V = ConstantInt::get(Context, VInt);
1004
Chris Lattner0eef0802007-04-24 04:04:35 +00001005 break;
1006 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001007 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001008 if (Record.empty())
1009 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001010 if (CurTy->isHalfTy())
1011 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1012 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001013 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001014 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001015 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001016 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001017 // Bits are not stored the same way as a normal i80 APInt, compensate.
1018 uint64_t Rearrange[2];
1019 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1020 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001021 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001022 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001023 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001024 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001025 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001026 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001027 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001028 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001029 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001030
Chris Lattner15e6d172007-05-04 19:11:41 +00001031 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1032 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001033 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001034
Chris Lattner15e6d172007-05-04 19:11:41 +00001035 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001036 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001037
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001038 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001039 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001040 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001041 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001042 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001043 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1044 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001045 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001046 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001047 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1049 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001050 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001051 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001052 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001053 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001054 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001055 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001056 break;
1057 }
Chris Lattner2237f842012-02-05 02:41:35 +00001058 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001059 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1060 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001061 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001062
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001063 unsigned Size = Record.size();
Chris Lattner2237f842012-02-05 02:41:35 +00001064 SmallString<16> Elts;
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001065 for (unsigned i = 0; i != Size; ++i)
Chris Lattner2237f842012-02-05 02:41:35 +00001066 Elts.push_back(Record[i]);
1067 V = ConstantDataArray::getString(Context, Elts,
1068 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001069 break;
1070 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001071 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1072 if (Record.empty())
1073 return Error("Invalid CST_DATA record");
1074
1075 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1076 unsigned Size = Record.size();
1077
1078 if (EltTy->isIntegerTy(8)) {
1079 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1080 if (isa<VectorType>(CurTy))
1081 V = ConstantDataVector::get(Context, Elts);
1082 else
1083 V = ConstantDataArray::get(Context, Elts);
1084 } else if (EltTy->isIntegerTy(16)) {
1085 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1088 else
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isIntegerTy(32)) {
1091 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1092 if (isa<VectorType>(CurTy))
1093 V = ConstantDataVector::get(Context, Elts);
1094 else
1095 V = ConstantDataArray::get(Context, Elts);
1096 } else if (EltTy->isIntegerTy(64)) {
1097 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1098 if (isa<VectorType>(CurTy))
1099 V = ConstantDataVector::get(Context, Elts);
1100 else
1101 V = ConstantDataArray::get(Context, Elts);
1102 } else if (EltTy->isFloatTy()) {
1103 SmallVector<float, 16> Elts;
1104 for (unsigned i = 0; i != Size; ++i) {
1105 union { uint32_t I; float F; };
1106 I = Record[i];
1107 Elts.push_back(F);
1108 }
1109 if (isa<VectorType>(CurTy))
1110 V = ConstantDataVector::get(Context, Elts);
1111 else
1112 V = ConstantDataArray::get(Context, Elts);
1113 } else if (EltTy->isDoubleTy()) {
1114 SmallVector<double, 16> Elts;
1115 for (unsigned i = 0; i != Size; ++i) {
1116 union { uint64_t I; double F; };
1117 I = Record[i];
1118 Elts.push_back(F);
1119 }
1120 if (isa<VectorType>(CurTy))
1121 V = ConstantDataVector::get(Context, Elts);
1122 else
1123 V = ConstantDataArray::get(Context, Elts);
1124 } else {
1125 return Error("Unknown element type in CE_DATA");
1126 }
1127 break;
1128 }
1129
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001130 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1131 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1132 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001133 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001134 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001135 } else {
1136 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1137 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001138 unsigned Flags = 0;
1139 if (Record.size() >= 4) {
1140 if (Opc == Instruction::Add ||
1141 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001142 Opc == Instruction::Mul ||
1143 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001144 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1145 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1146 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1147 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001148 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001149 Opc == Instruction::UDiv ||
1150 Opc == Instruction::LShr ||
1151 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001152 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001153 Flags |= SDivOperator::IsExact;
1154 }
1155 }
1156 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001157 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001158 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001159 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001160 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1161 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1162 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001163 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001164 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001165 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001166 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001167 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001168 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001169 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001170 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001171 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001172 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001173 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001174 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001175 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001176 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001177 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001178 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001179 if (!ElTy) return Error("Invalid CE_GEP record");
1180 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1181 }
Jay Foaddab3d292011-07-21 14:31:17 +00001182 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001183 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1184 BitCode ==
1185 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001186 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001187 }
1188 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1189 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001190 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001191 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001192 ValueList.getConstantFwdRef(Record[1],CurTy),
1193 ValueList.getConstantFwdRef(Record[2],CurTy));
1194 break;
1195 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1196 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001197 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001198 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1199 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1200 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001201 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001202 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001203 break;
1204 }
1205 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001206 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001207 if (Record.size() < 3 || OpTy == 0)
1208 return Error("Invalid CE_INSERTELT record");
1209 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1210 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1211 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001212 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001213 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001214 break;
1215 }
1216 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001217 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001219 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001220 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1221 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001222 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001223 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001224 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001225 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001226 break;
1227 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001228 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001229 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1230 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001231 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001232 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1233 return Error("Invalid CE_SHUFVEC_EX record");
1234 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1235 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001236 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001237 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001238 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001239 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001240 break;
1241 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001242 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1243 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001244 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001245 if (OpTy == 0) return Error("Invalid CE_CMP record");
1246 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1247 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1248
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001249 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001250 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001251 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001252 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001253 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001254 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001255 case bitc::CST_CODE_INLINEASM: {
1256 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1257 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001258 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001259 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001260 unsigned AsmStrSize = Record[1];
1261 if (2+AsmStrSize >= Record.size())
1262 return Error("Invalid INLINEASM record");
1263 unsigned ConstStrSize = Record[2+AsmStrSize];
1264 if (3+AsmStrSize+ConstStrSize > Record.size())
1265 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001266
Chris Lattner2bce93a2007-05-06 01:58:20 +00001267 for (unsigned i = 0; i != AsmStrSize; ++i)
1268 AsmStr += (char)Record[2+i];
1269 for (unsigned i = 0; i != ConstStrSize; ++i)
1270 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001271 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001272 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001273 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001274 break;
1275 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001276 case bitc::CST_CODE_BLOCKADDRESS:{
1277 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001278 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001279 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1280 Function *Fn =
1281 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1282 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1283
1284 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1285 Type::getInt8Ty(Context),
1286 false, GlobalValue::InternalLinkage,
1287 0, "");
1288 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1289 V = FwdRef;
1290 break;
1291 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001292 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001293
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001294 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001295 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001296 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001297
Chris Lattnerea693df2008-08-21 02:34:16 +00001298 if (NextCstNo != ValueList.size())
1299 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001300
Chris Lattnerea693df2008-08-21 02:34:16 +00001301 if (Stream.ReadBlockEnd())
1302 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001303
Chris Lattnerea693df2008-08-21 02:34:16 +00001304 // Once all the constants have been read, go through and resolve forward
1305 // references.
1306 ValueList.ResolveConstantForwardRefs();
1307 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001308}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001309
Chad Rosiercbbb0962011-12-07 21:44:12 +00001310bool BitcodeReader::ParseUseLists() {
1311 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1312 return Error("Malformed block record");
1313
1314 SmallVector<uint64_t, 64> Record;
1315
1316 // Read all the records.
1317 while (1) {
1318 unsigned Code = Stream.ReadCode();
1319 if (Code == bitc::END_BLOCK) {
1320 if (Stream.ReadBlockEnd())
1321 return Error("Error at end of use-list table block");
1322 return false;
1323 }
1324
1325 if (Code == bitc::ENTER_SUBBLOCK) {
1326 // No known subblocks, always skip them.
1327 Stream.ReadSubBlockID();
1328 if (Stream.SkipBlock())
1329 return Error("Malformed block record");
1330 continue;
1331 }
1332
1333 if (Code == bitc::DEFINE_ABBREV) {
1334 Stream.ReadAbbrevRecord();
1335 continue;
1336 }
1337
1338 // Read a use list record.
1339 Record.clear();
1340 switch (Stream.ReadRecord(Code, Record)) {
1341 default: // Default behavior: unknown type.
1342 break;
1343 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1344 unsigned RecordLength = Record.size();
1345 if (RecordLength < 1)
1346 return Error ("Invalid UseList reader!");
1347 UseListRecords.push_back(Record);
1348 break;
1349 }
1350 }
1351 }
1352}
1353
Chris Lattner980e5aa2007-05-01 05:52:21 +00001354/// RememberAndSkipFunctionBody - When we see the block for a function body,
1355/// remember where it is and then skip it. This lets us lazily deserialize the
1356/// functions.
1357bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001358 // Get the function we are talking about.
1359 if (FunctionsWithBodies.empty())
1360 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001361
Chris Lattner48f84872007-05-01 04:59:48 +00001362 Function *Fn = FunctionsWithBodies.back();
1363 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001364
Chris Lattner48f84872007-05-01 04:59:48 +00001365 // Save the current stream state.
1366 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001367 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001368
Chris Lattner48f84872007-05-01 04:59:48 +00001369 // Skip over the function block for now.
1370 if (Stream.SkipBlock())
1371 return Error("Malformed block record");
1372 return false;
1373}
1374
Derek Schuff2ea93872012-02-06 22:30:29 +00001375bool BitcodeReader::GlobalCleanup() {
1376 // Patch the initializers for globals and aliases up.
1377 ResolveGlobalAndAliasInits();
1378 if (!GlobalInits.empty() || !AliasInits.empty())
1379 return Error("Malformed global initializer set");
1380
1381 // Look for intrinsic functions which need to be upgraded at some point
1382 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1383 FI != FE; ++FI) {
1384 Function *NewFn;
1385 if (UpgradeIntrinsicFunction(FI, NewFn))
1386 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1387 }
1388
1389 // Look for global variables which need to be renamed.
1390 for (Module::global_iterator
1391 GI = TheModule->global_begin(), GE = TheModule->global_end();
1392 GI != GE; ++GI)
1393 UpgradeGlobalVariable(GI);
1394 // Force deallocation of memory for these vectors to favor the client that
1395 // want lazy deserialization.
1396 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1397 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1398 return false;
1399}
1400
1401bool BitcodeReader::ParseModule(bool Resume) {
1402 if (Resume)
1403 Stream.JumpToBit(NextUnreadBit);
1404 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001405 return Error("Malformed block record");
1406
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001407 SmallVector<uint64_t, 64> Record;
1408 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001409 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001410
1411 // Read all the records for this module.
1412 while (!Stream.AtEndOfStream()) {
1413 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001414 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001415 if (Stream.ReadBlockEnd())
1416 return Error("Error at end of module block");
1417
Derek Schuff2ea93872012-02-06 22:30:29 +00001418 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001419 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001420
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001421 if (Code == bitc::ENTER_SUBBLOCK) {
1422 switch (Stream.ReadSubBlockID()) {
1423 default: // Skip unknown content.
1424 if (Stream.SkipBlock())
1425 return Error("Malformed block record");
1426 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001427 case bitc::BLOCKINFO_BLOCK_ID:
1428 if (Stream.ReadBlockInfoBlock())
1429 return Error("Malformed BlockInfoBlock");
1430 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001431 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001432 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001433 return true;
1434 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001435 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001436 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001437 return true;
1438 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001439 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001440 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001441 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001442 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001443 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001444 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001445 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001446 return true;
1447 break;
Devang Patele54abc92009-07-22 17:43:22 +00001448 case bitc::METADATA_BLOCK_ID:
1449 if (ParseMetadata())
1450 return true;
1451 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001452 case bitc::FUNCTION_BLOCK_ID:
1453 // If this is the first function body we've seen, reverse the
1454 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001455 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001456 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001457 if (GlobalCleanup())
1458 return true;
1459 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001460 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001461
Chris Lattner980e5aa2007-05-01 05:52:21 +00001462 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001463 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001464 // For streaming bitcode, suspend parsing when we reach the function
1465 // bodies. Subsequent materialization calls will resume it when
1466 // necessary. For streaming, the function bodies must be at the end of
1467 // the bitcode. If the bitcode file is old, the symbol table will be
1468 // at the end instead and will not have been seen yet. In this case,
1469 // just finish the parse now.
1470 if (LazyStreamer && SeenValueSymbolTable) {
1471 NextUnreadBit = Stream.GetCurrentBitNo();
1472 return false;
1473 }
Chris Lattner48f84872007-05-01 04:59:48 +00001474 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001475 case bitc::USELIST_BLOCK_ID:
1476 if (ParseUseLists())
1477 return true;
1478 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001479 }
1480 continue;
1481 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001482
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001483 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001484 Stream.ReadAbbrevRecord();
1485 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001486 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001488 // Read a record.
1489 switch (Stream.ReadRecord(Code, Record)) {
1490 default: break; // Default behavior, ignore unknown content.
1491 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1492 if (Record.size() < 1)
1493 return Error("Malformed MODULE_CODE_VERSION");
1494 // Only version #0 is supported so far.
1495 if (Record[0] != 0)
1496 return Error("Unknown bitstream version!");
1497 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001498 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001499 std::string S;
1500 if (ConvertToString(Record, 0, S))
1501 return Error("Invalid MODULE_CODE_TRIPLE record");
1502 TheModule->setTargetTriple(S);
1503 break;
1504 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001505 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001506 std::string S;
1507 if (ConvertToString(Record, 0, S))
1508 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1509 TheModule->setDataLayout(S);
1510 break;
1511 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001512 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001513 std::string S;
1514 if (ConvertToString(Record, 0, S))
1515 return Error("Invalid MODULE_CODE_ASM record");
1516 TheModule->setModuleInlineAsm(S);
1517 break;
1518 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001519 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001520 std::string S;
1521 if (ConvertToString(Record, 0, S))
1522 return Error("Invalid MODULE_CODE_DEPLIB record");
1523 TheModule->addLibrary(S);
1524 break;
1525 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001526 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001527 std::string S;
1528 if (ConvertToString(Record, 0, S))
1529 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1530 SectionTable.push_back(S);
1531 break;
1532 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001533 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001534 std::string S;
1535 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001536 return Error("Invalid MODULE_CODE_GCNAME record");
1537 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001538 break;
1539 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001540 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001541 // linkage, alignment, section, visibility, threadlocal,
1542 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001543 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001544 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001545 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001546 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001547 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001548 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001549 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001550 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001551 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001552
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001553 bool isConstant = Record[1];
1554 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1555 unsigned Alignment = (1 << Record[4]) >> 1;
1556 std::string Section;
1557 if (Record[5]) {
1558 if (Record[5]-1 >= SectionTable.size())
1559 return Error("Invalid section ID");
1560 Section = SectionTable[Record[5]-1];
1561 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001562 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001563 if (Record.size() > 6)
1564 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001565 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001566 if (Record.size() > 7)
1567 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001568
Rafael Espindolabea46262011-01-08 16:42:36 +00001569 bool UnnamedAddr = false;
1570 if (Record.size() > 8)
1571 UnnamedAddr = Record[8];
1572
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001573 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001574 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001575 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001576 NewGV->setAlignment(Alignment);
1577 if (!Section.empty())
1578 NewGV->setSection(Section);
1579 NewGV->setVisibility(Visibility);
1580 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001581 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001582
Chris Lattner0b2482a2007-04-23 21:26:05 +00001583 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001584
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001585 // Remember which value to use for the global initializer.
1586 if (unsigned InitID = Record[2])
1587 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 break;
1589 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001590 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001591 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001593 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001595 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001596 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001597 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001599 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001600 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1601 if (!FTy)
1602 return Error("Function not a pointer to function type!");
1603
Gabor Greif051a9502008-04-06 20:25:17 +00001604 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1605 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001606
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001607 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001608 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001609 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001610 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Chris Lattnera9bb7132007-05-08 05:38:01 +00001612 Func->setAlignment((1 << Record[5]) >> 1);
1613 if (Record[6]) {
1614 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001615 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001616 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001618 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001619 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001620 if (Record[8]-1 > GCTable.size())
1621 return Error("Invalid GC ID");
1622 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001623 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001624 bool UnnamedAddr = false;
1625 if (Record.size() > 9)
1626 UnnamedAddr = Record[9];
1627 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001628 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner48f84872007-05-01 04:59:48 +00001630 // If this is a function with a body, remember the prototype we are
1631 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001632 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001633 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001634 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1635 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001636 break;
1637 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001638 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001639 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001640 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001641 if (Record.size() < 3)
1642 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001643 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001644 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001645 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001646 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattner07d98b42007-04-26 02:46:40 +00001648 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1649 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001650 // Old bitcode files didn't have visibility field.
1651 if (Record.size() > 3)
1652 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001653 ValueList.push_back(NewGA);
1654 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1655 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001656 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001657 /// MODULE_CODE_PURGEVALS: [numvals]
1658 case bitc::MODULE_CODE_PURGEVALS:
1659 // Trim down the value list to the specified size.
1660 if (Record.size() < 1 || Record[0] > ValueList.size())
1661 return Error("Invalid MODULE_PURGEVALS record");
1662 ValueList.shrinkTo(Record[0]);
1663 break;
1664 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001665 Record.clear();
1666 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001668 return Error("Premature end of bitstream");
1669}
1670
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001671bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001672 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001673
Derek Schuff2ea93872012-02-06 22:30:29 +00001674 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001675
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001676 // Sniff for the signature.
1677 if (Stream.Read(8) != 'B' ||
1678 Stream.Read(8) != 'C' ||
1679 Stream.Read(4) != 0x0 ||
1680 Stream.Read(4) != 0xC ||
1681 Stream.Read(4) != 0xE ||
1682 Stream.Read(4) != 0xD)
1683 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 // We expect a number of well-defined blocks, though we don't necessarily
1686 // need to understand them all.
1687 while (!Stream.AtEndOfStream()) {
1688 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001689
Rafael Espindolac9687b32011-05-26 18:59:54 +00001690 if (Code != bitc::ENTER_SUBBLOCK) {
1691
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001692 // The ranlib in xcode 4 will align archive members by appending newlines
1693 // to the end of them. If this file size is a multiple of 4 but not 8, we
1694 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001695 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1696 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1697 Stream.AtEndOfStream())
1698 return false;
1699
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001700 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001701 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001703 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001704
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001705 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001706 switch (BlockID) {
1707 case bitc::BLOCKINFO_BLOCK_ID:
1708 if (Stream.ReadBlockInfoBlock())
1709 return Error("Malformed BlockInfoBlock");
1710 break;
1711 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001712 // Reject multiple MODULE_BLOCK's in a single bitstream.
1713 if (TheModule)
1714 return Error("Multiple MODULE_BLOCKs in same stream");
1715 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001716 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001717 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001718 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001719 break;
1720 default:
1721 if (Stream.SkipBlock())
1722 return Error("Malformed block record");
1723 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001724 }
1725 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001726
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001727 return false;
1728}
Chris Lattnerc453f762007-04-29 07:54:31 +00001729
Bill Wendling34711742010-10-06 01:22:42 +00001730bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1731 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1732 return Error("Malformed block record");
1733
1734 SmallVector<uint64_t, 64> Record;
1735
1736 // Read all the records for this module.
1737 while (!Stream.AtEndOfStream()) {
1738 unsigned Code = Stream.ReadCode();
1739 if (Code == bitc::END_BLOCK) {
1740 if (Stream.ReadBlockEnd())
1741 return Error("Error at end of module block");
1742
1743 return false;
1744 }
1745
1746 if (Code == bitc::ENTER_SUBBLOCK) {
1747 switch (Stream.ReadSubBlockID()) {
1748 default: // Skip unknown content.
1749 if (Stream.SkipBlock())
1750 return Error("Malformed block record");
1751 break;
1752 }
1753 continue;
1754 }
1755
1756 if (Code == bitc::DEFINE_ABBREV) {
1757 Stream.ReadAbbrevRecord();
1758 continue;
1759 }
1760
1761 // Read a record.
1762 switch (Stream.ReadRecord(Code, Record)) {
1763 default: break; // Default behavior, ignore unknown content.
1764 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1765 if (Record.size() < 1)
1766 return Error("Malformed MODULE_CODE_VERSION");
1767 // Only version #0 is supported so far.
1768 if (Record[0] != 0)
1769 return Error("Unknown bitstream version!");
1770 break;
1771 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1772 std::string S;
1773 if (ConvertToString(Record, 0, S))
1774 return Error("Invalid MODULE_CODE_TRIPLE record");
1775 Triple = S;
1776 break;
1777 }
1778 }
1779 Record.clear();
1780 }
1781
1782 return Error("Premature end of bitstream");
1783}
1784
1785bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001786 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001787
1788 // Sniff for the signature.
1789 if (Stream.Read(8) != 'B' ||
1790 Stream.Read(8) != 'C' ||
1791 Stream.Read(4) != 0x0 ||
1792 Stream.Read(4) != 0xC ||
1793 Stream.Read(4) != 0xE ||
1794 Stream.Read(4) != 0xD)
1795 return Error("Invalid bitcode signature");
1796
1797 // We expect a number of well-defined blocks, though we don't necessarily
1798 // need to understand them all.
1799 while (!Stream.AtEndOfStream()) {
1800 unsigned Code = Stream.ReadCode();
1801
1802 if (Code != bitc::ENTER_SUBBLOCK)
1803 return Error("Invalid record at top-level");
1804
1805 unsigned BlockID = Stream.ReadSubBlockID();
1806
1807 // We only know the MODULE subblock ID.
1808 switch (BlockID) {
1809 case bitc::MODULE_BLOCK_ID:
1810 if (ParseModuleTriple(Triple))
1811 return true;
1812 break;
1813 default:
1814 if (Stream.SkipBlock())
1815 return Error("Malformed block record");
1816 break;
1817 }
1818 }
1819
1820 return false;
1821}
1822
Devang Patele8e02132009-09-18 19:26:43 +00001823/// ParseMetadataAttachment - Parse metadata attachments.
1824bool BitcodeReader::ParseMetadataAttachment() {
1825 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1826 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001827
Devang Patele8e02132009-09-18 19:26:43 +00001828 SmallVector<uint64_t, 64> Record;
1829 while(1) {
1830 unsigned Code = Stream.ReadCode();
1831 if (Code == bitc::END_BLOCK) {
1832 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001833 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001834 break;
1835 }
1836 if (Code == bitc::DEFINE_ABBREV) {
1837 Stream.ReadAbbrevRecord();
1838 continue;
1839 }
1840 // Read a metadata attachment record.
1841 Record.clear();
1842 switch (Stream.ReadRecord(Code, Record)) {
1843 default: // Default behavior: ignore.
1844 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001845 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001846 unsigned RecordLength = Record.size();
1847 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001848 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001849 Instruction *Inst = InstructionList[Record[0]];
1850 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001851 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001852 DenseMap<unsigned, unsigned>::iterator I =
1853 MDKindMap.find(Kind);
1854 if (I == MDKindMap.end())
1855 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001856 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001857 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001858 }
1859 break;
1860 }
1861 }
1862 }
1863 return false;
1864}
Chris Lattner48f84872007-05-01 04:59:48 +00001865
Chris Lattner980e5aa2007-05-01 05:52:21 +00001866/// ParseFunctionBody - Lazily parse the specified function body block.
1867bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001868 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001869 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Nick Lewycky9a49f152010-02-25 08:30:17 +00001871 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001872 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001873 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874
Chris Lattner980e5aa2007-05-01 05:52:21 +00001875 // Add all the function arguments to the value table.
1876 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1877 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001879 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001880 BasicBlock *CurBB = 0;
1881 unsigned CurBBNo = 0;
1882
Chris Lattnera6245242010-04-03 02:17:50 +00001883 DebugLoc LastLoc;
1884
Chris Lattner980e5aa2007-05-01 05:52:21 +00001885 // Read all the records.
1886 SmallVector<uint64_t, 64> Record;
1887 while (1) {
1888 unsigned Code = Stream.ReadCode();
1889 if (Code == bitc::END_BLOCK) {
1890 if (Stream.ReadBlockEnd())
1891 return Error("Error at end of function block");
1892 break;
1893 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
Chris Lattner980e5aa2007-05-01 05:52:21 +00001895 if (Code == bitc::ENTER_SUBBLOCK) {
1896 switch (Stream.ReadSubBlockID()) {
1897 default: // Skip unknown content.
1898 if (Stream.SkipBlock())
1899 return Error("Malformed block record");
1900 break;
1901 case bitc::CONSTANTS_BLOCK_ID:
1902 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001903 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001904 break;
1905 case bitc::VALUE_SYMTAB_BLOCK_ID:
1906 if (ParseValueSymbolTable()) return true;
1907 break;
Devang Patele8e02132009-09-18 19:26:43 +00001908 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001909 if (ParseMetadataAttachment()) return true;
1910 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001911 case bitc::METADATA_BLOCK_ID:
1912 if (ParseMetadata()) return true;
1913 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001914 }
1915 continue;
1916 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001917
Chris Lattner980e5aa2007-05-01 05:52:21 +00001918 if (Code == bitc::DEFINE_ABBREV) {
1919 Stream.ReadAbbrevRecord();
1920 continue;
1921 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001922
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 // Read a record.
1924 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001925 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001926 unsigned BitCode = Stream.ReadRecord(Code, Record);
1927 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001928 default: // Default behavior: reject
1929 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001930 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001931 if (Record.size() < 1 || Record[0] == 0)
1932 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001934 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001935 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001936 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001937 CurBB = FunctionBBs[0];
1938 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001939
1940 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1941 // This record indicates that the last instruction is at the same
1942 // location as the previous instruction with a location.
1943 I = 0;
1944
1945 // Get the last instruction emitted.
1946 if (CurBB && !CurBB->empty())
1947 I = &CurBB->back();
1948 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1949 !FunctionBBs[CurBBNo-1]->empty())
1950 I = &FunctionBBs[CurBBNo-1]->back();
1951
1952 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1953 I->setDebugLoc(LastLoc);
1954 I = 0;
1955 continue;
1956
Chris Lattner4f6bab92011-06-17 18:17:37 +00001957 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001958 I = 0; // Get the last instruction emitted.
1959 if (CurBB && !CurBB->empty())
1960 I = &CurBB->back();
1961 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1962 !FunctionBBs[CurBBNo-1]->empty())
1963 I = &FunctionBBs[CurBBNo-1]->back();
1964 if (I == 0 || Record.size() < 4)
1965 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1966
1967 unsigned Line = Record[0], Col = Record[1];
1968 unsigned ScopeID = Record[2], IAID = Record[3];
1969
1970 MDNode *Scope = 0, *IA = 0;
1971 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1972 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1973 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1974 I->setDebugLoc(LastLoc);
1975 I = 0;
1976 continue;
1977 }
1978
Chris Lattnerabfbf852007-05-06 00:21:25 +00001979 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1980 unsigned OpNum = 0;
1981 Value *LHS, *RHS;
1982 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1983 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001984 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001985 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001986
Dan Gohman1224c382009-07-20 21:19:07 +00001987 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001988 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001989 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001990 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001991 if (OpNum < Record.size()) {
1992 if (Opc == Instruction::Add ||
1993 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001994 Opc == Instruction::Mul ||
1995 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001996 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001997 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00001998 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001999 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002000 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002001 Opc == Instruction::UDiv ||
2002 Opc == Instruction::LShr ||
2003 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002004 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002005 cast<BinaryOperator>(I)->setIsExact(true);
2006 }
2007 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002008 break;
2009 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002010 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2011 unsigned OpNum = 0;
2012 Value *Op;
2013 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2014 OpNum+2 != Record.size())
2015 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002016
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002017 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002018 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2019 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002020 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002021 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002022 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002023 break;
2024 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002025 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002026 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002027 unsigned OpNum = 0;
2028 Value *BasePtr;
2029 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002030 return Error("Invalid GEP record");
2031
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002032 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002033 while (OpNum != Record.size()) {
2034 Value *Op;
2035 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002036 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002037 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002038 }
2039
Jay Foada9203102011-07-25 09:48:08 +00002040 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002041 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002042 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002043 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002044 break;
2045 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002046
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002047 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2048 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002049 unsigned OpNum = 0;
2050 Value *Agg;
2051 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2052 return Error("Invalid EXTRACTVAL record");
2053
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002054 SmallVector<unsigned, 4> EXTRACTVALIdx;
2055 for (unsigned RecSize = Record.size();
2056 OpNum != RecSize; ++OpNum) {
2057 uint64_t Index = Record[OpNum];
2058 if ((unsigned)Index != Index)
2059 return Error("Invalid EXTRACTVAL index");
2060 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002061 }
2062
Jay Foadfc6d3a42011-07-13 10:26:04 +00002063 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002064 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002065 break;
2066 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002067
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002068 case bitc::FUNC_CODE_INST_INSERTVAL: {
2069 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002070 unsigned OpNum = 0;
2071 Value *Agg;
2072 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2073 return Error("Invalid INSERTVAL record");
2074 Value *Val;
2075 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2076 return Error("Invalid INSERTVAL record");
2077
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002078 SmallVector<unsigned, 4> INSERTVALIdx;
2079 for (unsigned RecSize = Record.size();
2080 OpNum != RecSize; ++OpNum) {
2081 uint64_t Index = Record[OpNum];
2082 if ((unsigned)Index != Index)
2083 return Error("Invalid INSERTVAL index");
2084 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002085 }
2086
Jay Foadfc6d3a42011-07-13 10:26:04 +00002087 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002088 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002089 break;
2090 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002091
Chris Lattnerabfbf852007-05-06 00:21:25 +00002092 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002093 // obsolete form of select
2094 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002095 unsigned OpNum = 0;
2096 Value *TrueVal, *FalseVal, *Cond;
2097 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2098 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002099 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002100 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002101
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002102 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002103 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002104 break;
2105 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002106
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002107 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2108 // new form of select
2109 // handles select i1 or select [N x i1]
2110 unsigned OpNum = 0;
2111 Value *TrueVal, *FalseVal, *Cond;
2112 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2113 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2114 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2115 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002116
2117 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002118 if (VectorType* vector_type =
2119 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002120 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002121 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002122 return Error("Invalid SELECT condition type");
2123 } else {
2124 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002126 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002127 }
2128
Gabor Greif051a9502008-04-06 20:25:17 +00002129 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002130 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002131 break;
2132 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002133
Chris Lattner01ff65f2007-05-02 05:16:49 +00002134 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002135 unsigned OpNum = 0;
2136 Value *Vec, *Idx;
2137 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002138 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002139 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002140 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002141 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002142 break;
2143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Chris Lattner01ff65f2007-05-02 05:16:49 +00002145 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002146 unsigned OpNum = 0;
2147 Value *Vec, *Elt, *Idx;
2148 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002149 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002150 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002151 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002152 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002153 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002154 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002155 break;
2156 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157
Chris Lattnerabfbf852007-05-06 00:21:25 +00002158 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2159 unsigned OpNum = 0;
2160 Value *Vec1, *Vec2, *Mask;
2161 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2162 getValue(Record, OpNum, Vec1->getType(), Vec2))
2163 return Error("Invalid SHUFFLEVEC record");
2164
Mon P Wangaeb06d22008-11-10 04:46:22 +00002165 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002166 return Error("Invalid SHUFFLEVEC record");
2167 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002168 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002169 break;
2170 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002171
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002172 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2173 // Old form of ICmp/FCmp returning bool
2174 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2175 // both legal on vectors but had different behaviour.
2176 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2177 // FCmp/ICmp returning bool or vector of bool
2178
Chris Lattner7337ab92007-05-06 00:00:00 +00002179 unsigned OpNum = 0;
2180 Value *LHS, *RHS;
2181 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2182 getValue(Record, OpNum, LHS->getType(), RHS) ||
2183 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002184 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002185
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002186 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002187 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002188 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002189 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002190 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002191 break;
2192 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002193
Chris Lattner231cbcb2007-05-02 04:27:25 +00002194 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002195 {
2196 unsigned Size = Record.size();
2197 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002198 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002199 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002200 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002201 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002202
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002203 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002204 Value *Op = NULL;
2205 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2206 return Error("Invalid RET record");
2207 if (OpNum != Record.size())
2208 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002209
Chris Lattner96a74c52011-06-17 18:09:11 +00002210 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002211 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002212 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002213 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002214 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002215 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002216 return Error("Invalid BR record");
2217 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2218 if (TrueDest == 0)
2219 return Error("Invalid BR record");
2220
Devang Patele8e02132009-09-18 19:26:43 +00002221 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002222 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002224 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002225 else {
2226 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002227 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002228 if (FalseDest == 0 || Cond == 0)
2229 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002230 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002231 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002232 }
2233 break;
2234 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002235 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002236 // Check magic
2237 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2238 // New SwitchInst format with case ranges.
2239
2240 Type *OpTy = getTypeByID(Record[1]);
2241 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2242
2243 Value *Cond = getFnValueByID(Record[2], OpTy);
2244 BasicBlock *Default = getBasicBlock(Record[3]);
2245 if (OpTy == 0 || Cond == 0 || Default == 0)
2246 return Error("Invalid SWITCH record");
2247
2248 unsigned NumCases = Record[4];
2249
2250 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2251 InstructionList.push_back(SI);
2252
2253 unsigned CurIdx = 5;
2254 for (unsigned i = 0; i != NumCases; ++i) {
2255 CRSBuilder CaseBuilder;
2256 unsigned NumItems = Record[CurIdx++];
2257 for (unsigned ci = 0; ci != NumItems; ++ci) {
2258 bool isSingleNumber = Record[CurIdx++];
2259
2260 APInt Low;
2261 unsigned ActiveWords = 1;
2262 if (ValueBitWidth > 64)
2263 ActiveWords = Record[CurIdx++];
2264 Low = ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2265 CurIdx += ActiveWords;
2266
2267 if (!isSingleNumber) {
2268 ActiveWords = 1;
2269 if (ValueBitWidth > 64)
2270 ActiveWords = Record[CurIdx++];
2271 APInt High =
2272 ReadWideAPInt(&Record[CurIdx], ActiveWords, ValueBitWidth);
2273 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)),
2274 cast<ConstantInt>(ConstantInt::get(OpTy, High)));
2275 CurIdx += ActiveWords;
2276 } else
2277 CaseBuilder.add(cast<ConstantInt>(ConstantInt::get(OpTy, Low)));
2278 }
2279 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2280 ConstantRangesSet Case = CaseBuilder.getCase();
2281 SI->addCase(Case, DestBB);
2282 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002283 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002284 if (Hash != (Record[0] & 0xFFFF))
2285 return Error("Invalid SWITCH record");
2286 I = SI;
2287 break;
2288 }
2289
2290 // Old SwitchInst format without case ranges.
2291
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002292 if (Record.size() < 3 || (Record.size() & 1) == 0)
2293 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002294 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002295 Value *Cond = getFnValueByID(Record[1], OpTy);
2296 BasicBlock *Default = getBasicBlock(Record[2]);
2297 if (OpTy == 0 || Cond == 0 || Default == 0)
2298 return Error("Invalid SWITCH record");
2299 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002300 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002301 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002302 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002303 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002304 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2305 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2306 if (CaseVal == 0 || DestBB == 0) {
2307 delete SI;
2308 return Error("Invalid SWITCH record!");
2309 }
2310 SI->addCase(CaseVal, DestBB);
2311 }
2312 I = SI;
2313 break;
2314 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002315 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002316 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002317 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002318 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002319 Value *Address = getFnValueByID(Record[1], OpTy);
2320 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002321 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002322 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002323 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002324 InstructionList.push_back(IBI);
2325 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2326 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2327 IBI->addDestination(DestBB);
2328 } else {
2329 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002330 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002331 }
2332 }
2333 I = IBI;
2334 break;
2335 }
2336
Duncan Sandsdc024672007-11-27 13:23:08 +00002337 case bitc::FUNC_CODE_INST_INVOKE: {
2338 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002339 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002340 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002341 unsigned CCInfo = Record[1];
2342 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2343 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002344
Chris Lattnera9bb7132007-05-08 05:38:01 +00002345 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002346 Value *Callee;
2347 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002348 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002349
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002350 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2351 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002352 dyn_cast<FunctionType>(CalleeTy->getElementType());
2353
2354 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002355 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2356 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002357 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002358
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002359 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002360 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2361 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2362 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002363 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002364
Chris Lattner7337ab92007-05-06 00:00:00 +00002365 if (!FTy->isVarArg()) {
2366 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002367 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002368 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002369 // Read type/value pairs for varargs params.
2370 while (OpNum != Record.size()) {
2371 Value *Op;
2372 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2373 return Error("Invalid INVOKE record");
2374 Ops.push_back(Op);
2375 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002376 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002377
Jay Foada3efbb12011-07-15 08:37:34 +00002378 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002379 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002380 cast<InvokeInst>(I)->setCallingConv(
2381 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002382 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002383 break;
2384 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002385 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2386 unsigned Idx = 0;
2387 Value *Val = 0;
2388 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2389 return Error("Invalid RESUME record");
2390 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002391 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002392 break;
2393 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002394 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002395 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002396 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002397 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002398 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002399 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002400 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002401 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002402 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002403
Jay Foad3ecfc862011-03-30 11:28:46 +00002404 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002405 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattner15e6d172007-05-04 19:11:41 +00002407 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2408 Value *V = getFnValueByID(Record[1+i], Ty);
2409 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002410 if (!V || !BB) return Error("Invalid PHI record");
2411 PN->addIncoming(V, BB);
2412 }
2413 I = PN;
2414 break;
2415 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002416
Bill Wendlinge6e88262011-08-12 20:24:12 +00002417 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2418 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2419 unsigned Idx = 0;
2420 if (Record.size() < 4)
2421 return Error("Invalid LANDINGPAD record");
2422 Type *Ty = getTypeByID(Record[Idx++]);
2423 if (!Ty) return Error("Invalid LANDINGPAD record");
2424 Value *PersFn = 0;
2425 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2426 return Error("Invalid LANDINGPAD record");
2427
2428 bool IsCleanup = !!Record[Idx++];
2429 unsigned NumClauses = Record[Idx++];
2430 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2431 LP->setCleanup(IsCleanup);
2432 for (unsigned J = 0; J != NumClauses; ++J) {
2433 LandingPadInst::ClauseType CT =
2434 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2435 Value *Val;
2436
2437 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2438 delete LP;
2439 return Error("Invalid LANDINGPAD record");
2440 }
2441
2442 assert((CT != LandingPadInst::Catch ||
2443 !isa<ArrayType>(Val->getType())) &&
2444 "Catch clause has a invalid type!");
2445 assert((CT != LandingPadInst::Filter ||
2446 isa<ArrayType>(Val->getType())) &&
2447 "Filter clause has invalid type!");
2448 LP->addClause(Val);
2449 }
2450
2451 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002452 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002453 break;
2454 }
2455
Chris Lattner96a74c52011-06-17 18:09:11 +00002456 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2457 if (Record.size() != 4)
2458 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002459 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002460 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002461 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002462 Value *Size = getFnValueByID(Record[2], OpTy);
2463 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002464 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002465 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002466 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002467 break;
2468 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002469 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002470 unsigned OpNum = 0;
2471 Value *Op;
2472 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2473 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002474 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002475
Chris Lattner7337ab92007-05-06 00:00:00 +00002476 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002477 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002478 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002479 }
Eli Friedman21006d42011-08-09 23:02:53 +00002480 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2481 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2482 unsigned OpNum = 0;
2483 Value *Op;
2484 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2485 OpNum+4 != Record.size())
2486 return Error("Invalid LOADATOMIC record");
2487
2488
2489 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2490 if (Ordering == NotAtomic || Ordering == Release ||
2491 Ordering == AcquireRelease)
2492 return Error("Invalid LOADATOMIC record");
2493 if (Ordering != NotAtomic && Record[OpNum] == 0)
2494 return Error("Invalid LOADATOMIC record");
2495 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2496
2497 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2498 Ordering, SynchScope);
2499 InstructionList.push_back(I);
2500 break;
2501 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002502 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002503 unsigned OpNum = 0;
2504 Value *Val, *Ptr;
2505 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002506 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002507 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2508 OpNum+2 != Record.size())
2509 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002510
Christopher Lambfe63fb92007-12-11 08:59:05 +00002511 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002512 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002513 break;
2514 }
Eli Friedman21006d42011-08-09 23:02:53 +00002515 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2516 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2517 unsigned OpNum = 0;
2518 Value *Val, *Ptr;
2519 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2520 getValue(Record, OpNum,
2521 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2522 OpNum+4 != Record.size())
2523 return Error("Invalid STOREATOMIC record");
2524
2525 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002526 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002527 Ordering == AcquireRelease)
2528 return Error("Invalid STOREATOMIC record");
2529 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2530 if (Ordering != NotAtomic && Record[OpNum] == 0)
2531 return Error("Invalid STOREATOMIC record");
2532
2533 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2534 Ordering, SynchScope);
2535 InstructionList.push_back(I);
2536 break;
2537 }
Eli Friedmanff030482011-07-28 21:48:00 +00002538 case bitc::FUNC_CODE_INST_CMPXCHG: {
2539 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2540 unsigned OpNum = 0;
2541 Value *Ptr, *Cmp, *New;
2542 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2543 getValue(Record, OpNum,
2544 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2545 getValue(Record, OpNum,
2546 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2547 OpNum+3 != Record.size())
2548 return Error("Invalid CMPXCHG record");
2549 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002550 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002551 return Error("Invalid CMPXCHG record");
2552 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2553 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2554 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2555 InstructionList.push_back(I);
2556 break;
2557 }
2558 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2559 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2560 unsigned OpNum = 0;
2561 Value *Ptr, *Val;
2562 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2563 getValue(Record, OpNum,
2564 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2565 OpNum+4 != Record.size())
2566 return Error("Invalid ATOMICRMW record");
2567 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2568 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2569 Operation > AtomicRMWInst::LAST_BINOP)
2570 return Error("Invalid ATOMICRMW record");
2571 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002572 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002573 return Error("Invalid ATOMICRMW record");
2574 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2575 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2576 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2577 InstructionList.push_back(I);
2578 break;
2579 }
Eli Friedman47f35132011-07-25 23:16:38 +00002580 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2581 if (2 != Record.size())
2582 return Error("Invalid FENCE record");
2583 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2584 if (Ordering == NotAtomic || Ordering == Unordered ||
2585 Ordering == Monotonic)
2586 return Error("Invalid FENCE record");
2587 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2588 I = new FenceInst(Context, Ordering, SynchScope);
2589 InstructionList.push_back(I);
2590 break;
2591 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002592 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002593 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2594 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002595 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002596
Devang Patel05988662008-09-25 21:00:45 +00002597 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002598 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002599
Chris Lattnera9bb7132007-05-08 05:38:01 +00002600 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002601 Value *Callee;
2602 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2603 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002604
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002605 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2606 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002607 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002608 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002609 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002610
Chris Lattner0579f7f2007-05-03 22:04:19 +00002611 SmallVector<Value*, 16> Args;
2612 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002613 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002614 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002615 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002616 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002617 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002618 if (Args.back() == 0) return Error("Invalid CALL record");
2619 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002620
Chris Lattner0579f7f2007-05-03 22:04:19 +00002621 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002622 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002623 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002624 return Error("Invalid CALL record");
2625 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002626 while (OpNum != Record.size()) {
2627 Value *Op;
2628 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2629 return Error("Invalid CALL record");
2630 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002631 }
2632 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002633
Jay Foada3efbb12011-07-15 08:37:34 +00002634 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002635 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002636 cast<CallInst>(I)->setCallingConv(
2637 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002638 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002639 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002640 break;
2641 }
2642 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2643 if (Record.size() < 3)
2644 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002645 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002646 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002647 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002648 if (!OpTy || !Op || !ResTy)
2649 return Error("Invalid VAARG record");
2650 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002651 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002652 break;
2653 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002654 }
2655
2656 // Add instruction to end of current BB. If there is no current BB, reject
2657 // this file.
2658 if (CurBB == 0) {
2659 delete I;
2660 return Error("Invalid instruction with no BB");
2661 }
2662 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002663
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002664 // If this was a terminator instruction, move to the next block.
2665 if (isa<TerminatorInst>(I)) {
2666 ++CurBBNo;
2667 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2668 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002669
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002670 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002671 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002672 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002673 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002674
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002675 // Check the function list for unresolved values.
2676 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2677 if (A->getParent() == 0) {
2678 // We found at least one unresolved value. Nuke them all to avoid leaks.
2679 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002680 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002681 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002682 delete A;
2683 }
2684 }
Chris Lattner35a04702007-05-04 03:50:29 +00002685 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002686 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002687 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002688
Dan Gohman064ff3e2010-08-25 20:23:38 +00002689 // FIXME: Check for unresolved forward-declared metadata references
2690 // and clean up leaks.
2691
Chris Lattner50b136d2009-10-28 05:53:48 +00002692 // See if anything took the address of blocks in this function. If so,
2693 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002694 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2695 BlockAddrFwdRefs.find(F);
2696 if (BAFRI != BlockAddrFwdRefs.end()) {
2697 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2698 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2699 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002700 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002701 return Error("Invalid blockaddress block #");
2702
2703 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002704 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002705 FwdRef->eraseFromParent();
2706 }
2707
2708 BlockAddrFwdRefs.erase(BAFRI);
2709 }
2710
Chris Lattner980e5aa2007-05-01 05:52:21 +00002711 // Trim the value list down to the size it was before we parsed this function.
2712 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002713 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002714 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002715 return false;
2716}
2717
Derek Schuff2ea93872012-02-06 22:30:29 +00002718/// FindFunctionInStream - Find the function body in the bitcode stream
2719bool BitcodeReader::FindFunctionInStream(Function *F,
2720 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2721 while (DeferredFunctionInfoIterator->second == 0) {
2722 if (Stream.AtEndOfStream())
2723 return Error("Could not find Function in stream");
2724 // ParseModule will parse the next body in the stream and set its
2725 // position in the DeferredFunctionInfo map.
2726 if (ParseModule(true)) return true;
2727 }
2728 return false;
2729}
2730
Chris Lattnerb348bb82007-05-18 04:02:46 +00002731//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002732// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002733//===----------------------------------------------------------------------===//
2734
2735
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002736bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2737 if (const Function *F = dyn_cast<Function>(GV)) {
2738 return F->isDeclaration() &&
2739 DeferredFunctionInfo.count(const_cast<Function*>(F));
2740 }
2741 return false;
2742}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002743
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002744bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2745 Function *F = dyn_cast<Function>(GV);
2746 // If it's not a function or is already material, ignore the request.
2747 if (!F || !F->isMaterializable()) return false;
2748
2749 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002750 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002751 // If its position is recorded as 0, its body is somewhere in the stream
2752 // but we haven't seen it yet.
2753 if (DFII->second == 0)
2754 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002755
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002756 // Move the bit stream to the saved position of the deferred function body.
2757 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002758
Chris Lattnerb348bb82007-05-18 04:02:46 +00002759 if (ParseFunctionBody(F)) {
2760 if (ErrInfo) *ErrInfo = ErrorString;
2761 return true;
2762 }
Chandler Carruth69940402007-08-04 01:51:18 +00002763
2764 // Upgrade any old intrinsic calls in the function.
2765 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2766 E = UpgradedIntrinsics.end(); I != E; ++I) {
2767 if (I->first != I->second) {
2768 for (Value::use_iterator UI = I->first->use_begin(),
2769 UE = I->first->use_end(); UI != UE; ) {
2770 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2771 UpgradeIntrinsicCall(CI, I->second);
2772 }
2773 }
2774 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002775
Chris Lattnerb348bb82007-05-18 04:02:46 +00002776 return false;
2777}
2778
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002779bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2780 const Function *F = dyn_cast<Function>(GV);
2781 if (!F || F->isDeclaration())
2782 return false;
2783 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2784}
2785
2786void BitcodeReader::Dematerialize(GlobalValue *GV) {
2787 Function *F = dyn_cast<Function>(GV);
2788 // If this function isn't dematerializable, this is a noop.
2789 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002790 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerb348bb82007-05-18 04:02:46 +00002792 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002793
Chris Lattnerb348bb82007-05-18 04:02:46 +00002794 // Just forget the function body, we can remat it later.
2795 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002796}
2797
2798
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002799bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2800 assert(M == TheModule &&
2801 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002802 // Iterate over the module, deserializing any functions that are still on
2803 // disk.
2804 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2805 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002806 if (F->isMaterializable() &&
2807 Materialize(F, ErrInfo))
2808 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002809
Derek Schuff0ffe6982012-02-29 00:07:09 +00002810 // At this point, if there are any function bodies, the current bit is
2811 // pointing to the END_BLOCK record after them. Now make sure the rest
2812 // of the bits in the module have been read.
2813 if (NextUnreadBit)
2814 ParseModule(true);
2815
Daniel Dunbara279bc32009-09-20 02:20:51 +00002816 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2817 // delete the old functions to clean up. We can't do this unless the entire
2818 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002819 // with calls to the old function.
2820 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2821 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2822 if (I->first != I->second) {
2823 for (Value::use_iterator UI = I->first->use_begin(),
2824 UE = I->first->use_end(); UI != UE; ) {
2825 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2826 UpgradeIntrinsicCall(CI, I->second);
2827 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002828 if (!I->first->use_empty())
2829 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002830 I->first->eraseFromParent();
2831 }
2832 }
2833 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002834
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002835 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002836}
2837
Derek Schuff2ea93872012-02-06 22:30:29 +00002838bool BitcodeReader::InitStream() {
2839 if (LazyStreamer) return InitLazyStream();
2840 return InitStreamFromBuffer();
2841}
2842
2843bool BitcodeReader::InitStreamFromBuffer() {
2844 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2845 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2846
2847 if (Buffer->getBufferSize() & 3) {
2848 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2849 return Error("Invalid bitcode signature");
2850 else
2851 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2852 }
2853
2854 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2855 // The magic number is 0x0B17C0DE stored in little endian.
2856 if (isBitcodeWrapper(BufPtr, BufEnd))
2857 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2858 return Error("Invalid bitcode wrapper header");
2859
2860 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2861 Stream.init(*StreamFile);
2862
2863 return false;
2864}
2865
2866bool BitcodeReader::InitLazyStream() {
2867 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2868 // see it.
2869 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2870 StreamFile.reset(new BitstreamReader(Bytes));
2871 Stream.init(*StreamFile);
2872
2873 unsigned char buf[16];
2874 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2875 return Error("Bitcode stream must be at least 16 bytes in length");
2876
2877 if (!isBitcode(buf, buf + 16))
2878 return Error("Invalid bitcode signature");
2879
2880 if (isBitcodeWrapper(buf, buf + 4)) {
2881 const unsigned char *bitcodeStart = buf;
2882 const unsigned char *bitcodeEnd = buf + 16;
2883 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2884 Bytes->dropLeadingBytes(bitcodeStart - buf);
2885 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2886 }
2887 return false;
2888}
Chris Lattner48f84872007-05-01 04:59:48 +00002889
Chris Lattnerc453f762007-04-29 07:54:31 +00002890//===----------------------------------------------------------------------===//
2891// External interface
2892//===----------------------------------------------------------------------===//
2893
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002894/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002895///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002896Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2897 LLVMContext& Context,
2898 std::string *ErrMsg) {
2899 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002900 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002901 M->setMaterializer(R);
2902 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002903 if (ErrMsg)
2904 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002906 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002907 return 0;
2908 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002909 // Have the BitcodeReader dtor delete 'Buffer'.
2910 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002911
2912 R->materializeForwardReferencedFunctions();
2913
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002914 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002915}
2916
Derek Schuff2ea93872012-02-06 22:30:29 +00002917
2918Module *llvm::getStreamedBitcodeModule(const std::string &name,
2919 DataStreamer *streamer,
2920 LLVMContext &Context,
2921 std::string *ErrMsg) {
2922 Module *M = new Module(name, Context);
2923 BitcodeReader *R = new BitcodeReader(streamer, Context);
2924 M->setMaterializer(R);
2925 if (R->ParseBitcodeInto(M)) {
2926 if (ErrMsg)
2927 *ErrMsg = R->getErrorString();
2928 delete M; // Also deletes R.
2929 return 0;
2930 }
2931 R->setBufferOwned(false); // no buffer to delete
2932 return M;
2933}
2934
Chris Lattnerc453f762007-04-29 07:54:31 +00002935/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2936/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002937Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002938 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002939 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2940 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002941
2942 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2943 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002944 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002945
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002946 // Read in the entire module, and destroy the BitcodeReader.
2947 if (M->MaterializeAllPermanently(ErrMsg)) {
2948 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002949 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002950 }
Bill Wendling34711742010-10-06 01:22:42 +00002951
Chad Rosiercbbb0962011-12-07 21:44:12 +00002952 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2953 // written. We must defer until the Module has been fully materialized.
2954
Chris Lattnerc453f762007-04-29 07:54:31 +00002955 return M;
2956}
Bill Wendling34711742010-10-06 01:22:42 +00002957
2958std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2959 LLVMContext& Context,
2960 std::string *ErrMsg) {
2961 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2962 // Don't let the BitcodeReader dtor delete 'Buffer'.
2963 R->setBufferOwned(false);
2964
2965 std::string Triple("");
2966 if (R->ParseTriple(Triple))
2967 if (ErrMsg)
2968 *ErrMsg = R->getErrorString();
2969
2970 delete R;
2971 return Triple;
2972}