blob: e10e6d6476b2f0e694b2781d98e9fa5ee59ea670 [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//===----------------------------------------------------------------------===//
Chris Lattnercaee0dc2007-04-22 06:23:29 +00009
Chris Lattnerc453f762007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/Constants.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/InlineAsm.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OperandTraits.h"
21#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000022#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000023#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000025using namespace llvm;
26
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000027enum {
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
29};
30
Rafael Espindola47f79bb2012-01-02 07:49:53 +000031void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
34 F->Materialize();
35 }
36}
37
Chris Lattnerb348bb82007-05-18 04:02:46 +000038void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000039 if (BufferOwned)
40 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000041 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000042 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000044 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000045
Bill Wendling99faa3b2012-12-07 23:16:57 +000046 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000050 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000051
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000053}
54
Chris Lattner48c85b82007-05-04 03:30:17 +000055//===----------------------------------------------------------------------===//
56// Helper functions to implement forward reference resolution, etc.
57//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000058
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059/// ConvertToString - Convert a string from a record into an std::string, return
60/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000061template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000062static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000063 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000064 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000065 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000066
Chris Lattner15e6d172007-05-04 19:11:41 +000067 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return false;
70}
71
72static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000075 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000085 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000087 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000088 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000089 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000090 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000091 }
92}
93
94static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
95 switch (Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000099 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000100 }
101}
102
Hans Wennborgce718ff2012-06-23 11:37:03 +0000103static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
104 switch (Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
111 }
112}
113
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000114static int GetDecodedCastOpcode(unsigned Val) {
115 switch (Val) {
116 default: return -1;
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
129 }
130}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000131static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 switch (Val) {
133 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000134 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
152 }
153}
154
Eli Friedmanff030482011-07-28 21:48:00 +0000155static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
156 switch (Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
169 }
170}
171
Eli Friedman47f35132011-07-25 23:16:38 +0000172static AtomicOrdering GetDecodedOrdering(unsigned Val) {
173 switch (Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
182 }
183}
184
185static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
186 switch (Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
190 }
191}
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000194namespace {
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000199 public:
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
203 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000208
Chris Lattnerea693df2008-08-21 02:34:16 +0000209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000210 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
215
Gabor Greifefe65362008-05-10 08:32:32 +0000216 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000218 };
219}
220
Chris Lattner46e77402009-03-31 22:55:09 +0000221// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000222template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000223struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000225};
Gabor Greifefe65362008-05-10 08:32:32 +0000226}
227
Chris Lattner46e77402009-03-31 22:55:09 +0000228
229void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
230 if (Idx == size()) {
231 push_back(V);
232 return;
233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
Chris Lattner46e77402009-03-31 22:55:09 +0000235 if (Idx >= size())
236 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 WeakVH &OldV = ValuePtrs[Idx];
239 if (OldV == 0) {
240 OldV = V;
241 return;
242 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Chris Lattner46e77402009-03-31 22:55:09 +0000244 // Handle constants and non-constants (e.g. instrs) differently for
245 // efficiency.
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
248 OldV = V;
249 } else {
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
253 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000254 }
255}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000256
Gabor Greifefe65362008-05-10 08:32:32 +0000257
Chris Lattner522b7b12007-04-24 05:48:56 +0000258Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000260 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000261 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000262
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000266 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
268 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000269 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000270 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000271 return C;
272}
273
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000275 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000276 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
280 return V;
281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner01ff65f2007-05-02 05:16:49 +0000283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000288 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 return V;
290}
291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293/// resolves any forward references. The idea behind this is that we sometimes
294/// get constants (such as large arrays) which reference *many* forward ref
295/// constants. Replacing each of these causes a lot of thrashing when
296/// building/reuniquing the constant. Instead of doing this, we look at all the
297/// uses and rewrite all the place holders at once for any constant that uses
298/// a placeholder.
299void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000301 // binary search.
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000307 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
313 // at once.
314 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000315 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000316 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerea693df2008-08-21 02:34:16 +0000318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000321 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000322 continue;
323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000327 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
329 I != E; ++I) {
330 Value *NewOp;
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
333 NewOp = *I;
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
336 NewOp = RealVal;
337 } else {
338 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
342 0));
343 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000344 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000345 }
346
347 NewOps.push_back(cast<Constant>(NewOp));
348 }
349
350 // Make the new constant.
351 Constant *NewC;
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000356 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000357 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000358 } else {
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerea693df2008-08-21 02:34:16 +0000363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
365 NewOps.clear();
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Nick Lewyckycb337992009-05-10 20:57:05 +0000368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000370 delete Placeholder;
371 }
372}
373
Devang Pateld5ac4042009-08-04 06:00:18 +0000374void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
375 if (Idx == size()) {
376 push_back(V);
377 return;
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Devang Pateld5ac4042009-08-04 06:00:18 +0000380 if (Idx >= size())
381 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 WeakVH &OldV = MDValuePtrs[Idx];
384 if (OldV == 0) {
385 OldV = V;
386 return;
387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000390 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000392 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
394 // value for Idx.
395 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000396}
397
398Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
399 if (Idx >= size())
400 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Devang Pateld5ac4042009-08-04 06:00:18 +0000402 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000404 return V;
405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000408 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 MDValuePtrs[Idx] = V;
410 return V;
411}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
416 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418 if (Type *Ty = TypeList[ID])
419 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000423 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424}
425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426
Chris Lattner48c85b82007-05-04 03:30:17 +0000427//===----------------------------------------------------------------------===//
428// Functions for parsing blocks from the bitcode file
429//===----------------------------------------------------------------------===//
430
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000431
432/// \brief This fills an AttrBuilder object with the LLVM attributes that have
433/// been decoded from the given integer. This function must stay in sync with
434/// 'encodeLLVMAttributesForBitcode'.
435static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
436 uint64_t EncodedAttrs) {
437 // FIXME: Remove in 4.0.
438
439 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
440 // the bits above 31 down by 11 bits.
441 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
442 assert((!Alignment || isPowerOf2_32(Alignment)) &&
443 "Alignment must be a power of two.");
444
445 if (Alignment)
446 B.addAlignmentAttr(Alignment);
447 B.addRawValue(((EncodedAttrs & (0xffffULL << 32)) >> 11) |
448 (EncodedAttrs & 0xffff));
449}
450
Devang Patel05988662008-09-25 21:00:45 +0000451bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000452 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000453 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000454
Devang Patel19c87462008-09-26 22:53:05 +0000455 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Chris Lattner48c85b82007-05-04 03:30:17 +0000458 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000460 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Chris Lattner48c85b82007-05-04 03:30:17 +0000462 // Read all the records.
463 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000464 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
465
466 switch (Entry.Kind) {
467 case BitstreamEntry::SubBlock: // Handled for us already.
468 case BitstreamEntry::Error:
469 return Error("Error at end of PARAMATTR block");
470 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000471 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000472 case BitstreamEntry::Record:
473 // The interesting case.
474 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000475 }
Chris Lattner5a4251c2013-01-20 02:13:19 +0000476
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 // Read a record.
478 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000479 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 default: // Default behavior: ignore.
481 break;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000482 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
483 // FIXME: Remove in 4.0.
Chris Lattner48c85b82007-05-04 03:30:17 +0000484 if (Record.size() & 1)
485 return Error("Invalid ENTRY record");
486
Chris Lattner48c85b82007-05-04 03:30:17 +0000487 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling8232ece2013-01-29 01:43:29 +0000488 AttrBuilder B;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000489 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling8232ece2013-01-29 01:43:29 +0000490 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000491 }
Devang Patel19c87462008-09-26 22:53:05 +0000492
Bill Wendling99faa3b2012-12-07 23:16:57 +0000493 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000494 Attrs.clear();
495 break;
496 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000497 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000498 }
499}
500
Chris Lattner86697142007-05-01 05:01:34 +0000501bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000502 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000503 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000504
Chris Lattner1afcace2011-07-09 17:41:24 +0000505 return ParseTypeTableBody();
506}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000507
Chris Lattner1afcace2011-07-09 17:41:24 +0000508bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000509 if (!TypeList.empty())
510 return Error("Multiple TYPE_BLOCKs found!");
511
512 SmallVector<uint64_t, 64> Record;
513 unsigned NumRecords = 0;
514
Chris Lattner1afcace2011-07-09 17:41:24 +0000515 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000516
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000517 // Read all the records for this type table.
518 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000519 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
520
521 switch (Entry.Kind) {
522 case BitstreamEntry::SubBlock: // Handled for us already.
523 case BitstreamEntry::Error:
524 Error("Error in the type table block");
525 return true;
526 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000527 if (NumRecords != TypeList.size())
528 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000529 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000530 case BitstreamEntry::Record:
531 // The interesting case.
532 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000533 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000534
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000535 // Read a record.
536 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000537 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000538 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000539 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000540 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
541 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
542 // type list. This allows us to reserve space.
543 if (Record.size() < 1)
544 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000545 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000546 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000548 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 break;
Dan Gohmance163392011-12-17 00:04:22 +0000550 case bitc::TYPE_CODE_HALF: // HALF
551 ResultTy = Type::getHalfTy(Context);
552 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000553 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000554 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000555 break;
556 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000559 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000561 break;
562 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000564 break;
565 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000567 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000568 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000571 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000573 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000574 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
575 ResultTy = Type::getX86_MMXTy(Context);
576 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000577 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
578 if (Record.size() < 1)
579 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000580
Owen Anderson1d0be152009-08-13 21:58:54 +0000581 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000582 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000583 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000584 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 if (Record.size() < 1)
586 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000587 unsigned AddressSpace = 0;
588 if (Record.size() == 2)
589 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000590 ResultTy = getTypeByID(Record[0]);
591 if (ResultTy == 0) return Error("invalid element type in pointer type");
592 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000593 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000594 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000595 case bitc::TYPE_CODE_FUNCTION_OLD: {
596 // FIXME: attrid is dead, remove it in LLVM 4.0
597 // FUNCTION: [vararg, attrid, retty, paramty x N]
598 if (Record.size() < 3)
599 return Error("Invalid FUNCTION type record");
600 SmallVector<Type*, 8> ArgTys;
601 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
602 if (Type *T = getTypeByID(Record[i]))
603 ArgTys.push_back(T);
604 else
605 break;
606 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000607
Nuno Lopesee8100d2012-05-23 15:19:39 +0000608 ResultTy = getTypeByID(Record[2]);
609 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
610 return Error("invalid type in function type");
611
612 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
613 break;
614 }
Chad Rosiercde54642011-11-03 00:14:01 +0000615 case bitc::TYPE_CODE_FUNCTION: {
616 // FUNCTION: [vararg, retty, paramty x N]
617 if (Record.size() < 2)
618 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000619 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000620 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
621 if (Type *T = getTypeByID(Record[i]))
622 ArgTys.push_back(T);
623 else
624 break;
625 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000626
Chad Rosiercde54642011-11-03 00:14:01 +0000627 ResultTy = getTypeByID(Record[1]);
628 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
629 return Error("invalid type in function type");
630
631 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
632 break;
633 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000634 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000635 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000636 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000637 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000638 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
639 if (Type *T = getTypeByID(Record[i]))
640 EltTys.push_back(T);
641 else
642 break;
643 }
644 if (EltTys.size() != Record.size()-1)
645 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000646 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000647 break;
648 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000649 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
650 if (ConvertToString(Record, 0, TypeName))
651 return Error("Invalid STRUCT_NAME record");
652 continue;
653
654 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
655 if (Record.size() < 1)
656 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000657
Chris Lattner1afcace2011-07-09 17:41:24 +0000658 if (NumRecords >= TypeList.size())
659 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000660
Chris Lattner1afcace2011-07-09 17:41:24 +0000661 // Check to see if this was forward referenced, if so fill in the temp.
662 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
663 if (Res) {
664 Res->setName(TypeName);
665 TypeList[NumRecords] = 0;
666 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000667 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000668 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000669
Chris Lattner1afcace2011-07-09 17:41:24 +0000670 SmallVector<Type*, 8> EltTys;
671 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
672 if (Type *T = getTypeByID(Record[i]))
673 EltTys.push_back(T);
674 else
675 break;
676 }
677 if (EltTys.size() != Record.size()-1)
678 return Error("invalid STRUCT type record");
679 Res->setBody(EltTys, Record[0]);
680 ResultTy = Res;
681 break;
682 }
683 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
684 if (Record.size() != 1)
685 return Error("Invalid OPAQUE type record");
686
687 if (NumRecords >= TypeList.size())
688 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000689
Chris Lattner1afcace2011-07-09 17:41:24 +0000690 // Check to see if this was forward referenced, if so fill in the temp.
691 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
692 if (Res) {
693 Res->setName(TypeName);
694 TypeList[NumRecords] = 0;
695 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000696 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000697 TypeName.clear();
698 ResultTy = Res;
699 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000700 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000701 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
702 if (Record.size() < 2)
703 return Error("Invalid ARRAY type record");
704 if ((ResultTy = getTypeByID(Record[1])))
705 ResultTy = ArrayType::get(ResultTy, Record[0]);
706 else
707 return Error("Invalid ARRAY type element");
708 break;
709 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
710 if (Record.size() < 2)
711 return Error("Invalid VECTOR type record");
712 if ((ResultTy = getTypeByID(Record[1])))
713 ResultTy = VectorType::get(ResultTy, Record[0]);
714 else
715 return Error("Invalid ARRAY type element");
716 break;
717 }
718
719 if (NumRecords >= TypeList.size())
720 return Error("invalid TYPE table");
721 assert(ResultTy && "Didn't read a type?");
722 assert(TypeList[NumRecords] == 0 && "Already read type?");
723 TypeList[NumRecords++] = ResultTy;
724 }
725}
726
Chris Lattner86697142007-05-01 05:01:34 +0000727bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000728 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000729 return Error("Malformed block record");
730
731 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000732
Chris Lattner0b2482a2007-04-23 21:26:05 +0000733 // Read all the records for this value table.
734 SmallString<128> ValueName;
735 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000736 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
737
738 switch (Entry.Kind) {
739 case BitstreamEntry::SubBlock: // Handled for us already.
740 case BitstreamEntry::Error:
741 return Error("malformed value symbol table block");
742 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000743 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000744 case BitstreamEntry::Record:
745 // The interesting case.
746 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000748
Chris Lattner0b2482a2007-04-23 21:26:05 +0000749 // Read a record.
750 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000751 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000752 default: // Default behavior: unknown type.
753 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000754 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000755 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000756 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000757 unsigned ValueID = Record[0];
758 if (ValueID >= ValueList.size())
759 return Error("Invalid Value ID in VST_ENTRY record");
760 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000761
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000762 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000763 ValueName.clear();
764 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000765 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000766 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000767 if (ConvertToString(Record, 1, ValueName))
768 return Error("Invalid VST_BBENTRY record");
769 BasicBlock *BB = getBasicBlock(Record[0]);
770 if (BB == 0)
771 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000772
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000773 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000774 ValueName.clear();
775 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000776 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000777 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000778 }
779}
780
Devang Patele54abc92009-07-22 17:43:22 +0000781bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000782 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000783
784 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
785 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000786
Devang Patele54abc92009-07-22 17:43:22 +0000787 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000788
Devang Patele54abc92009-07-22 17:43:22 +0000789 // Read all the records.
790 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000791 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
792
793 switch (Entry.Kind) {
794 case BitstreamEntry::SubBlock: // Handled for us already.
795 case BitstreamEntry::Error:
796 Error("malformed metadata block");
797 return true;
798 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +0000799 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000800 case BitstreamEntry::Record:
801 // The interesting case.
802 break;
Devang Patele54abc92009-07-22 17:43:22 +0000803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000804
Victor Hernandez24e64df2010-01-10 07:14:18 +0000805 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000806 // Read a record.
807 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000808 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000809 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000810 default: // Default behavior: ignore.
811 break;
Devang Patelaa993142009-07-29 22:34:41 +0000812 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +0000813 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000814 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000815 Record.clear();
816 Code = Stream.ReadCode();
817
Chris Lattner9d61dd92011-06-17 17:50:30 +0000818 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +0000819 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000820 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000821
822 // Read named metadata elements.
823 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000824 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000825 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000826 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
827 if (MD == 0)
828 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000829 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000830 }
Devang Patelaa993142009-07-29 22:34:41 +0000831 break;
832 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000833 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000834 IsFunctionLocal = true;
835 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000836 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000837 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000838 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Devang Patel104cf9e2009-07-23 01:07:34 +0000840 unsigned Size = Record.size();
841 SmallVector<Value*, 8> Elts;
842 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000843 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000844 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000845 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000846 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000847 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000848 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
849 else
850 Elts.push_back(NULL);
851 }
Jay Foadec9186b2011-04-21 19:59:31 +0000852 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000853 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000854 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000855 break;
856 }
Devang Patele54abc92009-07-22 17:43:22 +0000857 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000858 SmallString<8> String(Record.begin(), Record.end());
859 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000860 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000861 break;
862 }
Devang Patele8e02132009-09-18 19:26:43 +0000863 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000864 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000865 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000866
Devang Patela2148402009-09-28 21:14:55 +0000867 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000868 SmallString<8> Name(Record.begin()+1, Record.end());
869
Chris Lattner08113472009-12-29 09:01:33 +0000870 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000871 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
872 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000873 break;
874 }
Devang Patele54abc92009-07-22 17:43:22 +0000875 }
876 }
877}
878
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000879/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000880/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000881uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000882 if ((V & 1) == 0)
883 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000884 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000885 return -(V >> 1);
886 // There is no such thing as -0 with integers. "-0" really means MININT.
887 return 1ULL << 63;
888}
889
Chris Lattner07d98b42007-04-26 02:46:40 +0000890/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
891/// values and aliases that we can.
892bool BitcodeReader::ResolveGlobalAndAliasInits() {
893 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
894 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895
Chris Lattner07d98b42007-04-26 02:46:40 +0000896 GlobalInitWorklist.swap(GlobalInits);
897 AliasInitWorklist.swap(AliasInits);
898
899 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000900 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000901 if (ValID >= ValueList.size()) {
902 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000903 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000904 } else {
905 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
906 GlobalInitWorklist.back().first->setInitializer(C);
907 else
908 return Error("Global variable initializer is not a constant!");
909 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000910 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000911 }
912
913 while (!AliasInitWorklist.empty()) {
914 unsigned ValID = AliasInitWorklist.back().second;
915 if (ValID >= ValueList.size()) {
916 AliasInits.push_back(AliasInitWorklist.back());
917 } else {
918 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000919 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000920 else
921 return Error("Alias initializer is not a constant!");
922 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000924 }
925 return false;
926}
927
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000928static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
929 SmallVector<uint64_t, 8> Words(Vals.size());
930 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000931 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000932
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000933 return APInt(TypeBits, Words);
934}
935
Chris Lattner86697142007-05-01 05:01:34 +0000936bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000937 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000938 return Error("Malformed block record");
939
940 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000941
Chris Lattnere16504e2007-04-24 03:30:34 +0000942 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000943 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000944 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000945 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000946 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
947
948 switch (Entry.Kind) {
949 case BitstreamEntry::SubBlock: // Handled for us already.
950 case BitstreamEntry::Error:
951 return Error("malformed block record in AST file");
952 case BitstreamEntry::EndBlock:
953 if (NextCstNo != ValueList.size())
954 return Error("Invalid constant reference!");
955
956 // Once all the constants have been read, go through and resolve forward
957 // references.
958 ValueList.ResolveConstantForwardRefs();
959 return false;
960 case BitstreamEntry::Record:
961 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +0000962 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000963 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 // Read a record.
966 Record.clear();
967 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000968 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +0000969 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000970 default: // Default behavior: unknown constant
971 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000972 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 break;
974 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
975 if (Record.empty())
976 return Error("Malformed CST_SETTYPE record");
977 if (Record[0] >= TypeList.size())
978 return Error("Invalid Type ID in CST_SETTYPE record");
979 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000980 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000981 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000982 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 break;
984 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000985 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000986 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000987 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000988 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000989 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000990 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000991 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000992
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000993 APInt VInt = ReadWideAPInt(Record,
994 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000995 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +0000996
Chris Lattner0eef0802007-04-24 04:04:35 +0000997 break;
998 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000999 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001000 if (Record.empty())
1001 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001002 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001003 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1004 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001005 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001006 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1007 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001008 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001009 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1010 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001011 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001012 // Bits are not stored the same way as a normal i80 APInt, compensate.
1013 uint64_t Rearrange[2];
1014 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1015 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001016 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1017 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001018 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001019 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1020 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001021 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001022 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1023 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001024 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001025 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001026 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001027 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001028
Chris Lattner15e6d172007-05-04 19:11:41 +00001029 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1030 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001031 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001032
Chris Lattner15e6d172007-05-04 19:11:41 +00001033 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001034 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001037 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001038 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001039 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001040 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001041 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1042 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001043 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001044 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001045 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001046 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1047 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001048 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001049 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001050 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001051 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001052 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001053 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001054 break;
1055 }
Chris Lattner2237f842012-02-05 02:41:35 +00001056 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001057 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1058 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001059 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001060
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001061 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001062 V = ConstantDataArray::getString(Context, Elts,
1063 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001064 break;
1065 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001066 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1067 if (Record.empty())
1068 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001069
Chris Lattnerd408f062012-01-30 00:51:16 +00001070 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1071 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001072
Chris Lattnerd408f062012-01-30 00:51:16 +00001073 if (EltTy->isIntegerTy(8)) {
1074 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1075 if (isa<VectorType>(CurTy))
1076 V = ConstantDataVector::get(Context, Elts);
1077 else
1078 V = ConstantDataArray::get(Context, Elts);
1079 } else if (EltTy->isIntegerTy(16)) {
1080 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1081 if (isa<VectorType>(CurTy))
1082 V = ConstantDataVector::get(Context, Elts);
1083 else
1084 V = ConstantDataArray::get(Context, Elts);
1085 } else if (EltTy->isIntegerTy(32)) {
1086 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1087 if (isa<VectorType>(CurTy))
1088 V = ConstantDataVector::get(Context, Elts);
1089 else
1090 V = ConstantDataArray::get(Context, Elts);
1091 } else if (EltTy->isIntegerTy(64)) {
1092 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1093 if (isa<VectorType>(CurTy))
1094 V = ConstantDataVector::get(Context, Elts);
1095 else
1096 V = ConstantDataArray::get(Context, Elts);
1097 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001098 SmallVector<float, 16> Elts(Size);
1099 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001100 if (isa<VectorType>(CurTy))
1101 V = ConstantDataVector::get(Context, Elts);
1102 else
1103 V = ConstantDataArray::get(Context, Elts);
1104 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001105 SmallVector<double, 16> Elts(Size);
1106 std::transform(Record.begin(), Record.end(), Elts.begin(),
1107 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001108 if (isa<VectorType>(CurTy))
1109 V = ConstantDataVector::get(Context, Elts);
1110 else
1111 V = ConstantDataArray::get(Context, Elts);
1112 } else {
1113 return Error("Unknown element type in CE_DATA");
1114 }
1115 break;
1116 }
1117
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001118 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1119 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1120 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001121 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001122 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001123 } else {
1124 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1125 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001126 unsigned Flags = 0;
1127 if (Record.size() >= 4) {
1128 if (Opc == Instruction::Add ||
1129 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001130 Opc == Instruction::Mul ||
1131 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001132 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1133 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1134 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1135 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001136 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001137 Opc == Instruction::UDiv ||
1138 Opc == Instruction::LShr ||
1139 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001140 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001141 Flags |= SDivOperator::IsExact;
1142 }
1143 }
1144 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001145 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001146 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001147 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001148 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1149 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1150 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001151 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001152 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001153 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001154 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001155 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001156 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001157 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001159 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001160 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001161 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001162 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001163 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001164 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001165 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001166 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001167 if (!ElTy) return Error("Invalid CE_GEP record");
1168 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1169 }
Jay Foaddab3d292011-07-21 14:31:17 +00001170 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001171 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1172 BitCode ==
1173 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001174 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001175 }
1176 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1177 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001178 V = ConstantExpr::getSelect(
1179 ValueList.getConstantFwdRef(Record[0],
1180 Type::getInt1Ty(Context)),
1181 ValueList.getConstantFwdRef(Record[1],CurTy),
1182 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001183 break;
1184 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1185 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001186 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001187 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1188 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1189 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001190 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001191 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001192 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001193 break;
1194 }
1195 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001196 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001197 if (Record.size() < 3 || OpTy == 0)
1198 return Error("Invalid CE_INSERTELT record");
1199 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1200 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1201 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001202 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001203 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001204 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001205 break;
1206 }
1207 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001208 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001209 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001210 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001211 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1212 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001213 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001214 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001215 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001216 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001217 break;
1218 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001219 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001220 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1221 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001222 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001223 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1224 return Error("Invalid CE_SHUFVEC_EX record");
1225 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1226 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001227 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001228 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001229 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001230 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001231 break;
1232 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001233 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1234 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001235 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 if (OpTy == 0) return Error("Invalid CE_CMP record");
1237 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1238 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1239
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001240 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001241 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001242 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001243 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001244 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001245 }
Chad Rosier581600b2012-09-05 19:00:49 +00001246 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001247 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001248 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001249 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1250 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001251 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001252 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001253 unsigned AsmStrSize = Record[1];
1254 if (2+AsmStrSize >= Record.size())
1255 return Error("Invalid INLINEASM record");
1256 unsigned ConstStrSize = Record[2+AsmStrSize];
1257 if (3+AsmStrSize+ConstStrSize > Record.size())
1258 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001259
Chris Lattner2bce93a2007-05-06 01:58:20 +00001260 for (unsigned i = 0; i != AsmStrSize; ++i)
1261 AsmStr += (char)Record[2+i];
1262 for (unsigned i = 0; i != ConstStrSize; ++i)
1263 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001264 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001265 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001266 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001267 break;
1268 }
Chad Rosier581600b2012-09-05 19:00:49 +00001269 // This version adds support for the asm dialect keywords (e.g.,
1270 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001271 case bitc::CST_CODE_INLINEASM: {
1272 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1273 std::string AsmStr, ConstrStr;
1274 bool HasSideEffects = Record[0] & 1;
1275 bool IsAlignStack = (Record[0] >> 1) & 1;
1276 unsigned AsmDialect = Record[0] >> 2;
1277 unsigned AsmStrSize = Record[1];
1278 if (2+AsmStrSize >= Record.size())
1279 return Error("Invalid INLINEASM record");
1280 unsigned ConstStrSize = Record[2+AsmStrSize];
1281 if (3+AsmStrSize+ConstStrSize > Record.size())
1282 return Error("Invalid INLINEASM record");
1283
1284 for (unsigned i = 0; i != AsmStrSize; ++i)
1285 AsmStr += (char)Record[2+i];
1286 for (unsigned i = 0; i != ConstStrSize; ++i)
1287 ConstrStr += (char)Record[3+AsmStrSize+i];
1288 PointerType *PTy = cast<PointerType>(CurTy);
1289 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1290 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001291 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001292 break;
1293 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001294 case bitc::CST_CODE_BLOCKADDRESS:{
1295 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001297 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1298 Function *Fn =
1299 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1300 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001301
1302 // If the function is already parsed we can insert the block address right
1303 // away.
1304 if (!Fn->empty()) {
1305 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1306 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1307 if (BBI == BBE)
1308 return Error("Invalid blockaddress block #");
1309 ++BBI;
1310 }
1311 V = BlockAddress::get(Fn, BBI);
1312 } else {
1313 // Otherwise insert a placeholder and remember it so it can be inserted
1314 // when the function is parsed.
1315 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1316 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001317 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001318 0, "");
1319 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1320 V = FwdRef;
1321 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001322 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001323 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001324 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001325
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001326 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001327 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001328 }
1329}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001330
Chad Rosiercbbb0962011-12-07 21:44:12 +00001331bool BitcodeReader::ParseUseLists() {
1332 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1333 return Error("Malformed block record");
1334
1335 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001336
Chad Rosiercbbb0962011-12-07 21:44:12 +00001337 // Read all the records.
1338 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001339 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1340
1341 switch (Entry.Kind) {
1342 case BitstreamEntry::SubBlock: // Handled for us already.
1343 case BitstreamEntry::Error:
1344 return Error("malformed use list block");
1345 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001346 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001347 case BitstreamEntry::Record:
1348 // The interesting case.
1349 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001350 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001351
Chad Rosiercbbb0962011-12-07 21:44:12 +00001352 // Read a use list record.
1353 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001354 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001355 default: // Default behavior: unknown type.
1356 break;
1357 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1358 unsigned RecordLength = Record.size();
1359 if (RecordLength < 1)
1360 return Error ("Invalid UseList reader!");
1361 UseListRecords.push_back(Record);
1362 break;
1363 }
1364 }
1365 }
1366}
1367
Chris Lattner980e5aa2007-05-01 05:52:21 +00001368/// RememberAndSkipFunctionBody - When we see the block for a function body,
1369/// remember where it is and then skip it. This lets us lazily deserialize the
1370/// functions.
1371bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001372 // Get the function we are talking about.
1373 if (FunctionsWithBodies.empty())
1374 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001375
Chris Lattner48f84872007-05-01 04:59:48 +00001376 Function *Fn = FunctionsWithBodies.back();
1377 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001378
Chris Lattner48f84872007-05-01 04:59:48 +00001379 // Save the current stream state.
1380 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001381 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001382
Chris Lattner48f84872007-05-01 04:59:48 +00001383 // Skip over the function block for now.
1384 if (Stream.SkipBlock())
1385 return Error("Malformed block record");
1386 return false;
1387}
1388
Derek Schuff2ea93872012-02-06 22:30:29 +00001389bool BitcodeReader::GlobalCleanup() {
1390 // Patch the initializers for globals and aliases up.
1391 ResolveGlobalAndAliasInits();
1392 if (!GlobalInits.empty() || !AliasInits.empty())
1393 return Error("Malformed global initializer set");
1394
1395 // Look for intrinsic functions which need to be upgraded at some point
1396 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1397 FI != FE; ++FI) {
1398 Function *NewFn;
1399 if (UpgradeIntrinsicFunction(FI, NewFn))
1400 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1401 }
1402
1403 // Look for global variables which need to be renamed.
1404 for (Module::global_iterator
1405 GI = TheModule->global_begin(), GE = TheModule->global_end();
1406 GI != GE; ++GI)
1407 UpgradeGlobalVariable(GI);
1408 // Force deallocation of memory for these vectors to favor the client that
1409 // want lazy deserialization.
1410 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1411 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1412 return false;
1413}
1414
1415bool BitcodeReader::ParseModule(bool Resume) {
1416 if (Resume)
1417 Stream.JumpToBit(NextUnreadBit);
1418 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001419 return Error("Malformed block record");
1420
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001421 SmallVector<uint64_t, 64> Record;
1422 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001423 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001424
1425 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001426 while (1) {
1427 BitstreamEntry Entry = Stream.advance();
1428
1429 switch (Entry.Kind) {
1430 case BitstreamEntry::Error:
1431 Error("malformed module block");
1432 return true;
1433 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001434 return GlobalCleanup();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001435
1436 case BitstreamEntry::SubBlock:
1437 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001438 default: // Skip unknown content.
1439 if (Stream.SkipBlock())
1440 return Error("Malformed block record");
1441 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001442 case bitc::BLOCKINFO_BLOCK_ID:
1443 if (Stream.ReadBlockInfoBlock())
1444 return Error("Malformed BlockInfoBlock");
1445 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001446 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001447 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001448 return true;
1449 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001450 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001451 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001452 return true;
1453 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001454 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001455 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001456 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001457 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001458 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001459 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001460 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001461 return true;
1462 break;
Devang Patele54abc92009-07-22 17:43:22 +00001463 case bitc::METADATA_BLOCK_ID:
1464 if (ParseMetadata())
1465 return true;
1466 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001467 case bitc::FUNCTION_BLOCK_ID:
1468 // If this is the first function body we've seen, reverse the
1469 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001470 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001471 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001472 if (GlobalCleanup())
1473 return true;
1474 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001475 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001476
Chris Lattner980e5aa2007-05-01 05:52:21 +00001477 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001478 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001479 // For streaming bitcode, suspend parsing when we reach the function
1480 // bodies. Subsequent materialization calls will resume it when
1481 // necessary. For streaming, the function bodies must be at the end of
1482 // the bitcode. If the bitcode file is old, the symbol table will be
1483 // at the end instead and will not have been seen yet. In this case,
1484 // just finish the parse now.
1485 if (LazyStreamer && SeenValueSymbolTable) {
1486 NextUnreadBit = Stream.GetCurrentBitNo();
1487 return false;
1488 }
Chris Lattner48f84872007-05-01 04:59:48 +00001489 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001490 case bitc::USELIST_BLOCK_ID:
1491 if (ParseUseLists())
1492 return true;
1493 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001494 }
1495 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001496
1497 case BitstreamEntry::Record:
1498 // The interesting case.
1499 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001500 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001501
Daniel Dunbara279bc32009-09-20 02:20:51 +00001502
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001503 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001504 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001505 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001506 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001507 if (Record.size() < 1)
1508 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001509 // Only version #0 and #1 are supported so far.
1510 unsigned module_version = Record[0];
1511 switch (module_version) {
1512 default: return Error("Unknown bitstream version!");
1513 case 0:
1514 UseRelativeIDs = false;
1515 break;
1516 case 1:
1517 UseRelativeIDs = true;
1518 break;
1519 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001520 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001521 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001522 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001523 std::string S;
1524 if (ConvertToString(Record, 0, S))
1525 return Error("Invalid MODULE_CODE_TRIPLE record");
1526 TheModule->setTargetTriple(S);
1527 break;
1528 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001529 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001530 std::string S;
1531 if (ConvertToString(Record, 0, S))
1532 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1533 TheModule->setDataLayout(S);
1534 break;
1535 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001536 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001537 std::string S;
1538 if (ConvertToString(Record, 0, S))
1539 return Error("Invalid MODULE_CODE_ASM record");
1540 TheModule->setModuleInlineAsm(S);
1541 break;
1542 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001543 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1544 // FIXME: Remove in 4.0.
1545 std::string S;
1546 if (ConvertToString(Record, 0, S))
1547 return Error("Invalid MODULE_CODE_DEPLIB record");
1548 // Ignore value.
1549 break;
1550 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001551 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001552 std::string S;
1553 if (ConvertToString(Record, 0, S))
1554 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1555 SectionTable.push_back(S);
1556 break;
1557 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001558 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001559 std::string S;
1560 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001561 return Error("Invalid MODULE_CODE_GCNAME record");
1562 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001563 break;
1564 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001565 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001566 // linkage, alignment, section, visibility, threadlocal,
1567 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001568 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001569 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001570 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001571 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001572 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001573 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001574 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001575 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001576 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001577
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001578 bool isConstant = Record[1];
1579 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1580 unsigned Alignment = (1 << Record[4]) >> 1;
1581 std::string Section;
1582 if (Record[5]) {
1583 if (Record[5]-1 >= SectionTable.size())
1584 return Error("Invalid section ID");
1585 Section = SectionTable[Record[5]-1];
1586 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001587 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001588 if (Record.size() > 6)
1589 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001590
1591 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001592 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001593 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594
Rafael Espindolabea46262011-01-08 16:42:36 +00001595 bool UnnamedAddr = false;
1596 if (Record.size() > 8)
1597 UnnamedAddr = Record[8];
1598
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001599 bool ExternallyInitialized = false;
1600 if (Record.size() > 9)
1601 ExternallyInitialized = Record[9];
1602
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001603 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001604 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001605 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001606 NewGV->setAlignment(Alignment);
1607 if (!Section.empty())
1608 NewGV->setSection(Section);
1609 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001610 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611
Chris Lattner0b2482a2007-04-23 21:26:05 +00001612 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001613
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001614 // Remember which value to use for the global initializer.
1615 if (unsigned InitID = Record[2])
1616 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617 break;
1618 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001619 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001620 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001621 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001622 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001623 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001624 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001625 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001626 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001627 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001628 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001629 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1630 if (!FTy)
1631 return Error("Function not a pointer to function type!");
1632
Gabor Greif051a9502008-04-06 20:25:17 +00001633 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1634 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001635
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001636 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001637 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001638 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001639 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001640
Chris Lattnera9bb7132007-05-08 05:38:01 +00001641 Func->setAlignment((1 << Record[5]) >> 1);
1642 if (Record[6]) {
1643 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001644 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001645 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001646 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001647 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001648 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001649 if (Record[8]-1 > GCTable.size())
1650 return Error("Invalid GC ID");
1651 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001652 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001653 bool UnnamedAddr = false;
1654 if (Record.size() > 9)
1655 UnnamedAddr = Record[9];
1656 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001657 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001658
Chris Lattner48f84872007-05-01 04:59:48 +00001659 // If this is a function with a body, remember the prototype we are
1660 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001661 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001662 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001663 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1664 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001665 break;
1666 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001667 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001668 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001669 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001670 if (Record.size() < 3)
1671 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001672 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001673 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001674 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001675 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676
Chris Lattner07d98b42007-04-26 02:46:40 +00001677 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1678 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001679 // Old bitcode files didn't have visibility field.
1680 if (Record.size() > 3)
1681 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001682 ValueList.push_back(NewGA);
1683 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1684 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001685 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001686 /// MODULE_CODE_PURGEVALS: [numvals]
1687 case bitc::MODULE_CODE_PURGEVALS:
1688 // Trim down the value list to the specified size.
1689 if (Record.size() < 1 || Record[0] > ValueList.size())
1690 return Error("Invalid MODULE_PURGEVALS record");
1691 ValueList.shrinkTo(Record[0]);
1692 break;
1693 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001694 Record.clear();
1695 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001696}
1697
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001698bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001699 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Derek Schuff2ea93872012-02-06 22:30:29 +00001701 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001702
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001703 // Sniff for the signature.
1704 if (Stream.Read(8) != 'B' ||
1705 Stream.Read(8) != 'C' ||
1706 Stream.Read(4) != 0x0 ||
1707 Stream.Read(4) != 0xC ||
1708 Stream.Read(4) != 0xE ||
1709 Stream.Read(4) != 0xD)
1710 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001712 // We expect a number of well-defined blocks, though we don't necessarily
1713 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001714 while (1) {
1715 if (Stream.AtEndOfStream())
1716 return false;
1717
1718 BitstreamEntry Entry =
1719 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1720
1721 switch (Entry.Kind) {
1722 case BitstreamEntry::Error:
1723 Error("malformed module file");
1724 return true;
1725 case BitstreamEntry::EndBlock:
1726 return false;
1727
1728 case BitstreamEntry::SubBlock:
1729 switch (Entry.ID) {
1730 case bitc::BLOCKINFO_BLOCK_ID:
1731 if (Stream.ReadBlockInfoBlock())
1732 return Error("Malformed BlockInfoBlock");
1733 break;
1734 case bitc::MODULE_BLOCK_ID:
1735 // Reject multiple MODULE_BLOCK's in a single bitstream.
1736 if (TheModule)
1737 return Error("Multiple MODULE_BLOCKs in same stream");
1738 TheModule = M;
1739 if (ParseModule(false))
1740 return true;
1741 if (LazyStreamer) return false;
1742 break;
1743 default:
1744 if (Stream.SkipBlock())
1745 return Error("Malformed block record");
1746 break;
1747 }
1748 continue;
1749 case BitstreamEntry::Record:
1750 // There should be no records in the top-level of blocks.
1751
1752 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001753 // to the end of them. If this file size is a multiple of 4 but not 8, we
1754 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001755 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001756 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001757 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001758 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001759
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001760 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001761 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001762 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001763}
Chris Lattnerc453f762007-04-29 07:54:31 +00001764
Bill Wendling34711742010-10-06 01:22:42 +00001765bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1766 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1767 return Error("Malformed block record");
1768
1769 SmallVector<uint64_t, 64> Record;
1770
1771 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001772 while (1) {
1773 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1774
1775 switch (Entry.Kind) {
1776 case BitstreamEntry::SubBlock: // Handled for us already.
1777 case BitstreamEntry::Error:
1778 return Error("malformed module block");
1779 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001780 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001781 case BitstreamEntry::Record:
1782 // The interesting case.
1783 break;
Bill Wendling34711742010-10-06 01:22:42 +00001784 }
1785
1786 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001787 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00001788 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001789 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1790 std::string S;
1791 if (ConvertToString(Record, 0, S))
1792 return Error("Invalid MODULE_CODE_TRIPLE record");
1793 Triple = S;
1794 break;
1795 }
1796 }
1797 Record.clear();
1798 }
Bill Wendling34711742010-10-06 01:22:42 +00001799}
1800
1801bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001802 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001803
1804 // Sniff for the signature.
1805 if (Stream.Read(8) != 'B' ||
1806 Stream.Read(8) != 'C' ||
1807 Stream.Read(4) != 0x0 ||
1808 Stream.Read(4) != 0xC ||
1809 Stream.Read(4) != 0xE ||
1810 Stream.Read(4) != 0xD)
1811 return Error("Invalid bitcode signature");
1812
1813 // We expect a number of well-defined blocks, though we don't necessarily
1814 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001815 while (1) {
1816 BitstreamEntry Entry = Stream.advance();
1817
1818 switch (Entry.Kind) {
1819 case BitstreamEntry::Error:
1820 Error("malformed module file");
1821 return true;
1822 case BitstreamEntry::EndBlock:
1823 return false;
1824
1825 case BitstreamEntry::SubBlock:
1826 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1827 return ParseModuleTriple(Triple);
1828
1829 // Ignore other sub-blocks.
1830 if (Stream.SkipBlock()) {
1831 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00001832 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001833 }
1834 continue;
1835
1836 case BitstreamEntry::Record:
1837 Stream.skipRecord(Entry.ID);
1838 continue;
Bill Wendling34711742010-10-06 01:22:42 +00001839 }
1840 }
Bill Wendling34711742010-10-06 01:22:42 +00001841}
1842
Devang Patele8e02132009-09-18 19:26:43 +00001843/// ParseMetadataAttachment - Parse metadata attachments.
1844bool BitcodeReader::ParseMetadataAttachment() {
1845 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1846 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001847
Devang Patele8e02132009-09-18 19:26:43 +00001848 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001849 while (1) {
1850 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1851
1852 switch (Entry.Kind) {
1853 case BitstreamEntry::SubBlock: // Handled for us already.
1854 case BitstreamEntry::Error:
1855 return Error("malformed metadata block");
1856 case BitstreamEntry::EndBlock:
1857 return false;
1858 case BitstreamEntry::Record:
1859 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00001860 break;
1861 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001862
Devang Patele8e02132009-09-18 19:26:43 +00001863 // Read a metadata attachment record.
1864 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001865 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00001866 default: // Default behavior: ignore.
1867 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001868 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001869 unsigned RecordLength = Record.size();
1870 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001872 Instruction *Inst = InstructionList[Record[0]];
1873 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001874 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001875 DenseMap<unsigned, unsigned>::iterator I =
1876 MDKindMap.find(Kind);
1877 if (I == MDKindMap.end())
1878 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001879 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001880 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001881 }
1882 break;
1883 }
1884 }
1885 }
Devang Patele8e02132009-09-18 19:26:43 +00001886}
Chris Lattner48f84872007-05-01 04:59:48 +00001887
Chris Lattner980e5aa2007-05-01 05:52:21 +00001888/// ParseFunctionBody - Lazily parse the specified function body block.
1889bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001890 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001891 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892
Nick Lewycky9a49f152010-02-25 08:30:17 +00001893 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001894 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001895 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001896
Chris Lattner980e5aa2007-05-01 05:52:21 +00001897 // Add all the function arguments to the value table.
1898 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1899 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001900
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001901 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001902 BasicBlock *CurBB = 0;
1903 unsigned CurBBNo = 0;
1904
Chris Lattnera6245242010-04-03 02:17:50 +00001905 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001906
Chris Lattner980e5aa2007-05-01 05:52:21 +00001907 // Read all the records.
1908 SmallVector<uint64_t, 64> Record;
1909 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001910 BitstreamEntry Entry = Stream.advance();
1911
1912 switch (Entry.Kind) {
1913 case BitstreamEntry::Error:
1914 return Error("Bitcode error in function block");
1915 case BitstreamEntry::EndBlock:
1916 goto OutOfRecordLoop;
1917
1918 case BitstreamEntry::SubBlock:
1919 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001920 default: // Skip unknown content.
1921 if (Stream.SkipBlock())
1922 return Error("Malformed block record");
1923 break;
1924 case bitc::CONSTANTS_BLOCK_ID:
1925 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001926 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 break;
1928 case bitc::VALUE_SYMTAB_BLOCK_ID:
1929 if (ParseValueSymbolTable()) return true;
1930 break;
Devang Patele8e02132009-09-18 19:26:43 +00001931 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932 if (ParseMetadataAttachment()) return true;
1933 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001934 case bitc::METADATA_BLOCK_ID:
1935 if (ParseMetadata()) return true;
1936 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 }
1938 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001939
1940 case BitstreamEntry::Record:
1941 // The interesting case.
1942 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001943 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001944
Chris Lattner980e5aa2007-05-01 05:52:21 +00001945 // Read a record.
1946 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001947 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001948 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001949 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001950 default: // Default behavior: reject
1951 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001952 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001953 if (Record.size() < 1 || Record[0] == 0)
1954 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001955 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001956 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001957 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001958 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001959 CurBB = FunctionBBs[0];
1960 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001961
Chris Lattnera6245242010-04-03 02:17:50 +00001962 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1963 // This record indicates that the last instruction is at the same
1964 // location as the previous instruction with a location.
1965 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00001966
Chris Lattnera6245242010-04-03 02:17:50 +00001967 // Get the last instruction emitted.
1968 if (CurBB && !CurBB->empty())
1969 I = &CurBB->back();
1970 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1971 !FunctionBBs[CurBBNo-1]->empty())
1972 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00001973
Chris Lattnera6245242010-04-03 02:17:50 +00001974 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1975 I->setDebugLoc(LastLoc);
1976 I = 0;
1977 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001978
Chris Lattner4f6bab92011-06-17 18:17:37 +00001979 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001980 I = 0; // Get the last instruction emitted.
1981 if (CurBB && !CurBB->empty())
1982 I = &CurBB->back();
1983 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1984 !FunctionBBs[CurBBNo-1]->empty())
1985 I = &FunctionBBs[CurBBNo-1]->back();
1986 if (I == 0 || Record.size() < 4)
1987 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001988
Chris Lattnera6245242010-04-03 02:17:50 +00001989 unsigned Line = Record[0], Col = Record[1];
1990 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00001991
Chris Lattnera6245242010-04-03 02:17:50 +00001992 MDNode *Scope = 0, *IA = 0;
1993 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1994 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1995 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1996 I->setDebugLoc(LastLoc);
1997 I = 0;
1998 continue;
1999 }
2000
Chris Lattnerabfbf852007-05-06 00:21:25 +00002001 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2002 unsigned OpNum = 0;
2003 Value *LHS, *RHS;
2004 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002005 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002006 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002007 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002008
Dan Gohman1224c382009-07-20 21:19:07 +00002009 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002010 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002011 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002012 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002013 if (OpNum < Record.size()) {
2014 if (Opc == Instruction::Add ||
2015 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002016 Opc == Instruction::Mul ||
2017 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002018 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002019 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002020 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002021 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002022 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002023 Opc == Instruction::UDiv ||
2024 Opc == Instruction::LShr ||
2025 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002026 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002027 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002028 } else if (isa<FPMathOperator>(I)) {
2029 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002030 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2031 FMF.setUnsafeAlgebra();
2032 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2033 FMF.setNoNaNs();
2034 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2035 FMF.setNoInfs();
2036 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2037 FMF.setNoSignedZeros();
2038 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2039 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002040 if (FMF.any())
2041 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002042 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002043
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002044 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002045 break;
2046 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002047 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2048 unsigned OpNum = 0;
2049 Value *Op;
2050 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2051 OpNum+2 != Record.size())
2052 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002053
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002054 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002055 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2056 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002057 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002058 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002059 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002060 break;
2061 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002062 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002063 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002064 unsigned OpNum = 0;
2065 Value *BasePtr;
2066 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002067 return Error("Invalid GEP record");
2068
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002069 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002070 while (OpNum != Record.size()) {
2071 Value *Op;
2072 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002073 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002074 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002075 }
2076
Jay Foada9203102011-07-25 09:48:08 +00002077 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002078 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002079 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002080 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002081 break;
2082 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002083
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002084 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2085 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002086 unsigned OpNum = 0;
2087 Value *Agg;
2088 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2089 return Error("Invalid EXTRACTVAL record");
2090
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002091 SmallVector<unsigned, 4> EXTRACTVALIdx;
2092 for (unsigned RecSize = Record.size();
2093 OpNum != RecSize; ++OpNum) {
2094 uint64_t Index = Record[OpNum];
2095 if ((unsigned)Index != Index)
2096 return Error("Invalid EXTRACTVAL index");
2097 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002098 }
2099
Jay Foadfc6d3a42011-07-13 10:26:04 +00002100 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002101 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002102 break;
2103 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002105 case bitc::FUNC_CODE_INST_INSERTVAL: {
2106 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002107 unsigned OpNum = 0;
2108 Value *Agg;
2109 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2110 return Error("Invalid INSERTVAL record");
2111 Value *Val;
2112 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2113 return Error("Invalid INSERTVAL record");
2114
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002115 SmallVector<unsigned, 4> INSERTVALIdx;
2116 for (unsigned RecSize = Record.size();
2117 OpNum != RecSize; ++OpNum) {
2118 uint64_t Index = Record[OpNum];
2119 if ((unsigned)Index != Index)
2120 return Error("Invalid INSERTVAL index");
2121 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002122 }
2123
Jay Foadfc6d3a42011-07-13 10:26:04 +00002124 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002125 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002126 break;
2127 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002128
Chris Lattnerabfbf852007-05-06 00:21:25 +00002129 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002130 // obsolete form of select
2131 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002132 unsigned OpNum = 0;
2133 Value *TrueVal, *FalseVal, *Cond;
2134 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002135 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2136 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002137 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002138
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002139 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002140 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002141 break;
2142 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002144 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2145 // new form of select
2146 // handles select i1 or select [N x i1]
2147 unsigned OpNum = 0;
2148 Value *TrueVal, *FalseVal, *Cond;
2149 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002150 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002151 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2152 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002153
2154 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002155 if (VectorType* vector_type =
2156 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002157 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002158 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002159 return Error("Invalid SELECT condition type");
2160 } else {
2161 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002162 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002163 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002164 }
2165
Gabor Greif051a9502008-04-06 20:25:17 +00002166 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002167 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002168 break;
2169 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002170
Chris Lattner01ff65f2007-05-02 05:16:49 +00002171 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002172 unsigned OpNum = 0;
2173 Value *Vec, *Idx;
2174 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002175 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002176 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002177 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002178 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002179 break;
2180 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181
Chris Lattner01ff65f2007-05-02 05:16:49 +00002182 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002183 unsigned OpNum = 0;
2184 Value *Vec, *Elt, *Idx;
2185 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002186 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002187 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002188 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002189 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002190 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002191 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002192 break;
2193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002194
Chris Lattnerabfbf852007-05-06 00:21:25 +00002195 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2196 unsigned OpNum = 0;
2197 Value *Vec1, *Vec2, *Mask;
2198 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002199 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002200 return Error("Invalid SHUFFLEVEC record");
2201
Mon P Wangaeb06d22008-11-10 04:46:22 +00002202 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002203 return Error("Invalid SHUFFLEVEC record");
2204 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002205 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002206 break;
2207 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002208
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002209 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2210 // Old form of ICmp/FCmp returning bool
2211 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2212 // both legal on vectors but had different behaviour.
2213 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2214 // FCmp/ICmp returning bool or vector of bool
2215
Chris Lattner7337ab92007-05-06 00:00:00 +00002216 unsigned OpNum = 0;
2217 Value *LHS, *RHS;
2218 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002219 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002220 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002221 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002222
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002223 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002224 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002225 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002226 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002227 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002228 break;
2229 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002230
Chris Lattner231cbcb2007-05-02 04:27:25 +00002231 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002232 {
2233 unsigned Size = Record.size();
2234 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002235 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002237 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002238 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002239
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002240 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002241 Value *Op = NULL;
2242 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2243 return Error("Invalid RET record");
2244 if (OpNum != Record.size())
2245 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002246
Chris Lattner96a74c52011-06-17 18:09:11 +00002247 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002248 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002249 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002250 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002251 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002252 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002253 return Error("Invalid BR record");
2254 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2255 if (TrueDest == 0)
2256 return Error("Invalid BR record");
2257
Devang Patele8e02132009-09-18 19:26:43 +00002258 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002259 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002260 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002261 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002262 else {
2263 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002264 Value *Cond = getValue(Record, 2, NextValueNo,
2265 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002266 if (FalseDest == 0 || Cond == 0)
2267 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002268 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002269 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002270 }
2271 break;
2272 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002273 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002274 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002275 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2276 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002277
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002278 Type *OpTy = getTypeByID(Record[1]);
2279 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2280
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002281 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002282 BasicBlock *Default = getBasicBlock(Record[3]);
2283 if (OpTy == 0 || Cond == 0 || Default == 0)
2284 return Error("Invalid SWITCH record");
2285
2286 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002287
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002288 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2289 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002290
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002291 unsigned CurIdx = 5;
2292 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002293 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002294 unsigned NumItems = Record[CurIdx++];
2295 for (unsigned ci = 0; ci != NumItems; ++ci) {
2296 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002297
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002298 APInt Low;
2299 unsigned ActiveWords = 1;
2300 if (ValueBitWidth > 64)
2301 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002302 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2303 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002304 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002305
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002306 if (!isSingleNumber) {
2307 ActiveWords = 1;
2308 if (ValueBitWidth > 64)
2309 ActiveWords = Record[CurIdx++];
2310 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002311 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2312 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002313
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002314 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2315 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002316 CurIdx += ActiveWords;
2317 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002318 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002319 }
2320 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002321 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002322 SI->addCase(Case, DestBB);
2323 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002324 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002325 if (Hash != (Record[0] & 0xFFFF))
2326 return Error("Invalid SWITCH record");
2327 I = SI;
2328 break;
2329 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002330
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002331 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002332
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002333 if (Record.size() < 3 || (Record.size() & 1) == 0)
2334 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002335 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002336 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002337 BasicBlock *Default = getBasicBlock(Record[2]);
2338 if (OpTy == 0 || Cond == 0 || Default == 0)
2339 return Error("Invalid SWITCH record");
2340 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002341 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002342 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002343 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002344 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002345 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2346 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2347 if (CaseVal == 0 || DestBB == 0) {
2348 delete SI;
2349 return Error("Invalid SWITCH record!");
2350 }
2351 SI->addCase(CaseVal, DestBB);
2352 }
2353 I = SI;
2354 break;
2355 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002356 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002357 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002358 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002359 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002360 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002361 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002362 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002363 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002364 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002365 InstructionList.push_back(IBI);
2366 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2367 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2368 IBI->addDestination(DestBB);
2369 } else {
2370 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002371 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002372 }
2373 }
2374 I = IBI;
2375 break;
2376 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002377
Duncan Sandsdc024672007-11-27 13:23:08 +00002378 case bitc::FUNC_CODE_INST_INVOKE: {
2379 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002380 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002381 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002382 unsigned CCInfo = Record[1];
2383 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2384 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002385
Chris Lattnera9bb7132007-05-08 05:38:01 +00002386 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002387 Value *Callee;
2388 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002389 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002390
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002391 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2392 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002393 dyn_cast<FunctionType>(CalleeTy->getElementType());
2394
2395 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002396 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2397 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002398 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002400 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002401 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002402 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2403 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002404 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002406
Chris Lattner7337ab92007-05-06 00:00:00 +00002407 if (!FTy->isVarArg()) {
2408 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002409 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002410 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002411 // Read type/value pairs for varargs params.
2412 while (OpNum != Record.size()) {
2413 Value *Op;
2414 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2415 return Error("Invalid INVOKE record");
2416 Ops.push_back(Op);
2417 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002418 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002419
Jay Foada3efbb12011-07-15 08:37:34 +00002420 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002421 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002422 cast<InvokeInst>(I)->setCallingConv(
2423 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002424 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002425 break;
2426 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002427 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2428 unsigned Idx = 0;
2429 Value *Val = 0;
2430 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2431 return Error("Invalid RESUME record");
2432 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002433 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002434 break;
2435 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002436 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002437 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002438 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002439 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002440 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002441 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002442 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002443 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002444 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Jay Foad3ecfc862011-03-30 11:28:46 +00002446 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002447 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002448
Chris Lattner15e6d172007-05-04 19:11:41 +00002449 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002450 Value *V;
2451 // With the new function encoding, it is possible that operands have
2452 // negative IDs (for forward references). Use a signed VBR
2453 // representation to keep the encoding small.
2454 if (UseRelativeIDs)
2455 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2456 else
2457 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002458 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002459 if (!V || !BB) return Error("Invalid PHI record");
2460 PN->addIncoming(V, BB);
2461 }
2462 I = PN;
2463 break;
2464 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002465
Bill Wendlinge6e88262011-08-12 20:24:12 +00002466 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2467 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2468 unsigned Idx = 0;
2469 if (Record.size() < 4)
2470 return Error("Invalid LANDINGPAD record");
2471 Type *Ty = getTypeByID(Record[Idx++]);
2472 if (!Ty) return Error("Invalid LANDINGPAD record");
2473 Value *PersFn = 0;
2474 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2475 return Error("Invalid LANDINGPAD record");
2476
2477 bool IsCleanup = !!Record[Idx++];
2478 unsigned NumClauses = Record[Idx++];
2479 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2480 LP->setCleanup(IsCleanup);
2481 for (unsigned J = 0; J != NumClauses; ++J) {
2482 LandingPadInst::ClauseType CT =
2483 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2484 Value *Val;
2485
2486 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2487 delete LP;
2488 return Error("Invalid LANDINGPAD record");
2489 }
2490
2491 assert((CT != LandingPadInst::Catch ||
2492 !isa<ArrayType>(Val->getType())) &&
2493 "Catch clause has a invalid type!");
2494 assert((CT != LandingPadInst::Filter ||
2495 isa<ArrayType>(Val->getType())) &&
2496 "Filter clause has invalid type!");
2497 LP->addClause(Val);
2498 }
2499
2500 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002501 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002502 break;
2503 }
2504
Chris Lattner96a74c52011-06-17 18:09:11 +00002505 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2506 if (Record.size() != 4)
2507 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002508 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002509 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002510 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002511 Value *Size = getFnValueByID(Record[2], OpTy);
2512 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002513 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002514 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002515 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002516 break;
2517 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002518 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002519 unsigned OpNum = 0;
2520 Value *Op;
2521 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2522 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002523 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002524
Chris Lattner7337ab92007-05-06 00:00:00 +00002525 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002526 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002527 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002528 }
Eli Friedman21006d42011-08-09 23:02:53 +00002529 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2530 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2531 unsigned OpNum = 0;
2532 Value *Op;
2533 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2534 OpNum+4 != Record.size())
2535 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002536
Eli Friedman21006d42011-08-09 23:02:53 +00002537
2538 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2539 if (Ordering == NotAtomic || Ordering == Release ||
2540 Ordering == AcquireRelease)
2541 return Error("Invalid LOADATOMIC record");
2542 if (Ordering != NotAtomic && Record[OpNum] == 0)
2543 return Error("Invalid LOADATOMIC record");
2544 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2545
2546 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2547 Ordering, SynchScope);
2548 InstructionList.push_back(I);
2549 break;
2550 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002551 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002552 unsigned OpNum = 0;
2553 Value *Val, *Ptr;
2554 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002555 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002556 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2557 OpNum+2 != Record.size())
2558 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002559
Christopher Lambfe63fb92007-12-11 08:59:05 +00002560 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002561 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002562 break;
2563 }
Eli Friedman21006d42011-08-09 23:02:53 +00002564 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2565 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2566 unsigned OpNum = 0;
2567 Value *Val, *Ptr;
2568 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002569 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002570 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2571 OpNum+4 != Record.size())
2572 return Error("Invalid STOREATOMIC record");
2573
2574 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002575 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002576 Ordering == AcquireRelease)
2577 return Error("Invalid STOREATOMIC record");
2578 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2579 if (Ordering != NotAtomic && Record[OpNum] == 0)
2580 return Error("Invalid STOREATOMIC record");
2581
2582 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2583 Ordering, SynchScope);
2584 InstructionList.push_back(I);
2585 break;
2586 }
Eli Friedmanff030482011-07-28 21:48:00 +00002587 case bitc::FUNC_CODE_INST_CMPXCHG: {
2588 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2589 unsigned OpNum = 0;
2590 Value *Ptr, *Cmp, *New;
2591 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002592 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002593 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002594 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002595 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2596 OpNum+3 != Record.size())
2597 return Error("Invalid CMPXCHG record");
2598 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002599 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002600 return Error("Invalid CMPXCHG record");
2601 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2602 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2603 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2604 InstructionList.push_back(I);
2605 break;
2606 }
2607 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2608 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2609 unsigned OpNum = 0;
2610 Value *Ptr, *Val;
2611 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002612 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002613 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2614 OpNum+4 != Record.size())
2615 return Error("Invalid ATOMICRMW record");
2616 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2617 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2618 Operation > AtomicRMWInst::LAST_BINOP)
2619 return Error("Invalid ATOMICRMW record");
2620 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002621 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002622 return Error("Invalid ATOMICRMW record");
2623 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2624 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2625 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2626 InstructionList.push_back(I);
2627 break;
2628 }
Eli Friedman47f35132011-07-25 23:16:38 +00002629 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2630 if (2 != Record.size())
2631 return Error("Invalid FENCE record");
2632 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2633 if (Ordering == NotAtomic || Ordering == Unordered ||
2634 Ordering == Monotonic)
2635 return Error("Invalid FENCE record");
2636 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2637 I = new FenceInst(Context, Ordering, SynchScope);
2638 InstructionList.push_back(I);
2639 break;
2640 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002641 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002642 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2643 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002644 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002645
Bill Wendling99faa3b2012-12-07 23:16:57 +00002646 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002647 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002648
Chris Lattnera9bb7132007-05-08 05:38:01 +00002649 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002650 Value *Callee;
2651 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2652 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002653
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002654 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2655 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002656 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002657 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002658 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002659
Chris Lattner0579f7f2007-05-03 22:04:19 +00002660 SmallVector<Value*, 16> Args;
2661 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002662 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002663 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002664 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002665 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002666 Args.push_back(getValue(Record, OpNum, NextValueNo,
2667 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002668 if (Args.back() == 0) return Error("Invalid CALL record");
2669 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002670
Chris Lattner0579f7f2007-05-03 22:04:19 +00002671 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002672 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002673 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002674 return Error("Invalid CALL record");
2675 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002676 while (OpNum != Record.size()) {
2677 Value *Op;
2678 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2679 return Error("Invalid CALL record");
2680 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002681 }
2682 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002683
Jay Foada3efbb12011-07-15 08:37:34 +00002684 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002685 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002686 cast<CallInst>(I)->setCallingConv(
2687 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002688 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002689 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002690 break;
2691 }
2692 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2693 if (Record.size() < 3)
2694 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002695 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002696 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002697 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002698 if (!OpTy || !Op || !ResTy)
2699 return Error("Invalid VAARG record");
2700 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002701 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002702 break;
2703 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002704 }
2705
2706 // Add instruction to end of current BB. If there is no current BB, reject
2707 // this file.
2708 if (CurBB == 0) {
2709 delete I;
2710 return Error("Invalid instruction with no BB");
2711 }
2712 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002713
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002714 // If this was a terminator instruction, move to the next block.
2715 if (isa<TerminatorInst>(I)) {
2716 ++CurBBNo;
2717 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002719
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002720 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002721 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002722 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002723 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002724
Chris Lattner5a4251c2013-01-20 02:13:19 +00002725OutOfRecordLoop:
2726
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002727 // Check the function list for unresolved values.
2728 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2729 if (A->getParent() == 0) {
2730 // We found at least one unresolved value. Nuke them all to avoid leaks.
2731 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002732 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002733 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002734 delete A;
2735 }
2736 }
Chris Lattner35a04702007-05-04 03:50:29 +00002737 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002738 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002739 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002740
Dan Gohman064ff3e2010-08-25 20:23:38 +00002741 // FIXME: Check for unresolved forward-declared metadata references
2742 // and clean up leaks.
2743
Chris Lattner50b136d2009-10-28 05:53:48 +00002744 // See if anything took the address of blocks in this function. If so,
2745 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002746 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2747 BlockAddrFwdRefs.find(F);
2748 if (BAFRI != BlockAddrFwdRefs.end()) {
2749 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2750 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2751 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002752 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002753 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002754
Chris Lattner50b136d2009-10-28 05:53:48 +00002755 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002756 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002757 FwdRef->eraseFromParent();
2758 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002759
Chris Lattner50b136d2009-10-28 05:53:48 +00002760 BlockAddrFwdRefs.erase(BAFRI);
2761 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002762
Chris Lattner980e5aa2007-05-01 05:52:21 +00002763 // Trim the value list down to the size it was before we parsed this function.
2764 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002765 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002766 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002767 return false;
2768}
2769
Derek Schuff2ea93872012-02-06 22:30:29 +00002770/// FindFunctionInStream - Find the function body in the bitcode stream
2771bool BitcodeReader::FindFunctionInStream(Function *F,
2772 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2773 while (DeferredFunctionInfoIterator->second == 0) {
2774 if (Stream.AtEndOfStream())
2775 return Error("Could not find Function in stream");
2776 // ParseModule will parse the next body in the stream and set its
2777 // position in the DeferredFunctionInfo map.
2778 if (ParseModule(true)) return true;
2779 }
2780 return false;
2781}
2782
Chris Lattnerb348bb82007-05-18 04:02:46 +00002783//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002784// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002785//===----------------------------------------------------------------------===//
2786
2787
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002788bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2789 if (const Function *F = dyn_cast<Function>(GV)) {
2790 return F->isDeclaration() &&
2791 DeferredFunctionInfo.count(const_cast<Function*>(F));
2792 }
2793 return false;
2794}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002795
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002796bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2797 Function *F = dyn_cast<Function>(GV);
2798 // If it's not a function or is already material, ignore the request.
2799 if (!F || !F->isMaterializable()) return false;
2800
2801 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002802 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002803 // If its position is recorded as 0, its body is somewhere in the stream
2804 // but we haven't seen it yet.
2805 if (DFII->second == 0)
2806 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002807
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002808 // Move the bit stream to the saved position of the deferred function body.
2809 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002810
Chris Lattnerb348bb82007-05-18 04:02:46 +00002811 if (ParseFunctionBody(F)) {
2812 if (ErrInfo) *ErrInfo = ErrorString;
2813 return true;
2814 }
Chandler Carruth69940402007-08-04 01:51:18 +00002815
2816 // Upgrade any old intrinsic calls in the function.
2817 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2818 E = UpgradedIntrinsics.end(); I != E; ++I) {
2819 if (I->first != I->second) {
2820 for (Value::use_iterator UI = I->first->use_begin(),
2821 UE = I->first->use_end(); UI != UE; ) {
2822 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2823 UpgradeIntrinsicCall(CI, I->second);
2824 }
2825 }
2826 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002827
Chris Lattnerb348bb82007-05-18 04:02:46 +00002828 return false;
2829}
2830
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002831bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2832 const Function *F = dyn_cast<Function>(GV);
2833 if (!F || F->isDeclaration())
2834 return false;
2835 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2836}
2837
2838void BitcodeReader::Dematerialize(GlobalValue *GV) {
2839 Function *F = dyn_cast<Function>(GV);
2840 // If this function isn't dematerializable, this is a noop.
2841 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002842 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002843
Chris Lattnerb348bb82007-05-18 04:02:46 +00002844 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002845
Chris Lattnerb348bb82007-05-18 04:02:46 +00002846 // Just forget the function body, we can remat it later.
2847 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002848}
2849
2850
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002851bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2852 assert(M == TheModule &&
2853 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002854 // Iterate over the module, deserializing any functions that are still on
2855 // disk.
2856 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2857 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002858 if (F->isMaterializable() &&
2859 Materialize(F, ErrInfo))
2860 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002861
Derek Schuff0ffe6982012-02-29 00:07:09 +00002862 // At this point, if there are any function bodies, the current bit is
2863 // pointing to the END_BLOCK record after them. Now make sure the rest
2864 // of the bits in the module have been read.
2865 if (NextUnreadBit)
2866 ParseModule(true);
2867
Daniel Dunbara279bc32009-09-20 02:20:51 +00002868 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2869 // delete the old functions to clean up. We can't do this unless the entire
2870 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002871 // with calls to the old function.
2872 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2873 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2874 if (I->first != I->second) {
2875 for (Value::use_iterator UI = I->first->use_begin(),
2876 UE = I->first->use_end(); UI != UE; ) {
2877 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2878 UpgradeIntrinsicCall(CI, I->second);
2879 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002880 if (!I->first->use_empty())
2881 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002882 I->first->eraseFromParent();
2883 }
2884 }
2885 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002886
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002887 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002888}
2889
Derek Schuff2ea93872012-02-06 22:30:29 +00002890bool BitcodeReader::InitStream() {
2891 if (LazyStreamer) return InitLazyStream();
2892 return InitStreamFromBuffer();
2893}
2894
2895bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002896 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002897 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2898
2899 if (Buffer->getBufferSize() & 3) {
2900 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2901 return Error("Invalid bitcode signature");
2902 else
2903 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2904 }
2905
2906 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2907 // The magic number is 0x0B17C0DE stored in little endian.
2908 if (isBitcodeWrapper(BufPtr, BufEnd))
2909 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2910 return Error("Invalid bitcode wrapper header");
2911
2912 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2913 Stream.init(*StreamFile);
2914
2915 return false;
2916}
2917
2918bool BitcodeReader::InitLazyStream() {
2919 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2920 // see it.
2921 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2922 StreamFile.reset(new BitstreamReader(Bytes));
2923 Stream.init(*StreamFile);
2924
2925 unsigned char buf[16];
2926 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2927 return Error("Bitcode stream must be at least 16 bytes in length");
2928
2929 if (!isBitcode(buf, buf + 16))
2930 return Error("Invalid bitcode signature");
2931
2932 if (isBitcodeWrapper(buf, buf + 4)) {
2933 const unsigned char *bitcodeStart = buf;
2934 const unsigned char *bitcodeEnd = buf + 16;
2935 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2936 Bytes->dropLeadingBytes(bitcodeStart - buf);
2937 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2938 }
2939 return false;
2940}
Chris Lattner48f84872007-05-01 04:59:48 +00002941
Chris Lattnerc453f762007-04-29 07:54:31 +00002942//===----------------------------------------------------------------------===//
2943// External interface
2944//===----------------------------------------------------------------------===//
2945
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002946/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002947///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002948Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2949 LLVMContext& Context,
2950 std::string *ErrMsg) {
2951 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002952 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002953 M->setMaterializer(R);
2954 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002955 if (ErrMsg)
2956 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002957
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002958 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002959 return 0;
2960 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002961 // Have the BitcodeReader dtor delete 'Buffer'.
2962 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002963
2964 R->materializeForwardReferencedFunctions();
2965
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002966 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002967}
2968
Derek Schuff2ea93872012-02-06 22:30:29 +00002969
2970Module *llvm::getStreamedBitcodeModule(const std::string &name,
2971 DataStreamer *streamer,
2972 LLVMContext &Context,
2973 std::string *ErrMsg) {
2974 Module *M = new Module(name, Context);
2975 BitcodeReader *R = new BitcodeReader(streamer, Context);
2976 M->setMaterializer(R);
2977 if (R->ParseBitcodeInto(M)) {
2978 if (ErrMsg)
2979 *ErrMsg = R->getErrorString();
2980 delete M; // Also deletes R.
2981 return 0;
2982 }
2983 R->setBufferOwned(false); // no buffer to delete
2984 return M;
2985}
2986
Chris Lattnerc453f762007-04-29 07:54:31 +00002987/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2988/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002989Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002990 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002991 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2992 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002993
2994 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2995 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002996 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002997
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002998 // Read in the entire module, and destroy the BitcodeReader.
2999 if (M->MaterializeAllPermanently(ErrMsg)) {
3000 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003001 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003002 }
Bill Wendling34711742010-10-06 01:22:42 +00003003
Chad Rosiercbbb0962011-12-07 21:44:12 +00003004 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3005 // written. We must defer until the Module has been fully materialized.
3006
Chris Lattnerc453f762007-04-29 07:54:31 +00003007 return M;
3008}
Bill Wendling34711742010-10-06 01:22:42 +00003009
3010std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3011 LLVMContext& Context,
3012 std::string *ErrMsg) {
3013 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3014 // Don't let the BitcodeReader dtor delete 'Buffer'.
3015 R->setBufferOwned(false);
3016
3017 std::string Triple("");
3018 if (R->ParseTriple(Triple))
3019 if (ErrMsg)
3020 *ErrMsg = R->getErrorString();
3021
3022 delete R;
3023 return Triple;
3024}