blob: 110f47c7d86968bc97e54ba4d5840901cca4e282 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattnercaee0dc2007-04-22 06:23:29 +00009
Chris Lattnerc453f762007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000011#include "BitcodeReader.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/Constants.h"
16#include "llvm/IR/DerivedTypes.h"
17#include "llvm/IR/InlineAsm.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OperandTraits.h"
21#include "llvm/IR/Operator.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000022#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000023#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000024#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000025using namespace llvm;
26
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000027enum {
28 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
29};
30
Rafael Espindola47f79bb2012-01-02 07:49:53 +000031void BitcodeReader::materializeForwardReferencedFunctions() {
32 while (!BlockAddrFwdRefs.empty()) {
33 Function *F = BlockAddrFwdRefs.begin()->first;
34 F->Materialize();
35 }
36}
37
Chris Lattnerb348bb82007-05-18 04:02:46 +000038void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000039 if (BufferOwned)
40 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000041 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000042 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000043 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000044 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000045
Bill Wendling99faa3b2012-12-07 23:16:57 +000046 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 std::vector<BasicBlock*>().swap(FunctionBBs);
48 std::vector<Function*>().swap(FunctionsWithBodies);
49 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000050 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000051
52 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000053}
54
Chris Lattner48c85b82007-05-04 03:30:17 +000055//===----------------------------------------------------------------------===//
56// Helper functions to implement forward reference resolution, etc.
57//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000058
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059/// ConvertToString - Convert a string from a record into an std::string, return
60/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000061template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000062static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000063 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000064 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000065 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000066
Chris Lattner15e6d172007-05-04 19:11:41 +000067 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
68 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return false;
70}
71
72static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
73 switch (Val) {
74 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000075 case 0: return GlobalValue::ExternalLinkage;
76 case 1: return GlobalValue::WeakAnyLinkage;
77 case 2: return GlobalValue::AppendingLinkage;
78 case 3: return GlobalValue::InternalLinkage;
79 case 4: return GlobalValue::LinkOnceAnyLinkage;
80 case 5: return GlobalValue::DLLImportLinkage;
81 case 6: return GlobalValue::DLLExportLinkage;
82 case 7: return GlobalValue::ExternalWeakLinkage;
83 case 8: return GlobalValue::CommonLinkage;
84 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000085 case 10: return GlobalValue::WeakODRLinkage;
86 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000087 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000088 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000089 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000090 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000091 }
92}
93
94static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
95 switch (Val) {
96 default: // Map unknown visibilities to default.
97 case 0: return GlobalValue::DefaultVisibility;
98 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000099 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000100 }
101}
102
Hans Wennborgce718ff2012-06-23 11:37:03 +0000103static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
104 switch (Val) {
105 case 0: return GlobalVariable::NotThreadLocal;
106 default: // Map unknown non-zero value to general dynamic.
107 case 1: return GlobalVariable::GeneralDynamicTLSModel;
108 case 2: return GlobalVariable::LocalDynamicTLSModel;
109 case 3: return GlobalVariable::InitialExecTLSModel;
110 case 4: return GlobalVariable::LocalExecTLSModel;
111 }
112}
113
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000114static int GetDecodedCastOpcode(unsigned Val) {
115 switch (Val) {
116 default: return -1;
117 case bitc::CAST_TRUNC : return Instruction::Trunc;
118 case bitc::CAST_ZEXT : return Instruction::ZExt;
119 case bitc::CAST_SEXT : return Instruction::SExt;
120 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
121 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
122 case bitc::CAST_UITOFP : return Instruction::UIToFP;
123 case bitc::CAST_SITOFP : return Instruction::SIToFP;
124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
125 case bitc::CAST_FPEXT : return Instruction::FPExt;
126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
128 case bitc::CAST_BITCAST : return Instruction::BitCast;
129 }
130}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000131static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 switch (Val) {
133 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000134 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000140 case bitc::BINOP_UDIV: return Instruction::UDiv;
141 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000143 case bitc::BINOP_UREM: return Instruction::URem;
144 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000146 case bitc::BINOP_SHL: return Instruction::Shl;
147 case bitc::BINOP_LSHR: return Instruction::LShr;
148 case bitc::BINOP_ASHR: return Instruction::AShr;
149 case bitc::BINOP_AND: return Instruction::And;
150 case bitc::BINOP_OR: return Instruction::Or;
151 case bitc::BINOP_XOR: return Instruction::Xor;
152 }
153}
154
Eli Friedmanff030482011-07-28 21:48:00 +0000155static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
156 switch (Val) {
157 default: return AtomicRMWInst::BAD_BINOP;
158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
159 case bitc::RMW_ADD: return AtomicRMWInst::Add;
160 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
161 case bitc::RMW_AND: return AtomicRMWInst::And;
162 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
163 case bitc::RMW_OR: return AtomicRMWInst::Or;
164 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
165 case bitc::RMW_MAX: return AtomicRMWInst::Max;
166 case bitc::RMW_MIN: return AtomicRMWInst::Min;
167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
169 }
170}
171
Eli Friedman47f35132011-07-25 23:16:38 +0000172static AtomicOrdering GetDecodedOrdering(unsigned Val) {
173 switch (Val) {
174 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
175 case bitc::ORDERING_UNORDERED: return Unordered;
176 case bitc::ORDERING_MONOTONIC: return Monotonic;
177 case bitc::ORDERING_ACQUIRE: return Acquire;
178 case bitc::ORDERING_RELEASE: return Release;
179 case bitc::ORDERING_ACQREL: return AcquireRelease;
180 default: // Map unknown orderings to sequentially-consistent.
181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
182 }
183}
184
185static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
186 switch (Val) {
187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
188 default: // Map unknown scopes to cross-thread.
189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
190 }
191}
192
Gabor Greifefe65362008-05-10 08:32:32 +0000193namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000194namespace {
195 /// @brief A class for maintaining the slot number definition
196 /// as a placeholder for the actual definition for forward constants defs.
197 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000199 public:
200 // allocate space for exactly one operand
201 void *operator new(size_t s) {
202 return User::operator new(s, 1);
203 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000207 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000208
Chris Lattnerea693df2008-08-21 02:34:16 +0000209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattnerea693df2008-08-21 02:34:16 +0000210 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000211 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
213 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214
215
Gabor Greifefe65362008-05-10 08:32:32 +0000216 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000218 };
219}
220
Chris Lattner46e77402009-03-31 22:55:09 +0000221// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000222template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000223struct OperandTraits<ConstantPlaceHolder> :
224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000225};
Gabor Greifefe65362008-05-10 08:32:32 +0000226}
227
Chris Lattner46e77402009-03-31 22:55:09 +0000228
229void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
230 if (Idx == size()) {
231 push_back(V);
232 return;
233 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000234
Chris Lattner46e77402009-03-31 22:55:09 +0000235 if (Idx >= size())
236 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 WeakVH &OldV = ValuePtrs[Idx];
239 if (OldV == 0) {
240 OldV = V;
241 return;
242 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Chris Lattner46e77402009-03-31 22:55:09 +0000244 // Handle constants and non-constants (e.g. instrs) differently for
245 // efficiency.
246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
247 ResolveConstants.push_back(std::make_pair(PHC, Idx));
248 OldV = V;
249 } else {
250 // If there was a forward reference to this value, replace it.
251 Value *PrevVal = OldV;
252 OldV->replaceAllUsesWith(V);
253 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000254 }
255}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000256
Gabor Greifefe65362008-05-10 08:32:32 +0000257
Chris Lattner522b7b12007-04-24 05:48:56 +0000258Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000260 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000261 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000262
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000264 assert(Ty == V->getType() && "Type mismatch in constant table!");
265 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000266 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
268 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000269 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000270 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000271 return C;
272}
273
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000275 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000276 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000277
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
280 return V;
281 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner01ff65f2007-05-02 05:16:49 +0000283 // No type specified, must be invalid reference.
284 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000286 // Create and return a placeholder, which will later be RAUW'd.
287 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000288 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 return V;
290}
291
Chris Lattnerea693df2008-08-21 02:34:16 +0000292/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
293/// resolves any forward references. The idea behind this is that we sometimes
294/// get constants (such as large arrays) which reference *many* forward ref
295/// constants. Replacing each of these causes a lot of thrashing when
296/// building/reuniquing the constant. Instead of doing this, we look at all the
297/// uses and rewrite all the place holders at once for any constant that uses
298/// a placeholder.
299void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000301 // binary search.
302 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000307 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000308 Constant *Placeholder = ResolveConstants.back().first;
309 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 // Loop over all users of the placeholder, updating them to reference the
312 // new value. If they reference more than one placeholder, update them all
313 // at once.
314 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000315 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000316 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000317
Chris Lattnerea693df2008-08-21 02:34:16 +0000318 // If the using object isn't uniqued, just update the operands. This
319 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000321 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000322 continue;
323 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000324
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 // Otherwise, we have a constant that uses the placeholder. Replace that
326 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000327 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
329 I != E; ++I) {
330 Value *NewOp;
331 if (!isa<ConstantPlaceHolder>(*I)) {
332 // Not a placeholder reference.
333 NewOp = *I;
334 } else if (*I == Placeholder) {
335 // Common case is that it just references this one placeholder.
336 NewOp = RealVal;
337 } else {
338 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000339 ResolveConstantsTy::iterator It =
340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 std::pair<Constant*, unsigned>(cast<Constant>(*I),
342 0));
343 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000344 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000345 }
346
347 NewOps.push_back(cast<Constant>(NewOp));
348 }
349
350 // Make the new constant.
351 Constant *NewC;
352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000353 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000355 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000356 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000357 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000358 } else {
359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000362
Chris Lattnerea693df2008-08-21 02:34:16 +0000363 UserC->replaceAllUsesWith(NewC);
364 UserC->destroyConstant();
365 NewOps.clear();
366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Nick Lewyckycb337992009-05-10 20:57:05 +0000368 // Update all ValueHandles, they should be the only users at this point.
369 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000370 delete Placeholder;
371 }
372}
373
Devang Pateld5ac4042009-08-04 06:00:18 +0000374void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
375 if (Idx == size()) {
376 push_back(V);
377 return;
378 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000379
Devang Pateld5ac4042009-08-04 06:00:18 +0000380 if (Idx >= size())
381 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 WeakVH &OldV = MDValuePtrs[Idx];
384 if (OldV == 0) {
385 OldV = V;
386 return;
387 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000390 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000392 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
394 // value for Idx.
395 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000396}
397
398Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
399 if (Idx >= size())
400 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000401
Devang Pateld5ac4042009-08-04 06:00:18 +0000402 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000404 return V;
405 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000408 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 MDValuePtrs[Idx] = V;
410 return V;
411}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413Type *BitcodeReader::getTypeByID(unsigned ID) {
414 // The type table size is always specified correctly.
415 if (ID >= TypeList.size())
416 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418 if (Type *Ty = TypeList[ID])
419 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 // If we have a forward reference, the only possible case is when it is to a
422 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000423 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000424}
425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426
Chris Lattner48c85b82007-05-04 03:30:17 +0000427//===----------------------------------------------------------------------===//
428// Functions for parsing blocks from the bitcode file
429//===----------------------------------------------------------------------===//
430
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000431
432/// \brief This fills an AttrBuilder object with the LLVM attributes that have
433/// been decoded from the given integer. This function must stay in sync with
434/// 'encodeLLVMAttributesForBitcode'.
435static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
436 uint64_t EncodedAttrs) {
437 // FIXME: Remove in 4.0.
438
439 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
440 // the bits above 31 down by 11 bits.
441 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
442 assert((!Alignment || isPowerOf2_32(Alignment)) &&
443 "Alignment must be a power of two.");
444
445 if (Alignment)
446 B.addAlignmentAttr(Alignment);
447 B.addRawValue(((EncodedAttrs & (0xffffULL << 32)) >> 11) |
448 (EncodedAttrs & 0xffff));
449}
450
Devang Patel05988662008-09-25 21:00:45 +0000451bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000452 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000453 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000454
Devang Patel19c87462008-09-26 22:53:05 +0000455 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000457
Chris Lattner48c85b82007-05-04 03:30:17 +0000458 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000459
Bill Wendling0c2f0ff2013-01-27 00:36:48 +0000460 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Chris Lattner48c85b82007-05-04 03:30:17 +0000462 // Read all the records.
463 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000464 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000465
Chris Lattner5a4251c2013-01-20 02:13:19 +0000466 switch (Entry.Kind) {
467 case BitstreamEntry::SubBlock: // Handled for us already.
468 case BitstreamEntry::Error:
469 return Error("Error at end of PARAMATTR block");
470 case BitstreamEntry::EndBlock:
Chris Lattner48c85b82007-05-04 03:30:17 +0000471 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000472 case BitstreamEntry::Record:
473 // The interesting case.
474 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000475 }
Joe Abbeyacb61942013-02-06 22:14:06 +0000476
Chris Lattner48c85b82007-05-04 03:30:17 +0000477 // Read a record.
478 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000479 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 default: // Default behavior: ignore.
481 break;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000482 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
483 // FIXME: Remove in 4.0.
Chris Lattner48c85b82007-05-04 03:30:17 +0000484 if (Record.size() & 1)
485 return Error("Invalid ENTRY record");
486
Chris Lattner48c85b82007-05-04 03:30:17 +0000487 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling8232ece2013-01-29 01:43:29 +0000488 AttrBuilder B;
Bill Wendlingf9271ea2013-02-04 23:32:23 +0000489 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling8232ece2013-01-29 01:43:29 +0000490 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patel19c87462008-09-26 22:53:05 +0000491 }
Devang Patel19c87462008-09-26 22:53:05 +0000492
Bill Wendling99faa3b2012-12-07 23:16:57 +0000493 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000494 Attrs.clear();
495 break;
496 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000497 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000498 }
499}
500
Bill Wendlingc3ba0a82013-02-10 23:24:25 +0000501bool BitcodeReader::ParseAttributeGroupBlock() {
502 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
503 return Error("Malformed block record");
504
505 if (!MAttributeGroups.empty())
506 return Error("Multiple PARAMATTR_GROUP blocks found!");
507
508 SmallVector<uint64_t, 64> Record;
509
510 // Read all the records.
511 while (1) {
512 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
513
514 switch (Entry.Kind) {
515 case BitstreamEntry::SubBlock: // Handled for us already.
516 case BitstreamEntry::Error:
517 return Error("Error at end of PARAMATTR_GROUP block");
518 case BitstreamEntry::EndBlock:
519 return false;
520 case BitstreamEntry::Record:
521 // The interesting case.
522 break;
523 }
524
525 // Read a record.
526 Record.clear();
527 switch (Stream.readRecord(Entry.ID, Record)) {
528 default: // Default behavior: ignore.
529 break;
530 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
531 if (Record.size() < 3)
532 return Error("Invalid ENTRY record");
533
534 // FIXME: Record[0] is the 'group ID'. What should we do with it here?
535
536 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
537
538 AttrBuilder B;
539 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
540 if (Record[i] == 0) { // Enum attribute
541 B.addAttribute(Attribute::AttrKind(Record[++i]));
542 } else if (Record[i] == 1) { // Align attribute
543 if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment)
544 B.addAlignmentAttr(Record[++i]);
545 else
546 B.addStackAlignmentAttr(Record[++i]);
547 } else { // String attribute
548 bool HasValue = (Record[i++] == 4);
549 SmallString<64> KindStr;
550 SmallString<64> ValStr;
551
552 while (Record[i] != 0 && i != e)
553 KindStr += Record[i++];
554 assert(Record[i] == 0 && "Kind string not terminated with 0");
555
556 if (HasValue) {
557 // Has a value associated with it.
558 ++i; // Skip the '0' that terminates the kind string.
559 while (Record[i] != 0 && i != e)
560 ValStr += Record[i++];
561 assert(Record[i] == 0 && "Value string not terminated with 0");
562 }
563
564 B.addAttribute(KindStr.str(), ValStr.str());
565 }
566 }
567
568 MAttributeGroups.push_back(AttributeSet::get(Context, Idx, B));
569 break;
570 }
571 }
572 }
573}
574
Chris Lattner86697142007-05-01 05:01:34 +0000575bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000576 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000577 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000578
Chris Lattner1afcace2011-07-09 17:41:24 +0000579 return ParseTypeTableBody();
580}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000581
Chris Lattner1afcace2011-07-09 17:41:24 +0000582bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 if (!TypeList.empty())
584 return Error("Multiple TYPE_BLOCKs found!");
585
586 SmallVector<uint64_t, 64> Record;
587 unsigned NumRecords = 0;
588
Chris Lattner1afcace2011-07-09 17:41:24 +0000589 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000590
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000591 // Read all the records for this type table.
592 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000593 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000594
Chris Lattner5a4251c2013-01-20 02:13:19 +0000595 switch (Entry.Kind) {
596 case BitstreamEntry::SubBlock: // Handled for us already.
597 case BitstreamEntry::Error:
598 Error("Error in the type table block");
599 return true;
600 case BitstreamEntry::EndBlock:
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000601 if (NumRecords != TypeList.size())
602 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000603 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000604 case BitstreamEntry::Record:
605 // The interesting case.
606 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000607 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000609 // Read a record.
610 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000611 Type *ResultTy = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000612 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000613 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000614 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
615 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
616 // type list. This allows us to reserve space.
617 if (Record.size() < 1)
618 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000619 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000620 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000621 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000622 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000623 break;
Dan Gohmance163392011-12-17 00:04:22 +0000624 case bitc::TYPE_CODE_HALF: // HALF
625 ResultTy = Type::getHalfTy(Context);
626 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000627 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000628 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000629 break;
630 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000631 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000632 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000633 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000634 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000635 break;
636 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000637 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000638 break;
639 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000640 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000641 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000642 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000643 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000644 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000645 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000646 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000647 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000648 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
649 ResultTy = Type::getX86_MMXTy(Context);
650 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000651 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
652 if (Record.size() < 1)
653 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000654
Owen Anderson1d0be152009-08-13 21:58:54 +0000655 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000656 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000658 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000659 if (Record.size() < 1)
660 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000661 unsigned AddressSpace = 0;
662 if (Record.size() == 2)
663 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000664 ResultTy = getTypeByID(Record[0]);
665 if (ResultTy == 0) return Error("invalid element type in pointer type");
666 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000667 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000668 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000669 case bitc::TYPE_CODE_FUNCTION_OLD: {
670 // FIXME: attrid is dead, remove it in LLVM 4.0
671 // FUNCTION: [vararg, attrid, retty, paramty x N]
672 if (Record.size() < 3)
673 return Error("Invalid FUNCTION type record");
674 SmallVector<Type*, 8> ArgTys;
675 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
676 if (Type *T = getTypeByID(Record[i]))
677 ArgTys.push_back(T);
678 else
679 break;
680 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000681
Nuno Lopesee8100d2012-05-23 15:19:39 +0000682 ResultTy = getTypeByID(Record[2]);
683 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
684 return Error("invalid type in function type");
685
686 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
687 break;
688 }
Chad Rosiercde54642011-11-03 00:14:01 +0000689 case bitc::TYPE_CODE_FUNCTION: {
690 // FUNCTION: [vararg, retty, paramty x N]
691 if (Record.size() < 2)
692 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000693 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000694 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
695 if (Type *T = getTypeByID(Record[i]))
696 ArgTys.push_back(T);
697 else
698 break;
699 }
Michael Ilseman407a6162012-11-15 22:34:00 +0000700
Chad Rosiercde54642011-11-03 00:14:01 +0000701 ResultTy = getTypeByID(Record[1]);
702 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
703 return Error("invalid type in function type");
704
705 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
706 break;
707 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000708 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000709 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000710 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000711 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000712 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
713 if (Type *T = getTypeByID(Record[i]))
714 EltTys.push_back(T);
715 else
716 break;
717 }
718 if (EltTys.size() != Record.size()-1)
719 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000720 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000721 break;
722 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000723 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
724 if (ConvertToString(Record, 0, TypeName))
725 return Error("Invalid STRUCT_NAME record");
726 continue;
727
728 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
729 if (Record.size() < 1)
730 return Error("Invalid STRUCT type record");
Michael Ilseman407a6162012-11-15 22:34:00 +0000731
Chris Lattner1afcace2011-07-09 17:41:24 +0000732 if (NumRecords >= TypeList.size())
733 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000734
Chris Lattner1afcace2011-07-09 17:41:24 +0000735 // Check to see if this was forward referenced, if so fill in the temp.
736 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
737 if (Res) {
738 Res->setName(TypeName);
739 TypeList[NumRecords] = 0;
740 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000741 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000742 TypeName.clear();
Michael Ilseman407a6162012-11-15 22:34:00 +0000743
Chris Lattner1afcace2011-07-09 17:41:24 +0000744 SmallVector<Type*, 8> EltTys;
745 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
746 if (Type *T = getTypeByID(Record[i]))
747 EltTys.push_back(T);
748 else
749 break;
750 }
751 if (EltTys.size() != Record.size()-1)
752 return Error("invalid STRUCT type record");
753 Res->setBody(EltTys, Record[0]);
754 ResultTy = Res;
755 break;
756 }
757 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
758 if (Record.size() != 1)
759 return Error("Invalid OPAQUE type record");
760
761 if (NumRecords >= TypeList.size())
762 return Error("invalid TYPE table");
Michael Ilseman407a6162012-11-15 22:34:00 +0000763
Chris Lattner1afcace2011-07-09 17:41:24 +0000764 // Check to see if this was forward referenced, if so fill in the temp.
765 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
766 if (Res) {
767 Res->setName(TypeName);
768 TypeList[NumRecords] = 0;
769 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000770 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000771 TypeName.clear();
772 ResultTy = Res;
773 break;
Michael Ilseman407a6162012-11-15 22:34:00 +0000774 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000775 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
776 if (Record.size() < 2)
777 return Error("Invalid ARRAY type record");
778 if ((ResultTy = getTypeByID(Record[1])))
779 ResultTy = ArrayType::get(ResultTy, Record[0]);
780 else
781 return Error("Invalid ARRAY type element");
782 break;
783 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
784 if (Record.size() < 2)
785 return Error("Invalid VECTOR type record");
786 if ((ResultTy = getTypeByID(Record[1])))
787 ResultTy = VectorType::get(ResultTy, Record[0]);
788 else
789 return Error("Invalid ARRAY type element");
790 break;
791 }
792
793 if (NumRecords >= TypeList.size())
794 return Error("invalid TYPE table");
795 assert(ResultTy && "Didn't read a type?");
796 assert(TypeList[NumRecords] == 0 && "Already read type?");
797 TypeList[NumRecords++] = ResultTy;
798 }
799}
800
Chris Lattner86697142007-05-01 05:01:34 +0000801bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000802 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000803 return Error("Malformed block record");
804
805 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Chris Lattner0b2482a2007-04-23 21:26:05 +0000807 // Read all the records for this value table.
808 SmallString<128> ValueName;
809 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000810 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000811
Chris Lattner5a4251c2013-01-20 02:13:19 +0000812 switch (Entry.Kind) {
813 case BitstreamEntry::SubBlock: // Handled for us already.
814 case BitstreamEntry::Error:
815 return Error("malformed value symbol table block");
816 case BitstreamEntry::EndBlock:
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000817 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000818 case BitstreamEntry::Record:
819 // The interesting case.
820 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000821 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000822
Chris Lattner0b2482a2007-04-23 21:26:05 +0000823 // Read a record.
824 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000825 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000826 default: // Default behavior: unknown type.
827 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000828 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000829 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000830 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000831 unsigned ValueID = Record[0];
832 if (ValueID >= ValueList.size())
833 return Error("Invalid Value ID in VST_ENTRY record");
834 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000835
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000836 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000837 ValueName.clear();
838 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000839 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000840 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000841 if (ConvertToString(Record, 1, ValueName))
842 return Error("Invalid VST_BBENTRY record");
843 BasicBlock *BB = getBasicBlock(Record[0]);
844 if (BB == 0)
845 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000846
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000847 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000848 ValueName.clear();
849 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000850 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000851 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000852 }
853}
854
Devang Patele54abc92009-07-22 17:43:22 +0000855bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000856 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000857
858 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
859 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000860
Devang Patele54abc92009-07-22 17:43:22 +0000861 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000862
Devang Patele54abc92009-07-22 17:43:22 +0000863 // Read all the records.
864 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +0000865 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +0000866
Chris Lattner5a4251c2013-01-20 02:13:19 +0000867 switch (Entry.Kind) {
868 case BitstreamEntry::SubBlock: // Handled for us already.
869 case BitstreamEntry::Error:
870 Error("malformed metadata block");
871 return true;
872 case BitstreamEntry::EndBlock:
Devang Patele54abc92009-07-22 17:43:22 +0000873 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +0000874 case BitstreamEntry::Record:
875 // The interesting case.
876 break;
Devang Patele54abc92009-07-22 17:43:22 +0000877 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000878
Victor Hernandez24e64df2010-01-10 07:14:18 +0000879 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000880 // Read a record.
881 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +0000882 unsigned Code = Stream.readRecord(Entry.ID, Record);
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000883 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000884 default: // Default behavior: ignore.
885 break;
Devang Patelaa993142009-07-29 22:34:41 +0000886 case bitc::METADATA_NAME: {
Chris Lattner1ca114a2013-01-20 02:54:05 +0000887 // Read name of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000888 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000889 Record.clear();
890 Code = Stream.ReadCode();
891
Chris Lattner9d61dd92011-06-17 17:50:30 +0000892 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner5a4251c2013-01-20 02:13:19 +0000893 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000894 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000895
896 // Read named metadata elements.
897 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000898 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000899 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000900 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
901 if (MD == 0)
902 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000903 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000904 }
Devang Patelaa993142009-07-29 22:34:41 +0000905 break;
906 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000907 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000908 IsFunctionLocal = true;
909 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000910 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000911 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000912 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000913
Devang Patel104cf9e2009-07-23 01:07:34 +0000914 unsigned Size = Record.size();
915 SmallVector<Value*, 8> Elts;
916 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000917 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000918 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000919 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000920 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000921 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000922 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
923 else
924 Elts.push_back(NULL);
925 }
Jay Foadec9186b2011-04-21 19:59:31 +0000926 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000927 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000928 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000929 break;
930 }
Devang Patele54abc92009-07-22 17:43:22 +0000931 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000932 SmallString<8> String(Record.begin(), Record.end());
933 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000934 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000935 break;
936 }
Devang Patele8e02132009-09-18 19:26:43 +0000937 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000938 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000939 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000940
Devang Patela2148402009-09-28 21:14:55 +0000941 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000942 SmallString<8> Name(Record.begin()+1, Record.end());
943
Chris Lattner08113472009-12-29 09:01:33 +0000944 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000945 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
946 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000947 break;
948 }
Devang Patele54abc92009-07-22 17:43:22 +0000949 }
950 }
951}
952
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000953/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000954/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000955uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000956 if ((V & 1) == 0)
957 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000958 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000959 return -(V >> 1);
960 // There is no such thing as -0 with integers. "-0" really means MININT.
961 return 1ULL << 63;
962}
963
Chris Lattner07d98b42007-04-26 02:46:40 +0000964/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
965/// values and aliases that we can.
966bool BitcodeReader::ResolveGlobalAndAliasInits() {
967 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
968 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000969
Chris Lattner07d98b42007-04-26 02:46:40 +0000970 GlobalInitWorklist.swap(GlobalInits);
971 AliasInitWorklist.swap(AliasInits);
972
973 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000974 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000975 if (ValID >= ValueList.size()) {
976 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000977 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000978 } else {
979 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
980 GlobalInitWorklist.back().first->setInitializer(C);
981 else
982 return Error("Global variable initializer is not a constant!");
983 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000984 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000985 }
986
987 while (!AliasInitWorklist.empty()) {
988 unsigned ValID = AliasInitWorklist.back().second;
989 if (ValID >= ValueList.size()) {
990 AliasInits.push_back(AliasInitWorklist.back());
991 } else {
992 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000993 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000994 else
995 return Error("Alias initializer is not a constant!");
996 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000997 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000998 }
999 return false;
1000}
1001
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001002static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1003 SmallVector<uint64_t, 8> Words(Vals.size());
1004 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001005 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001006
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001007 return APInt(TypeBits, Words);
1008}
1009
Chris Lattner86697142007-05-01 05:01:34 +00001010bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001011 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +00001012 return Error("Malformed block record");
1013
1014 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001015
Chris Lattnere16504e2007-04-24 03:30:34 +00001016 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001017 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +00001018 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +00001019 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001020 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001021
Chris Lattner5a4251c2013-01-20 02:13:19 +00001022 switch (Entry.Kind) {
1023 case BitstreamEntry::SubBlock: // Handled for us already.
1024 case BitstreamEntry::Error:
1025 return Error("malformed block record in AST file");
1026 case BitstreamEntry::EndBlock:
1027 if (NextCstNo != ValueList.size())
1028 return Error("Invalid constant reference!");
Joe Abbeyacb61942013-02-06 22:14:06 +00001029
Chris Lattner5a4251c2013-01-20 02:13:19 +00001030 // Once all the constants have been read, go through and resolve forward
1031 // references.
1032 ValueList.ResolveConstantForwardRefs();
1033 return false;
1034 case BitstreamEntry::Record:
1035 // The interesting case.
Chris Lattnerea693df2008-08-21 02:34:16 +00001036 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001037 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001038
Chris Lattnere16504e2007-04-24 03:30:34 +00001039 // Read a record.
1040 Record.clear();
1041 Value *V = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001042 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00001043 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001044 default: // Default behavior: unknown constant
1045 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001046 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001047 break;
1048 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1049 if (Record.empty())
1050 return Error("Malformed CST_SETTYPE record");
1051 if (Record[0] >= TypeList.size())
1052 return Error("Invalid Type ID in CST_SETTYPE record");
1053 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001054 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001055 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001056 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001057 break;
1058 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001059 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001060 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001061 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001062 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001063 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001064 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001065 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001066
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001067 APInt VInt = ReadWideAPInt(Record,
1068 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001069 V = ConstantInt::get(Context, VInt);
Michael Ilseman407a6162012-11-15 22:34:00 +00001070
Chris Lattner0eef0802007-04-24 04:04:35 +00001071 break;
1072 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001073 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001074 if (Record.empty())
1075 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001076 if (CurTy->isHalfTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001077 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1078 APInt(16, (uint16_t)Record[0])));
Dan Gohmance163392011-12-17 00:04:22 +00001079 else if (CurTy->isFloatTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001080 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1081 APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001082 else if (CurTy->isDoubleTy())
Tim Northover0a29cb02013-01-22 09:46:31 +00001083 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1084 APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001085 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001086 // Bits are not stored the same way as a normal i80 APInt, compensate.
1087 uint64_t Rearrange[2];
1088 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1089 Rearrange[1] = Record[0] >> 48;
Tim Northover0a29cb02013-01-22 09:46:31 +00001090 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1091 APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001092 } else if (CurTy->isFP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001093 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1094 APInt(128, Record)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001095 else if (CurTy->isPPC_FP128Ty())
Tim Northover0a29cb02013-01-22 09:46:31 +00001096 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1097 APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001098 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001099 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001100 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001101 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001102
Chris Lattner15e6d172007-05-04 19:11:41 +00001103 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1104 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001105 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001106
Chris Lattner15e6d172007-05-04 19:11:41 +00001107 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001108 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001109
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001110 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001111 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001112 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001113 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001114 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001115 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1116 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001117 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001118 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001119 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001120 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1121 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001122 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001123 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001124 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001125 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001126 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001127 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001128 break;
1129 }
Chris Lattner2237f842012-02-05 02:41:35 +00001130 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001131 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1132 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001133 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001134
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001135 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001136 V = ConstantDataArray::getString(Context, Elts,
1137 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001138 break;
1139 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001140 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1141 if (Record.empty())
1142 return Error("Invalid CST_DATA record");
Michael Ilseman407a6162012-11-15 22:34:00 +00001143
Chris Lattnerd408f062012-01-30 00:51:16 +00001144 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1145 unsigned Size = Record.size();
Michael Ilseman407a6162012-11-15 22:34:00 +00001146
Chris Lattnerd408f062012-01-30 00:51:16 +00001147 if (EltTy->isIntegerTy(8)) {
1148 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1149 if (isa<VectorType>(CurTy))
1150 V = ConstantDataVector::get(Context, Elts);
1151 else
1152 V = ConstantDataArray::get(Context, Elts);
1153 } else if (EltTy->isIntegerTy(16)) {
1154 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1155 if (isa<VectorType>(CurTy))
1156 V = ConstantDataVector::get(Context, Elts);
1157 else
1158 V = ConstantDataArray::get(Context, Elts);
1159 } else if (EltTy->isIntegerTy(32)) {
1160 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1161 if (isa<VectorType>(CurTy))
1162 V = ConstantDataVector::get(Context, Elts);
1163 else
1164 V = ConstantDataArray::get(Context, Elts);
1165 } else if (EltTy->isIntegerTy(64)) {
1166 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1167 if (isa<VectorType>(CurTy))
1168 V = ConstantDataVector::get(Context, Elts);
1169 else
1170 V = ConstantDataArray::get(Context, Elts);
1171 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001172 SmallVector<float, 16> Elts(Size);
1173 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001174 if (isa<VectorType>(CurTy))
1175 V = ConstantDataVector::get(Context, Elts);
1176 else
1177 V = ConstantDataArray::get(Context, Elts);
1178 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001179 SmallVector<double, 16> Elts(Size);
1180 std::transform(Record.begin(), Record.end(), Elts.begin(),
1181 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001182 if (isa<VectorType>(CurTy))
1183 V = ConstantDataVector::get(Context, Elts);
1184 else
1185 V = ConstantDataArray::get(Context, Elts);
1186 } else {
1187 return Error("Unknown element type in CE_DATA");
1188 }
1189 break;
1190 }
1191
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001192 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1193 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1194 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001195 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001196 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001197 } else {
1198 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1199 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001200 unsigned Flags = 0;
1201 if (Record.size() >= 4) {
1202 if (Opc == Instruction::Add ||
1203 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001204 Opc == Instruction::Mul ||
1205 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001206 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1207 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1208 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1209 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001210 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001211 Opc == Instruction::UDiv ||
1212 Opc == Instruction::LShr ||
1213 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001214 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001215 Flags |= SDivOperator::IsExact;
1216 }
1217 }
1218 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001219 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001220 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001221 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001222 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1223 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1224 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001225 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001226 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001227 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001228 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001229 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001230 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001231 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001232 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001233 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001234 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001235 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001236 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001237 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001238 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001239 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001240 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001241 if (!ElTy) return Error("Invalid CE_GEP record");
1242 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1243 }
Jay Foaddab3d292011-07-21 14:31:17 +00001244 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001245 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1246 BitCode ==
1247 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001248 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001249 }
1250 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1251 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Joe Abbeye46b14a2012-11-19 19:22:55 +00001252 V = ConstantExpr::getSelect(
1253 ValueList.getConstantFwdRef(Record[0],
1254 Type::getInt1Ty(Context)),
1255 ValueList.getConstantFwdRef(Record[1],CurTy),
1256 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001257 break;
1258 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1259 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001260 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001261 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1262 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1263 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Joe Abbey170a15e2012-11-25 15:23:39 +00001264 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001265 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001266 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001267 break;
1268 }
1269 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001270 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001271 if (Record.size() < 3 || OpTy == 0)
1272 return Error("Invalid CE_INSERTELT record");
1273 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1274 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1275 OpTy->getElementType());
Joe Abbey170a15e2012-11-25 15:23:39 +00001276 Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
Joe Abbeye46b14a2012-11-19 19:22:55 +00001277 Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001278 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001279 break;
1280 }
1281 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001283 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001284 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001285 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1286 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001287 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001288 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001289 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001290 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001291 break;
1292 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001293 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001294 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1295 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001296 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001297 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1298 return Error("Invalid CE_SHUFVEC_EX record");
1299 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1300 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001301 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001302 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001303 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001304 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001305 break;
1306 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001307 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1308 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001309 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001310 if (OpTy == 0) return Error("Invalid CE_CMP record");
1311 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1312 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1313
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001314 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001315 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001316 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001317 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001318 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001319 }
Chad Rosier581600b2012-09-05 19:00:49 +00001320 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001321 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001322 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001323 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1324 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001325 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001326 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001327 unsigned AsmStrSize = Record[1];
1328 if (2+AsmStrSize >= Record.size())
1329 return Error("Invalid INLINEASM record");
1330 unsigned ConstStrSize = Record[2+AsmStrSize];
1331 if (3+AsmStrSize+ConstStrSize > Record.size())
1332 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattner2bce93a2007-05-06 01:58:20 +00001334 for (unsigned i = 0; i != AsmStrSize; ++i)
1335 AsmStr += (char)Record[2+i];
1336 for (unsigned i = 0; i != ConstStrSize; ++i)
1337 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001338 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001339 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001340 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001341 break;
1342 }
Chad Rosier581600b2012-09-05 19:00:49 +00001343 // This version adds support for the asm dialect keywords (e.g.,
1344 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001345 case bitc::CST_CODE_INLINEASM: {
1346 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1347 std::string AsmStr, ConstrStr;
1348 bool HasSideEffects = Record[0] & 1;
1349 bool IsAlignStack = (Record[0] >> 1) & 1;
1350 unsigned AsmDialect = Record[0] >> 2;
1351 unsigned AsmStrSize = Record[1];
1352 if (2+AsmStrSize >= Record.size())
1353 return Error("Invalid INLINEASM record");
1354 unsigned ConstStrSize = Record[2+AsmStrSize];
1355 if (3+AsmStrSize+ConstStrSize > Record.size())
1356 return Error("Invalid INLINEASM record");
1357
1358 for (unsigned i = 0; i != AsmStrSize; ++i)
1359 AsmStr += (char)Record[2+i];
1360 for (unsigned i = 0; i != ConstStrSize; ++i)
1361 ConstrStr += (char)Record[3+AsmStrSize+i];
1362 PointerType *PTy = cast<PointerType>(CurTy);
1363 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1364 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001365 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001366 break;
1367 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001368 case bitc::CST_CODE_BLOCKADDRESS:{
1369 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001370 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001371 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1372 Function *Fn =
1373 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1374 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001375
1376 // If the function is already parsed we can insert the block address right
1377 // away.
1378 if (!Fn->empty()) {
1379 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1380 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1381 if (BBI == BBE)
1382 return Error("Invalid blockaddress block #");
1383 ++BBI;
1384 }
1385 V = BlockAddress::get(Fn, BBI);
1386 } else {
1387 // Otherwise insert a placeholder and remember it so it can be inserted
1388 // when the function is parsed.
1389 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1390 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001391 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001392 0, "");
1393 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1394 V = FwdRef;
1395 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001396 break;
Michael Ilseman407a6162012-11-15 22:34:00 +00001397 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001399
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001400 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001401 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001402 }
1403}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001404
Chad Rosiercbbb0962011-12-07 21:44:12 +00001405bool BitcodeReader::ParseUseLists() {
1406 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1407 return Error("Malformed block record");
1408
1409 SmallVector<uint64_t, 64> Record;
Michael Ilseman407a6162012-11-15 22:34:00 +00001410
Chad Rosiercbbb0962011-12-07 21:44:12 +00001411 // Read all the records.
1412 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001413 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001414
Chris Lattner5a4251c2013-01-20 02:13:19 +00001415 switch (Entry.Kind) {
1416 case BitstreamEntry::SubBlock: // Handled for us already.
1417 case BitstreamEntry::Error:
1418 return Error("malformed use list block");
1419 case BitstreamEntry::EndBlock:
Chad Rosiercbbb0962011-12-07 21:44:12 +00001420 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001421 case BitstreamEntry::Record:
1422 // The interesting case.
1423 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001424 }
Michael Ilseman407a6162012-11-15 22:34:00 +00001425
Chad Rosiercbbb0962011-12-07 21:44:12 +00001426 // Read a use list record.
1427 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001428 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosiercbbb0962011-12-07 21:44:12 +00001429 default: // Default behavior: unknown type.
1430 break;
1431 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1432 unsigned RecordLength = Record.size();
1433 if (RecordLength < 1)
1434 return Error ("Invalid UseList reader!");
1435 UseListRecords.push_back(Record);
1436 break;
1437 }
1438 }
1439 }
1440}
1441
Chris Lattner980e5aa2007-05-01 05:52:21 +00001442/// RememberAndSkipFunctionBody - When we see the block for a function body,
1443/// remember where it is and then skip it. This lets us lazily deserialize the
1444/// functions.
1445bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001446 // Get the function we are talking about.
1447 if (FunctionsWithBodies.empty())
1448 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001449
Chris Lattner48f84872007-05-01 04:59:48 +00001450 Function *Fn = FunctionsWithBodies.back();
1451 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001452
Chris Lattner48f84872007-05-01 04:59:48 +00001453 // Save the current stream state.
1454 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001455 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattner48f84872007-05-01 04:59:48 +00001457 // Skip over the function block for now.
1458 if (Stream.SkipBlock())
1459 return Error("Malformed block record");
1460 return false;
1461}
1462
Derek Schuff2ea93872012-02-06 22:30:29 +00001463bool BitcodeReader::GlobalCleanup() {
1464 // Patch the initializers for globals and aliases up.
1465 ResolveGlobalAndAliasInits();
1466 if (!GlobalInits.empty() || !AliasInits.empty())
1467 return Error("Malformed global initializer set");
1468
1469 // Look for intrinsic functions which need to be upgraded at some point
1470 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1471 FI != FE; ++FI) {
1472 Function *NewFn;
1473 if (UpgradeIntrinsicFunction(FI, NewFn))
1474 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1475 }
1476
1477 // Look for global variables which need to be renamed.
1478 for (Module::global_iterator
1479 GI = TheModule->global_begin(), GE = TheModule->global_end();
1480 GI != GE; ++GI)
1481 UpgradeGlobalVariable(GI);
1482 // Force deallocation of memory for these vectors to favor the client that
1483 // want lazy deserialization.
1484 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1485 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1486 return false;
1487}
1488
1489bool BitcodeReader::ParseModule(bool Resume) {
1490 if (Resume)
1491 Stream.JumpToBit(NextUnreadBit);
1492 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001493 return Error("Malformed block record");
1494
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001495 SmallVector<uint64_t, 64> Record;
1496 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001497 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001498
1499 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001500 while (1) {
1501 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001502
Chris Lattner5a4251c2013-01-20 02:13:19 +00001503 switch (Entry.Kind) {
1504 case BitstreamEntry::Error:
1505 Error("malformed module block");
1506 return true;
1507 case BitstreamEntry::EndBlock:
Derek Schuff2ea93872012-02-06 22:30:29 +00001508 return GlobalCleanup();
Joe Abbeyacb61942013-02-06 22:14:06 +00001509
Chris Lattner5a4251c2013-01-20 02:13:19 +00001510 case BitstreamEntry::SubBlock:
1511 switch (Entry.ID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001512 default: // Skip unknown content.
1513 if (Stream.SkipBlock())
1514 return Error("Malformed block record");
1515 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001516 case bitc::BLOCKINFO_BLOCK_ID:
1517 if (Stream.ReadBlockInfoBlock())
1518 return Error("Malformed BlockInfoBlock");
1519 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001520 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001521 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001522 return true;
1523 break;
Bill Wendlingc3ba0a82013-02-10 23:24:25 +00001524 case bitc::PARAMATTR_GROUP_BLOCK_ID:
1525 if (ParseAttributeGroupBlock())
1526 return true;
1527 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001528 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001529 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001530 return true;
1531 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001532 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001533 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001534 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001535 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001536 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001537 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001538 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001539 return true;
1540 break;
Devang Patele54abc92009-07-22 17:43:22 +00001541 case bitc::METADATA_BLOCK_ID:
1542 if (ParseMetadata())
1543 return true;
1544 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001545 case bitc::FUNCTION_BLOCK_ID:
1546 // If this is the first function body we've seen, reverse the
1547 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001548 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001549 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001550 if (GlobalCleanup())
1551 return true;
1552 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001553 }
Joe Abbeyacb61942013-02-06 22:14:06 +00001554
Chris Lattner980e5aa2007-05-01 05:52:21 +00001555 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001556 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001557 // For streaming bitcode, suspend parsing when we reach the function
1558 // bodies. Subsequent materialization calls will resume it when
1559 // necessary. For streaming, the function bodies must be at the end of
1560 // the bitcode. If the bitcode file is old, the symbol table will be
1561 // at the end instead and will not have been seen yet. In this case,
1562 // just finish the parse now.
1563 if (LazyStreamer && SeenValueSymbolTable) {
1564 NextUnreadBit = Stream.GetCurrentBitNo();
1565 return false;
1566 }
Chris Lattner48f84872007-05-01 04:59:48 +00001567 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001568 case bitc::USELIST_BLOCK_ID:
1569 if (ParseUseLists())
1570 return true;
1571 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001572 }
1573 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001574
Chris Lattner5a4251c2013-01-20 02:13:19 +00001575 case BitstreamEntry::Record:
1576 // The interesting case.
1577 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001578 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001579
Daniel Dunbara279bc32009-09-20 02:20:51 +00001580
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001581 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001582 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001583 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001584 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001585 if (Record.size() < 1)
1586 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001587 // Only version #0 and #1 are supported so far.
1588 unsigned module_version = Record[0];
1589 switch (module_version) {
1590 default: return Error("Unknown bitstream version!");
1591 case 0:
1592 UseRelativeIDs = false;
1593 break;
1594 case 1:
1595 UseRelativeIDs = true;
1596 break;
1597 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001599 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001600 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001601 std::string S;
1602 if (ConvertToString(Record, 0, S))
1603 return Error("Invalid MODULE_CODE_TRIPLE record");
1604 TheModule->setTargetTriple(S);
1605 break;
1606 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001607 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001608 std::string S;
1609 if (ConvertToString(Record, 0, S))
1610 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1611 TheModule->setDataLayout(S);
1612 break;
1613 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001614 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001615 std::string S;
1616 if (ConvertToString(Record, 0, S))
1617 return Error("Invalid MODULE_CODE_ASM record");
1618 TheModule->setModuleInlineAsm(S);
1619 break;
1620 }
Bill Wendling3defc0b2012-11-28 08:41:48 +00001621 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1622 // FIXME: Remove in 4.0.
1623 std::string S;
1624 if (ConvertToString(Record, 0, S))
1625 return Error("Invalid MODULE_CODE_DEPLIB record");
1626 // Ignore value.
1627 break;
1628 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001629 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001630 std::string S;
1631 if (ConvertToString(Record, 0, S))
1632 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1633 SectionTable.push_back(S);
1634 break;
1635 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001636 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001637 std::string S;
1638 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001639 return Error("Invalid MODULE_CODE_GCNAME record");
1640 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001641 break;
1642 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001643 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001644 // linkage, alignment, section, visibility, threadlocal,
1645 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001646 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001647 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001648 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001649 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001650 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001651 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001652 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001653 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001654 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001655
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001656 bool isConstant = Record[1];
1657 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1658 unsigned Alignment = (1 << Record[4]) >> 1;
1659 std::string Section;
1660 if (Record[5]) {
1661 if (Record[5]-1 >= SectionTable.size())
1662 return Error("Invalid section ID");
1663 Section = SectionTable[Record[5]-1];
1664 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001665 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001666 if (Record.size() > 6)
1667 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001668
1669 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001670 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001671 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001672
Rafael Espindolabea46262011-01-08 16:42:36 +00001673 bool UnnamedAddr = false;
1674 if (Record.size() > 8)
1675 UnnamedAddr = Record[8];
1676
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001677 bool ExternallyInitialized = false;
1678 if (Record.size() > 9)
1679 ExternallyInitialized = Record[9];
1680
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001682 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Michael Gottesmana2de37c2013-02-05 05:57:38 +00001683 TLM, AddressSpace, ExternallyInitialized);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001684 NewGV->setAlignment(Alignment);
1685 if (!Section.empty())
1686 NewGV->setSection(Section);
1687 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001688 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001689
Chris Lattner0b2482a2007-04-23 21:26:05 +00001690 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001691
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001692 // Remember which value to use for the global initializer.
1693 if (unsigned InitID = Record[2])
1694 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001695 break;
1696 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001697 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001698 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001699 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001700 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001701 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001702 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001703 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001704 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001705 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001706 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001707 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1708 if (!FTy)
1709 return Error("Function not a pointer to function type!");
1710
Gabor Greif051a9502008-04-06 20:25:17 +00001711 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1712 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001713
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001714 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001715 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001716 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001717 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Chris Lattnera9bb7132007-05-08 05:38:01 +00001719 Func->setAlignment((1 << Record[5]) >> 1);
1720 if (Record[6]) {
1721 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001722 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001723 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001724 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001725 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001726 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001727 if (Record[8]-1 > GCTable.size())
1728 return Error("Invalid GC ID");
1729 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001730 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001731 bool UnnamedAddr = false;
1732 if (Record.size() > 9)
1733 UnnamedAddr = Record[9];
1734 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001735 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001736
Chris Lattner48f84872007-05-01 04:59:48 +00001737 // If this is a function with a body, remember the prototype we are
1738 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001739 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001740 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001741 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1742 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001743 break;
1744 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001745 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001746 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001747 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001748 if (Record.size() < 3)
1749 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001750 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001751 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001752 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001753 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001754
Chris Lattner07d98b42007-04-26 02:46:40 +00001755 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1756 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001757 // Old bitcode files didn't have visibility field.
1758 if (Record.size() > 3)
1759 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001760 ValueList.push_back(NewGA);
1761 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1762 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001763 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001764 /// MODULE_CODE_PURGEVALS: [numvals]
1765 case bitc::MODULE_CODE_PURGEVALS:
1766 // Trim down the value list to the specified size.
1767 if (Record.size() < 1 || Record[0] > ValueList.size())
1768 return Error("Invalid MODULE_PURGEVALS record");
1769 ValueList.shrinkTo(Record[0]);
1770 break;
1771 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001772 Record.clear();
1773 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001774}
1775
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001776bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001777 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001778
Derek Schuff2ea93872012-02-06 22:30:29 +00001779 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001780
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001781 // Sniff for the signature.
1782 if (Stream.Read(8) != 'B' ||
1783 Stream.Read(8) != 'C' ||
1784 Stream.Read(4) != 0x0 ||
1785 Stream.Read(4) != 0xC ||
1786 Stream.Read(4) != 0xE ||
1787 Stream.Read(4) != 0xD)
1788 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001789
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001790 // We expect a number of well-defined blocks, though we don't necessarily
1791 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001792 while (1) {
1793 if (Stream.AtEndOfStream())
1794 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001795
Chris Lattner5a4251c2013-01-20 02:13:19 +00001796 BitstreamEntry Entry =
1797 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbeyacb61942013-02-06 22:14:06 +00001798
Chris Lattner5a4251c2013-01-20 02:13:19 +00001799 switch (Entry.Kind) {
1800 case BitstreamEntry::Error:
1801 Error("malformed module file");
1802 return true;
1803 case BitstreamEntry::EndBlock:
1804 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001805
Chris Lattner5a4251c2013-01-20 02:13:19 +00001806 case BitstreamEntry::SubBlock:
1807 switch (Entry.ID) {
1808 case bitc::BLOCKINFO_BLOCK_ID:
1809 if (Stream.ReadBlockInfoBlock())
1810 return Error("Malformed BlockInfoBlock");
1811 break;
1812 case bitc::MODULE_BLOCK_ID:
1813 // Reject multiple MODULE_BLOCK's in a single bitstream.
1814 if (TheModule)
1815 return Error("Multiple MODULE_BLOCKs in same stream");
1816 TheModule = M;
1817 if (ParseModule(false))
1818 return true;
1819 if (LazyStreamer) return false;
1820 break;
1821 default:
1822 if (Stream.SkipBlock())
1823 return Error("Malformed block record");
1824 break;
1825 }
1826 continue;
1827 case BitstreamEntry::Record:
1828 // There should be no records in the top-level of blocks.
Joe Abbeyacb61942013-02-06 22:14:06 +00001829
Chris Lattner5a4251c2013-01-20 02:13:19 +00001830 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001831 // to the end of them. If this file size is a multiple of 4 but not 8, we
1832 // have to read and ignore these final 4 bytes :-(
Chris Lattner5a4251c2013-01-20 02:13:19 +00001833 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolac9687b32011-05-26 18:59:54 +00001834 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001835 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001836 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001837
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001838 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001839 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001840 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001841}
Chris Lattnerc453f762007-04-29 07:54:31 +00001842
Bill Wendling34711742010-10-06 01:22:42 +00001843bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1844 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1845 return Error("Malformed block record");
1846
1847 SmallVector<uint64_t, 64> Record;
1848
1849 // Read all the records for this module.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001850 while (1) {
1851 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001852
Chris Lattner5a4251c2013-01-20 02:13:19 +00001853 switch (Entry.Kind) {
1854 case BitstreamEntry::SubBlock: // Handled for us already.
1855 case BitstreamEntry::Error:
1856 return Error("malformed module block");
1857 case BitstreamEntry::EndBlock:
Bill Wendling34711742010-10-06 01:22:42 +00001858 return false;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001859 case BitstreamEntry::Record:
1860 // The interesting case.
1861 break;
Bill Wendling34711742010-10-06 01:22:42 +00001862 }
1863
1864 // Read a record.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001865 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling34711742010-10-06 01:22:42 +00001866 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001867 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1868 std::string S;
1869 if (ConvertToString(Record, 0, S))
1870 return Error("Invalid MODULE_CODE_TRIPLE record");
1871 Triple = S;
1872 break;
1873 }
1874 }
1875 Record.clear();
1876 }
Bill Wendling34711742010-10-06 01:22:42 +00001877}
1878
1879bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001880 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001881
1882 // Sniff for the signature.
1883 if (Stream.Read(8) != 'B' ||
1884 Stream.Read(8) != 'C' ||
1885 Stream.Read(4) != 0x0 ||
1886 Stream.Read(4) != 0xC ||
1887 Stream.Read(4) != 0xE ||
1888 Stream.Read(4) != 0xD)
1889 return Error("Invalid bitcode signature");
1890
1891 // We expect a number of well-defined blocks, though we don't necessarily
1892 // need to understand them all.
Chris Lattner5a4251c2013-01-20 02:13:19 +00001893 while (1) {
1894 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001895
Chris Lattner5a4251c2013-01-20 02:13:19 +00001896 switch (Entry.Kind) {
1897 case BitstreamEntry::Error:
1898 Error("malformed module file");
1899 return true;
1900 case BitstreamEntry::EndBlock:
1901 return false;
Joe Abbeyacb61942013-02-06 22:14:06 +00001902
Chris Lattner5a4251c2013-01-20 02:13:19 +00001903 case BitstreamEntry::SubBlock:
1904 if (Entry.ID == bitc::MODULE_BLOCK_ID)
1905 return ParseModuleTriple(Triple);
Joe Abbeyacb61942013-02-06 22:14:06 +00001906
Chris Lattner5a4251c2013-01-20 02:13:19 +00001907 // Ignore other sub-blocks.
1908 if (Stream.SkipBlock()) {
1909 Error("malformed block record in AST file");
Bill Wendling34711742010-10-06 01:22:42 +00001910 return true;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001911 }
1912 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00001913
Chris Lattner5a4251c2013-01-20 02:13:19 +00001914 case BitstreamEntry::Record:
1915 Stream.skipRecord(Entry.ID);
1916 continue;
Bill Wendling34711742010-10-06 01:22:42 +00001917 }
1918 }
Bill Wendling34711742010-10-06 01:22:42 +00001919}
1920
Devang Patele8e02132009-09-18 19:26:43 +00001921/// ParseMetadataAttachment - Parse metadata attachments.
1922bool BitcodeReader::ParseMetadataAttachment() {
1923 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1924 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001925
Devang Patele8e02132009-09-18 19:26:43 +00001926 SmallVector<uint64_t, 64> Record;
Chris Lattner5a4251c2013-01-20 02:13:19 +00001927 while (1) {
1928 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbeyacb61942013-02-06 22:14:06 +00001929
Chris Lattner5a4251c2013-01-20 02:13:19 +00001930 switch (Entry.Kind) {
1931 case BitstreamEntry::SubBlock: // Handled for us already.
1932 case BitstreamEntry::Error:
1933 return Error("malformed metadata block");
1934 case BitstreamEntry::EndBlock:
1935 return false;
1936 case BitstreamEntry::Record:
1937 // The interesting case.
Devang Patele8e02132009-09-18 19:26:43 +00001938 break;
1939 }
Chris Lattner5a4251c2013-01-20 02:13:19 +00001940
Devang Patele8e02132009-09-18 19:26:43 +00001941 // Read a metadata attachment record.
1942 Record.clear();
Chris Lattner5a4251c2013-01-20 02:13:19 +00001943 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patele8e02132009-09-18 19:26:43 +00001944 default: // Default behavior: ignore.
1945 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001946 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001947 unsigned RecordLength = Record.size();
1948 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001949 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001950 Instruction *Inst = InstructionList[Record[0]];
1951 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001952 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001953 DenseMap<unsigned, unsigned>::iterator I =
1954 MDKindMap.find(Kind);
1955 if (I == MDKindMap.end())
1956 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001957 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001958 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001959 }
1960 break;
1961 }
1962 }
1963 }
Devang Patele8e02132009-09-18 19:26:43 +00001964}
Chris Lattner48f84872007-05-01 04:59:48 +00001965
Chris Lattner980e5aa2007-05-01 05:52:21 +00001966/// ParseFunctionBody - Lazily parse the specified function body block.
1967bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001968 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001969 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Nick Lewycky9a49f152010-02-25 08:30:17 +00001971 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001972 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001973 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001974
Chris Lattner980e5aa2007-05-01 05:52:21 +00001975 // Add all the function arguments to the value table.
1976 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1977 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001978
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001979 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001980 BasicBlock *CurBB = 0;
1981 unsigned CurBBNo = 0;
1982
Chris Lattnera6245242010-04-03 02:17:50 +00001983 DebugLoc LastLoc;
Michael Ilseman407a6162012-11-15 22:34:00 +00001984
Chris Lattner980e5aa2007-05-01 05:52:21 +00001985 // Read all the records.
1986 SmallVector<uint64_t, 64> Record;
1987 while (1) {
Chris Lattner5a4251c2013-01-20 02:13:19 +00001988 BitstreamEntry Entry = Stream.advance();
Joe Abbeyacb61942013-02-06 22:14:06 +00001989
Chris Lattner5a4251c2013-01-20 02:13:19 +00001990 switch (Entry.Kind) {
1991 case BitstreamEntry::Error:
1992 return Error("Bitcode error in function block");
1993 case BitstreamEntry::EndBlock:
1994 goto OutOfRecordLoop;
Joe Abbeyacb61942013-02-06 22:14:06 +00001995
Chris Lattner5a4251c2013-01-20 02:13:19 +00001996 case BitstreamEntry::SubBlock:
1997 switch (Entry.ID) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001998 default: // Skip unknown content.
1999 if (Stream.SkipBlock())
2000 return Error("Malformed block record");
2001 break;
2002 case bitc::CONSTANTS_BLOCK_ID:
2003 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002004 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00002005 break;
2006 case bitc::VALUE_SYMTAB_BLOCK_ID:
2007 if (ParseValueSymbolTable()) return true;
2008 break;
Devang Patele8e02132009-09-18 19:26:43 +00002009 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00002010 if (ParseMetadataAttachment()) return true;
2011 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00002012 case bitc::METADATA_BLOCK_ID:
2013 if (ParseMetadata()) return true;
2014 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002015 }
2016 continue;
Joe Abbeyacb61942013-02-06 22:14:06 +00002017
Chris Lattner5a4251c2013-01-20 02:13:19 +00002018 case BitstreamEntry::Record:
2019 // The interesting case.
2020 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00002021 }
Joe Abbeyacb61942013-02-06 22:14:06 +00002022
Chris Lattner980e5aa2007-05-01 05:52:21 +00002023 // Read a record.
2024 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002025 Instruction *I = 0;
Chris Lattner5a4251c2013-01-20 02:13:19 +00002026 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman1224c382009-07-20 21:19:07 +00002027 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002028 default: // Default behavior: reject
2029 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002030 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002031 if (Record.size() < 1 || Record[0] == 0)
2032 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00002033 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00002034 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002035 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00002036 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002037 CurBB = FunctionBBs[0];
2038 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002039
Chris Lattnera6245242010-04-03 02:17:50 +00002040 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
2041 // This record indicates that the last instruction is at the same
2042 // location as the previous instruction with a location.
2043 I = 0;
Michael Ilseman407a6162012-11-15 22:34:00 +00002044
Chris Lattnera6245242010-04-03 02:17:50 +00002045 // Get the last instruction emitted.
2046 if (CurBB && !CurBB->empty())
2047 I = &CurBB->back();
2048 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2049 !FunctionBBs[CurBBNo-1]->empty())
2050 I = &FunctionBBs[CurBBNo-1]->back();
Michael Ilseman407a6162012-11-15 22:34:00 +00002051
Chris Lattnera6245242010-04-03 02:17:50 +00002052 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2053 I->setDebugLoc(LastLoc);
2054 I = 0;
2055 continue;
Michael Ilseman407a6162012-11-15 22:34:00 +00002056
Chris Lattner4f6bab92011-06-17 18:17:37 +00002057 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00002058 I = 0; // Get the last instruction emitted.
2059 if (CurBB && !CurBB->empty())
2060 I = &CurBB->back();
2061 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2062 !FunctionBBs[CurBBNo-1]->empty())
2063 I = &FunctionBBs[CurBBNo-1]->back();
2064 if (I == 0 || Record.size() < 4)
2065 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002066
Chris Lattnera6245242010-04-03 02:17:50 +00002067 unsigned Line = Record[0], Col = Record[1];
2068 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman407a6162012-11-15 22:34:00 +00002069
Chris Lattnera6245242010-04-03 02:17:50 +00002070 MDNode *Scope = 0, *IA = 0;
2071 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2072 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2073 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2074 I->setDebugLoc(LastLoc);
2075 I = 0;
2076 continue;
2077 }
2078
Chris Lattnerabfbf852007-05-06 00:21:25 +00002079 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2080 unsigned OpNum = 0;
2081 Value *LHS, *RHS;
2082 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002083 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002084 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002085 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002086
Dan Gohman1224c382009-07-20 21:19:07 +00002087 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002088 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002089 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002090 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002091 if (OpNum < Record.size()) {
2092 if (Opc == Instruction::Add ||
2093 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002094 Opc == Instruction::Mul ||
2095 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002096 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002097 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002098 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002099 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002100 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002101 Opc == Instruction::UDiv ||
2102 Opc == Instruction::LShr ||
2103 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002104 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002105 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman495d10a2012-11-27 00:43:38 +00002106 } else if (isa<FPMathOperator>(I)) {
2107 FastMathFlags FMF;
Michael Ilseman1638b832012-12-09 21:12:04 +00002108 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2109 FMF.setUnsafeAlgebra();
2110 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2111 FMF.setNoNaNs();
2112 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2113 FMF.setNoInfs();
2114 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2115 FMF.setNoSignedZeros();
2116 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2117 FMF.setAllowReciprocal();
Michael Ilseman495d10a2012-11-27 00:43:38 +00002118 if (FMF.any())
2119 I->setFastMathFlags(FMF);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002120 }
Michael Ilseman495d10a2012-11-27 00:43:38 +00002121
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002122 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002123 break;
2124 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002125 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2126 unsigned OpNum = 0;
2127 Value *Op;
2128 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2129 OpNum+2 != Record.size())
2130 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002131
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002132 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002133 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2134 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002135 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002136 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002137 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002138 break;
2139 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002140 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002141 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002142 unsigned OpNum = 0;
2143 Value *BasePtr;
2144 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002145 return Error("Invalid GEP record");
2146
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002147 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002148 while (OpNum != Record.size()) {
2149 Value *Op;
2150 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002151 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002152 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002153 }
2154
Jay Foada9203102011-07-25 09:48:08 +00002155 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002156 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002157 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002158 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002159 break;
2160 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002162 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2163 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002164 unsigned OpNum = 0;
2165 Value *Agg;
2166 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2167 return Error("Invalid EXTRACTVAL record");
2168
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002169 SmallVector<unsigned, 4> EXTRACTVALIdx;
2170 for (unsigned RecSize = Record.size();
2171 OpNum != RecSize; ++OpNum) {
2172 uint64_t Index = Record[OpNum];
2173 if ((unsigned)Index != Index)
2174 return Error("Invalid EXTRACTVAL index");
2175 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002176 }
2177
Jay Foadfc6d3a42011-07-13 10:26:04 +00002178 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002179 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002180 break;
2181 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002182
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002183 case bitc::FUNC_CODE_INST_INSERTVAL: {
2184 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002185 unsigned OpNum = 0;
2186 Value *Agg;
2187 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2188 return Error("Invalid INSERTVAL record");
2189 Value *Val;
2190 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2191 return Error("Invalid INSERTVAL record");
2192
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002193 SmallVector<unsigned, 4> INSERTVALIdx;
2194 for (unsigned RecSize = Record.size();
2195 OpNum != RecSize; ++OpNum) {
2196 uint64_t Index = Record[OpNum];
2197 if ((unsigned)Index != Index)
2198 return Error("Invalid INSERTVAL index");
2199 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002200 }
2201
Jay Foadfc6d3a42011-07-13 10:26:04 +00002202 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002203 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002204 break;
2205 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002206
Chris Lattnerabfbf852007-05-06 00:21:25 +00002207 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002208 // obsolete form of select
2209 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002210 unsigned OpNum = 0;
2211 Value *TrueVal, *FalseVal, *Cond;
2212 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002213 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2214 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002215 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002216
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002217 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002218 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002219 break;
2220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002222 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2223 // new form of select
2224 // handles select i1 or select [N x i1]
2225 unsigned OpNum = 0;
2226 Value *TrueVal, *FalseVal, *Cond;
2227 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002228 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002229 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2230 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002231
2232 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002233 if (VectorType* vector_type =
2234 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002235 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002237 return Error("Invalid SELECT condition type");
2238 } else {
2239 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002240 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002241 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002242 }
2243
Gabor Greif051a9502008-04-06 20:25:17 +00002244 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002245 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002246 break;
2247 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002248
Chris Lattner01ff65f2007-05-02 05:16:49 +00002249 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002250 unsigned OpNum = 0;
2251 Value *Vec, *Idx;
2252 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002253 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002254 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002255 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002256 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002257 break;
2258 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002259
Chris Lattner01ff65f2007-05-02 05:16:49 +00002260 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002261 unsigned OpNum = 0;
2262 Value *Vec, *Elt, *Idx;
2263 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002264 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002265 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002266 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002267 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002268 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002269 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002270 break;
2271 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002272
Chris Lattnerabfbf852007-05-06 00:21:25 +00002273 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2274 unsigned OpNum = 0;
2275 Value *Vec1, *Vec2, *Mask;
2276 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002277 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002278 return Error("Invalid SHUFFLEVEC record");
2279
Mon P Wangaeb06d22008-11-10 04:46:22 +00002280 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002281 return Error("Invalid SHUFFLEVEC record");
2282 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002283 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002284 break;
2285 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002286
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002287 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2288 // Old form of ICmp/FCmp returning bool
2289 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2290 // both legal on vectors but had different behaviour.
2291 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2292 // FCmp/ICmp returning bool or vector of bool
2293
Chris Lattner7337ab92007-05-06 00:00:00 +00002294 unsigned OpNum = 0;
2295 Value *LHS, *RHS;
2296 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002297 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002298 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002299 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002300
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002301 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002302 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002303 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002304 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002305 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002306 break;
2307 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002308
Chris Lattner231cbcb2007-05-02 04:27:25 +00002309 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002310 {
2311 unsigned Size = Record.size();
2312 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002313 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002314 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002315 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002316 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002317
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002318 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002319 Value *Op = NULL;
2320 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2321 return Error("Invalid RET record");
2322 if (OpNum != Record.size())
2323 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002324
Chris Lattner96a74c52011-06-17 18:09:11 +00002325 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002326 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002327 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002328 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002329 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002330 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002331 return Error("Invalid BR record");
2332 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2333 if (TrueDest == 0)
2334 return Error("Invalid BR record");
2335
Devang Patele8e02132009-09-18 19:26:43 +00002336 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002337 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002339 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002340 else {
2341 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002342 Value *Cond = getValue(Record, 2, NextValueNo,
2343 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002344 if (FalseDest == 0 || Cond == 0)
2345 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002346 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002347 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002348 }
2349 break;
2350 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002351 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman407a6162012-11-15 22:34:00 +00002352 // Check magic
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002353 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2354 // New SwitchInst format with case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002355
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002356 Type *OpTy = getTypeByID(Record[1]);
2357 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2358
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002359 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002360 BasicBlock *Default = getBasicBlock(Record[3]);
2361 if (OpTy == 0 || Cond == 0 || Default == 0)
2362 return Error("Invalid SWITCH record");
2363
2364 unsigned NumCases = Record[4];
Michael Ilseman407a6162012-11-15 22:34:00 +00002365
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002366 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2367 InstructionList.push_back(SI);
Michael Ilseman407a6162012-11-15 22:34:00 +00002368
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002369 unsigned CurIdx = 5;
2370 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002371 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002372 unsigned NumItems = Record[CurIdx++];
2373 for (unsigned ci = 0; ci != NumItems; ++ci) {
2374 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman407a6162012-11-15 22:34:00 +00002375
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002376 APInt Low;
2377 unsigned ActiveWords = 1;
2378 if (ValueBitWidth > 64)
2379 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002380 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2381 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002382 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002383
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002384 if (!isSingleNumber) {
2385 ActiveWords = 1;
2386 if (ValueBitWidth > 64)
2387 ActiveWords = Record[CurIdx++];
2388 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002389 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2390 ValueBitWidth);
Michael Ilseman407a6162012-11-15 22:34:00 +00002391
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002392 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2393 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002394 CurIdx += ActiveWords;
2395 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002396 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002397 }
2398 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Michael Ilseman407a6162012-11-15 22:34:00 +00002399 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002400 SI->addCase(Case, DestBB);
2401 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002402 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002403 if (Hash != (Record[0] & 0xFFFF))
2404 return Error("Invalid SWITCH record");
2405 I = SI;
2406 break;
2407 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002408
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002409 // Old SwitchInst format without case ranges.
Michael Ilseman407a6162012-11-15 22:34:00 +00002410
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002411 if (Record.size() < 3 || (Record.size() & 1) == 0)
2412 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002413 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002414 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002415 BasicBlock *Default = getBasicBlock(Record[2]);
2416 if (OpTy == 0 || Cond == 0 || Default == 0)
2417 return Error("Invalid SWITCH record");
2418 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002419 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002420 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002421 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002422 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002423 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2424 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2425 if (CaseVal == 0 || DestBB == 0) {
2426 delete SI;
2427 return Error("Invalid SWITCH record!");
2428 }
2429 SI->addCase(CaseVal, DestBB);
2430 }
2431 I = SI;
2432 break;
2433 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002434 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002435 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002436 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002437 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002438 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002439 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002440 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002441 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002442 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002443 InstructionList.push_back(IBI);
2444 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2445 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2446 IBI->addDestination(DestBB);
2447 } else {
2448 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002449 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002450 }
2451 }
2452 I = IBI;
2453 break;
2454 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002455
Duncan Sandsdc024672007-11-27 13:23:08 +00002456 case bitc::FUNC_CODE_INST_INVOKE: {
2457 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002458 if (Record.size() < 4) return Error("Invalid INVOKE record");
Bill Wendling99faa3b2012-12-07 23:16:57 +00002459 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002460 unsigned CCInfo = Record[1];
2461 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2462 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002463
Chris Lattnera9bb7132007-05-08 05:38:01 +00002464 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002465 Value *Callee;
2466 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002467 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002468
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002469 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2470 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002471 dyn_cast<FunctionType>(CalleeTy->getElementType());
2472
2473 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002474 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2475 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002476 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002477
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002478 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002479 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002480 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2481 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002482 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002483 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002484
Chris Lattner7337ab92007-05-06 00:00:00 +00002485 if (!FTy->isVarArg()) {
2486 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002487 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002488 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002489 // Read type/value pairs for varargs params.
2490 while (OpNum != Record.size()) {
2491 Value *Op;
2492 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2493 return Error("Invalid INVOKE record");
2494 Ops.push_back(Op);
2495 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002496 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002497
Jay Foada3efbb12011-07-15 08:37:34 +00002498 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002499 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002500 cast<InvokeInst>(I)->setCallingConv(
2501 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002502 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002503 break;
2504 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002505 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2506 unsigned Idx = 0;
2507 Value *Val = 0;
2508 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2509 return Error("Invalid RESUME record");
2510 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002511 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002512 break;
2513 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002514 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002515 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002516 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002517 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002518 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002519 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002520 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002521 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002522 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002523
Jay Foad3ecfc862011-03-30 11:28:46 +00002524 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002525 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002526
Chris Lattner15e6d172007-05-04 19:11:41 +00002527 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002528 Value *V;
2529 // With the new function encoding, it is possible that operands have
2530 // negative IDs (for forward references). Use a signed VBR
2531 // representation to keep the encoding small.
2532 if (UseRelativeIDs)
2533 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2534 else
2535 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002536 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002537 if (!V || !BB) return Error("Invalid PHI record");
2538 PN->addIncoming(V, BB);
2539 }
2540 I = PN;
2541 break;
2542 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002543
Bill Wendlinge6e88262011-08-12 20:24:12 +00002544 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2545 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2546 unsigned Idx = 0;
2547 if (Record.size() < 4)
2548 return Error("Invalid LANDINGPAD record");
2549 Type *Ty = getTypeByID(Record[Idx++]);
2550 if (!Ty) return Error("Invalid LANDINGPAD record");
2551 Value *PersFn = 0;
2552 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2553 return Error("Invalid LANDINGPAD record");
2554
2555 bool IsCleanup = !!Record[Idx++];
2556 unsigned NumClauses = Record[Idx++];
2557 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2558 LP->setCleanup(IsCleanup);
2559 for (unsigned J = 0; J != NumClauses; ++J) {
2560 LandingPadInst::ClauseType CT =
2561 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2562 Value *Val;
2563
2564 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2565 delete LP;
2566 return Error("Invalid LANDINGPAD record");
2567 }
2568
2569 assert((CT != LandingPadInst::Catch ||
2570 !isa<ArrayType>(Val->getType())) &&
2571 "Catch clause has a invalid type!");
2572 assert((CT != LandingPadInst::Filter ||
2573 isa<ArrayType>(Val->getType())) &&
2574 "Filter clause has invalid type!");
2575 LP->addClause(Val);
2576 }
2577
2578 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002579 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002580 break;
2581 }
2582
Chris Lattner96a74c52011-06-17 18:09:11 +00002583 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2584 if (Record.size() != 4)
2585 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002586 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002587 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002588 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002589 Value *Size = getFnValueByID(Record[2], OpTy);
2590 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002591 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002592 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002593 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002594 break;
2595 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002596 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002597 unsigned OpNum = 0;
2598 Value *Op;
2599 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2600 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002601 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002602
Chris Lattner7337ab92007-05-06 00:00:00 +00002603 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002604 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002605 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002606 }
Eli Friedman21006d42011-08-09 23:02:53 +00002607 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2608 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2609 unsigned OpNum = 0;
2610 Value *Op;
2611 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2612 OpNum+4 != Record.size())
2613 return Error("Invalid LOADATOMIC record");
Michael Ilseman407a6162012-11-15 22:34:00 +00002614
Eli Friedman21006d42011-08-09 23:02:53 +00002615
2616 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2617 if (Ordering == NotAtomic || Ordering == Release ||
2618 Ordering == AcquireRelease)
2619 return Error("Invalid LOADATOMIC record");
2620 if (Ordering != NotAtomic && Record[OpNum] == 0)
2621 return Error("Invalid LOADATOMIC record");
2622 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2623
2624 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2625 Ordering, SynchScope);
2626 InstructionList.push_back(I);
2627 break;
2628 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002629 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002630 unsigned OpNum = 0;
2631 Value *Val, *Ptr;
2632 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002633 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002634 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2635 OpNum+2 != Record.size())
2636 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002637
Christopher Lambfe63fb92007-12-11 08:59:05 +00002638 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002639 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002640 break;
2641 }
Eli Friedman21006d42011-08-09 23:02:53 +00002642 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2643 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2644 unsigned OpNum = 0;
2645 Value *Val, *Ptr;
2646 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002647 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002648 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2649 OpNum+4 != Record.size())
2650 return Error("Invalid STOREATOMIC record");
2651
2652 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002653 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002654 Ordering == AcquireRelease)
2655 return Error("Invalid STOREATOMIC record");
2656 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2657 if (Ordering != NotAtomic && Record[OpNum] == 0)
2658 return Error("Invalid STOREATOMIC record");
2659
2660 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2661 Ordering, SynchScope);
2662 InstructionList.push_back(I);
2663 break;
2664 }
Eli Friedmanff030482011-07-28 21:48:00 +00002665 case bitc::FUNC_CODE_INST_CMPXCHG: {
2666 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2667 unsigned OpNum = 0;
2668 Value *Ptr, *Cmp, *New;
2669 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002670 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002671 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002672 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002673 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2674 OpNum+3 != Record.size())
2675 return Error("Invalid CMPXCHG record");
2676 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002677 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002678 return Error("Invalid CMPXCHG record");
2679 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2680 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2681 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2682 InstructionList.push_back(I);
2683 break;
2684 }
2685 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2686 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2687 unsigned OpNum = 0;
2688 Value *Ptr, *Val;
2689 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002690 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002691 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2692 OpNum+4 != Record.size())
2693 return Error("Invalid ATOMICRMW record");
2694 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2695 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2696 Operation > AtomicRMWInst::LAST_BINOP)
2697 return Error("Invalid ATOMICRMW record");
2698 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002699 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002700 return Error("Invalid ATOMICRMW record");
2701 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2702 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2703 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2704 InstructionList.push_back(I);
2705 break;
2706 }
Eli Friedman47f35132011-07-25 23:16:38 +00002707 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2708 if (2 != Record.size())
2709 return Error("Invalid FENCE record");
2710 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2711 if (Ordering == NotAtomic || Ordering == Unordered ||
2712 Ordering == Monotonic)
2713 return Error("Invalid FENCE record");
2714 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2715 I = new FenceInst(Context, Ordering, SynchScope);
2716 InstructionList.push_back(I);
2717 break;
2718 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002719 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002720 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2721 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002722 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002723
Bill Wendling99faa3b2012-12-07 23:16:57 +00002724 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002725 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattnera9bb7132007-05-08 05:38:01 +00002727 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002728 Value *Callee;
2729 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2730 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002731
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002732 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2733 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002734 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002735 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002736 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002737
Chris Lattner0579f7f2007-05-03 22:04:19 +00002738 SmallVector<Value*, 16> Args;
2739 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002740 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002741 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002742 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002743 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002744 Args.push_back(getValue(Record, OpNum, NextValueNo,
2745 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002746 if (Args.back() == 0) return Error("Invalid CALL record");
2747 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002748
Chris Lattner0579f7f2007-05-03 22:04:19 +00002749 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002750 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002751 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002752 return Error("Invalid CALL record");
2753 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002754 while (OpNum != Record.size()) {
2755 Value *Op;
2756 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2757 return Error("Invalid CALL record");
2758 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002759 }
2760 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002761
Jay Foada3efbb12011-07-15 08:37:34 +00002762 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002763 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002764 cast<CallInst>(I)->setCallingConv(
2765 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002766 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002767 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002768 break;
2769 }
2770 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2771 if (Record.size() < 3)
2772 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002773 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002774 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002775 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002776 if (!OpTy || !Op || !ResTy)
2777 return Error("Invalid VAARG record");
2778 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002779 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002780 break;
2781 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002782 }
2783
2784 // Add instruction to end of current BB. If there is no current BB, reject
2785 // this file.
2786 if (CurBB == 0) {
2787 delete I;
2788 return Error("Invalid instruction with no BB");
2789 }
2790 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002791
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002792 // If this was a terminator instruction, move to the next block.
2793 if (isa<TerminatorInst>(I)) {
2794 ++CurBBNo;
2795 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2796 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002798 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002799 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002800 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002801 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002802
Chris Lattner5a4251c2013-01-20 02:13:19 +00002803OutOfRecordLoop:
Joe Abbeyacb61942013-02-06 22:14:06 +00002804
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002805 // Check the function list for unresolved values.
2806 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2807 if (A->getParent() == 0) {
2808 // We found at least one unresolved value. Nuke them all to avoid leaks.
2809 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002810 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002811 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002812 delete A;
2813 }
2814 }
Chris Lattner35a04702007-05-04 03:50:29 +00002815 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002816 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002818
Dan Gohman064ff3e2010-08-25 20:23:38 +00002819 // FIXME: Check for unresolved forward-declared metadata references
2820 // and clean up leaks.
2821
Chris Lattner50b136d2009-10-28 05:53:48 +00002822 // See if anything took the address of blocks in this function. If so,
2823 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002824 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2825 BlockAddrFwdRefs.find(F);
2826 if (BAFRI != BlockAddrFwdRefs.end()) {
2827 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2828 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2829 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002830 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002831 return Error("Invalid blockaddress block #");
Michael Ilseman407a6162012-11-15 22:34:00 +00002832
Chris Lattner50b136d2009-10-28 05:53:48 +00002833 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002834 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002835 FwdRef->eraseFromParent();
2836 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002837
Chris Lattner50b136d2009-10-28 05:53:48 +00002838 BlockAddrFwdRefs.erase(BAFRI);
2839 }
Michael Ilseman407a6162012-11-15 22:34:00 +00002840
Chris Lattner980e5aa2007-05-01 05:52:21 +00002841 // Trim the value list down to the size it was before we parsed this function.
2842 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002843 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002844 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002845 return false;
2846}
2847
Derek Schuff2ea93872012-02-06 22:30:29 +00002848/// FindFunctionInStream - Find the function body in the bitcode stream
2849bool BitcodeReader::FindFunctionInStream(Function *F,
2850 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2851 while (DeferredFunctionInfoIterator->second == 0) {
2852 if (Stream.AtEndOfStream())
2853 return Error("Could not find Function in stream");
2854 // ParseModule will parse the next body in the stream and set its
2855 // position in the DeferredFunctionInfo map.
2856 if (ParseModule(true)) return true;
2857 }
2858 return false;
2859}
2860
Chris Lattnerb348bb82007-05-18 04:02:46 +00002861//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002862// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002863//===----------------------------------------------------------------------===//
2864
2865
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002866bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2867 if (const Function *F = dyn_cast<Function>(GV)) {
2868 return F->isDeclaration() &&
2869 DeferredFunctionInfo.count(const_cast<Function*>(F));
2870 }
2871 return false;
2872}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002873
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002874bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2875 Function *F = dyn_cast<Function>(GV);
2876 // If it's not a function or is already material, ignore the request.
2877 if (!F || !F->isMaterializable()) return false;
2878
2879 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002880 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002881 // If its position is recorded as 0, its body is somewhere in the stream
2882 // but we haven't seen it yet.
2883 if (DFII->second == 0)
2884 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002885
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002886 // Move the bit stream to the saved position of the deferred function body.
2887 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002888
Chris Lattnerb348bb82007-05-18 04:02:46 +00002889 if (ParseFunctionBody(F)) {
2890 if (ErrInfo) *ErrInfo = ErrorString;
2891 return true;
2892 }
Chandler Carruth69940402007-08-04 01:51:18 +00002893
2894 // Upgrade any old intrinsic calls in the function.
2895 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2896 E = UpgradedIntrinsics.end(); I != E; ++I) {
2897 if (I->first != I->second) {
2898 for (Value::use_iterator UI = I->first->use_begin(),
2899 UE = I->first->use_end(); UI != UE; ) {
2900 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2901 UpgradeIntrinsicCall(CI, I->second);
2902 }
2903 }
2904 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002905
Chris Lattnerb348bb82007-05-18 04:02:46 +00002906 return false;
2907}
2908
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002909bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2910 const Function *F = dyn_cast<Function>(GV);
2911 if (!F || F->isDeclaration())
2912 return false;
2913 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2914}
2915
2916void BitcodeReader::Dematerialize(GlobalValue *GV) {
2917 Function *F = dyn_cast<Function>(GV);
2918 // If this function isn't dematerializable, this is a noop.
2919 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002920 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002921
Chris Lattnerb348bb82007-05-18 04:02:46 +00002922 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002923
Chris Lattnerb348bb82007-05-18 04:02:46 +00002924 // Just forget the function body, we can remat it later.
2925 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002926}
2927
2928
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002929bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2930 assert(M == TheModule &&
2931 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002932 // Iterate over the module, deserializing any functions that are still on
2933 // disk.
2934 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2935 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002936 if (F->isMaterializable() &&
2937 Materialize(F, ErrInfo))
2938 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002939
Derek Schuff0ffe6982012-02-29 00:07:09 +00002940 // At this point, if there are any function bodies, the current bit is
2941 // pointing to the END_BLOCK record after them. Now make sure the rest
2942 // of the bits in the module have been read.
2943 if (NextUnreadBit)
2944 ParseModule(true);
2945
Daniel Dunbara279bc32009-09-20 02:20:51 +00002946 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2947 // delete the old functions to clean up. We can't do this unless the entire
2948 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002949 // with calls to the old function.
2950 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2951 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2952 if (I->first != I->second) {
2953 for (Value::use_iterator UI = I->first->use_begin(),
2954 UE = I->first->use_end(); UI != UE; ) {
2955 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2956 UpgradeIntrinsicCall(CI, I->second);
2957 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002958 if (!I->first->use_empty())
2959 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002960 I->first->eraseFromParent();
2961 }
2962 }
2963 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002964
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002965 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002966}
2967
Derek Schuff2ea93872012-02-06 22:30:29 +00002968bool BitcodeReader::InitStream() {
2969 if (LazyStreamer) return InitLazyStream();
2970 return InitStreamFromBuffer();
2971}
2972
2973bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002974 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002975 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2976
2977 if (Buffer->getBufferSize() & 3) {
2978 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2979 return Error("Invalid bitcode signature");
2980 else
2981 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2982 }
2983
2984 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2985 // The magic number is 0x0B17C0DE stored in little endian.
2986 if (isBitcodeWrapper(BufPtr, BufEnd))
2987 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2988 return Error("Invalid bitcode wrapper header");
2989
2990 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2991 Stream.init(*StreamFile);
2992
2993 return false;
2994}
2995
2996bool BitcodeReader::InitLazyStream() {
2997 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2998 // see it.
2999 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3000 StreamFile.reset(new BitstreamReader(Bytes));
3001 Stream.init(*StreamFile);
3002
3003 unsigned char buf[16];
3004 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
3005 return Error("Bitcode stream must be at least 16 bytes in length");
3006
3007 if (!isBitcode(buf, buf + 16))
3008 return Error("Invalid bitcode signature");
3009
3010 if (isBitcodeWrapper(buf, buf + 4)) {
3011 const unsigned char *bitcodeStart = buf;
3012 const unsigned char *bitcodeEnd = buf + 16;
3013 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3014 Bytes->dropLeadingBytes(bitcodeStart - buf);
3015 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3016 }
3017 return false;
3018}
Chris Lattner48f84872007-05-01 04:59:48 +00003019
Chris Lattnerc453f762007-04-29 07:54:31 +00003020//===----------------------------------------------------------------------===//
3021// External interface
3022//===----------------------------------------------------------------------===//
3023
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003024/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00003025///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003026Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3027 LLVMContext& Context,
3028 std::string *ErrMsg) {
3029 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00003030 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003031 M->setMaterializer(R);
3032 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00003033 if (ErrMsg)
3034 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00003035
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003036 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00003037 return 0;
3038 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003039 // Have the BitcodeReader dtor delete 'Buffer'.
3040 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00003041
3042 R->materializeForwardReferencedFunctions();
3043
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003044 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00003045}
3046
Derek Schuff2ea93872012-02-06 22:30:29 +00003047
3048Module *llvm::getStreamedBitcodeModule(const std::string &name,
3049 DataStreamer *streamer,
3050 LLVMContext &Context,
3051 std::string *ErrMsg) {
3052 Module *M = new Module(name, Context);
3053 BitcodeReader *R = new BitcodeReader(streamer, Context);
3054 M->setMaterializer(R);
3055 if (R->ParseBitcodeInto(M)) {
3056 if (ErrMsg)
3057 *ErrMsg = R->getErrorString();
3058 delete M; // Also deletes R.
3059 return 0;
3060 }
3061 R->setBufferOwned(false); // no buffer to delete
3062 return M;
3063}
3064
Chris Lattnerc453f762007-04-29 07:54:31 +00003065/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3066/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00003067Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00003068 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003069 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3070 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00003071
3072 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3073 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003074 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00003075
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003076 // Read in the entire module, and destroy the BitcodeReader.
3077 if (M->MaterializeAllPermanently(ErrMsg)) {
3078 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003079 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003080 }
Bill Wendling34711742010-10-06 01:22:42 +00003081
Chad Rosiercbbb0962011-12-07 21:44:12 +00003082 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3083 // written. We must defer until the Module has been fully materialized.
3084
Chris Lattnerc453f762007-04-29 07:54:31 +00003085 return M;
3086}
Bill Wendling34711742010-10-06 01:22:42 +00003087
3088std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3089 LLVMContext& Context,
3090 std::string *ErrMsg) {
3091 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3092 // Don't let the BitcodeReader dtor delete 'Buffer'.
3093 R->setBufferOwned(false);
3094
3095 std::string Triple("");
3096 if (R->ParseTriple(Triple))
3097 if (ErrMsg)
3098 *ErrMsg = R->getErrorString();
3099
3100 delete R;
3101 return Triple;
3102}