blob: 2e1a5125fe96317394098de7bbd13c8d41d5181a [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
Devang Patel05988662008-09-25 21:00:45 +0000431bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000432 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000433 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000434
Devang Patel19c87462008-09-26 22:53:05 +0000435 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000436 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000439
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000440 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000441
Chris Lattner48c85b82007-05-04 03:30:17 +0000442 // Read all the records.
443 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000444 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
445
446 switch (Entry.Kind) {
447 case BitstreamEntry::SubBlock: // Handled for us already.
448 case BitstreamEntry::Error:
449 return Error("Error at end of PARAMATTR block");
450 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000452 case BitstreamEntry::Record:
453 // The interesting case.
454 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000455 }
Chris Lattner5a4251c2013-01-20 02:13:19 +0000456
Chris Lattner48c85b82007-05-04 03:30:17 +0000457 // Read a record.
458 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000459 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000460 default: // Default behavior: ignore.
461 break;
462 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
463 if (Record.size() & 1)
464 return Error("Invalid ENTRY record");
465
Chris Lattner48c85b82007-05-04 03:30:17 +0000466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling034b94b2012-12-19 07:18:57 +0000467 Attribute ReconstitutedAttr =
Bill Wendling8e47daf2013-01-25 23:09:36 +0000468 AttributeFuncs::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
Bill Wendling1db9b692013-01-09 23:36:50 +0000469 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000470 }
Chris Lattner461edd92008-03-12 02:25:52 +0000471
Devang Patel19c87462008-09-26 22:53:05 +0000472 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling702cc912012-10-15 20:35:56 +0000473 AttrBuilder B(Record[i+1]);
Bill Wendlingcb3de0b2012-10-15 04:46:55 +0000474 if (B.hasAttributes())
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000475 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000476 }
Devang Patel19c87462008-09-26 22:53:05 +0000477
Bill Wendling99faa3b2012-12-07 23:16:57 +0000478 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000479 Attrs.clear();
480 break;
481 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000482 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000483 }
484}
485
Chris Lattner86697142007-05-01 05:01:34 +0000486bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000487 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000488 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000489
Chris Lattner1afcace2011-07-09 17:41:24 +0000490 return ParseTypeTableBody();
491}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000492
Chris Lattner1afcace2011-07-09 17:41:24 +0000493bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000494 if (!TypeList.empty())
495 return Error("Multiple TYPE_BLOCKs found!");
496
497 SmallVector<uint64_t, 64> Record;
498 unsigned NumRecords = 0;
499
Chris Lattner1afcace2011-07-09 17:41:24 +0000500 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000501
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000502 // Read all the records for this type table.
503 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000504 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
505
506 switch (Entry.Kind) {
507 case BitstreamEntry::SubBlock: // Handled for us already.
508 case BitstreamEntry::Error:
509 Error("Error in the type table block");
510 return true;
511 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000512 if (NumRecords != TypeList.size())
513 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000514 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000515 case BitstreamEntry::Record:
516 // The interesting case.
517 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000518 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000519
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000520 // Read a record.
521 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000522 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000523 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
526 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
527 // type list. This allows us to reserve space.
528 if (Record.size() < 1)
529 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000530 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000531 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000532 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000533 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000534 break;
Dan Gohmance163392011-12-17 00:04:22 +0000535 case bitc::TYPE_CODE_HALF: // HALF
536 ResultTy = Type::getHalfTy(Context);
537 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000539 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000540 break;
541 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000542 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000544 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000545 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000546 break;
547 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000548 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000549 break;
550 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000551 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000552 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000553 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000554 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000555 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000556 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000558 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000559 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
560 ResultTy = Type::getX86_MMXTy(Context);
561 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000562 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
563 if (Record.size() < 1)
564 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000565
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000567 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000568 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000569 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000570 if (Record.size() < 1)
571 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000572 unsigned AddressSpace = 0;
573 if (Record.size() == 2)
574 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000575 ResultTy = getTypeByID(Record[0]);
576 if (ResultTy == 0) return Error("invalid element type in pointer type");
577 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000579 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000580 case bitc::TYPE_CODE_FUNCTION_OLD: {
581 // FIXME: attrid is dead, remove it in LLVM 4.0
582 // FUNCTION: [vararg, attrid, retty, paramty x N]
583 if (Record.size() < 3)
584 return Error("Invalid FUNCTION type record");
585 SmallVector<Type*, 8> ArgTys;
586 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
587 if (Type *T = getTypeByID(Record[i]))
588 ArgTys.push_back(T);
589 else
590 break;
591 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000592
Nuno Lopesee8100d2012-05-23 15:19:39 +0000593 ResultTy = getTypeByID(Record[2]);
594 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
595 return Error("invalid type in function type");
596
597 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
598 break;
599 }
Chad Rosiercde54642011-11-03 00:14:01 +0000600 case bitc::TYPE_CODE_FUNCTION: {
601 // FUNCTION: [vararg, retty, paramty x N]
602 if (Record.size() < 2)
603 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000604 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000605 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
606 if (Type *T = getTypeByID(Record[i]))
607 ArgTys.push_back(T);
608 else
609 break;
610 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000611
Chad Rosiercde54642011-11-03 00:14:01 +0000612 ResultTy = getTypeByID(Record[1]);
613 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
614 return Error("invalid type in function type");
615
616 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
617 break;
618 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000619 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000620 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000621 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000622 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000623 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
624 if (Type *T = getTypeByID(Record[i]))
625 EltTys.push_back(T);
626 else
627 break;
628 }
629 if (EltTys.size() != Record.size()-1)
630 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000631 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000632 break;
633 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000634 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
635 if (ConvertToString(Record, 0, TypeName))
636 return Error("Invalid STRUCT_NAME record");
637 continue;
638
639 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
640 if (Record.size() < 1)
641 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000642
Chris Lattner1afcace2011-07-09 17:41:24 +0000643 if (NumRecords >= TypeList.size())
644 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000645
Chris Lattner1afcace2011-07-09 17:41:24 +0000646 // Check to see if this was forward referenced, if so fill in the temp.
647 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
648 if (Res) {
649 Res->setName(TypeName);
650 TypeList[NumRecords] = 0;
651 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000652 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000653 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000654
Chris Lattner1afcace2011-07-09 17:41:24 +0000655 SmallVector<Type*, 8> EltTys;
656 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
657 if (Type *T = getTypeByID(Record[i]))
658 EltTys.push_back(T);
659 else
660 break;
661 }
662 if (EltTys.size() != Record.size()-1)
663 return Error("invalid STRUCT type record");
664 Res->setBody(EltTys, Record[0]);
665 ResultTy = Res;
666 break;
667 }
668 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
669 if (Record.size() != 1)
670 return Error("Invalid OPAQUE type record");
671
672 if (NumRecords >= TypeList.size())
673 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000674
Chris Lattner1afcace2011-07-09 17:41:24 +0000675 // Check to see if this was forward referenced, if so fill in the temp.
676 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
677 if (Res) {
678 Res->setName(TypeName);
679 TypeList[NumRecords] = 0;
680 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000681 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000682 TypeName.clear();
683 ResultTy = Res;
684 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000685 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000686 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
687 if (Record.size() < 2)
688 return Error("Invalid ARRAY type record");
689 if ((ResultTy = getTypeByID(Record[1])))
690 ResultTy = ArrayType::get(ResultTy, Record[0]);
691 else
692 return Error("Invalid ARRAY type element");
693 break;
694 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
695 if (Record.size() < 2)
696 return Error("Invalid VECTOR type record");
697 if ((ResultTy = getTypeByID(Record[1])))
698 ResultTy = VectorType::get(ResultTy, Record[0]);
699 else
700 return Error("Invalid ARRAY type element");
701 break;
702 }
703
704 if (NumRecords >= TypeList.size())
705 return Error("invalid TYPE table");
706 assert(ResultTy && "Didn't read a type?");
707 assert(TypeList[NumRecords] == 0 && "Already read type?");
708 TypeList[NumRecords++] = ResultTy;
709 }
710}
711
Chris Lattner86697142007-05-01 05:01:34 +0000712bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000713 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000714 return Error("Malformed block record");
715
716 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Chris Lattner0b2482a2007-04-23 21:26:05 +0000718 // Read all the records for this value table.
719 SmallString<128> ValueName;
720 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000721 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
722
723 switch (Entry.Kind) {
724 case BitstreamEntry::SubBlock: // Handled for us already.
725 case BitstreamEntry::Error:
726 return Error("malformed value symbol table block");
727 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000728 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000729 case BitstreamEntry::Record:
730 // The interesting case.
731 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000733
Chris Lattner0b2482a2007-04-23 21:26:05 +0000734 // Read a record.
735 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000736 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000737 default: // Default behavior: unknown type.
738 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000739 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000740 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000741 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000742 unsigned ValueID = Record[0];
743 if (ValueID >= ValueList.size())
744 return Error("Invalid Value ID in VST_ENTRY record");
745 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000746
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000747 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000748 ValueName.clear();
749 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000750 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000751 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000752 if (ConvertToString(Record, 1, ValueName))
753 return Error("Invalid VST_BBENTRY record");
754 BasicBlock *BB = getBasicBlock(Record[0]);
755 if (BB == 0)
756 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000758 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000759 ValueName.clear();
760 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000762 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000763 }
764}
765
Devang Patele54abc92009-07-22 17:43:22 +0000766bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000767 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000768
769 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
770 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000771
Devang Patele54abc92009-07-22 17:43:22 +0000772 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000773
Devang Patele54abc92009-07-22 17:43:22 +0000774 // Read all the records.
775 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
777
778 switch (Entry.Kind) {
779 case BitstreamEntry::SubBlock: // Handled for us already.
780 case BitstreamEntry::Error:
781 Error("malformed metadata block");
782 return true;
783 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +0000784 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000785 case BitstreamEntry::Record:
786 // The interesting case.
787 break;
Devang Patele54abc92009-07-22 17:43:22 +0000788 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000789
Victor Hernandez24e64df2010-01-10 07:14:18 +0000790 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000791 // Read a record.
792 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000793 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000794 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000795 default: // Default behavior: ignore.
796 break;
Devang Patelaa993142009-07-29 22:34:41 +0000797 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +0000798 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000799 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000800 Record.clear();
801 Code = Stream.ReadCode();
802
Chris Lattner9d61dd92011-06-17 17:50:30 +0000803 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +0000804 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000805 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000806
807 // Read named metadata elements.
808 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000809 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000810 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000811 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
812 if (MD == 0)
813 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000814 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000815 }
Devang Patelaa993142009-07-29 22:34:41 +0000816 break;
817 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000818 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000819 IsFunctionLocal = true;
820 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000821 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000822 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000823 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000824
Devang Patel104cf9e2009-07-23 01:07:34 +0000825 unsigned Size = Record.size();
826 SmallVector<Value*, 8> Elts;
827 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000828 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000829 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000830 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000831 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000832 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000833 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
834 else
835 Elts.push_back(NULL);
836 }
Jay Foadec9186b2011-04-21 19:59:31 +0000837 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000838 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000839 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000840 break;
841 }
Devang Patele54abc92009-07-22 17:43:22 +0000842 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000843 SmallString<8> String(Record.begin(), Record.end());
844 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000845 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000846 break;
847 }
Devang Patele8e02132009-09-18 19:26:43 +0000848 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000849 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000850 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000851
Devang Patela2148402009-09-28 21:14:55 +0000852 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000853 SmallString<8> Name(Record.begin()+1, Record.end());
854
Chris Lattner08113472009-12-29 09:01:33 +0000855 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000856 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
857 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000858 break;
859 }
Devang Patele54abc92009-07-22 17:43:22 +0000860 }
861 }
862}
863
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000864/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000865/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000866uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000867 if ((V & 1) == 0)
868 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000869 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000870 return -(V >> 1);
871 // There is no such thing as -0 with integers. "-0" really means MININT.
872 return 1ULL << 63;
873}
874
Chris Lattner07d98b42007-04-26 02:46:40 +0000875/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
876/// values and aliases that we can.
877bool BitcodeReader::ResolveGlobalAndAliasInits() {
878 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
879 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880
Chris Lattner07d98b42007-04-26 02:46:40 +0000881 GlobalInitWorklist.swap(GlobalInits);
882 AliasInitWorklist.swap(AliasInits);
883
884 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000885 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000886 if (ValID >= ValueList.size()) {
887 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000888 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000889 } else {
890 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
891 GlobalInitWorklist.back().first->setInitializer(C);
892 else
893 return Error("Global variable initializer is not a constant!");
894 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000895 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000896 }
897
898 while (!AliasInitWorklist.empty()) {
899 unsigned ValID = AliasInitWorklist.back().second;
900 if (ValID >= ValueList.size()) {
901 AliasInits.push_back(AliasInitWorklist.back());
902 } else {
903 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000904 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000905 else
906 return Error("Alias initializer is not a constant!");
907 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000908 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000909 }
910 return false;
911}
912
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000913static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
914 SmallVector<uint64_t, 8> Words(Vals.size());
915 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000916 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000917
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000918 return APInt(TypeBits, Words);
919}
920
Chris Lattner86697142007-05-01 05:01:34 +0000921bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000922 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000923 return Error("Malformed block record");
924
925 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000926
Chris Lattnere16504e2007-04-24 03:30:34 +0000927 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000928 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000929 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000930 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000931 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
932
933 switch (Entry.Kind) {
934 case BitstreamEntry::SubBlock: // Handled for us already.
935 case BitstreamEntry::Error:
936 return Error("malformed block record in AST file");
937 case BitstreamEntry::EndBlock:
938 if (NextCstNo != ValueList.size())
939 return Error("Invalid constant reference!");
940
941 // Once all the constants have been read, go through and resolve forward
942 // references.
943 ValueList.ResolveConstantForwardRefs();
944 return false;
945 case BitstreamEntry::Record:
946 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +0000947 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000948 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000949
Chris Lattnere16504e2007-04-24 03:30:34 +0000950 // Read a record.
951 Record.clear();
952 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000953 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +0000954 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000955 default: // Default behavior: unknown constant
956 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000957 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000958 break;
959 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
960 if (Record.empty())
961 return Error("Malformed CST_SETTYPE record");
962 if (Record[0] >= TypeList.size())
963 return Error("Invalid Type ID in CST_SETTYPE record");
964 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000965 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000966 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000967 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000968 break;
969 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000970 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000971 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000972 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000973 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000974 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000975 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000976 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000978 APInt VInt = ReadWideAPInt(Record,
979 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000980 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +0000981
Chris Lattner0eef0802007-04-24 04:04:35 +0000982 break;
983 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000984 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000985 if (Record.empty())
986 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +0000987 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000988 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
989 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +0000990 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000991 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
992 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000993 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +0000994 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
995 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000996 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +0000997 // Bits are not stored the same way as a normal i80 APInt, compensate.
998 uint64_t Rearrange[2];
999 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1000 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001001 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1002 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001003 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001004 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1005 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001006 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001007 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1008 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001009 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001010 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001011 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001012 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001013
Chris Lattner15e6d172007-05-04 19:11:41 +00001014 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1015 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001016 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001017
Chris Lattner15e6d172007-05-04 19:11:41 +00001018 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001019 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001020
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001021 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001022 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001023 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001024 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001025 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001026 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1027 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001028 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001029 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001030 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1032 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001033 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001034 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001035 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001036 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001037 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001038 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001039 break;
1040 }
Chris Lattner2237f842012-02-05 02:41:35 +00001041 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001042 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1043 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001044 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001045
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001046 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001047 V = ConstantDataArray::getString(Context, Elts,
1048 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001049 break;
1050 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001051 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1052 if (Record.empty())
1053 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001054
Chris Lattnerd408f062012-01-30 00:51:16 +00001055 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1056 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001057
Chris Lattnerd408f062012-01-30 00:51:16 +00001058 if (EltTy->isIntegerTy(8)) {
1059 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1060 if (isa<VectorType>(CurTy))
1061 V = ConstantDataVector::get(Context, Elts);
1062 else
1063 V = ConstantDataArray::get(Context, Elts);
1064 } else if (EltTy->isIntegerTy(16)) {
1065 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1066 if (isa<VectorType>(CurTy))
1067 V = ConstantDataVector::get(Context, Elts);
1068 else
1069 V = ConstantDataArray::get(Context, Elts);
1070 } else if (EltTy->isIntegerTy(32)) {
1071 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1072 if (isa<VectorType>(CurTy))
1073 V = ConstantDataVector::get(Context, Elts);
1074 else
1075 V = ConstantDataArray::get(Context, Elts);
1076 } else if (EltTy->isIntegerTy(64)) {
1077 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1078 if (isa<VectorType>(CurTy))
1079 V = ConstantDataVector::get(Context, Elts);
1080 else
1081 V = ConstantDataArray::get(Context, Elts);
1082 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001083 SmallVector<float, 16> Elts(Size);
1084 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001085 if (isa<VectorType>(CurTy))
1086 V = ConstantDataVector::get(Context, Elts);
1087 else
1088 V = ConstantDataArray::get(Context, Elts);
1089 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001090 SmallVector<double, 16> Elts(Size);
1091 std::transform(Record.begin(), Record.end(), Elts.begin(),
1092 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001093 if (isa<VectorType>(CurTy))
1094 V = ConstantDataVector::get(Context, Elts);
1095 else
1096 V = ConstantDataArray::get(Context, Elts);
1097 } else {
1098 return Error("Unknown element type in CE_DATA");
1099 }
1100 break;
1101 }
1102
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001103 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1104 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1105 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001106 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001107 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001108 } else {
1109 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1110 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001111 unsigned Flags = 0;
1112 if (Record.size() >= 4) {
1113 if (Opc == Instruction::Add ||
1114 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001115 Opc == Instruction::Mul ||
1116 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001117 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1118 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1119 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1120 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001121 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001122 Opc == Instruction::UDiv ||
1123 Opc == Instruction::LShr ||
1124 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001125 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001126 Flags |= SDivOperator::IsExact;
1127 }
1128 }
1129 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001130 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001131 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001132 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001133 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1134 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1135 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001136 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001137 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001138 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001139 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001140 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001141 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001142 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001143 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001144 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001145 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001146 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001147 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001148 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001149 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001150 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001151 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001152 if (!ElTy) return Error("Invalid CE_GEP record");
1153 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1154 }
Jay Foaddab3d292011-07-21 14:31:17 +00001155 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001156 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1157 BitCode ==
1158 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001159 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001160 }
1161 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1162 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001163 V = ConstantExpr::getSelect(
1164 ValueList.getConstantFwdRef(Record[0],
1165 Type::getInt1Ty(Context)),
1166 ValueList.getConstantFwdRef(Record[1],CurTy),
1167 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001168 break;
1169 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1170 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001171 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001172 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1173 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1174 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001175 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001176 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001177 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001178 break;
1179 }
1180 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001181 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001182 if (Record.size() < 3 || OpTy == 0)
1183 return Error("Invalid CE_INSERTELT record");
1184 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1185 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1186 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001187 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001188 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001189 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001190 break;
1191 }
1192 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001193 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001194 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001195 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001196 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1197 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001198 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001199 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001201 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001202 break;
1203 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001204 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001205 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1206 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001207 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001208 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1209 return Error("Invalid CE_SHUFVEC_EX record");
1210 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1211 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001212 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001213 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001214 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001215 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001216 break;
1217 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1219 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001220 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001221 if (OpTy == 0) return Error("Invalid CE_CMP record");
1222 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1223 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1224
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001225 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001226 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001227 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001228 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001229 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001230 }
Chad Rosier581600b2012-09-05 19:00:49 +00001231 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001232 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001233 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001234 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1235 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001236 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001237 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001238 unsigned AsmStrSize = Record[1];
1239 if (2+AsmStrSize >= Record.size())
1240 return Error("Invalid INLINEASM record");
1241 unsigned ConstStrSize = Record[2+AsmStrSize];
1242 if (3+AsmStrSize+ConstStrSize > Record.size())
1243 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001244
Chris Lattner2bce93a2007-05-06 01:58:20 +00001245 for (unsigned i = 0; i != AsmStrSize; ++i)
1246 AsmStr += (char)Record[2+i];
1247 for (unsigned i = 0; i != ConstStrSize; ++i)
1248 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001249 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001250 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001251 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001252 break;
1253 }
Chad Rosier581600b2012-09-05 19:00:49 +00001254 // This version adds support for the asm dialect keywords (e.g.,
1255 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001256 case bitc::CST_CODE_INLINEASM: {
1257 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1258 std::string AsmStr, ConstrStr;
1259 bool HasSideEffects = Record[0] & 1;
1260 bool IsAlignStack = (Record[0] >> 1) & 1;
1261 unsigned AsmDialect = Record[0] >> 2;
1262 unsigned AsmStrSize = Record[1];
1263 if (2+AsmStrSize >= Record.size())
1264 return Error("Invalid INLINEASM record");
1265 unsigned ConstStrSize = Record[2+AsmStrSize];
1266 if (3+AsmStrSize+ConstStrSize > Record.size())
1267 return Error("Invalid INLINEASM record");
1268
1269 for (unsigned i = 0; i != AsmStrSize; ++i)
1270 AsmStr += (char)Record[2+i];
1271 for (unsigned i = 0; i != ConstStrSize; ++i)
1272 ConstrStr += (char)Record[3+AsmStrSize+i];
1273 PointerType *PTy = cast<PointerType>(CurTy);
1274 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1275 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001276 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001277 break;
1278 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001279 case bitc::CST_CODE_BLOCKADDRESS:{
1280 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001281 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001282 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1283 Function *Fn =
1284 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1285 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001286
1287 // If the function is already parsed we can insert the block address right
1288 // away.
1289 if (!Fn->empty()) {
1290 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1291 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1292 if (BBI == BBE)
1293 return Error("Invalid blockaddress block #");
1294 ++BBI;
1295 }
1296 V = BlockAddress::get(Fn, BBI);
1297 } else {
1298 // Otherwise insert a placeholder and remember it so it can be inserted
1299 // when the function is parsed.
1300 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1301 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001302 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001303 0, "");
1304 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1305 V = FwdRef;
1306 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001307 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001308 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001309 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001310
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001311 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001312 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001313 }
1314}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001315
Chad Rosiercbbb0962011-12-07 21:44:12 +00001316bool BitcodeReader::ParseUseLists() {
1317 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1318 return Error("Malformed block record");
1319
1320 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001321
Chad Rosiercbbb0962011-12-07 21:44:12 +00001322 // Read all the records.
1323 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001324 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1325
1326 switch (Entry.Kind) {
1327 case BitstreamEntry::SubBlock: // Handled for us already.
1328 case BitstreamEntry::Error:
1329 return Error("malformed use list block");
1330 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001331 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001332 case BitstreamEntry::Record:
1333 // The interesting case.
1334 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001335 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001336
Chad Rosiercbbb0962011-12-07 21:44:12 +00001337 // Read a use list record.
1338 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001339 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001340 default: // Default behavior: unknown type.
1341 break;
1342 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1343 unsigned RecordLength = Record.size();
1344 if (RecordLength < 1)
1345 return Error ("Invalid UseList reader!");
1346 UseListRecords.push_back(Record);
1347 break;
1348 }
1349 }
1350 }
1351}
1352
Chris Lattner980e5aa2007-05-01 05:52:21 +00001353/// RememberAndSkipFunctionBody - When we see the block for a function body,
1354/// remember where it is and then skip it. This lets us lazily deserialize the
1355/// functions.
1356bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001357 // Get the function we are talking about.
1358 if (FunctionsWithBodies.empty())
1359 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001360
Chris Lattner48f84872007-05-01 04:59:48 +00001361 Function *Fn = FunctionsWithBodies.back();
1362 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001363
Chris Lattner48f84872007-05-01 04:59:48 +00001364 // Save the current stream state.
1365 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001366 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001367
Chris Lattner48f84872007-05-01 04:59:48 +00001368 // Skip over the function block for now.
1369 if (Stream.SkipBlock())
1370 return Error("Malformed block record");
1371 return false;
1372}
1373
Derek Schuff2ea93872012-02-06 22:30:29 +00001374bool BitcodeReader::GlobalCleanup() {
1375 // Patch the initializers for globals and aliases up.
1376 ResolveGlobalAndAliasInits();
1377 if (!GlobalInits.empty() || !AliasInits.empty())
1378 return Error("Malformed global initializer set");
1379
1380 // Look for intrinsic functions which need to be upgraded at some point
1381 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1382 FI != FE; ++FI) {
1383 Function *NewFn;
1384 if (UpgradeIntrinsicFunction(FI, NewFn))
1385 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1386 }
1387
1388 // Look for global variables which need to be renamed.
1389 for (Module::global_iterator
1390 GI = TheModule->global_begin(), GE = TheModule->global_end();
1391 GI != GE; ++GI)
1392 UpgradeGlobalVariable(GI);
1393 // Force deallocation of memory for these vectors to favor the client that
1394 // want lazy deserialization.
1395 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1396 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1397 return false;
1398}
1399
1400bool BitcodeReader::ParseModule(bool Resume) {
1401 if (Resume)
1402 Stream.JumpToBit(NextUnreadBit);
1403 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001404 return Error("Malformed block record");
1405
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001406 SmallVector<uint64_t, 64> Record;
1407 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001408 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001409
1410 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001411 while (1) {
1412 BitstreamEntry Entry = Stream.advance();
1413
1414 switch (Entry.Kind) {
1415 case BitstreamEntry::Error:
1416 Error("malformed module block");
1417 return true;
1418 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001419 return GlobalCleanup();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001420
1421 case BitstreamEntry::SubBlock:
1422 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001423 default: // Skip unknown content.
1424 if (Stream.SkipBlock())
1425 return Error("Malformed block record");
1426 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001427 case bitc::BLOCKINFO_BLOCK_ID:
1428 if (Stream.ReadBlockInfoBlock())
1429 return Error("Malformed BlockInfoBlock");
1430 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001431 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001432 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001433 return true;
1434 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001435 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001436 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001437 return true;
1438 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001439 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001440 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001441 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001442 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001443 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001444 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001445 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001446 return true;
1447 break;
Devang Patele54abc92009-07-22 17:43:22 +00001448 case bitc::METADATA_BLOCK_ID:
1449 if (ParseMetadata())
1450 return true;
1451 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001452 case bitc::FUNCTION_BLOCK_ID:
1453 // If this is the first function body we've seen, reverse the
1454 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001455 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001456 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001457 if (GlobalCleanup())
1458 return true;
1459 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001460 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001461
Chris Lattner980e5aa2007-05-01 05:52:21 +00001462 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001463 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001464 // For streaming bitcode, suspend parsing when we reach the function
1465 // bodies. Subsequent materialization calls will resume it when
1466 // necessary. For streaming, the function bodies must be at the end of
1467 // the bitcode. If the bitcode file is old, the symbol table will be
1468 // at the end instead and will not have been seen yet. In this case,
1469 // just finish the parse now.
1470 if (LazyStreamer && SeenValueSymbolTable) {
1471 NextUnreadBit = Stream.GetCurrentBitNo();
1472 return false;
1473 }
Chris Lattner48f84872007-05-01 04:59:48 +00001474 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001475 case bitc::USELIST_BLOCK_ID:
1476 if (ParseUseLists())
1477 return true;
1478 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001479 }
1480 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001481
1482 case BitstreamEntry::Record:
1483 // The interesting case.
1484 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001485 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Daniel Dunbara279bc32009-09-20 02:20:51 +00001487
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001488 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001489 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001490 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001491 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001492 if (Record.size() < 1)
1493 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001494 // Only version #0 and #1 are supported so far.
1495 unsigned module_version = Record[0];
1496 switch (module_version) {
1497 default: return Error("Unknown bitstream version!");
1498 case 0:
1499 UseRelativeIDs = false;
1500 break;
1501 case 1:
1502 UseRelativeIDs = true;
1503 break;
1504 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001505 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001506 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001507 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001508 std::string S;
1509 if (ConvertToString(Record, 0, S))
1510 return Error("Invalid MODULE_CODE_TRIPLE record");
1511 TheModule->setTargetTriple(S);
1512 break;
1513 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001514 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001515 std::string S;
1516 if (ConvertToString(Record, 0, S))
1517 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1518 TheModule->setDataLayout(S);
1519 break;
1520 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001521 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001522 std::string S;
1523 if (ConvertToString(Record, 0, S))
1524 return Error("Invalid MODULE_CODE_ASM record");
1525 TheModule->setModuleInlineAsm(S);
1526 break;
1527 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001528 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1529 // FIXME: Remove in 4.0.
1530 std::string S;
1531 if (ConvertToString(Record, 0, S))
1532 return Error("Invalid MODULE_CODE_DEPLIB record");
1533 // Ignore value.
1534 break;
1535 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001536 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [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_SECTIONNAME record");
1540 SectionTable.push_back(S);
1541 break;
1542 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001543 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001544 std::string S;
1545 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001546 return Error("Invalid MODULE_CODE_GCNAME record");
1547 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001548 break;
1549 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001550 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001551 // linkage, alignment, section, visibility, threadlocal,
1552 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001553 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001554 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001555 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001556 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001557 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001558 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001559 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001560 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001561 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001562
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001563 bool isConstant = Record[1];
1564 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1565 unsigned Alignment = (1 << Record[4]) >> 1;
1566 std::string Section;
1567 if (Record[5]) {
1568 if (Record[5]-1 >= SectionTable.size())
1569 return Error("Invalid section ID");
1570 Section = SectionTable[Record[5]-1];
1571 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001572 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001573 if (Record.size() > 6)
1574 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001575
1576 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001577 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001578 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001579
Rafael Espindolabea46262011-01-08 16:42:36 +00001580 bool UnnamedAddr = false;
1581 if (Record.size() > 8)
1582 UnnamedAddr = Record[8];
1583
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001584 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001585 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001586 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001587 NewGV->setAlignment(Alignment);
1588 if (!Section.empty())
1589 NewGV->setSection(Section);
1590 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001591 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001592
Chris Lattner0b2482a2007-04-23 21:26:05 +00001593 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001595 // Remember which value to use for the global initializer.
1596 if (unsigned InitID = Record[2])
1597 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 break;
1599 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001600 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001601 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001602 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001603 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001604 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001605 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001606 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001607 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001608 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001609 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001610 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1611 if (!FTy)
1612 return Error("Function not a pointer to function type!");
1613
Gabor Greif051a9502008-04-06 20:25:17 +00001614 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1615 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001616
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001617 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001618 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001620 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001621
Chris Lattnera9bb7132007-05-08 05:38:01 +00001622 Func->setAlignment((1 << Record[5]) >> 1);
1623 if (Record[6]) {
1624 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001625 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001626 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001627 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001628 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001629 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001630 if (Record[8]-1 > GCTable.size())
1631 return Error("Invalid GC ID");
1632 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001633 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001634 bool UnnamedAddr = false;
1635 if (Record.size() > 9)
1636 UnnamedAddr = Record[9];
1637 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001638 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001639
Chris Lattner48f84872007-05-01 04:59:48 +00001640 // If this is a function with a body, remember the prototype we are
1641 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001642 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001643 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001644 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1645 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001646 break;
1647 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001648 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001649 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001650 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001651 if (Record.size() < 3)
1652 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001653 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001654 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001655 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001656 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattner07d98b42007-04-26 02:46:40 +00001658 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1659 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001660 // Old bitcode files didn't have visibility field.
1661 if (Record.size() > 3)
1662 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001663 ValueList.push_back(NewGA);
1664 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1665 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001666 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001667 /// MODULE_CODE_PURGEVALS: [numvals]
1668 case bitc::MODULE_CODE_PURGEVALS:
1669 // Trim down the value list to the specified size.
1670 if (Record.size() < 1 || Record[0] > ValueList.size())
1671 return Error("Invalid MODULE_PURGEVALS record");
1672 ValueList.shrinkTo(Record[0]);
1673 break;
1674 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001675 Record.clear();
1676 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001677}
1678
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001679bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001680 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Derek Schuff2ea93872012-02-06 22:30:29 +00001682 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001683
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001684 // Sniff for the signature.
1685 if (Stream.Read(8) != 'B' ||
1686 Stream.Read(8) != 'C' ||
1687 Stream.Read(4) != 0x0 ||
1688 Stream.Read(4) != 0xC ||
1689 Stream.Read(4) != 0xE ||
1690 Stream.Read(4) != 0xD)
1691 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001693 // We expect a number of well-defined blocks, though we don't necessarily
1694 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001695 while (1) {
1696 if (Stream.AtEndOfStream())
1697 return false;
1698
1699 BitstreamEntry Entry =
1700 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1701
1702 switch (Entry.Kind) {
1703 case BitstreamEntry::Error:
1704 Error("malformed module file");
1705 return true;
1706 case BitstreamEntry::EndBlock:
1707 return false;
1708
1709 case BitstreamEntry::SubBlock:
1710 switch (Entry.ID) {
1711 case bitc::BLOCKINFO_BLOCK_ID:
1712 if (Stream.ReadBlockInfoBlock())
1713 return Error("Malformed BlockInfoBlock");
1714 break;
1715 case bitc::MODULE_BLOCK_ID:
1716 // Reject multiple MODULE_BLOCK's in a single bitstream.
1717 if (TheModule)
1718 return Error("Multiple MODULE_BLOCKs in same stream");
1719 TheModule = M;
1720 if (ParseModule(false))
1721 return true;
1722 if (LazyStreamer) return false;
1723 break;
1724 default:
1725 if (Stream.SkipBlock())
1726 return Error("Malformed block record");
1727 break;
1728 }
1729 continue;
1730 case BitstreamEntry::Record:
1731 // There should be no records in the top-level of blocks.
1732
1733 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001734 // to the end of them. If this file size is a multiple of 4 but not 8, we
1735 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001736 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001737 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001738 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001739 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001740
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001741 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001742 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001743 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001744}
Chris Lattnerc453f762007-04-29 07:54:31 +00001745
Bill Wendling34711742010-10-06 01:22:42 +00001746bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1747 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1748 return Error("Malformed block record");
1749
1750 SmallVector<uint64_t, 64> Record;
1751
1752 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001753 while (1) {
1754 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1755
1756 switch (Entry.Kind) {
1757 case BitstreamEntry::SubBlock: // Handled for us already.
1758 case BitstreamEntry::Error:
1759 return Error("malformed module block");
1760 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001761 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001762 case BitstreamEntry::Record:
1763 // The interesting case.
1764 break;
Bill Wendling34711742010-10-06 01:22:42 +00001765 }
1766
1767 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001768 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00001769 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001770 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1771 std::string S;
1772 if (ConvertToString(Record, 0, S))
1773 return Error("Invalid MODULE_CODE_TRIPLE record");
1774 Triple = S;
1775 break;
1776 }
1777 }
1778 Record.clear();
1779 }
Bill Wendling34711742010-10-06 01:22:42 +00001780}
1781
1782bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001783 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001784
1785 // Sniff for the signature.
1786 if (Stream.Read(8) != 'B' ||
1787 Stream.Read(8) != 'C' ||
1788 Stream.Read(4) != 0x0 ||
1789 Stream.Read(4) != 0xC ||
1790 Stream.Read(4) != 0xE ||
1791 Stream.Read(4) != 0xD)
1792 return Error("Invalid bitcode signature");
1793
1794 // We expect a number of well-defined blocks, though we don't necessarily
1795 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001796 while (1) {
1797 BitstreamEntry Entry = Stream.advance();
1798
1799 switch (Entry.Kind) {
1800 case BitstreamEntry::Error:
1801 Error("malformed module file");
1802 return true;
1803 case BitstreamEntry::EndBlock:
1804 return false;
1805
1806 case BitstreamEntry::SubBlock:
1807 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1808 return ParseModuleTriple(Triple);
1809
1810 // Ignore other sub-blocks.
1811 if (Stream.SkipBlock()) {
1812 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00001813 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001814 }
1815 continue;
1816
1817 case BitstreamEntry::Record:
1818 Stream.skipRecord(Entry.ID);
1819 continue;
Bill Wendling34711742010-10-06 01:22:42 +00001820 }
1821 }
Bill Wendling34711742010-10-06 01:22:42 +00001822}
1823
Devang Patele8e02132009-09-18 19:26:43 +00001824/// ParseMetadataAttachment - Parse metadata attachments.
1825bool BitcodeReader::ParseMetadataAttachment() {
1826 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1827 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001828
Devang Patele8e02132009-09-18 19:26:43 +00001829 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001830 while (1) {
1831 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1832
1833 switch (Entry.Kind) {
1834 case BitstreamEntry::SubBlock: // Handled for us already.
1835 case BitstreamEntry::Error:
1836 return Error("malformed metadata block");
1837 case BitstreamEntry::EndBlock:
1838 return false;
1839 case BitstreamEntry::Record:
1840 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00001841 break;
1842 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001843
Devang Patele8e02132009-09-18 19:26:43 +00001844 // Read a metadata attachment record.
1845 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001846 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00001847 default: // Default behavior: ignore.
1848 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001849 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001850 unsigned RecordLength = Record.size();
1851 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001853 Instruction *Inst = InstructionList[Record[0]];
1854 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001855 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001856 DenseMap<unsigned, unsigned>::iterator I =
1857 MDKindMap.find(Kind);
1858 if (I == MDKindMap.end())
1859 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001861 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001862 }
1863 break;
1864 }
1865 }
1866 }
Devang Patele8e02132009-09-18 19:26:43 +00001867}
Chris Lattner48f84872007-05-01 04:59:48 +00001868
Chris Lattner980e5aa2007-05-01 05:52:21 +00001869/// ParseFunctionBody - Lazily parse the specified function body block.
1870bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001871 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001872 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001873
Nick Lewycky9a49f152010-02-25 08:30:17 +00001874 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001875 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001876 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001877
Chris Lattner980e5aa2007-05-01 05:52:21 +00001878 // Add all the function arguments to the value table.
1879 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1880 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001881
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001882 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001883 BasicBlock *CurBB = 0;
1884 unsigned CurBBNo = 0;
1885
Chris Lattnera6245242010-04-03 02:17:50 +00001886 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001887
Chris Lattner980e5aa2007-05-01 05:52:21 +00001888 // Read all the records.
1889 SmallVector<uint64_t, 64> Record;
1890 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001891 BitstreamEntry Entry = Stream.advance();
1892
1893 switch (Entry.Kind) {
1894 case BitstreamEntry::Error:
1895 return Error("Bitcode error in function block");
1896 case BitstreamEntry::EndBlock:
1897 goto OutOfRecordLoop;
1898
1899 case BitstreamEntry::SubBlock:
1900 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001901 default: // Skip unknown content.
1902 if (Stream.SkipBlock())
1903 return Error("Malformed block record");
1904 break;
1905 case bitc::CONSTANTS_BLOCK_ID:
1906 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001907 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001908 break;
1909 case bitc::VALUE_SYMTAB_BLOCK_ID:
1910 if (ParseValueSymbolTable()) return true;
1911 break;
Devang Patele8e02132009-09-18 19:26:43 +00001912 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913 if (ParseMetadataAttachment()) return true;
1914 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001915 case bitc::METADATA_BLOCK_ID:
1916 if (ParseMetadata()) return true;
1917 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001918 }
1919 continue;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001920
1921 case BitstreamEntry::Record:
1922 // The interesting case.
1923 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001924 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001925
Chris Lattner980e5aa2007-05-01 05:52:21 +00001926 // Read a record.
1927 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001928 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001929 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001930 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001931 default: // Default behavior: reject
1932 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001934 if (Record.size() < 1 || Record[0] == 0)
1935 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001936 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001937 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001938 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001939 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001940 CurBB = FunctionBBs[0];
1941 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001942
Chris Lattnera6245242010-04-03 02:17:50 +00001943 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1944 // This record indicates that the last instruction is at the same
1945 // location as the previous instruction with a location.
1946 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00001947
Chris Lattnera6245242010-04-03 02:17:50 +00001948 // Get the last instruction emitted.
1949 if (CurBB && !CurBB->empty())
1950 I = &CurBB->back();
1951 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1952 !FunctionBBs[CurBBNo-1]->empty())
1953 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00001954
Chris Lattnera6245242010-04-03 02:17:50 +00001955 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1956 I->setDebugLoc(LastLoc);
1957 I = 0;
1958 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00001959
Chris Lattner4f6bab92011-06-17 18:17:37 +00001960 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001961 I = 0; // Get the last instruction emitted.
1962 if (CurBB && !CurBB->empty())
1963 I = &CurBB->back();
1964 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1965 !FunctionBBs[CurBBNo-1]->empty())
1966 I = &FunctionBBs[CurBBNo-1]->back();
1967 if (I == 0 || Record.size() < 4)
1968 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001969
Chris Lattnera6245242010-04-03 02:17:50 +00001970 unsigned Line = Record[0], Col = Record[1];
1971 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00001972
Chris Lattnera6245242010-04-03 02:17:50 +00001973 MDNode *Scope = 0, *IA = 0;
1974 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1975 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1976 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1977 I->setDebugLoc(LastLoc);
1978 I = 0;
1979 continue;
1980 }
1981
Chris Lattnerabfbf852007-05-06 00:21:25 +00001982 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1983 unsigned OpNum = 0;
1984 Value *LHS, *RHS;
1985 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001986 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001987 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001988 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001989
Dan Gohman1224c382009-07-20 21:19:07 +00001990 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001991 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001992 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001993 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001994 if (OpNum < Record.size()) {
1995 if (Opc == Instruction::Add ||
1996 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001997 Opc == Instruction::Mul ||
1998 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00001999 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002000 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002001 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002002 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002003 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002004 Opc == Instruction::UDiv ||
2005 Opc == Instruction::LShr ||
2006 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002007 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002008 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002009 } else if (isa<FPMathOperator>(I)) {
2010 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002011 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2012 FMF.setUnsafeAlgebra();
2013 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2014 FMF.setNoNaNs();
2015 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2016 FMF.setNoInfs();
2017 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2018 FMF.setNoSignedZeros();
2019 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2020 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002021 if (FMF.any())
2022 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002023 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002024
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002025 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002026 break;
2027 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002028 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2029 unsigned OpNum = 0;
2030 Value *Op;
2031 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2032 OpNum+2 != Record.size())
2033 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002034
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002035 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002036 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2037 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002038 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002039 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002040 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002041 break;
2042 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002043 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002044 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002045 unsigned OpNum = 0;
2046 Value *BasePtr;
2047 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002048 return Error("Invalid GEP record");
2049
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002050 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002051 while (OpNum != Record.size()) {
2052 Value *Op;
2053 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002054 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002055 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002056 }
2057
Jay Foada9203102011-07-25 09:48:08 +00002058 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002059 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002060 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002061 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002062 break;
2063 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002064
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002065 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2066 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002067 unsigned OpNum = 0;
2068 Value *Agg;
2069 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2070 return Error("Invalid EXTRACTVAL record");
2071
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002072 SmallVector<unsigned, 4> EXTRACTVALIdx;
2073 for (unsigned RecSize = Record.size();
2074 OpNum != RecSize; ++OpNum) {
2075 uint64_t Index = Record[OpNum];
2076 if ((unsigned)Index != Index)
2077 return Error("Invalid EXTRACTVAL index");
2078 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002079 }
2080
Jay Foadfc6d3a42011-07-13 10:26:04 +00002081 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002082 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002083 break;
2084 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002085
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002086 case bitc::FUNC_CODE_INST_INSERTVAL: {
2087 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002088 unsigned OpNum = 0;
2089 Value *Agg;
2090 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2091 return Error("Invalid INSERTVAL record");
2092 Value *Val;
2093 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2094 return Error("Invalid INSERTVAL record");
2095
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002096 SmallVector<unsigned, 4> INSERTVALIdx;
2097 for (unsigned RecSize = Record.size();
2098 OpNum != RecSize; ++OpNum) {
2099 uint64_t Index = Record[OpNum];
2100 if ((unsigned)Index != Index)
2101 return Error("Invalid INSERTVAL index");
2102 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002103 }
2104
Jay Foadfc6d3a42011-07-13 10:26:04 +00002105 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002106 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002107 break;
2108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Chris Lattnerabfbf852007-05-06 00:21:25 +00002110 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002111 // obsolete form of select
2112 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002113 unsigned OpNum = 0;
2114 Value *TrueVal, *FalseVal, *Cond;
2115 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002116 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2117 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002118 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002119
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002120 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002121 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002122 break;
2123 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002124
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002125 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2126 // new form of select
2127 // handles select i1 or select [N x i1]
2128 unsigned OpNum = 0;
2129 Value *TrueVal, *FalseVal, *Cond;
2130 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002131 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002132 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2133 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002134
2135 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002136 if (VectorType* vector_type =
2137 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002138 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002140 return Error("Invalid SELECT condition type");
2141 } else {
2142 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002143 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002144 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145 }
2146
Gabor Greif051a9502008-04-06 20:25:17 +00002147 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002148 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002149 break;
2150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattner01ff65f2007-05-02 05:16:49 +00002152 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002153 unsigned OpNum = 0;
2154 Value *Vec, *Idx;
2155 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002156 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002157 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002158 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002159 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002160 break;
2161 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002162
Chris Lattner01ff65f2007-05-02 05:16:49 +00002163 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002164 unsigned OpNum = 0;
2165 Value *Vec, *Elt, *Idx;
2166 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002167 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002168 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002169 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002170 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002171 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002172 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002173 break;
2174 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002175
Chris Lattnerabfbf852007-05-06 00:21:25 +00002176 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2177 unsigned OpNum = 0;
2178 Value *Vec1, *Vec2, *Mask;
2179 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002180 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002181 return Error("Invalid SHUFFLEVEC record");
2182
Mon P Wangaeb06d22008-11-10 04:46:22 +00002183 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002184 return Error("Invalid SHUFFLEVEC record");
2185 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002186 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002187 break;
2188 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002189
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002190 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2191 // Old form of ICmp/FCmp returning bool
2192 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2193 // both legal on vectors but had different behaviour.
2194 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2195 // FCmp/ICmp returning bool or vector of bool
2196
Chris Lattner7337ab92007-05-06 00:00:00 +00002197 unsigned OpNum = 0;
2198 Value *LHS, *RHS;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002200 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002201 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002202 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002203
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002204 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002205 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002206 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002207 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002208 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002209 break;
2210 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002211
Chris Lattner231cbcb2007-05-02 04:27:25 +00002212 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002213 {
2214 unsigned Size = Record.size();
2215 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002216 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002218 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002219 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002220
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002221 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002222 Value *Op = NULL;
2223 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2224 return Error("Invalid RET record");
2225 if (OpNum != Record.size())
2226 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002227
Chris Lattner96a74c52011-06-17 18:09:11 +00002228 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002229 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002230 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002231 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002232 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002233 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002234 return Error("Invalid BR record");
2235 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2236 if (TrueDest == 0)
2237 return Error("Invalid BR record");
2238
Devang Patele8e02132009-09-18 19:26:43 +00002239 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002240 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002241 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002242 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002243 else {
2244 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002245 Value *Cond = getValue(Record, 2, NextValueNo,
2246 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002247 if (FalseDest == 0 || Cond == 0)
2248 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002249 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002251 }
2252 break;
2253 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002254 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002255 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002256 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2257 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002258
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002259 Type *OpTy = getTypeByID(Record[1]);
2260 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2261
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002262 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002263 BasicBlock *Default = getBasicBlock(Record[3]);
2264 if (OpTy == 0 || Cond == 0 || Default == 0)
2265 return Error("Invalid SWITCH record");
2266
2267 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002268
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002269 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2270 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002271
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002272 unsigned CurIdx = 5;
2273 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002274 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002275 unsigned NumItems = Record[CurIdx++];
2276 for (unsigned ci = 0; ci != NumItems; ++ci) {
2277 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002278
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002279 APInt Low;
2280 unsigned ActiveWords = 1;
2281 if (ValueBitWidth > 64)
2282 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002283 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2284 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002285 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002286
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002287 if (!isSingleNumber) {
2288 ActiveWords = 1;
2289 if (ValueBitWidth > 64)
2290 ActiveWords = Record[CurIdx++];
2291 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002292 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2293 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002294
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002295 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2296 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002297 CurIdx += ActiveWords;
2298 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002299 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002300 }
2301 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002302 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002303 SI->addCase(Case, DestBB);
2304 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002305 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002306 if (Hash != (Record[0] & 0xFFFF))
2307 return Error("Invalid SWITCH record");
2308 I = SI;
2309 break;
2310 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002311
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002312 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002313
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002314 if (Record.size() < 3 || (Record.size() & 1) == 0)
2315 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002316 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002317 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002318 BasicBlock *Default = getBasicBlock(Record[2]);
2319 if (OpTy == 0 || Cond == 0 || Default == 0)
2320 return Error("Invalid SWITCH record");
2321 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002322 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002323 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002324 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002325 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002326 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2327 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2328 if (CaseVal == 0 || DestBB == 0) {
2329 delete SI;
2330 return Error("Invalid SWITCH record!");
2331 }
2332 SI->addCase(CaseVal, DestBB);
2333 }
2334 I = SI;
2335 break;
2336 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002337 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002338 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002339 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002340 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002341 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002342 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002343 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002344 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002345 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002346 InstructionList.push_back(IBI);
2347 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2348 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2349 IBI->addDestination(DestBB);
2350 } else {
2351 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002352 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002353 }
2354 }
2355 I = IBI;
2356 break;
2357 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002358
Duncan Sandsdc024672007-11-27 13:23:08 +00002359 case bitc::FUNC_CODE_INST_INVOKE: {
2360 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002361 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002362 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002363 unsigned CCInfo = Record[1];
2364 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2365 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002366
Chris Lattnera9bb7132007-05-08 05:38:01 +00002367 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002368 Value *Callee;
2369 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002370 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002371
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002372 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2373 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002374 dyn_cast<FunctionType>(CalleeTy->getElementType());
2375
2376 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002377 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2378 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002379 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002380
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002381 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002382 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002383 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2384 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002385 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002386 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002387
Chris Lattner7337ab92007-05-06 00:00:00 +00002388 if (!FTy->isVarArg()) {
2389 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002390 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002391 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002392 // Read type/value pairs for varargs params.
2393 while (OpNum != Record.size()) {
2394 Value *Op;
2395 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2396 return Error("Invalid INVOKE record");
2397 Ops.push_back(Op);
2398 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002399 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002400
Jay Foada3efbb12011-07-15 08:37:34 +00002401 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002402 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002403 cast<InvokeInst>(I)->setCallingConv(
2404 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002405 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002406 break;
2407 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002408 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2409 unsigned Idx = 0;
2410 Value *Val = 0;
2411 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2412 return Error("Invalid RESUME record");
2413 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002414 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002415 break;
2416 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002417 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002418 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002419 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002420 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002421 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002422 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002423 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002424 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002425 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002426
Jay Foad3ecfc862011-03-30 11:28:46 +00002427 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002428 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429
Chris Lattner15e6d172007-05-04 19:11:41 +00002430 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002431 Value *V;
2432 // With the new function encoding, it is possible that operands have
2433 // negative IDs (for forward references). Use a signed VBR
2434 // representation to keep the encoding small.
2435 if (UseRelativeIDs)
2436 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2437 else
2438 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002439 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002440 if (!V || !BB) return Error("Invalid PHI record");
2441 PN->addIncoming(V, BB);
2442 }
2443 I = PN;
2444 break;
2445 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002446
Bill Wendlinge6e88262011-08-12 20:24:12 +00002447 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2448 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2449 unsigned Idx = 0;
2450 if (Record.size() < 4)
2451 return Error("Invalid LANDINGPAD record");
2452 Type *Ty = getTypeByID(Record[Idx++]);
2453 if (!Ty) return Error("Invalid LANDINGPAD record");
2454 Value *PersFn = 0;
2455 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2456 return Error("Invalid LANDINGPAD record");
2457
2458 bool IsCleanup = !!Record[Idx++];
2459 unsigned NumClauses = Record[Idx++];
2460 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2461 LP->setCleanup(IsCleanup);
2462 for (unsigned J = 0; J != NumClauses; ++J) {
2463 LandingPadInst::ClauseType CT =
2464 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2465 Value *Val;
2466
2467 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2468 delete LP;
2469 return Error("Invalid LANDINGPAD record");
2470 }
2471
2472 assert((CT != LandingPadInst::Catch ||
2473 !isa<ArrayType>(Val->getType())) &&
2474 "Catch clause has a invalid type!");
2475 assert((CT != LandingPadInst::Filter ||
2476 isa<ArrayType>(Val->getType())) &&
2477 "Filter clause has invalid type!");
2478 LP->addClause(Val);
2479 }
2480
2481 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002482 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002483 break;
2484 }
2485
Chris Lattner96a74c52011-06-17 18:09:11 +00002486 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2487 if (Record.size() != 4)
2488 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002489 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002490 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002491 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002492 Value *Size = getFnValueByID(Record[2], OpTy);
2493 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002494 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002495 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002496 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002497 break;
2498 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002499 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002500 unsigned OpNum = 0;
2501 Value *Op;
2502 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2503 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002504 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002505
Chris Lattner7337ab92007-05-06 00:00:00 +00002506 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002507 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002508 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002509 }
Eli Friedman21006d42011-08-09 23:02:53 +00002510 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2511 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2512 unsigned OpNum = 0;
2513 Value *Op;
2514 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2515 OpNum+4 != Record.size())
2516 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002517
Eli Friedman21006d42011-08-09 23:02:53 +00002518
2519 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2520 if (Ordering == NotAtomic || Ordering == Release ||
2521 Ordering == AcquireRelease)
2522 return Error("Invalid LOADATOMIC record");
2523 if (Ordering != NotAtomic && Record[OpNum] == 0)
2524 return Error("Invalid LOADATOMIC record");
2525 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2526
2527 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2528 Ordering, SynchScope);
2529 InstructionList.push_back(I);
2530 break;
2531 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002532 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002533 unsigned OpNum = 0;
2534 Value *Val, *Ptr;
2535 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002536 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002537 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2538 OpNum+2 != Record.size())
2539 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002540
Christopher Lambfe63fb92007-12-11 08:59:05 +00002541 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002542 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002543 break;
2544 }
Eli Friedman21006d42011-08-09 23:02:53 +00002545 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2546 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2547 unsigned OpNum = 0;
2548 Value *Val, *Ptr;
2549 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002550 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002551 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2552 OpNum+4 != Record.size())
2553 return Error("Invalid STOREATOMIC record");
2554
2555 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002556 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002557 Ordering == AcquireRelease)
2558 return Error("Invalid STOREATOMIC record");
2559 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2560 if (Ordering != NotAtomic && Record[OpNum] == 0)
2561 return Error("Invalid STOREATOMIC record");
2562
2563 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2564 Ordering, SynchScope);
2565 InstructionList.push_back(I);
2566 break;
2567 }
Eli Friedmanff030482011-07-28 21:48:00 +00002568 case bitc::FUNC_CODE_INST_CMPXCHG: {
2569 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2570 unsigned OpNum = 0;
2571 Value *Ptr, *Cmp, *New;
2572 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002573 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002574 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002575 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002576 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2577 OpNum+3 != Record.size())
2578 return Error("Invalid CMPXCHG record");
2579 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002580 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002581 return Error("Invalid CMPXCHG record");
2582 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2583 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2584 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2585 InstructionList.push_back(I);
2586 break;
2587 }
2588 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2589 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2590 unsigned OpNum = 0;
2591 Value *Ptr, *Val;
2592 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002593 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002594 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2595 OpNum+4 != Record.size())
2596 return Error("Invalid ATOMICRMW record");
2597 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2598 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2599 Operation > AtomicRMWInst::LAST_BINOP)
2600 return Error("Invalid ATOMICRMW record");
2601 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002602 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002603 return Error("Invalid ATOMICRMW record");
2604 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2605 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2606 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2607 InstructionList.push_back(I);
2608 break;
2609 }
Eli Friedman47f35132011-07-25 23:16:38 +00002610 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2611 if (2 != Record.size())
2612 return Error("Invalid FENCE record");
2613 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2614 if (Ordering == NotAtomic || Ordering == Unordered ||
2615 Ordering == Monotonic)
2616 return Error("Invalid FENCE record");
2617 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2618 I = new FenceInst(Context, Ordering, SynchScope);
2619 InstructionList.push_back(I);
2620 break;
2621 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002622 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002623 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2624 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002625 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Bill Wendling99faa3b2012-12-07 23:16:57 +00002627 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002628 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002629
Chris Lattnera9bb7132007-05-08 05:38:01 +00002630 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002631 Value *Callee;
2632 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2633 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002634
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002635 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2636 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002637 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002638 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002639 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002640
Chris Lattner0579f7f2007-05-03 22:04:19 +00002641 SmallVector<Value*, 16> Args;
2642 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002643 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002644 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002645 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002646 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002647 Args.push_back(getValue(Record, OpNum, NextValueNo,
2648 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002649 if (Args.back() == 0) return Error("Invalid CALL record");
2650 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002651
Chris Lattner0579f7f2007-05-03 22:04:19 +00002652 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002653 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002654 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002655 return Error("Invalid CALL record");
2656 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002657 while (OpNum != Record.size()) {
2658 Value *Op;
2659 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2660 return Error("Invalid CALL record");
2661 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002662 }
2663 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002664
Jay Foada3efbb12011-07-15 08:37:34 +00002665 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002666 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002667 cast<CallInst>(I)->setCallingConv(
2668 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002669 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002670 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002671 break;
2672 }
2673 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2674 if (Record.size() < 3)
2675 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002676 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002677 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002678 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002679 if (!OpTy || !Op || !ResTy)
2680 return Error("Invalid VAARG record");
2681 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002682 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002683 break;
2684 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002685 }
2686
2687 // Add instruction to end of current BB. If there is no current BB, reject
2688 // this file.
2689 if (CurBB == 0) {
2690 delete I;
2691 return Error("Invalid instruction with no BB");
2692 }
2693 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002694
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002695 // If this was a terminator instruction, move to the next block.
2696 if (isa<TerminatorInst>(I)) {
2697 ++CurBBNo;
2698 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2699 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002700
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002701 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002702 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002703 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002704 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002705
Chris Lattner5a4251c2013-01-20 02:13:19 +00002706OutOfRecordLoop:
2707
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002708 // Check the function list for unresolved values.
2709 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2710 if (A->getParent() == 0) {
2711 // We found at least one unresolved value. Nuke them all to avoid leaks.
2712 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002713 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002714 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002715 delete A;
2716 }
2717 }
Chris Lattner35a04702007-05-04 03:50:29 +00002718 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002719 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002721
Dan Gohman064ff3e2010-08-25 20:23:38 +00002722 // FIXME: Check for unresolved forward-declared metadata references
2723 // and clean up leaks.
2724
Chris Lattner50b136d2009-10-28 05:53:48 +00002725 // See if anything took the address of blocks in this function. If so,
2726 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002727 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2728 BlockAddrFwdRefs.find(F);
2729 if (BAFRI != BlockAddrFwdRefs.end()) {
2730 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2731 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2732 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002733 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002734 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002735
Chris Lattner50b136d2009-10-28 05:53:48 +00002736 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002737 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002738 FwdRef->eraseFromParent();
2739 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002740
Chris Lattner50b136d2009-10-28 05:53:48 +00002741 BlockAddrFwdRefs.erase(BAFRI);
2742 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002743
Chris Lattner980e5aa2007-05-01 05:52:21 +00002744 // Trim the value list down to the size it was before we parsed this function.
2745 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002746 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002747 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002748 return false;
2749}
2750
Derek Schuff2ea93872012-02-06 22:30:29 +00002751/// FindFunctionInStream - Find the function body in the bitcode stream
2752bool BitcodeReader::FindFunctionInStream(Function *F,
2753 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2754 while (DeferredFunctionInfoIterator->second == 0) {
2755 if (Stream.AtEndOfStream())
2756 return Error("Could not find Function in stream");
2757 // ParseModule will parse the next body in the stream and set its
2758 // position in the DeferredFunctionInfo map.
2759 if (ParseModule(true)) return true;
2760 }
2761 return false;
2762}
2763
Chris Lattnerb348bb82007-05-18 04:02:46 +00002764//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002765// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002766//===----------------------------------------------------------------------===//
2767
2768
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002769bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2770 if (const Function *F = dyn_cast<Function>(GV)) {
2771 return F->isDeclaration() &&
2772 DeferredFunctionInfo.count(const_cast<Function*>(F));
2773 }
2774 return false;
2775}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002776
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002777bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2778 Function *F = dyn_cast<Function>(GV);
2779 // If it's not a function or is already material, ignore the request.
2780 if (!F || !F->isMaterializable()) return false;
2781
2782 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002783 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002784 // If its position is recorded as 0, its body is somewhere in the stream
2785 // but we haven't seen it yet.
2786 if (DFII->second == 0)
2787 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002788
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002789 // Move the bit stream to the saved position of the deferred function body.
2790 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnerb348bb82007-05-18 04:02:46 +00002792 if (ParseFunctionBody(F)) {
2793 if (ErrInfo) *ErrInfo = ErrorString;
2794 return true;
2795 }
Chandler Carruth69940402007-08-04 01:51:18 +00002796
2797 // Upgrade any old intrinsic calls in the function.
2798 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2799 E = UpgradedIntrinsics.end(); I != E; ++I) {
2800 if (I->first != I->second) {
2801 for (Value::use_iterator UI = I->first->use_begin(),
2802 UE = I->first->use_end(); UI != UE; ) {
2803 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2804 UpgradeIntrinsicCall(CI, I->second);
2805 }
2806 }
2807 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002808
Chris Lattnerb348bb82007-05-18 04:02:46 +00002809 return false;
2810}
2811
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002812bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2813 const Function *F = dyn_cast<Function>(GV);
2814 if (!F || F->isDeclaration())
2815 return false;
2816 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2817}
2818
2819void BitcodeReader::Dematerialize(GlobalValue *GV) {
2820 Function *F = dyn_cast<Function>(GV);
2821 // If this function isn't dematerializable, this is a noop.
2822 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002823 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002824
Chris Lattnerb348bb82007-05-18 04:02:46 +00002825 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002826
Chris Lattnerb348bb82007-05-18 04:02:46 +00002827 // Just forget the function body, we can remat it later.
2828 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002829}
2830
2831
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002832bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2833 assert(M == TheModule &&
2834 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002835 // Iterate over the module, deserializing any functions that are still on
2836 // disk.
2837 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2838 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002839 if (F->isMaterializable() &&
2840 Materialize(F, ErrInfo))
2841 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002842
Derek Schuff0ffe6982012-02-29 00:07:09 +00002843 // At this point, if there are any function bodies, the current bit is
2844 // pointing to the END_BLOCK record after them. Now make sure the rest
2845 // of the bits in the module have been read.
2846 if (NextUnreadBit)
2847 ParseModule(true);
2848
Daniel Dunbara279bc32009-09-20 02:20:51 +00002849 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2850 // delete the old functions to clean up. We can't do this unless the entire
2851 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002852 // with calls to the old function.
2853 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2854 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2855 if (I->first != I->second) {
2856 for (Value::use_iterator UI = I->first->use_begin(),
2857 UE = I->first->use_end(); UI != UE; ) {
2858 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2859 UpgradeIntrinsicCall(CI, I->second);
2860 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002861 if (!I->first->use_empty())
2862 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002863 I->first->eraseFromParent();
2864 }
2865 }
2866 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002867
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002868 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002869}
2870
Derek Schuff2ea93872012-02-06 22:30:29 +00002871bool BitcodeReader::InitStream() {
2872 if (LazyStreamer) return InitLazyStream();
2873 return InitStreamFromBuffer();
2874}
2875
2876bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002877 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002878 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2879
2880 if (Buffer->getBufferSize() & 3) {
2881 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2882 return Error("Invalid bitcode signature");
2883 else
2884 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2885 }
2886
2887 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2888 // The magic number is 0x0B17C0DE stored in little endian.
2889 if (isBitcodeWrapper(BufPtr, BufEnd))
2890 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2891 return Error("Invalid bitcode wrapper header");
2892
2893 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2894 Stream.init(*StreamFile);
2895
2896 return false;
2897}
2898
2899bool BitcodeReader::InitLazyStream() {
2900 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2901 // see it.
2902 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2903 StreamFile.reset(new BitstreamReader(Bytes));
2904 Stream.init(*StreamFile);
2905
2906 unsigned char buf[16];
2907 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2908 return Error("Bitcode stream must be at least 16 bytes in length");
2909
2910 if (!isBitcode(buf, buf + 16))
2911 return Error("Invalid bitcode signature");
2912
2913 if (isBitcodeWrapper(buf, buf + 4)) {
2914 const unsigned char *bitcodeStart = buf;
2915 const unsigned char *bitcodeEnd = buf + 16;
2916 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2917 Bytes->dropLeadingBytes(bitcodeStart - buf);
2918 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2919 }
2920 return false;
2921}
Chris Lattner48f84872007-05-01 04:59:48 +00002922
Chris Lattnerc453f762007-04-29 07:54:31 +00002923//===----------------------------------------------------------------------===//
2924// External interface
2925//===----------------------------------------------------------------------===//
2926
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002927/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002928///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002929Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2930 LLVMContext& Context,
2931 std::string *ErrMsg) {
2932 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002933 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002934 M->setMaterializer(R);
2935 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002936 if (ErrMsg)
2937 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002938
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002939 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002940 return 0;
2941 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002942 // Have the BitcodeReader dtor delete 'Buffer'.
2943 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002944
2945 R->materializeForwardReferencedFunctions();
2946
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002947 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002948}
2949
Derek Schuff2ea93872012-02-06 22:30:29 +00002950
2951Module *llvm::getStreamedBitcodeModule(const std::string &name,
2952 DataStreamer *streamer,
2953 LLVMContext &Context,
2954 std::string *ErrMsg) {
2955 Module *M = new Module(name, Context);
2956 BitcodeReader *R = new BitcodeReader(streamer, Context);
2957 M->setMaterializer(R);
2958 if (R->ParseBitcodeInto(M)) {
2959 if (ErrMsg)
2960 *ErrMsg = R->getErrorString();
2961 delete M; // Also deletes R.
2962 return 0;
2963 }
2964 R->setBufferOwned(false); // no buffer to delete
2965 return M;
2966}
2967
Chris Lattnerc453f762007-04-29 07:54:31 +00002968/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2969/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002970Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002971 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002972 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2973 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002974
2975 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2976 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002977 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002978
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002979 // Read in the entire module, and destroy the BitcodeReader.
2980 if (M->MaterializeAllPermanently(ErrMsg)) {
2981 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002982 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002983 }
Bill Wendling34711742010-10-06 01:22:42 +00002984
Chad Rosiercbbb0962011-12-07 21:44:12 +00002985 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2986 // written. We must defer until the Module has been fully materialized.
2987
Chris Lattnerc453f762007-04-29 07:54:31 +00002988 return M;
2989}
Bill Wendling34711742010-10-06 01:22:42 +00002990
2991std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2992 LLVMContext& Context,
2993 std::string *ErrMsg) {
2994 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2995 // Don't let the BitcodeReader dtor delete 'Buffer'.
2996 R->setBufferOwned(false);
2997
2998 std::string Triple("");
2999 if (R->ParseTriple(Triple))
3000 if (ErrMsg)
3001 *ErrMsg = R->getErrorString();
3002
3003 delete R;
3004 return Triple;
3005}