blob: 1a3a7b0f3f5304f10f8ffe8b6596296933b7ec98 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
Devang Patel19c87462008-09-26 22:53:05 +000050 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000051 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000054 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000055
56 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000057}
58
Chris Lattner48c85b82007-05-04 03:30:17 +000059//===----------------------------------------------------------------------===//
60// Helper functions to implement forward reference resolution, etc.
61//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000062
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063/// ConvertToString - Convert a string from a record into an std::string, return
64/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000065template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000066static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000067 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000068 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000070
Chris Lattner15e6d172007-05-04 19:11:41 +000071 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
72 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 return false;
74}
75
76static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000079 case 0: return GlobalValue::ExternalLinkage;
80 case 1: return GlobalValue::WeakAnyLinkage;
81 case 2: return GlobalValue::AppendingLinkage;
82 case 3: return GlobalValue::InternalLinkage;
83 case 4: return GlobalValue::LinkOnceAnyLinkage;
84 case 5: return GlobalValue::DLLImportLinkage;
85 case 6: return GlobalValue::DLLExportLinkage;
86 case 7: return GlobalValue::ExternalWeakLinkage;
87 case 8: return GlobalValue::CommonLinkage;
88 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000089 case 10: return GlobalValue::WeakODRLinkage;
90 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000091 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000092 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000093 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000094 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000095 }
96}
97
98static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 switch (Val) {
100 default: // Map unknown visibilities to default.
101 case 0: return GlobalValue::DefaultVisibility;
102 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000103 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000104 }
105}
106
Hans Wennborgce718ff2012-06-23 11:37:03 +0000107static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
108 switch (Val) {
109 case 0: return GlobalVariable::NotThreadLocal;
110 default: // Map unknown non-zero value to general dynamic.
111 case 1: return GlobalVariable::GeneralDynamicTLSModel;
112 case 2: return GlobalVariable::LocalDynamicTLSModel;
113 case 3: return GlobalVariable::InitialExecTLSModel;
114 case 4: return GlobalVariable::LocalExecTLSModel;
115 }
116}
117
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000118static int GetDecodedCastOpcode(unsigned Val) {
119 switch (Val) {
120 default: return -1;
121 case bitc::CAST_TRUNC : return Instruction::Trunc;
122 case bitc::CAST_ZEXT : return Instruction::ZExt;
123 case bitc::CAST_SEXT : return Instruction::SExt;
124 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
125 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
126 case bitc::CAST_UITOFP : return Instruction::UIToFP;
127 case bitc::CAST_SITOFP : return Instruction::SIToFP;
128 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
129 case bitc::CAST_FPEXT : return Instruction::FPExt;
130 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
131 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
132 case bitc::CAST_BITCAST : return Instruction::BitCast;
133 }
134}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000136 switch (Val) {
137 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000140 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000141 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000142 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000143 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000144 case bitc::BINOP_UDIV: return Instruction::UDiv;
145 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000146 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000147 case bitc::BINOP_UREM: return Instruction::URem;
148 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000149 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000150 case bitc::BINOP_SHL: return Instruction::Shl;
151 case bitc::BINOP_LSHR: return Instruction::LShr;
152 case bitc::BINOP_ASHR: return Instruction::AShr;
153 case bitc::BINOP_AND: return Instruction::And;
154 case bitc::BINOP_OR: return Instruction::Or;
155 case bitc::BINOP_XOR: return Instruction::Xor;
156 }
157}
158
Eli Friedmanff030482011-07-28 21:48:00 +0000159static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160 switch (Val) {
161 default: return AtomicRMWInst::BAD_BINOP;
162 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
163 case bitc::RMW_ADD: return AtomicRMWInst::Add;
164 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
165 case bitc::RMW_AND: return AtomicRMWInst::And;
166 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
167 case bitc::RMW_OR: return AtomicRMWInst::Or;
168 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
169 case bitc::RMW_MAX: return AtomicRMWInst::Max;
170 case bitc::RMW_MIN: return AtomicRMWInst::Min;
171 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
172 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
173 }
174}
175
Eli Friedman47f35132011-07-25 23:16:38 +0000176static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177 switch (Val) {
178 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
179 case bitc::ORDERING_UNORDERED: return Unordered;
180 case bitc::ORDERING_MONOTONIC: return Monotonic;
181 case bitc::ORDERING_ACQUIRE: return Acquire;
182 case bitc::ORDERING_RELEASE: return Release;
183 case bitc::ORDERING_ACQREL: return AcquireRelease;
184 default: // Map unknown orderings to sequentially-consistent.
185 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
186 }
187}
188
189static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190 switch (Val) {
191 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
192 default: // Map unknown scopes to cross-thread.
193 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
194 }
195}
196
Gabor Greifefe65362008-05-10 08:32:32 +0000197namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000198namespace {
199 /// @brief A class for maintaining the slot number definition
200 /// as a placeholder for the actual definition for forward constants defs.
201 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000202 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000203 public:
204 // allocate space for exactly one operand
205 void *operator new(size_t s) {
206 return User::operator new(s, 1);
207 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000208 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000209 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000210 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000211 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000212
Chris Lattnerea693df2008-08-21 02:34:16 +0000213 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000214 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000215 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000217 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
218 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000219
220
Gabor Greifefe65362008-05-10 08:32:32 +0000221 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000222 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000223 };
224}
225
Chris Lattner46e77402009-03-31 22:55:09 +0000226// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000227template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000228struct OperandTraits<ConstantPlaceHolder> :
229 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000230};
Gabor Greifefe65362008-05-10 08:32:32 +0000231}
232
Chris Lattner46e77402009-03-31 22:55:09 +0000233
234void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
235 if (Idx == size()) {
236 push_back(V);
237 return;
238 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000239
Chris Lattner46e77402009-03-31 22:55:09 +0000240 if (Idx >= size())
241 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000242
Chris Lattner46e77402009-03-31 22:55:09 +0000243 WeakVH &OldV = ValuePtrs[Idx];
244 if (OldV == 0) {
245 OldV = V;
246 return;
247 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000248
Chris Lattner46e77402009-03-31 22:55:09 +0000249 // Handle constants and non-constants (e.g. instrs) differently for
250 // efficiency.
251 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
252 ResolveConstants.push_back(std::make_pair(PHC, Idx));
253 OldV = V;
254 } else {
255 // If there was a forward reference to this value, replace it.
256 Value *PrevVal = OldV;
257 OldV->replaceAllUsesWith(V);
258 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000259 }
260}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000261
Gabor Greifefe65362008-05-10 08:32:32 +0000262
Chris Lattner522b7b12007-04-24 05:48:56 +0000263Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000264 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000265 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000266 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
Chris Lattner46e77402009-03-31 22:55:09 +0000268 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000269 assert(Ty == V->getType() && "Type mismatch in constant table!");
270 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000271 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000272
273 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000274 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000275 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000276 return C;
277}
278
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000279Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000280 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000281 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner46e77402009-03-31 22:55:09 +0000283 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000284 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
285 return V;
286 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287
Chris Lattner01ff65f2007-05-02 05:16:49 +0000288 // No type specified, must be invalid reference.
289 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000291 // Create and return a placeholder, which will later be RAUW'd.
292 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000293 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000294 return V;
295}
296
Chris Lattnerea693df2008-08-21 02:34:16 +0000297/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
298/// resolves any forward references. The idea behind this is that we sometimes
299/// get constants (such as large arrays) which reference *many* forward ref
300/// constants. Replacing each of these causes a lot of thrashing when
301/// building/reuniquing the constant. Instead of doing this, we look at all the
302/// uses and rewrite all the place holders at once for any constant that uses
303/// a placeholder.
304void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 // binary search.
307 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000312 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 Constant *Placeholder = ResolveConstants.back().first;
314 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnerea693df2008-08-21 02:34:16 +0000316 // Loop over all users of the placeholder, updating them to reference the
317 // new value. If they reference more than one placeholder, update them all
318 // at once.
319 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000320 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000321 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerea693df2008-08-21 02:34:16 +0000323 // If the using object isn't uniqued, just update the operands. This
324 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000325 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000326 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000327 continue;
328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Chris Lattnerea693df2008-08-21 02:34:16 +0000330 // Otherwise, we have a constant that uses the placeholder. Replace that
331 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000332 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
334 I != E; ++I) {
335 Value *NewOp;
336 if (!isa<ConstantPlaceHolder>(*I)) {
337 // Not a placeholder reference.
338 NewOp = *I;
339 } else if (*I == Placeholder) {
340 // Common case is that it just references this one placeholder.
341 NewOp = RealVal;
342 } else {
343 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344 ResolveConstantsTy::iterator It =
345 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000346 std::pair<Constant*, unsigned>(cast<Constant>(*I),
347 0));
348 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000349 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 }
351
352 NewOps.push_back(cast<Constant>(NewOp));
353 }
354
355 // Make the new constant.
356 Constant *NewC;
357 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000358 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000359 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000360 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000362 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000363 } else {
364 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000365 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerea693df2008-08-21 02:34:16 +0000368 UserC->replaceAllUsesWith(NewC);
369 UserC->destroyConstant();
370 NewOps.clear();
371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000372
Nick Lewyckycb337992009-05-10 20:57:05 +0000373 // Update all ValueHandles, they should be the only users at this point.
374 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000375 delete Placeholder;
376 }
377}
378
Devang Pateld5ac4042009-08-04 06:00:18 +0000379void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
380 if (Idx == size()) {
381 push_back(V);
382 return;
383 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Devang Pateld5ac4042009-08-04 06:00:18 +0000385 if (Idx >= size())
386 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000387
Devang Pateld5ac4042009-08-04 06:00:18 +0000388 WeakVH &OldV = MDValuePtrs[Idx];
389 if (OldV == 0) {
390 OldV = V;
391 return;
392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000395 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000397 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000398 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
399 // value for Idx.
400 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000401}
402
403Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
404 if (Idx >= size())
405 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000408 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 return V;
410 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Devang Pateld5ac4042009-08-04 06:00:18 +0000412 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000413 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000414 MDValuePtrs[Idx] = V;
415 return V;
416}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418Type *BitcodeReader::getTypeByID(unsigned ID) {
419 // The type table size is always specified correctly.
420 if (ID >= TypeList.size())
421 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000422
Chris Lattner1afcace2011-07-09 17:41:24 +0000423 if (Type *Ty = TypeList[ID])
424 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426 // If we have a forward reference, the only possible case is when it is to a
427 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000428 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429}
430
Chris Lattner1afcace2011-07-09 17:41:24 +0000431
Chris Lattner48c85b82007-05-04 03:30:17 +0000432//===----------------------------------------------------------------------===//
433// Functions for parsing blocks from the bitcode file
434//===----------------------------------------------------------------------===//
435
Devang Patel05988662008-09-25 21:00:45 +0000436bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000437 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000439
Devang Patel19c87462008-09-26 22:53:05 +0000440 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000441 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Chris Lattner48c85b82007-05-04 03:30:17 +0000443 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Devang Patel05988662008-09-25 21:00:45 +0000445 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000446
Chris Lattner48c85b82007-05-04 03:30:17 +0000447 // Read all the records.
448 while (1) {
449 unsigned Code = Stream.ReadCode();
450 if (Code == bitc::END_BLOCK) {
451 if (Stream.ReadBlockEnd())
452 return Error("Error at end of PARAMATTR block");
453 return false;
454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000455
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 if (Code == bitc::ENTER_SUBBLOCK) {
457 // No known subblocks, always skip them.
458 Stream.ReadSubBlockID();
459 if (Stream.SkipBlock())
460 return Error("Malformed block record");
461 continue;
462 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000463
Chris Lattner48c85b82007-05-04 03:30:17 +0000464 if (Code == bitc::DEFINE_ABBREV) {
465 Stream.ReadAbbrevRecord();
466 continue;
467 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000468
Chris Lattner48c85b82007-05-04 03:30:17 +0000469 // Read a record.
470 Record.clear();
471 switch (Stream.ReadRecord(Code, Record)) {
472 default: // Default behavior: ignore.
473 break;
474 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
475 if (Record.size() & 1)
476 return Error("Invalid ENTRY record");
477
Chris Lattner48c85b82007-05-04 03:30:17 +0000478 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Meador Ingee99f8be2012-05-28 15:45:43 +0000479 Attributes ReconstitutedAttr =
Bill Wendling2039a8f2012-09-25 20:57:48 +0000480 Attributes::decodeLLVMAttributesForBitcode(Record[i+1]);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000481 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000482 }
Chris Lattner461edd92008-03-12 02:25:52 +0000483
Devang Patel19c87462008-09-26 22:53:05 +0000484 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling47a33952012-10-04 07:19:46 +0000485 if (Attributes(Record[i+1]).hasAttributes())
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 Attrs.push_back(AttributeWithIndex::get(Record[i],
487 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000488 }
Devang Patel19c87462008-09-26 22:53:05 +0000489
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000490 MAttributes.push_back(AttrListPtr::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000491 Attrs.clear();
492 break;
493 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000494 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000495 }
496}
497
Chris Lattner86697142007-05-01 05:01:34 +0000498bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000500 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000501
Chris Lattner1afcace2011-07-09 17:41:24 +0000502 return ParseTypeTableBody();
503}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504
Chris Lattner1afcace2011-07-09 17:41:24 +0000505bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000506 if (!TypeList.empty())
507 return Error("Multiple TYPE_BLOCKs found!");
508
509 SmallVector<uint64_t, 64> Record;
510 unsigned NumRecords = 0;
511
Chris Lattner1afcace2011-07-09 17:41:24 +0000512 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000513
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000514 // Read all the records for this type table.
515 while (1) {
516 unsigned Code = Stream.ReadCode();
517 if (Code == bitc::END_BLOCK) {
518 if (NumRecords != TypeList.size())
519 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000520 if (Stream.ReadBlockEnd())
521 return Error("Error at end of type table block");
522 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 if (Code == bitc::ENTER_SUBBLOCK) {
526 // No known subblocks, always skip them.
527 Stream.ReadSubBlockID();
528 if (Stream.SkipBlock())
529 return Error("Malformed block record");
530 continue;
531 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000533 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000534 Stream.ReadAbbrevRecord();
535 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 // Read a record.
539 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000540 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000541 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000542 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
544 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
545 // type list. This allows us to reserve space.
546 if (Record.size() < 1)
547 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000548 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000551 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000552 break;
Dan Gohmance163392011-12-17 00:04:22 +0000553 case bitc::TYPE_CODE_HALF: // HALF
554 ResultTy = Type::getHalfTy(Context);
555 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
559 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000562 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000564 break;
565 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000567 break;
568 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000570 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000574 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000576 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000577 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
578 ResultTy = Type::getX86_MMXTy(Context);
579 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
581 if (Record.size() < 1)
582 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000583
Owen Anderson1d0be152009-08-13 21:58:54 +0000584 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000587 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000588 if (Record.size() < 1)
589 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000590 unsigned AddressSpace = 0;
591 if (Record.size() == 2)
592 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000593 ResultTy = getTypeByID(Record[0]);
594 if (ResultTy == 0) return Error("invalid element type in pointer type");
595 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000597 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000598 case bitc::TYPE_CODE_FUNCTION_OLD: {
599 // FIXME: attrid is dead, remove it in LLVM 4.0
600 // FUNCTION: [vararg, attrid, retty, paramty x N]
601 if (Record.size() < 3)
602 return Error("Invalid FUNCTION type record");
603 SmallVector<Type*, 8> ArgTys;
604 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
605 if (Type *T = getTypeByID(Record[i]))
606 ArgTys.push_back(T);
607 else
608 break;
609 }
610
611 ResultTy = getTypeByID(Record[2]);
612 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
613 return Error("invalid type in function type");
614
615 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
616 break;
617 }
Chad Rosiercde54642011-11-03 00:14:01 +0000618 case bitc::TYPE_CODE_FUNCTION: {
619 // FUNCTION: [vararg, retty, paramty x N]
620 if (Record.size() < 2)
621 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000622 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000623 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
624 if (Type *T = getTypeByID(Record[i]))
625 ArgTys.push_back(T);
626 else
627 break;
628 }
629
630 ResultTy = getTypeByID(Record[1]);
631 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
632 return Error("invalid type in function type");
633
634 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
635 break;
636 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000638 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000639 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000640 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000641 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
642 if (Type *T = getTypeByID(Record[i]))
643 EltTys.push_back(T);
644 else
645 break;
646 }
647 if (EltTys.size() != Record.size()-1)
648 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000649 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000650 break;
651 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000652 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
653 if (ConvertToString(Record, 0, TypeName))
654 return Error("Invalid STRUCT_NAME record");
655 continue;
656
657 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
658 if (Record.size() < 1)
659 return Error("Invalid STRUCT type record");
660
661 if (NumRecords >= TypeList.size())
662 return Error("invalid TYPE table");
663
664 // Check to see if this was forward referenced, if so fill in the temp.
665 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
666 if (Res) {
667 Res->setName(TypeName);
668 TypeList[NumRecords] = 0;
669 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000670 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000671 TypeName.clear();
672
673 SmallVector<Type*, 8> EltTys;
674 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
675 if (Type *T = getTypeByID(Record[i]))
676 EltTys.push_back(T);
677 else
678 break;
679 }
680 if (EltTys.size() != Record.size()-1)
681 return Error("invalid STRUCT type record");
682 Res->setBody(EltTys, Record[0]);
683 ResultTy = Res;
684 break;
685 }
686 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
687 if (Record.size() != 1)
688 return Error("Invalid OPAQUE type record");
689
690 if (NumRecords >= TypeList.size())
691 return Error("invalid TYPE table");
692
693 // Check to see if this was forward referenced, if so fill in the temp.
694 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
695 if (Res) {
696 Res->setName(TypeName);
697 TypeList[NumRecords] = 0;
698 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000699 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 TypeName.clear();
701 ResultTy = Res;
702 break;
703 }
704 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
705 if (Record.size() < 2)
706 return Error("Invalid ARRAY type record");
707 if ((ResultTy = getTypeByID(Record[1])))
708 ResultTy = ArrayType::get(ResultTy, Record[0]);
709 else
710 return Error("Invalid ARRAY type element");
711 break;
712 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
713 if (Record.size() < 2)
714 return Error("Invalid VECTOR type record");
715 if ((ResultTy = getTypeByID(Record[1])))
716 ResultTy = VectorType::get(ResultTy, Record[0]);
717 else
718 return Error("Invalid ARRAY type element");
719 break;
720 }
721
722 if (NumRecords >= TypeList.size())
723 return Error("invalid TYPE table");
724 assert(ResultTy && "Didn't read a type?");
725 assert(TypeList[NumRecords] == 0 && "Already read type?");
726 TypeList[NumRecords++] = ResultTy;
727 }
728}
729
Chris Lattner86697142007-05-01 05:01:34 +0000730bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000731 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 return Error("Malformed block record");
733
734 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattner0b2482a2007-04-23 21:26:05 +0000736 // Read all the records for this value table.
737 SmallString<128> ValueName;
738 while (1) {
739 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 if (Code == bitc::END_BLOCK) {
741 if (Stream.ReadBlockEnd())
742 return Error("Error at end of value symbol table block");
743 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000745 if (Code == bitc::ENTER_SUBBLOCK) {
746 // No known subblocks, always skip them.
747 Stream.ReadSubBlockID();
748 if (Stream.SkipBlock())
749 return Error("Malformed block record");
750 continue;
751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000752
Chris Lattner0b2482a2007-04-23 21:26:05 +0000753 if (Code == bitc::DEFINE_ABBREV) {
754 Stream.ReadAbbrevRecord();
755 continue;
756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattner0b2482a2007-04-23 21:26:05 +0000758 // Read a record.
759 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000760 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 default: // Default behavior: unknown type.
762 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000763 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000765 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000766 unsigned ValueID = Record[0];
767 if (ValueID >= ValueList.size())
768 return Error("Invalid Value ID in VST_ENTRY record");
769 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000771 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000772 ValueName.clear();
773 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000774 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000775 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000776 if (ConvertToString(Record, 1, ValueName))
777 return Error("Invalid VST_BBENTRY record");
778 BasicBlock *BB = getBasicBlock(Record[0]);
779 if (BB == 0)
780 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000782 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000783 ValueName.clear();
784 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000785 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000786 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000787 }
788}
789
Devang Patele54abc92009-07-22 17:43:22 +0000790bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000791 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000792
793 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
794 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Devang Patele54abc92009-07-22 17:43:22 +0000796 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Devang Patele54abc92009-07-22 17:43:22 +0000798 // Read all the records.
799 while (1) {
800 unsigned Code = Stream.ReadCode();
801 if (Code == bitc::END_BLOCK) {
802 if (Stream.ReadBlockEnd())
803 return Error("Error at end of PARAMATTR block");
804 return false;
805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Devang Patele54abc92009-07-22 17:43:22 +0000807 if (Code == bitc::ENTER_SUBBLOCK) {
808 // No known subblocks, always skip them.
809 Stream.ReadSubBlockID();
810 if (Stream.SkipBlock())
811 return Error("Malformed block record");
812 continue;
813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Devang Patele54abc92009-07-22 17:43:22 +0000815 if (Code == bitc::DEFINE_ABBREV) {
816 Stream.ReadAbbrevRecord();
817 continue;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Victor Hernandez24e64df2010-01-10 07:14:18 +0000820 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000821 // Read a record.
822 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000823 Code = Stream.ReadRecord(Code, Record);
824 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000825 default: // Default behavior: ignore.
826 break;
Devang Patelaa993142009-07-29 22:34:41 +0000827 case bitc::METADATA_NAME: {
828 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000829 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000830 Record.clear();
831 Code = Stream.ReadCode();
832
Chris Lattner9d61dd92011-06-17 17:50:30 +0000833 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000834 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000835 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000836
837 // Read named metadata elements.
838 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000839 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000840 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000841 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
842 if (MD == 0)
843 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000844 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000845 }
Devang Patelaa993142009-07-29 22:34:41 +0000846 break;
847 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000848 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000849 IsFunctionLocal = true;
850 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000851 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000852 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000853 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Devang Patel104cf9e2009-07-23 01:07:34 +0000855 unsigned Size = Record.size();
856 SmallVector<Value*, 8> Elts;
857 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000858 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000859 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000860 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000861 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000862 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000863 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
864 else
865 Elts.push_back(NULL);
866 }
Jay Foadec9186b2011-04-21 19:59:31 +0000867 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000868 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000869 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000870 break;
871 }
Devang Patele54abc92009-07-22 17:43:22 +0000872 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000873 SmallString<8> String(Record.begin(), Record.end());
874 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000875 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000876 break;
877 }
Devang Patele8e02132009-09-18 19:26:43 +0000878 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000879 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000881
Devang Patela2148402009-09-28 21:14:55 +0000882 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000883 SmallString<8> Name(Record.begin()+1, Record.end());
884
Chris Lattner08113472009-12-29 09:01:33 +0000885 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000886 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
887 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000888 break;
889 }
Devang Patele54abc92009-07-22 17:43:22 +0000890 }
891 }
892}
893
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000894/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner0eef0802007-04-24 04:04:35 +0000895/// the LSB for dense VBR encoding.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000896uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner0eef0802007-04-24 04:04:35 +0000897 if ((V & 1) == 0)
898 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000899 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000900 return -(V >> 1);
901 // There is no such thing as -0 with integers. "-0" really means MININT.
902 return 1ULL << 63;
903}
904
Chris Lattner07d98b42007-04-26 02:46:40 +0000905/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
906/// values and aliases that we can.
907bool BitcodeReader::ResolveGlobalAndAliasInits() {
908 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
909 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000910
Chris Lattner07d98b42007-04-26 02:46:40 +0000911 GlobalInitWorklist.swap(GlobalInits);
912 AliasInitWorklist.swap(AliasInits);
913
914 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000915 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000916 if (ValID >= ValueList.size()) {
917 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000918 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000919 } else {
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
921 GlobalInitWorklist.back().first->setInitializer(C);
922 else
923 return Error("Global variable initializer is not a constant!");
924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 }
927
928 while (!AliasInitWorklist.empty()) {
929 unsigned ValID = AliasInitWorklist.back().second;
930 if (ValID >= ValueList.size()) {
931 AliasInits.push_back(AliasInitWorklist.back());
932 } else {
933 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000934 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000935 else
936 return Error("Alias initializer is not a constant!");
937 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000939 }
940 return false;
941}
942
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000943static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
944 SmallVector<uint64_t, 8> Words(Vals.size());
945 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +0000946 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000947
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000948 return APInt(TypeBits, Words);
949}
950
Chris Lattner86697142007-05-01 05:01:34 +0000951bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000952 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 return Error("Malformed block record");
954
955 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000956
Chris Lattnere16504e2007-04-24 03:30:34 +0000957 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000958 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000959 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000960 while (1) {
961 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000962 if (Code == bitc::END_BLOCK)
963 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 if (Code == bitc::ENTER_SUBBLOCK) {
966 // No known subblocks, always skip them.
967 Stream.ReadSubBlockID();
968 if (Stream.SkipBlock())
969 return Error("Malformed block record");
970 continue;
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 if (Code == bitc::DEFINE_ABBREV) {
974 Stream.ReadAbbrevRecord();
975 continue;
976 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977
Chris Lattnere16504e2007-04-24 03:30:34 +0000978 // Read a record.
979 Record.clear();
980 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000981 unsigned BitCode = Stream.ReadRecord(Code, Record);
982 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 default: // Default behavior: unknown constant
984 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000985 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000986 break;
987 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
988 if (Record.empty())
989 return Error("Malformed CST_SETTYPE record");
990 if (Record[0] >= TypeList.size())
991 return Error("Invalid Type ID in CST_SETTYPE record");
992 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000993 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000995 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000996 break;
997 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000998 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000999 return Error("Invalid CST_INTEGER record");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001000 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001001 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001002 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001003 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001004 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001005
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001006 APInt VInt = ReadWideAPInt(Record,
1007 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001008 V = ConstantInt::get(Context, VInt);
1009
Chris Lattner0eef0802007-04-24 04:04:35 +00001010 break;
1011 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001012 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001013 if (Record.empty())
1014 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001015 if (CurTy->isHalfTy())
1016 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1017 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001018 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001019 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001020 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001021 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001022 // Bits are not stored the same way as a normal i80 APInt, compensate.
1023 uint64_t Rearrange[2];
1024 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1025 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001026 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001027 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001028 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001029 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001030 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001031 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001032 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001033 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001034 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattner15e6d172007-05-04 19:11:41 +00001036 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1037 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001038 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001039
Chris Lattner15e6d172007-05-04 19:11:41 +00001040 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001041 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001042
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001043 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001044 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001045 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001046 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001047 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1049 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001050 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001051 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001052 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1054 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001055 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001056 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001057 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001058 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001059 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001060 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001061 break;
1062 }
Chris Lattner2237f842012-02-05 02:41:35 +00001063 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001064 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1065 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001066 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001067
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001068 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001069 V = ConstantDataArray::getString(Context, Elts,
1070 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001071 break;
1072 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001073 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1074 if (Record.empty())
1075 return Error("Invalid CST_DATA record");
1076
1077 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1078 unsigned Size = Record.size();
1079
1080 if (EltTy->isIntegerTy(8)) {
1081 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1082 if (isa<VectorType>(CurTy))
1083 V = ConstantDataVector::get(Context, Elts);
1084 else
1085 V = ConstantDataArray::get(Context, Elts);
1086 } else if (EltTy->isIntegerTy(16)) {
1087 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1088 if (isa<VectorType>(CurTy))
1089 V = ConstantDataVector::get(Context, Elts);
1090 else
1091 V = ConstantDataArray::get(Context, Elts);
1092 } else if (EltTy->isIntegerTy(32)) {
1093 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1094 if (isa<VectorType>(CurTy))
1095 V = ConstantDataVector::get(Context, Elts);
1096 else
1097 V = ConstantDataArray::get(Context, Elts);
1098 } else if (EltTy->isIntegerTy(64)) {
1099 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1100 if (isa<VectorType>(CurTy))
1101 V = ConstantDataVector::get(Context, Elts);
1102 else
1103 V = ConstantDataArray::get(Context, Elts);
1104 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001105 SmallVector<float, 16> Elts(Size);
1106 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001107 if (isa<VectorType>(CurTy))
1108 V = ConstantDataVector::get(Context, Elts);
1109 else
1110 V = ConstantDataArray::get(Context, Elts);
1111 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001112 SmallVector<double, 16> Elts(Size);
1113 std::transform(Record.begin(), Record.end(), Elts.begin(),
1114 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001115 if (isa<VectorType>(CurTy))
1116 V = ConstantDataVector::get(Context, Elts);
1117 else
1118 V = ConstantDataArray::get(Context, Elts);
1119 } else {
1120 return Error("Unknown element type in CE_DATA");
1121 }
1122 break;
1123 }
1124
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001125 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1126 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1127 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001128 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001129 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001130 } else {
1131 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1132 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001133 unsigned Flags = 0;
1134 if (Record.size() >= 4) {
1135 if (Opc == Instruction::Add ||
1136 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001137 Opc == Instruction::Mul ||
1138 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001139 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1140 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1141 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1142 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001143 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001144 Opc == Instruction::UDiv ||
1145 Opc == Instruction::LShr ||
1146 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001147 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001148 Flags |= SDivOperator::IsExact;
1149 }
1150 }
1151 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001152 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001154 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001155 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1156 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1157 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001159 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001160 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001161 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001162 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001163 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001164 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001165 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001166 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001167 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001168 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001170 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001171 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001172 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001173 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001174 if (!ElTy) return Error("Invalid CE_GEP record");
1175 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1176 }
Jay Foaddab3d292011-07-21 14:31:17 +00001177 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001178 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1179 BitCode ==
1180 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001181 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001182 }
1183 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1184 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001185 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001186 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001187 ValueList.getConstantFwdRef(Record[1],CurTy),
1188 ValueList.getConstantFwdRef(Record[2],CurTy));
1189 break;
1190 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1191 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001192 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001193 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1194 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1195 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001196 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001197 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001198 break;
1199 }
1200 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001201 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001202 if (Record.size() < 3 || OpTy == 0)
1203 return Error("Invalid CE_INSERTELT record");
1204 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1205 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1206 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001207 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001208 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001209 break;
1210 }
1211 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001212 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001213 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001214 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001215 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1216 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001217 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001218 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001219 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001220 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001221 break;
1222 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001223 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001224 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1225 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001226 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001227 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1228 return Error("Invalid CE_SHUFVEC_EX record");
1229 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1230 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001231 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001232 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001233 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001234 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001235 break;
1236 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001237 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1238 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001239 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001240 if (OpTy == 0) return Error("Invalid CE_CMP record");
1241 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1242 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1243
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001244 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001245 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001246 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001247 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001248 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001249 }
Chad Rosier581600b2012-09-05 19:00:49 +00001250 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001251 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001252 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001253 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1254 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001255 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001256 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001257 unsigned AsmStrSize = Record[1];
1258 if (2+AsmStrSize >= Record.size())
1259 return Error("Invalid INLINEASM record");
1260 unsigned ConstStrSize = Record[2+AsmStrSize];
1261 if (3+AsmStrSize+ConstStrSize > Record.size())
1262 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001263
Chris Lattner2bce93a2007-05-06 01:58:20 +00001264 for (unsigned i = 0; i != AsmStrSize; ++i)
1265 AsmStr += (char)Record[2+i];
1266 for (unsigned i = 0; i != ConstStrSize; ++i)
1267 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001269 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001270 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001271 break;
1272 }
Chad Rosier581600b2012-09-05 19:00:49 +00001273 // This version adds support for the asm dialect keywords (e.g.,
1274 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001275 case bitc::CST_CODE_INLINEASM: {
1276 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1277 std::string AsmStr, ConstrStr;
1278 bool HasSideEffects = Record[0] & 1;
1279 bool IsAlignStack = (Record[0] >> 1) & 1;
1280 unsigned AsmDialect = Record[0] >> 2;
1281 unsigned AsmStrSize = Record[1];
1282 if (2+AsmStrSize >= Record.size())
1283 return Error("Invalid INLINEASM record");
1284 unsigned ConstStrSize = Record[2+AsmStrSize];
1285 if (3+AsmStrSize+ConstStrSize > Record.size())
1286 return Error("Invalid INLINEASM record");
1287
1288 for (unsigned i = 0; i != AsmStrSize; ++i)
1289 AsmStr += (char)Record[2+i];
1290 for (unsigned i = 0; i != ConstStrSize; ++i)
1291 ConstrStr += (char)Record[3+AsmStrSize+i];
1292 PointerType *PTy = cast<PointerType>(CurTy);
1293 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1294 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001295 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001296 break;
1297 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001298 case bitc::CST_CODE_BLOCKADDRESS:{
1299 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001300 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001301 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1302 Function *Fn =
1303 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1304 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001305
1306 // If the function is already parsed we can insert the block address right
1307 // away.
1308 if (!Fn->empty()) {
1309 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1310 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1311 if (BBI == BBE)
1312 return Error("Invalid blockaddress block #");
1313 ++BBI;
1314 }
1315 V = BlockAddress::get(Fn, BBI);
1316 } else {
1317 // Otherwise insert a placeholder and remember it so it can be inserted
1318 // when the function is parsed.
1319 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1320 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001321 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001322 0, "");
1323 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1324 V = FwdRef;
1325 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001326 break;
1327 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001330 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001331 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001332 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattnerea693df2008-08-21 02:34:16 +00001334 if (NextCstNo != ValueList.size())
1335 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001336
Chris Lattnerea693df2008-08-21 02:34:16 +00001337 if (Stream.ReadBlockEnd())
1338 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001339
Chris Lattnerea693df2008-08-21 02:34:16 +00001340 // Once all the constants have been read, go through and resolve forward
1341 // references.
1342 ValueList.ResolveConstantForwardRefs();
1343 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001344}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001345
Chad Rosiercbbb0962011-12-07 21:44:12 +00001346bool BitcodeReader::ParseUseLists() {
1347 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1348 return Error("Malformed block record");
1349
1350 SmallVector<uint64_t, 64> Record;
1351
1352 // Read all the records.
1353 while (1) {
1354 unsigned Code = Stream.ReadCode();
1355 if (Code == bitc::END_BLOCK) {
1356 if (Stream.ReadBlockEnd())
1357 return Error("Error at end of use-list table block");
1358 return false;
1359 }
1360
1361 if (Code == bitc::ENTER_SUBBLOCK) {
1362 // No known subblocks, always skip them.
1363 Stream.ReadSubBlockID();
1364 if (Stream.SkipBlock())
1365 return Error("Malformed block record");
1366 continue;
1367 }
1368
1369 if (Code == bitc::DEFINE_ABBREV) {
1370 Stream.ReadAbbrevRecord();
1371 continue;
1372 }
1373
1374 // Read a use list record.
1375 Record.clear();
1376 switch (Stream.ReadRecord(Code, Record)) {
1377 default: // Default behavior: unknown type.
1378 break;
1379 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1380 unsigned RecordLength = Record.size();
1381 if (RecordLength < 1)
1382 return Error ("Invalid UseList reader!");
1383 UseListRecords.push_back(Record);
1384 break;
1385 }
1386 }
1387 }
1388}
1389
Chris Lattner980e5aa2007-05-01 05:52:21 +00001390/// RememberAndSkipFunctionBody - When we see the block for a function body,
1391/// remember where it is and then skip it. This lets us lazily deserialize the
1392/// functions.
1393bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001394 // Get the function we are talking about.
1395 if (FunctionsWithBodies.empty())
1396 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397
Chris Lattner48f84872007-05-01 04:59:48 +00001398 Function *Fn = FunctionsWithBodies.back();
1399 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400
Chris Lattner48f84872007-05-01 04:59:48 +00001401 // Save the current stream state.
1402 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001403 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattner48f84872007-05-01 04:59:48 +00001405 // Skip over the function block for now.
1406 if (Stream.SkipBlock())
1407 return Error("Malformed block record");
1408 return false;
1409}
1410
Derek Schuff2ea93872012-02-06 22:30:29 +00001411bool BitcodeReader::GlobalCleanup() {
1412 // Patch the initializers for globals and aliases up.
1413 ResolveGlobalAndAliasInits();
1414 if (!GlobalInits.empty() || !AliasInits.empty())
1415 return Error("Malformed global initializer set");
1416
1417 // Look for intrinsic functions which need to be upgraded at some point
1418 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1419 FI != FE; ++FI) {
1420 Function *NewFn;
1421 if (UpgradeIntrinsicFunction(FI, NewFn))
1422 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1423 }
1424
1425 // Look for global variables which need to be renamed.
1426 for (Module::global_iterator
1427 GI = TheModule->global_begin(), GE = TheModule->global_end();
1428 GI != GE; ++GI)
1429 UpgradeGlobalVariable(GI);
1430 // Force deallocation of memory for these vectors to favor the client that
1431 // want lazy deserialization.
1432 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1433 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1434 return false;
1435}
1436
1437bool BitcodeReader::ParseModule(bool Resume) {
1438 if (Resume)
1439 Stream.JumpToBit(NextUnreadBit);
1440 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001441 return Error("Malformed block record");
1442
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001443 SmallVector<uint64_t, 64> Record;
1444 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001445 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001446
1447 // Read all the records for this module.
1448 while (!Stream.AtEndOfStream()) {
1449 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001450 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001451 if (Stream.ReadBlockEnd())
1452 return Error("Error at end of module block");
1453
Derek Schuff2ea93872012-02-06 22:30:29 +00001454 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001455 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001457 if (Code == bitc::ENTER_SUBBLOCK) {
1458 switch (Stream.ReadSubBlockID()) {
1459 default: // Skip unknown content.
1460 if (Stream.SkipBlock())
1461 return Error("Malformed block record");
1462 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001463 case bitc::BLOCKINFO_BLOCK_ID:
1464 if (Stream.ReadBlockInfoBlock())
1465 return Error("Malformed BlockInfoBlock");
1466 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001467 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001468 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001469 return true;
1470 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001471 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001472 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001473 return true;
1474 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001475 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001476 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001477 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001478 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001479 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001480 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001481 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001482 return true;
1483 break;
Devang Patele54abc92009-07-22 17:43:22 +00001484 case bitc::METADATA_BLOCK_ID:
1485 if (ParseMetadata())
1486 return true;
1487 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001488 case bitc::FUNCTION_BLOCK_ID:
1489 // If this is the first function body we've seen, reverse the
1490 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001491 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001492 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001493 if (GlobalCleanup())
1494 return true;
1495 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001496 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001497
Chris Lattner980e5aa2007-05-01 05:52:21 +00001498 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001499 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001500 // For streaming bitcode, suspend parsing when we reach the function
1501 // bodies. Subsequent materialization calls will resume it when
1502 // necessary. For streaming, the function bodies must be at the end of
1503 // the bitcode. If the bitcode file is old, the symbol table will be
1504 // at the end instead and will not have been seen yet. In this case,
1505 // just finish the parse now.
1506 if (LazyStreamer && SeenValueSymbolTable) {
1507 NextUnreadBit = Stream.GetCurrentBitNo();
1508 return false;
1509 }
Chris Lattner48f84872007-05-01 04:59:48 +00001510 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001511 case bitc::USELIST_BLOCK_ID:
1512 if (ParseUseLists())
1513 return true;
1514 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001515 }
1516 continue;
1517 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001518
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001519 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001520 Stream.ReadAbbrevRecord();
1521 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001524 // Read a record.
1525 switch (Stream.ReadRecord(Code, Record)) {
1526 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001527 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001528 if (Record.size() < 1)
1529 return Error("Malformed MODULE_CODE_VERSION");
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001530 // Only version #0 and #1 are supported so far.
1531 unsigned module_version = Record[0];
1532 switch (module_version) {
1533 default: return Error("Unknown bitstream version!");
1534 case 0:
1535 UseRelativeIDs = false;
1536 break;
1537 case 1:
1538 UseRelativeIDs = true;
1539 break;
1540 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001541 break;
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00001542 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001543 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001544 std::string S;
1545 if (ConvertToString(Record, 0, S))
1546 return Error("Invalid MODULE_CODE_TRIPLE record");
1547 TheModule->setTargetTriple(S);
1548 break;
1549 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001550 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001551 std::string S;
1552 if (ConvertToString(Record, 0, S))
1553 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1554 TheModule->setDataLayout(S);
1555 break;
1556 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001557 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001558 std::string S;
1559 if (ConvertToString(Record, 0, S))
1560 return Error("Invalid MODULE_CODE_ASM record");
1561 TheModule->setModuleInlineAsm(S);
1562 break;
1563 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001564 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001565 std::string S;
1566 if (ConvertToString(Record, 0, S))
1567 return Error("Invalid MODULE_CODE_DEPLIB record");
1568 TheModule->addLibrary(S);
1569 break;
1570 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001571 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001572 std::string S;
1573 if (ConvertToString(Record, 0, S))
1574 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1575 SectionTable.push_back(S);
1576 break;
1577 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001578 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001579 std::string S;
1580 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001581 return Error("Invalid MODULE_CODE_GCNAME record");
1582 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001583 break;
1584 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001585 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001586 // linkage, alignment, section, visibility, threadlocal,
1587 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001589 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001590 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001591 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001592 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001593 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001595 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001596 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001597
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001598 bool isConstant = Record[1];
1599 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1600 unsigned Alignment = (1 << Record[4]) >> 1;
1601 std::string Section;
1602 if (Record[5]) {
1603 if (Record[5]-1 >= SectionTable.size())
1604 return Error("Invalid section ID");
1605 Section = SectionTable[Record[5]-1];
1606 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001607 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001608 if (Record.size() > 6)
1609 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001610
1611 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001612 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001613 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001614
Rafael Espindolabea46262011-01-08 16:42:36 +00001615 bool UnnamedAddr = false;
1616 if (Record.size() > 8)
1617 UnnamedAddr = Record[8];
1618
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001621 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001622 NewGV->setAlignment(Alignment);
1623 if (!Section.empty())
1624 NewGV->setSection(Section);
1625 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001626 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001627
Chris Lattner0b2482a2007-04-23 21:26:05 +00001628 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001629
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001630 // Remember which value to use for the global initializer.
1631 if (unsigned InitID = Record[2])
1632 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001633 break;
1634 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001635 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001636 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001637 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001638 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001639 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001640 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001641 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001642 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001643 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001644 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001645 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1646 if (!FTy)
1647 return Error("Function not a pointer to function type!");
1648
Gabor Greif051a9502008-04-06 20:25:17 +00001649 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1650 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001651
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001652 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001653 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001654 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001655 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Chris Lattnera9bb7132007-05-08 05:38:01 +00001657 Func->setAlignment((1 << Record[5]) >> 1);
1658 if (Record[6]) {
1659 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001660 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001661 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001662 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001663 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001664 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001665 if (Record[8]-1 > GCTable.size())
1666 return Error("Invalid GC ID");
1667 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001668 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001669 bool UnnamedAddr = false;
1670 if (Record.size() > 9)
1671 UnnamedAddr = Record[9];
1672 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001673 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001674
Chris Lattner48f84872007-05-01 04:59:48 +00001675 // If this is a function with a body, remember the prototype we are
1676 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001677 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001678 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001679 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1680 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001681 break;
1682 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001683 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001684 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001685 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001686 if (Record.size() < 3)
1687 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001688 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001689 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001690 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001691 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Chris Lattner07d98b42007-04-26 02:46:40 +00001693 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1694 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001695 // Old bitcode files didn't have visibility field.
1696 if (Record.size() > 3)
1697 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001698 ValueList.push_back(NewGA);
1699 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1700 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001701 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001702 /// MODULE_CODE_PURGEVALS: [numvals]
1703 case bitc::MODULE_CODE_PURGEVALS:
1704 // Trim down the value list to the specified size.
1705 if (Record.size() < 1 || Record[0] > ValueList.size())
1706 return Error("Invalid MODULE_PURGEVALS record");
1707 ValueList.shrinkTo(Record[0]);
1708 break;
1709 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001710 Record.clear();
1711 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001712
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001713 return Error("Premature end of bitstream");
1714}
1715
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001716bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001717 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001718
Derek Schuff2ea93872012-02-06 22:30:29 +00001719 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 // Sniff for the signature.
1722 if (Stream.Read(8) != 'B' ||
1723 Stream.Read(8) != 'C' ||
1724 Stream.Read(4) != 0x0 ||
1725 Stream.Read(4) != 0xC ||
1726 Stream.Read(4) != 0xE ||
1727 Stream.Read(4) != 0xD)
1728 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001729
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001730 // We expect a number of well-defined blocks, though we don't necessarily
1731 // need to understand them all.
1732 while (!Stream.AtEndOfStream()) {
1733 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001734
Rafael Espindolac9687b32011-05-26 18:59:54 +00001735 if (Code != bitc::ENTER_SUBBLOCK) {
1736
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001737 // The ranlib in xcode 4 will align archive members by appending newlines
1738 // to the end of them. If this file size is a multiple of 4 but not 8, we
1739 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001740 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1741 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001742 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001743 return false;
1744
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001745 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001746 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001747
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001748 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001749
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001750 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001751 switch (BlockID) {
1752 case bitc::BLOCKINFO_BLOCK_ID:
1753 if (Stream.ReadBlockInfoBlock())
1754 return Error("Malformed BlockInfoBlock");
1755 break;
1756 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001757 // Reject multiple MODULE_BLOCK's in a single bitstream.
1758 if (TheModule)
1759 return Error("Multiple MODULE_BLOCKs in same stream");
1760 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001761 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001762 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001763 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001764 break;
1765 default:
1766 if (Stream.SkipBlock())
1767 return Error("Malformed block record");
1768 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001769 }
1770 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001771
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001772 return false;
1773}
Chris Lattnerc453f762007-04-29 07:54:31 +00001774
Bill Wendling34711742010-10-06 01:22:42 +00001775bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1776 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1777 return Error("Malformed block record");
1778
1779 SmallVector<uint64_t, 64> Record;
1780
1781 // Read all the records for this module.
1782 while (!Stream.AtEndOfStream()) {
1783 unsigned Code = Stream.ReadCode();
1784 if (Code == bitc::END_BLOCK) {
1785 if (Stream.ReadBlockEnd())
1786 return Error("Error at end of module block");
1787
1788 return false;
1789 }
1790
1791 if (Code == bitc::ENTER_SUBBLOCK) {
1792 switch (Stream.ReadSubBlockID()) {
1793 default: // Skip unknown content.
1794 if (Stream.SkipBlock())
1795 return Error("Malformed block record");
1796 break;
1797 }
1798 continue;
1799 }
1800
1801 if (Code == bitc::DEFINE_ABBREV) {
1802 Stream.ReadAbbrevRecord();
1803 continue;
1804 }
1805
1806 // Read a record.
1807 switch (Stream.ReadRecord(Code, Record)) {
1808 default: break; // Default behavior, ignore unknown content.
Bill Wendling34711742010-10-06 01:22:42 +00001809 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1810 std::string S;
1811 if (ConvertToString(Record, 0, S))
1812 return Error("Invalid MODULE_CODE_TRIPLE record");
1813 Triple = S;
1814 break;
1815 }
1816 }
1817 Record.clear();
1818 }
1819
1820 return Error("Premature end of bitstream");
1821}
1822
1823bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001824 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001825
1826 // Sniff for the signature.
1827 if (Stream.Read(8) != 'B' ||
1828 Stream.Read(8) != 'C' ||
1829 Stream.Read(4) != 0x0 ||
1830 Stream.Read(4) != 0xC ||
1831 Stream.Read(4) != 0xE ||
1832 Stream.Read(4) != 0xD)
1833 return Error("Invalid bitcode signature");
1834
1835 // We expect a number of well-defined blocks, though we don't necessarily
1836 // need to understand them all.
1837 while (!Stream.AtEndOfStream()) {
1838 unsigned Code = Stream.ReadCode();
1839
1840 if (Code != bitc::ENTER_SUBBLOCK)
1841 return Error("Invalid record at top-level");
1842
1843 unsigned BlockID = Stream.ReadSubBlockID();
1844
1845 // We only know the MODULE subblock ID.
1846 switch (BlockID) {
1847 case bitc::MODULE_BLOCK_ID:
1848 if (ParseModuleTriple(Triple))
1849 return true;
1850 break;
1851 default:
1852 if (Stream.SkipBlock())
1853 return Error("Malformed block record");
1854 break;
1855 }
1856 }
1857
1858 return false;
1859}
1860
Devang Patele8e02132009-09-18 19:26:43 +00001861/// ParseMetadataAttachment - Parse metadata attachments.
1862bool BitcodeReader::ParseMetadataAttachment() {
1863 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1864 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001865
Devang Patele8e02132009-09-18 19:26:43 +00001866 SmallVector<uint64_t, 64> Record;
1867 while(1) {
1868 unsigned Code = Stream.ReadCode();
1869 if (Code == bitc::END_BLOCK) {
1870 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001871 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001872 break;
1873 }
1874 if (Code == bitc::DEFINE_ABBREV) {
1875 Stream.ReadAbbrevRecord();
1876 continue;
1877 }
1878 // Read a metadata attachment record.
1879 Record.clear();
1880 switch (Stream.ReadRecord(Code, Record)) {
1881 default: // Default behavior: ignore.
1882 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001883 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001884 unsigned RecordLength = Record.size();
1885 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001886 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001887 Instruction *Inst = InstructionList[Record[0]];
1888 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001889 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001890 DenseMap<unsigned, unsigned>::iterator I =
1891 MDKindMap.find(Kind);
1892 if (I == MDKindMap.end())
1893 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001895 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001896 }
1897 break;
1898 }
1899 }
1900 }
1901 return false;
1902}
Chris Lattner48f84872007-05-01 04:59:48 +00001903
Chris Lattner980e5aa2007-05-01 05:52:21 +00001904/// ParseFunctionBody - Lazily parse the specified function body block.
1905bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001906 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001907 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001908
Nick Lewycky9a49f152010-02-25 08:30:17 +00001909 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001910 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001911 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001912
Chris Lattner980e5aa2007-05-01 05:52:21 +00001913 // Add all the function arguments to the value table.
1914 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1915 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001917 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001918 BasicBlock *CurBB = 0;
1919 unsigned CurBBNo = 0;
1920
Chris Lattnera6245242010-04-03 02:17:50 +00001921 DebugLoc LastLoc;
1922
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 // Read all the records.
1924 SmallVector<uint64_t, 64> Record;
1925 while (1) {
1926 unsigned Code = Stream.ReadCode();
1927 if (Code == bitc::END_BLOCK) {
1928 if (Stream.ReadBlockEnd())
1929 return Error("Error at end of function block");
1930 break;
1931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 if (Code == bitc::ENTER_SUBBLOCK) {
1934 switch (Stream.ReadSubBlockID()) {
1935 default: // Skip unknown content.
1936 if (Stream.SkipBlock())
1937 return Error("Malformed block record");
1938 break;
1939 case bitc::CONSTANTS_BLOCK_ID:
1940 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001941 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001942 break;
1943 case bitc::VALUE_SYMTAB_BLOCK_ID:
1944 if (ParseValueSymbolTable()) return true;
1945 break;
Devang Patele8e02132009-09-18 19:26:43 +00001946 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001947 if (ParseMetadataAttachment()) return true;
1948 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001949 case bitc::METADATA_BLOCK_ID:
1950 if (ParseMetadata()) return true;
1951 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001952 }
1953 continue;
1954 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001955
Chris Lattner980e5aa2007-05-01 05:52:21 +00001956 if (Code == bitc::DEFINE_ABBREV) {
1957 Stream.ReadAbbrevRecord();
1958 continue;
1959 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001960
Chris Lattner980e5aa2007-05-01 05:52:21 +00001961 // Read a record.
1962 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001963 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001964 unsigned BitCode = Stream.ReadRecord(Code, Record);
1965 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001966 default: // Default behavior: reject
1967 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001968 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001969 if (Record.size() < 1 || Record[0] == 0)
1970 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001972 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001973 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001974 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001975 CurBB = FunctionBBs[0];
1976 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001977
1978 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1979 // This record indicates that the last instruction is at the same
1980 // location as the previous instruction with a location.
1981 I = 0;
1982
1983 // Get the last instruction emitted.
1984 if (CurBB && !CurBB->empty())
1985 I = &CurBB->back();
1986 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1987 !FunctionBBs[CurBBNo-1]->empty())
1988 I = &FunctionBBs[CurBBNo-1]->back();
1989
1990 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1991 I->setDebugLoc(LastLoc);
1992 I = 0;
1993 continue;
1994
Chris Lattner4f6bab92011-06-17 18:17:37 +00001995 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001996 I = 0; // Get the last instruction emitted.
1997 if (CurBB && !CurBB->empty())
1998 I = &CurBB->back();
1999 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2000 !FunctionBBs[CurBBNo-1]->empty())
2001 I = &FunctionBBs[CurBBNo-1]->back();
2002 if (I == 0 || Record.size() < 4)
2003 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2004
2005 unsigned Line = Record[0], Col = Record[1];
2006 unsigned ScopeID = Record[2], IAID = Record[3];
2007
2008 MDNode *Scope = 0, *IA = 0;
2009 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2010 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2011 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2012 I->setDebugLoc(LastLoc);
2013 I = 0;
2014 continue;
2015 }
2016
Chris Lattnerabfbf852007-05-06 00:21:25 +00002017 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2018 unsigned OpNum = 0;
2019 Value *LHS, *RHS;
2020 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002021 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002022 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002023 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002024
Dan Gohman1224c382009-07-20 21:19:07 +00002025 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002026 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002027 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002028 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002029 if (OpNum < Record.size()) {
2030 if (Opc == Instruction::Add ||
2031 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002032 Opc == Instruction::Mul ||
2033 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002034 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002035 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002036 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002037 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002038 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002039 Opc == Instruction::UDiv ||
2040 Opc == Instruction::LShr ||
2041 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002042 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002043 cast<BinaryOperator>(I)->setIsExact(true);
2044 }
2045 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002046 break;
2047 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002048 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2049 unsigned OpNum = 0;
2050 Value *Op;
2051 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2052 OpNum+2 != Record.size())
2053 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002054
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002055 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002056 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2057 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002058 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002059 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002060 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002061 break;
2062 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002063 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002064 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002065 unsigned OpNum = 0;
2066 Value *BasePtr;
2067 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002068 return Error("Invalid GEP record");
2069
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002070 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002071 while (OpNum != Record.size()) {
2072 Value *Op;
2073 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002074 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002075 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002076 }
2077
Jay Foada9203102011-07-25 09:48:08 +00002078 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002079 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002080 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002081 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002082 break;
2083 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002084
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002085 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2086 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002087 unsigned OpNum = 0;
2088 Value *Agg;
2089 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2090 return Error("Invalid EXTRACTVAL record");
2091
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002092 SmallVector<unsigned, 4> EXTRACTVALIdx;
2093 for (unsigned RecSize = Record.size();
2094 OpNum != RecSize; ++OpNum) {
2095 uint64_t Index = Record[OpNum];
2096 if ((unsigned)Index != Index)
2097 return Error("Invalid EXTRACTVAL index");
2098 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002099 }
2100
Jay Foadfc6d3a42011-07-13 10:26:04 +00002101 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002102 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002103 break;
2104 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002105
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002106 case bitc::FUNC_CODE_INST_INSERTVAL: {
2107 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002108 unsigned OpNum = 0;
2109 Value *Agg;
2110 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2111 return Error("Invalid INSERTVAL record");
2112 Value *Val;
2113 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2114 return Error("Invalid INSERTVAL record");
2115
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002116 SmallVector<unsigned, 4> INSERTVALIdx;
2117 for (unsigned RecSize = Record.size();
2118 OpNum != RecSize; ++OpNum) {
2119 uint64_t Index = Record[OpNum];
2120 if ((unsigned)Index != Index)
2121 return Error("Invalid INSERTVAL index");
2122 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002123 }
2124
Jay Foadfc6d3a42011-07-13 10:26:04 +00002125 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002126 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002127 break;
2128 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002129
Chris Lattnerabfbf852007-05-06 00:21:25 +00002130 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002131 // obsolete form of select
2132 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002133 unsigned OpNum = 0;
2134 Value *TrueVal, *FalseVal, *Cond;
2135 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002136 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2137 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002138 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002139
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002140 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002141 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002142 break;
2143 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002145 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2146 // new form of select
2147 // handles select i1 or select [N x i1]
2148 unsigned OpNum = 0;
2149 Value *TrueVal, *FalseVal, *Cond;
2150 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002151 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002152 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2153 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002154
2155 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002156 if (VectorType* vector_type =
2157 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002158 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002159 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002160 return Error("Invalid SELECT condition type");
2161 } else {
2162 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002164 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002165 }
2166
Gabor Greif051a9502008-04-06 20:25:17 +00002167 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002168 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002169 break;
2170 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002171
Chris Lattner01ff65f2007-05-02 05:16:49 +00002172 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002173 unsigned OpNum = 0;
2174 Value *Vec, *Idx;
2175 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002176 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002177 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002178 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002179 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002180 break;
2181 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002182
Chris Lattner01ff65f2007-05-02 05:16:49 +00002183 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002184 unsigned OpNum = 0;
2185 Value *Vec, *Elt, *Idx;
2186 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002187 popValue(Record, OpNum, NextValueNo,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002188 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002189 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002190 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002191 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002192 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002193 break;
2194 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002195
Chris Lattnerabfbf852007-05-06 00:21:25 +00002196 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2197 unsigned OpNum = 0;
2198 Value *Vec1, *Vec2, *Mask;
2199 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002200 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Chris Lattnerabfbf852007-05-06 00:21:25 +00002201 return Error("Invalid SHUFFLEVEC record");
2202
Mon P Wangaeb06d22008-11-10 04:46:22 +00002203 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002204 return Error("Invalid SHUFFLEVEC record");
2205 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002206 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002207 break;
2208 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002209
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002210 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2211 // Old form of ICmp/FCmp returning bool
2212 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2213 // both legal on vectors but had different behaviour.
2214 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2215 // FCmp/ICmp returning bool or vector of bool
2216
Chris Lattner7337ab92007-05-06 00:00:00 +00002217 unsigned OpNum = 0;
2218 Value *LHS, *RHS;
2219 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002220 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattner7337ab92007-05-06 00:00:00 +00002221 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002222 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002223
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002224 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002225 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002226 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002227 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002228 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002229 break;
2230 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002231
Chris Lattner231cbcb2007-05-02 04:27:25 +00002232 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002233 {
2234 unsigned Size = Record.size();
2235 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002237 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002238 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002239 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002240
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002241 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002242 Value *Op = NULL;
2243 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2244 return Error("Invalid RET record");
2245 if (OpNum != Record.size())
2246 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002247
Chris Lattner96a74c52011-06-17 18:09:11 +00002248 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002249 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002250 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002251 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002252 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002253 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002254 return Error("Invalid BR record");
2255 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2256 if (TrueDest == 0)
2257 return Error("Invalid BR record");
2258
Devang Patele8e02132009-09-18 19:26:43 +00002259 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002260 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002261 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002262 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002263 else {
2264 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002265 Value *Cond = getValue(Record, 2, NextValueNo,
2266 Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002267 if (FalseDest == 0 || Cond == 0)
2268 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002269 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002270 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002271 }
2272 break;
2273 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002274 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002275 // Check magic
2276 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2277 // New SwitchInst format with case ranges.
2278
2279 Type *OpTy = getTypeByID(Record[1]);
2280 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2281
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002282 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002283 BasicBlock *Default = getBasicBlock(Record[3]);
2284 if (OpTy == 0 || Cond == 0 || Default == 0)
2285 return Error("Invalid SWITCH record");
2286
2287 unsigned NumCases = Record[4];
2288
2289 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2290 InstructionList.push_back(SI);
2291
2292 unsigned CurIdx = 5;
2293 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002294 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002295 unsigned NumItems = Record[CurIdx++];
2296 for (unsigned ci = 0; ci != NumItems; ++ci) {
2297 bool isSingleNumber = Record[CurIdx++];
2298
2299 APInt Low;
2300 unsigned ActiveWords = 1;
2301 if (ValueBitWidth > 64)
2302 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002303 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2304 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002305 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002306
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002307 if (!isSingleNumber) {
2308 ActiveWords = 1;
2309 if (ValueBitWidth > 64)
2310 ActiveWords = Record[CurIdx++];
2311 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002312 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2313 ValueBitWidth);
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002314
2315 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2316 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002317 CurIdx += ActiveWords;
2318 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002319 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002320 }
2321 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002322 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002323 SI->addCase(Case, DestBB);
2324 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002325 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002326 if (Hash != (Record[0] & 0xFFFF))
2327 return Error("Invalid SWITCH record");
2328 I = SI;
2329 break;
2330 }
2331
2332 // Old SwitchInst format without case ranges.
2333
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002334 if (Record.size() < 3 || (Record.size() & 1) == 0)
2335 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002336 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002337 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002338 BasicBlock *Default = getBasicBlock(Record[2]);
2339 if (OpTy == 0 || Cond == 0 || Default == 0)
2340 return Error("Invalid SWITCH record");
2341 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002342 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002343 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002344 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002346 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2347 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2348 if (CaseVal == 0 || DestBB == 0) {
2349 delete SI;
2350 return Error("Invalid SWITCH record!");
2351 }
2352 SI->addCase(CaseVal, DestBB);
2353 }
2354 I = SI;
2355 break;
2356 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002357 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002358 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002359 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002360 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002361 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002362 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002363 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002364 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002365 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002366 InstructionList.push_back(IBI);
2367 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2368 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2369 IBI->addDestination(DestBB);
2370 } else {
2371 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002372 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002373 }
2374 }
2375 I = IBI;
2376 break;
2377 }
2378
Duncan Sandsdc024672007-11-27 13:23:08 +00002379 case bitc::FUNC_CODE_INST_INVOKE: {
2380 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002381 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002382 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002383 unsigned CCInfo = Record[1];
2384 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2385 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002386
Chris Lattnera9bb7132007-05-08 05:38:01 +00002387 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002388 Value *Callee;
2389 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002390 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002391
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002392 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2393 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002394 dyn_cast<FunctionType>(CalleeTy->getElementType());
2395
2396 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002397 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2398 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002399 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002400
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002401 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002402 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002403 Ops.push_back(getValue(Record, OpNum, NextValueNo,
2404 FTy->getParamType(i)));
Chris Lattner7337ab92007-05-06 00:00:00 +00002405 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002406 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002407
Chris Lattner7337ab92007-05-06 00:00:00 +00002408 if (!FTy->isVarArg()) {
2409 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002410 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002411 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002412 // Read type/value pairs for varargs params.
2413 while (OpNum != Record.size()) {
2414 Value *Op;
2415 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2416 return Error("Invalid INVOKE record");
2417 Ops.push_back(Op);
2418 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002419 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002420
Jay Foada3efbb12011-07-15 08:37:34 +00002421 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002422 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002423 cast<InvokeInst>(I)->setCallingConv(
2424 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002425 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002426 break;
2427 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002428 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2429 unsigned Idx = 0;
2430 Value *Val = 0;
2431 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2432 return Error("Invalid RESUME record");
2433 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002434 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002435 break;
2436 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002437 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002438 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002439 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002440 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002441 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002442 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002443 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002444 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002445 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002446
Jay Foad3ecfc862011-03-30 11:28:46 +00002447 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002448 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002449
Chris Lattner15e6d172007-05-04 19:11:41 +00002450 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002451 Value *V;
2452 // With the new function encoding, it is possible that operands have
2453 // negative IDs (for forward references). Use a signed VBR
2454 // representation to keep the encoding small.
2455 if (UseRelativeIDs)
2456 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2457 else
2458 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00002459 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002460 if (!V || !BB) return Error("Invalid PHI record");
2461 PN->addIncoming(V, BB);
2462 }
2463 I = PN;
2464 break;
2465 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002466
Bill Wendlinge6e88262011-08-12 20:24:12 +00002467 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2468 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2469 unsigned Idx = 0;
2470 if (Record.size() < 4)
2471 return Error("Invalid LANDINGPAD record");
2472 Type *Ty = getTypeByID(Record[Idx++]);
2473 if (!Ty) return Error("Invalid LANDINGPAD record");
2474 Value *PersFn = 0;
2475 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2476 return Error("Invalid LANDINGPAD record");
2477
2478 bool IsCleanup = !!Record[Idx++];
2479 unsigned NumClauses = Record[Idx++];
2480 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2481 LP->setCleanup(IsCleanup);
2482 for (unsigned J = 0; J != NumClauses; ++J) {
2483 LandingPadInst::ClauseType CT =
2484 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2485 Value *Val;
2486
2487 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2488 delete LP;
2489 return Error("Invalid LANDINGPAD record");
2490 }
2491
2492 assert((CT != LandingPadInst::Catch ||
2493 !isa<ArrayType>(Val->getType())) &&
2494 "Catch clause has a invalid type!");
2495 assert((CT != LandingPadInst::Filter ||
2496 isa<ArrayType>(Val->getType())) &&
2497 "Filter clause has invalid type!");
2498 LP->addClause(Val);
2499 }
2500
2501 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002502 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002503 break;
2504 }
2505
Chris Lattner96a74c52011-06-17 18:09:11 +00002506 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2507 if (Record.size() != 4)
2508 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002509 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002510 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002511 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002512 Value *Size = getFnValueByID(Record[2], OpTy);
2513 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002514 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002515 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002516 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002517 break;
2518 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002519 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002520 unsigned OpNum = 0;
2521 Value *Op;
2522 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2523 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002524 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002525
Chris Lattner7337ab92007-05-06 00:00:00 +00002526 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002527 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002528 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002529 }
Eli Friedman21006d42011-08-09 23:02:53 +00002530 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2531 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2532 unsigned OpNum = 0;
2533 Value *Op;
2534 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2535 OpNum+4 != Record.size())
2536 return Error("Invalid LOADATOMIC record");
2537
2538
2539 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2540 if (Ordering == NotAtomic || Ordering == Release ||
2541 Ordering == AcquireRelease)
2542 return Error("Invalid LOADATOMIC record");
2543 if (Ordering != NotAtomic && Record[OpNum] == 0)
2544 return Error("Invalid LOADATOMIC record");
2545 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2546
2547 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2548 Ordering, SynchScope);
2549 InstructionList.push_back(I);
2550 break;
2551 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002552 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002553 unsigned OpNum = 0;
2554 Value *Val, *Ptr;
2555 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002556 popValue(Record, OpNum, NextValueNo,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002557 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2558 OpNum+2 != Record.size())
2559 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002560
Christopher Lambfe63fb92007-12-11 08:59:05 +00002561 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002562 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002563 break;
2564 }
Eli Friedman21006d42011-08-09 23:02:53 +00002565 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2566 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2567 unsigned OpNum = 0;
2568 Value *Val, *Ptr;
2569 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002570 popValue(Record, OpNum, NextValueNo,
Eli Friedman21006d42011-08-09 23:02:53 +00002571 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2572 OpNum+4 != Record.size())
2573 return Error("Invalid STOREATOMIC record");
2574
2575 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002576 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002577 Ordering == AcquireRelease)
2578 return Error("Invalid STOREATOMIC record");
2579 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2580 if (Ordering != NotAtomic && Record[OpNum] == 0)
2581 return Error("Invalid STOREATOMIC record");
2582
2583 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2584 Ordering, SynchScope);
2585 InstructionList.push_back(I);
2586 break;
2587 }
Eli Friedmanff030482011-07-28 21:48:00 +00002588 case bitc::FUNC_CODE_INST_CMPXCHG: {
2589 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2590 unsigned OpNum = 0;
2591 Value *Ptr, *Cmp, *New;
2592 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002593 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002594 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002595 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002596 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2597 OpNum+3 != Record.size())
2598 return Error("Invalid CMPXCHG record");
2599 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002600 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002601 return Error("Invalid CMPXCHG record");
2602 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2603 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2604 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2605 InstructionList.push_back(I);
2606 break;
2607 }
2608 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2609 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2610 unsigned OpNum = 0;
2611 Value *Ptr, *Val;
2612 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002613 popValue(Record, OpNum, NextValueNo,
Eli Friedmanff030482011-07-28 21:48:00 +00002614 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2615 OpNum+4 != Record.size())
2616 return Error("Invalid ATOMICRMW record");
2617 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2618 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2619 Operation > AtomicRMWInst::LAST_BINOP)
2620 return Error("Invalid ATOMICRMW record");
2621 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002622 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002623 return Error("Invalid ATOMICRMW record");
2624 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2625 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2626 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2627 InstructionList.push_back(I);
2628 break;
2629 }
Eli Friedman47f35132011-07-25 23:16:38 +00002630 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2631 if (2 != Record.size())
2632 return Error("Invalid FENCE record");
2633 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2634 if (Ordering == NotAtomic || Ordering == Unordered ||
2635 Ordering == Monotonic)
2636 return Error("Invalid FENCE record");
2637 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2638 I = new FenceInst(Context, Ordering, SynchScope);
2639 InstructionList.push_back(I);
2640 break;
2641 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002642 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002643 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2644 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002645 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002646
Devang Patel05988662008-09-25 21:00:45 +00002647 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002648 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002649
Chris Lattnera9bb7132007-05-08 05:38:01 +00002650 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002651 Value *Callee;
2652 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2653 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002654
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002655 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2656 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002657 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002658 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002659 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002660
Chris Lattner0579f7f2007-05-03 22:04:19 +00002661 SmallVector<Value*, 16> Args;
2662 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002663 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002664 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002665 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002666 else
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002667 Args.push_back(getValue(Record, OpNum, NextValueNo,
2668 FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002669 if (Args.back() == 0) return Error("Invalid CALL record");
2670 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002671
Chris Lattner0579f7f2007-05-03 22:04:19 +00002672 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002673 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002674 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002675 return Error("Invalid CALL record");
2676 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002677 while (OpNum != Record.size()) {
2678 Value *Op;
2679 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2680 return Error("Invalid CALL record");
2681 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002682 }
2683 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002684
Jay Foada3efbb12011-07-15 08:37:34 +00002685 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002686 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002687 cast<CallInst>(I)->setCallingConv(
2688 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002689 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002690 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002691 break;
2692 }
2693 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2694 if (Record.size() < 3)
2695 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002696 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungd9a3bad2012-10-11 20:20:40 +00002697 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002698 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002699 if (!OpTy || !Op || !ResTy)
2700 return Error("Invalid VAARG record");
2701 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002702 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002703 break;
2704 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002705 }
2706
2707 // Add instruction to end of current BB. If there is no current BB, reject
2708 // this file.
2709 if (CurBB == 0) {
2710 delete I;
2711 return Error("Invalid instruction with no BB");
2712 }
2713 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002714
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002715 // If this was a terminator instruction, move to the next block.
2716 if (isa<TerminatorInst>(I)) {
2717 ++CurBBNo;
2718 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2719 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002720
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002721 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002722 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002723 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002724 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002725
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002726 // Check the function list for unresolved values.
2727 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2728 if (A->getParent() == 0) {
2729 // We found at least one unresolved value. Nuke them all to avoid leaks.
2730 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002731 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002732 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002733 delete A;
2734 }
2735 }
Chris Lattner35a04702007-05-04 03:50:29 +00002736 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002737 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002738 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002739
Dan Gohman064ff3e2010-08-25 20:23:38 +00002740 // FIXME: Check for unresolved forward-declared metadata references
2741 // and clean up leaks.
2742
Chris Lattner50b136d2009-10-28 05:53:48 +00002743 // See if anything took the address of blocks in this function. If so,
2744 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002745 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2746 BlockAddrFwdRefs.find(F);
2747 if (BAFRI != BlockAddrFwdRefs.end()) {
2748 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2749 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2750 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002751 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002752 return Error("Invalid blockaddress block #");
2753
2754 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002755 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002756 FwdRef->eraseFromParent();
2757 }
2758
2759 BlockAddrFwdRefs.erase(BAFRI);
2760 }
2761
Chris Lattner980e5aa2007-05-01 05:52:21 +00002762 // Trim the value list down to the size it was before we parsed this function.
2763 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002764 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002765 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002766 return false;
2767}
2768
Derek Schuff2ea93872012-02-06 22:30:29 +00002769/// FindFunctionInStream - Find the function body in the bitcode stream
2770bool BitcodeReader::FindFunctionInStream(Function *F,
2771 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2772 while (DeferredFunctionInfoIterator->second == 0) {
2773 if (Stream.AtEndOfStream())
2774 return Error("Could not find Function in stream");
2775 // ParseModule will parse the next body in the stream and set its
2776 // position in the DeferredFunctionInfo map.
2777 if (ParseModule(true)) return true;
2778 }
2779 return false;
2780}
2781
Chris Lattnerb348bb82007-05-18 04:02:46 +00002782//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002783// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002784//===----------------------------------------------------------------------===//
2785
2786
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002787bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2788 if (const Function *F = dyn_cast<Function>(GV)) {
2789 return F->isDeclaration() &&
2790 DeferredFunctionInfo.count(const_cast<Function*>(F));
2791 }
2792 return false;
2793}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002795bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2796 Function *F = dyn_cast<Function>(GV);
2797 // If it's not a function or is already material, ignore the request.
2798 if (!F || !F->isMaterializable()) return false;
2799
2800 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002801 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002802 // If its position is recorded as 0, its body is somewhere in the stream
2803 // but we haven't seen it yet.
2804 if (DFII->second == 0)
2805 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002806
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002807 // Move the bit stream to the saved position of the deferred function body.
2808 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002809
Chris Lattnerb348bb82007-05-18 04:02:46 +00002810 if (ParseFunctionBody(F)) {
2811 if (ErrInfo) *ErrInfo = ErrorString;
2812 return true;
2813 }
Chandler Carruth69940402007-08-04 01:51:18 +00002814
2815 // Upgrade any old intrinsic calls in the function.
2816 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2817 E = UpgradedIntrinsics.end(); I != E; ++I) {
2818 if (I->first != I->second) {
2819 for (Value::use_iterator UI = I->first->use_begin(),
2820 UE = I->first->use_end(); UI != UE; ) {
2821 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2822 UpgradeIntrinsicCall(CI, I->second);
2823 }
2824 }
2825 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002826
Chris Lattnerb348bb82007-05-18 04:02:46 +00002827 return false;
2828}
2829
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002830bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2831 const Function *F = dyn_cast<Function>(GV);
2832 if (!F || F->isDeclaration())
2833 return false;
2834 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2835}
2836
2837void BitcodeReader::Dematerialize(GlobalValue *GV) {
2838 Function *F = dyn_cast<Function>(GV);
2839 // If this function isn't dematerializable, this is a noop.
2840 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002841 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002842
Chris Lattnerb348bb82007-05-18 04:02:46 +00002843 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002844
Chris Lattnerb348bb82007-05-18 04:02:46 +00002845 // Just forget the function body, we can remat it later.
2846 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002847}
2848
2849
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002850bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2851 assert(M == TheModule &&
2852 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002853 // Iterate over the module, deserializing any functions that are still on
2854 // disk.
2855 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2856 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002857 if (F->isMaterializable() &&
2858 Materialize(F, ErrInfo))
2859 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002860
Derek Schuff0ffe6982012-02-29 00:07:09 +00002861 // At this point, if there are any function bodies, the current bit is
2862 // pointing to the END_BLOCK record after them. Now make sure the rest
2863 // of the bits in the module have been read.
2864 if (NextUnreadBit)
2865 ParseModule(true);
2866
Daniel Dunbara279bc32009-09-20 02:20:51 +00002867 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2868 // delete the old functions to clean up. We can't do this unless the entire
2869 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002870 // with calls to the old function.
2871 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2872 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2873 if (I->first != I->second) {
2874 for (Value::use_iterator UI = I->first->use_begin(),
2875 UE = I->first->use_end(); UI != UE; ) {
2876 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2877 UpgradeIntrinsicCall(CI, I->second);
2878 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002879 if (!I->first->use_empty())
2880 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002881 I->first->eraseFromParent();
2882 }
2883 }
2884 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002885
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002886 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002887}
2888
Derek Schuff2ea93872012-02-06 22:30:29 +00002889bool BitcodeReader::InitStream() {
2890 if (LazyStreamer) return InitLazyStream();
2891 return InitStreamFromBuffer();
2892}
2893
2894bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002895 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002896 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2897
2898 if (Buffer->getBufferSize() & 3) {
2899 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2900 return Error("Invalid bitcode signature");
2901 else
2902 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2903 }
2904
2905 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2906 // The magic number is 0x0B17C0DE stored in little endian.
2907 if (isBitcodeWrapper(BufPtr, BufEnd))
2908 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2909 return Error("Invalid bitcode wrapper header");
2910
2911 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2912 Stream.init(*StreamFile);
2913
2914 return false;
2915}
2916
2917bool BitcodeReader::InitLazyStream() {
2918 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2919 // see it.
2920 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2921 StreamFile.reset(new BitstreamReader(Bytes));
2922 Stream.init(*StreamFile);
2923
2924 unsigned char buf[16];
2925 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2926 return Error("Bitcode stream must be at least 16 bytes in length");
2927
2928 if (!isBitcode(buf, buf + 16))
2929 return Error("Invalid bitcode signature");
2930
2931 if (isBitcodeWrapper(buf, buf + 4)) {
2932 const unsigned char *bitcodeStart = buf;
2933 const unsigned char *bitcodeEnd = buf + 16;
2934 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2935 Bytes->dropLeadingBytes(bitcodeStart - buf);
2936 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2937 }
2938 return false;
2939}
Chris Lattner48f84872007-05-01 04:59:48 +00002940
Chris Lattnerc453f762007-04-29 07:54:31 +00002941//===----------------------------------------------------------------------===//
2942// External interface
2943//===----------------------------------------------------------------------===//
2944
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002945/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002946///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002947Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2948 LLVMContext& Context,
2949 std::string *ErrMsg) {
2950 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002951 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002952 M->setMaterializer(R);
2953 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002954 if (ErrMsg)
2955 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002956
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002957 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002958 return 0;
2959 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002960 // Have the BitcodeReader dtor delete 'Buffer'.
2961 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002962
2963 R->materializeForwardReferencedFunctions();
2964
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002965 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002966}
2967
Derek Schuff2ea93872012-02-06 22:30:29 +00002968
2969Module *llvm::getStreamedBitcodeModule(const std::string &name,
2970 DataStreamer *streamer,
2971 LLVMContext &Context,
2972 std::string *ErrMsg) {
2973 Module *M = new Module(name, Context);
2974 BitcodeReader *R = new BitcodeReader(streamer, Context);
2975 M->setMaterializer(R);
2976 if (R->ParseBitcodeInto(M)) {
2977 if (ErrMsg)
2978 *ErrMsg = R->getErrorString();
2979 delete M; // Also deletes R.
2980 return 0;
2981 }
2982 R->setBufferOwned(false); // no buffer to delete
2983 return M;
2984}
2985
Chris Lattnerc453f762007-04-29 07:54:31 +00002986/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2987/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002988Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002989 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002990 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2991 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002992
2993 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2994 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002995 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002996
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002997 // Read in the entire module, and destroy the BitcodeReader.
2998 if (M->MaterializeAllPermanently(ErrMsg)) {
2999 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00003000 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00003001 }
Bill Wendling34711742010-10-06 01:22:42 +00003002
Chad Rosiercbbb0962011-12-07 21:44:12 +00003003 // TODO: Restore the use-lists to the in-memory state when the bitcode was
3004 // written. We must defer until the Module has been fully materialized.
3005
Chris Lattnerc453f762007-04-29 07:54:31 +00003006 return M;
3007}
Bill Wendling34711742010-10-06 01:22:42 +00003008
3009std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3010 LLVMContext& Context,
3011 std::string *ErrMsg) {
3012 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3013 // Don't let the BitcodeReader dtor delete 'Buffer'.
3014 R->setBufferOwned(false);
3015
3016 std::string Triple("");
3017 if (R->ParseTriple(Triple))
3018 if (ErrMsg)
3019 *ErrMsg = R->getErrorString();
3020
3021 delete R;
3022 return Triple;
3023}