blob: 078188b742cf88587bd7479bd5694113d9e5d7e6 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
Devang Patel19c87462008-09-26 22:53:05 +000050 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000051 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000054 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000055}
56
Chris Lattner48c85b82007-05-04 03:30:17 +000057//===----------------------------------------------------------------------===//
58// Helper functions to implement forward reference resolution, etc.
59//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000060
Chris Lattnercaee0dc2007-04-22 06:23:29 +000061/// ConvertToString - Convert a string from a record into an std::string, return
62/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000063template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000064static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000065 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000066 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000067 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000068
Chris Lattner15e6d172007-05-04 19:11:41 +000069 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
70 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000071 return false;
72}
73
74static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
75 switch (Val) {
76 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000077 case 0: return GlobalValue::ExternalLinkage;
78 case 1: return GlobalValue::WeakAnyLinkage;
79 case 2: return GlobalValue::AppendingLinkage;
80 case 3: return GlobalValue::InternalLinkage;
81 case 4: return GlobalValue::LinkOnceAnyLinkage;
82 case 5: return GlobalValue::DLLImportLinkage;
83 case 6: return GlobalValue::DLLExportLinkage;
84 case 7: return GlobalValue::ExternalWeakLinkage;
85 case 8: return GlobalValue::CommonLinkage;
86 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000087 case 10: return GlobalValue::WeakODRLinkage;
88 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000089 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000090 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000091 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000092 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000093 }
94}
95
96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
97 switch (Val) {
98 default: // Map unknown visibilities to default.
99 case 0: return GlobalValue::DefaultVisibility;
100 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000101 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000102 }
103}
104
Hans Wennborgce718ff2012-06-23 11:37:03 +0000105static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
106 switch (Val) {
107 case 0: return GlobalVariable::NotThreadLocal;
108 default: // Map unknown non-zero value to general dynamic.
109 case 1: return GlobalVariable::GeneralDynamicTLSModel;
110 case 2: return GlobalVariable::LocalDynamicTLSModel;
111 case 3: return GlobalVariable::InitialExecTLSModel;
112 case 4: return GlobalVariable::LocalExecTLSModel;
113 }
114}
115
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000116static int GetDecodedCastOpcode(unsigned Val) {
117 switch (Val) {
118 default: return -1;
119 case bitc::CAST_TRUNC : return Instruction::Trunc;
120 case bitc::CAST_ZEXT : return Instruction::ZExt;
121 case bitc::CAST_SEXT : return Instruction::SExt;
122 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
123 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
124 case bitc::CAST_UITOFP : return Instruction::UIToFP;
125 case bitc::CAST_SITOFP : return Instruction::SIToFP;
126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
127 case bitc::CAST_FPEXT : return Instruction::FPExt;
128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
130 case bitc::CAST_BITCAST : return Instruction::BitCast;
131 }
132}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000133static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000134 switch (Val) {
135 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000136 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000137 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000140 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000141 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000142 case bitc::BINOP_UDIV: return Instruction::UDiv;
143 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000144 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000145 case bitc::BINOP_UREM: return Instruction::URem;
146 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000147 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000148 case bitc::BINOP_SHL: return Instruction::Shl;
149 case bitc::BINOP_LSHR: return Instruction::LShr;
150 case bitc::BINOP_ASHR: return Instruction::AShr;
151 case bitc::BINOP_AND: return Instruction::And;
152 case bitc::BINOP_OR: return Instruction::Or;
153 case bitc::BINOP_XOR: return Instruction::Xor;
154 }
155}
156
Eli Friedmanff030482011-07-28 21:48:00 +0000157static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
158 switch (Val) {
159 default: return AtomicRMWInst::BAD_BINOP;
160 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
161 case bitc::RMW_ADD: return AtomicRMWInst::Add;
162 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
163 case bitc::RMW_AND: return AtomicRMWInst::And;
164 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
165 case bitc::RMW_OR: return AtomicRMWInst::Or;
166 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
167 case bitc::RMW_MAX: return AtomicRMWInst::Max;
168 case bitc::RMW_MIN: return AtomicRMWInst::Min;
169 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
170 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
171 }
172}
173
Eli Friedman47f35132011-07-25 23:16:38 +0000174static AtomicOrdering GetDecodedOrdering(unsigned Val) {
175 switch (Val) {
176 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
177 case bitc::ORDERING_UNORDERED: return Unordered;
178 case bitc::ORDERING_MONOTONIC: return Monotonic;
179 case bitc::ORDERING_ACQUIRE: return Acquire;
180 case bitc::ORDERING_RELEASE: return Release;
181 case bitc::ORDERING_ACQREL: return AcquireRelease;
182 default: // Map unknown orderings to sequentially-consistent.
183 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
184 }
185}
186
187static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
188 switch (Val) {
189 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
190 default: // Map unknown scopes to cross-thread.
191 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
192 }
193}
194
Gabor Greifefe65362008-05-10 08:32:32 +0000195namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000196namespace {
197 /// @brief A class for maintaining the slot number definition
198 /// as a placeholder for the actual definition for forward constants defs.
199 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000200 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000201 public:
202 // allocate space for exactly one operand
203 void *operator new(size_t s) {
204 return User::operator new(s, 1);
205 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000206 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000207 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000208 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000209 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000210
Chris Lattnerea693df2008-08-21 02:34:16 +0000211 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000212 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000213 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000214 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000215 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000217
218
Gabor Greifefe65362008-05-10 08:32:32 +0000219 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000220 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000221 };
222}
223
Chris Lattner46e77402009-03-31 22:55:09 +0000224// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000225template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000226struct OperandTraits<ConstantPlaceHolder> :
227 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000228};
Gabor Greifefe65362008-05-10 08:32:32 +0000229}
230
Chris Lattner46e77402009-03-31 22:55:09 +0000231
232void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
233 if (Idx == size()) {
234 push_back(V);
235 return;
236 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000237
Chris Lattner46e77402009-03-31 22:55:09 +0000238 if (Idx >= size())
239 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000240
Chris Lattner46e77402009-03-31 22:55:09 +0000241 WeakVH &OldV = ValuePtrs[Idx];
242 if (OldV == 0) {
243 OldV = V;
244 return;
245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000246
Chris Lattner46e77402009-03-31 22:55:09 +0000247 // Handle constants and non-constants (e.g. instrs) differently for
248 // efficiency.
249 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250 ResolveConstants.push_back(std::make_pair(PHC, Idx));
251 OldV = V;
252 } else {
253 // If there was a forward reference to this value, replace it.
254 Value *PrevVal = OldV;
255 OldV->replaceAllUsesWith(V);
256 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000257 }
258}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000259
Gabor Greifefe65362008-05-10 08:32:32 +0000260
Chris Lattner522b7b12007-04-24 05:48:56 +0000261Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000262 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000263 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000264 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000265
Chris Lattner46e77402009-03-31 22:55:09 +0000266 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000267 assert(Ty == V->getType() && "Type mismatch in constant table!");
268 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000269 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000270
271 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000272 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000273 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000274 return C;
275}
276
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000277Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000278 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000279 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000280
Chris Lattner46e77402009-03-31 22:55:09 +0000281 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000282 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283 return V;
284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Chris Lattner01ff65f2007-05-02 05:16:49 +0000286 // No type specified, must be invalid reference.
287 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000288
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000289 // Create and return a placeholder, which will later be RAUW'd.
290 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000291 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000292 return V;
293}
294
Chris Lattnerea693df2008-08-21 02:34:16 +0000295/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296/// resolves any forward references. The idea behind this is that we sometimes
297/// get constants (such as large arrays) which reference *many* forward ref
298/// constants. Replacing each of these causes a lot of thrashing when
299/// building/reuniquing the constant. Instead of doing this, we look at all the
300/// uses and rewrite all the place holders at once for any constant that uses
301/// a placeholder.
302void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000303 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000304 // binary search.
305 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000306
Chris Lattnerea693df2008-08-21 02:34:16 +0000307 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000310 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 Constant *Placeholder = ResolveConstants.back().first;
312 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000313
Chris Lattnerea693df2008-08-21 02:34:16 +0000314 // Loop over all users of the placeholder, updating them to reference the
315 // new value. If they reference more than one placeholder, update them all
316 // at once.
317 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000318 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000319 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000320
Chris Lattnerea693df2008-08-21 02:34:16 +0000321 // If the using object isn't uniqued, just update the operands. This
322 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000323 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000324 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000325 continue;
326 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000327
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 // Otherwise, we have a constant that uses the placeholder. Replace that
329 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000330 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000331 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
332 I != E; ++I) {
333 Value *NewOp;
334 if (!isa<ConstantPlaceHolder>(*I)) {
335 // Not a placeholder reference.
336 NewOp = *I;
337 } else if (*I == Placeholder) {
338 // Common case is that it just references this one placeholder.
339 NewOp = RealVal;
340 } else {
341 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342 ResolveConstantsTy::iterator It =
343 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000344 std::pair<Constant*, unsigned>(cast<Constant>(*I),
345 0));
346 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000347 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 }
349
350 NewOps.push_back(cast<Constant>(NewOp));
351 }
352
353 // Make the new constant.
354 Constant *NewC;
355 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000356 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000357 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000358 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000359 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000360 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000361 } else {
362 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000363 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000364 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000365
Chris Lattnerea693df2008-08-21 02:34:16 +0000366 UserC->replaceAllUsesWith(NewC);
367 UserC->destroyConstant();
368 NewOps.clear();
369 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000370
Nick Lewyckycb337992009-05-10 20:57:05 +0000371 // Update all ValueHandles, they should be the only users at this point.
372 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000373 delete Placeholder;
374 }
375}
376
Devang Pateld5ac4042009-08-04 06:00:18 +0000377void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
378 if (Idx == size()) {
379 push_back(V);
380 return;
381 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000382
Devang Pateld5ac4042009-08-04 06:00:18 +0000383 if (Idx >= size())
384 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000385
Devang Pateld5ac4042009-08-04 06:00:18 +0000386 WeakVH &OldV = MDValuePtrs[Idx];
387 if (OldV == 0) {
388 OldV = V;
389 return;
390 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000391
Devang Pateld5ac4042009-08-04 06:00:18 +0000392 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000393 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000395 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000396 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397 // value for Idx.
398 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000399}
400
401Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402 if (Idx >= size())
403 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000404
Devang Pateld5ac4042009-08-04 06:00:18 +0000405 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000406 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 return V;
408 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000409
Devang Pateld5ac4042009-08-04 06:00:18 +0000410 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000411 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000412 MDValuePtrs[Idx] = V;
413 return V;
414}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000415
Chris Lattner1afcace2011-07-09 17:41:24 +0000416Type *BitcodeReader::getTypeByID(unsigned ID) {
417 // The type table size is always specified correctly.
418 if (ID >= TypeList.size())
419 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000420
Chris Lattner1afcace2011-07-09 17:41:24 +0000421 if (Type *Ty = TypeList[ID])
422 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000423
Chris Lattner1afcace2011-07-09 17:41:24 +0000424 // If we have a forward reference, the only possible case is when it is to a
425 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000426 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000427}
428
Chris Lattner1afcace2011-07-09 17:41:24 +0000429
Chris Lattner48c85b82007-05-04 03:30:17 +0000430//===----------------------------------------------------------------------===//
431// Functions for parsing blocks from the bitcode file
432//===----------------------------------------------------------------------===//
433
Devang Patel05988662008-09-25 21:00:45 +0000434bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000435 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000436 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Devang Patel19c87462008-09-26 22:53:05 +0000438 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000439 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000440
Chris Lattner48c85b82007-05-04 03:30:17 +0000441 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Devang Patel05988662008-09-25 21:00:45 +0000443 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Chris Lattner48c85b82007-05-04 03:30:17 +0000445 // Read all the records.
446 while (1) {
447 unsigned Code = Stream.ReadCode();
448 if (Code == bitc::END_BLOCK) {
449 if (Stream.ReadBlockEnd())
450 return Error("Error at end of PARAMATTR block");
451 return false;
452 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000453
Chris Lattner48c85b82007-05-04 03:30:17 +0000454 if (Code == bitc::ENTER_SUBBLOCK) {
455 // No known subblocks, always skip them.
456 Stream.ReadSubBlockID();
457 if (Stream.SkipBlock())
458 return Error("Malformed block record");
459 continue;
460 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000461
Chris Lattner48c85b82007-05-04 03:30:17 +0000462 if (Code == bitc::DEFINE_ABBREV) {
463 Stream.ReadAbbrevRecord();
464 continue;
465 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000466
Chris Lattner48c85b82007-05-04 03:30:17 +0000467 // Read a record.
468 Record.clear();
469 switch (Stream.ReadRecord(Code, Record)) {
470 default: // Default behavior: ignore.
471 break;
472 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
473 if (Record.size() & 1)
474 return Error("Invalid ENTRY record");
475
Chris Lattner48c85b82007-05-04 03:30:17 +0000476 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Meador Ingee99f8be2012-05-28 15:45:43 +0000477 Attributes ReconstitutedAttr =
478 Attribute::decodeLLVMAttributesForBitcode(Record[i+1]);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000479 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000480 }
Chris Lattner461edd92008-03-12 02:25:52 +0000481
Devang Patel19c87462008-09-26 22:53:05 +0000482 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nuno Lopes006c7b92012-05-08 17:07:35 +0000483 if (Attributes(Record[i+1]) != Attribute::None)
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000484 Attrs.push_back(AttributeWithIndex::get(Record[i],
485 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000486 }
Devang Patel19c87462008-09-26 22:53:05 +0000487
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000488 MAttributes.push_back(AttrListPtr::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000489 Attrs.clear();
490 break;
491 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000492 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000493 }
494}
495
Chris Lattner86697142007-05-01 05:01:34 +0000496bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000497 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000498 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000499
Chris Lattner1afcace2011-07-09 17:41:24 +0000500 return ParseTypeTableBody();
501}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000502
Chris Lattner1afcace2011-07-09 17:41:24 +0000503bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000504 if (!TypeList.empty())
505 return Error("Multiple TYPE_BLOCKs found!");
506
507 SmallVector<uint64_t, 64> Record;
508 unsigned NumRecords = 0;
509
Chris Lattner1afcace2011-07-09 17:41:24 +0000510 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000511
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000512 // Read all the records for this type table.
513 while (1) {
514 unsigned Code = Stream.ReadCode();
515 if (Code == bitc::END_BLOCK) {
516 if (NumRecords != TypeList.size())
517 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000518 if (Stream.ReadBlockEnd())
519 return Error("Error at end of type table block");
520 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000521 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000522
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 if (Code == bitc::ENTER_SUBBLOCK) {
524 // No known subblocks, always skip them.
525 Stream.ReadSubBlockID();
526 if (Stream.SkipBlock())
527 return Error("Malformed block record");
528 continue;
529 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000530
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000531 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000532 Stream.ReadAbbrevRecord();
533 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000534 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000535
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 // Read a record.
537 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000538 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000539 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000540 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000541 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
542 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
543 // type list. This allows us to reserve space.
544 if (Record.size() < 1)
545 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000546 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000548 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000549 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 break;
Dan Gohmance163392011-12-17 00:04:22 +0000551 case bitc::TYPE_CODE_HALF: // HALF
552 ResultTy = Type::getHalfTy(Context);
553 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000554 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 break;
557 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000559 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000560 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000561 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000562 break;
563 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000564 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000565 break;
566 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000567 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000568 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000569 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000570 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000572 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000573 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000574 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000575 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
576 ResultTy = Type::getX86_MMXTy(Context);
577 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
579 if (Record.size() < 1)
580 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000581
Owen Anderson1d0be152009-08-13 21:58:54 +0000582 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000584 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000585 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000586 if (Record.size() < 1)
587 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000588 unsigned AddressSpace = 0;
589 if (Record.size() == 2)
590 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000591 ResultTy = getTypeByID(Record[0]);
592 if (ResultTy == 0) return Error("invalid element type in pointer type");
593 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000594 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000595 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000596 case bitc::TYPE_CODE_FUNCTION_OLD: {
597 // FIXME: attrid is dead, remove it in LLVM 4.0
598 // FUNCTION: [vararg, attrid, retty, paramty x N]
599 if (Record.size() < 3)
600 return Error("Invalid FUNCTION type record");
601 SmallVector<Type*, 8> ArgTys;
602 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
603 if (Type *T = getTypeByID(Record[i]))
604 ArgTys.push_back(T);
605 else
606 break;
607 }
608
609 ResultTy = getTypeByID(Record[2]);
610 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
611 return Error("invalid type in function type");
612
613 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
614 break;
615 }
Chad Rosiercde54642011-11-03 00:14:01 +0000616 case bitc::TYPE_CODE_FUNCTION: {
617 // FUNCTION: [vararg, retty, paramty x N]
618 if (Record.size() < 2)
619 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000620 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000621 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
622 if (Type *T = getTypeByID(Record[i]))
623 ArgTys.push_back(T);
624 else
625 break;
626 }
627
628 ResultTy = getTypeByID(Record[1]);
629 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
630 return Error("invalid type in function type");
631
632 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
633 break;
634 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000635 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000636 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000637 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000638 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000639 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
640 if (Type *T = getTypeByID(Record[i]))
641 EltTys.push_back(T);
642 else
643 break;
644 }
645 if (EltTys.size() != Record.size()-1)
646 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000647 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000648 break;
649 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000650 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
651 if (ConvertToString(Record, 0, TypeName))
652 return Error("Invalid STRUCT_NAME record");
653 continue;
654
655 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
656 if (Record.size() < 1)
657 return Error("Invalid STRUCT type record");
658
659 if (NumRecords >= TypeList.size())
660 return Error("invalid TYPE table");
661
662 // Check to see if this was forward referenced, if so fill in the temp.
663 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
664 if (Res) {
665 Res->setName(TypeName);
666 TypeList[NumRecords] = 0;
667 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000668 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000669 TypeName.clear();
670
671 SmallVector<Type*, 8> EltTys;
672 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
673 if (Type *T = getTypeByID(Record[i]))
674 EltTys.push_back(T);
675 else
676 break;
677 }
678 if (EltTys.size() != Record.size()-1)
679 return Error("invalid STRUCT type record");
680 Res->setBody(EltTys, Record[0]);
681 ResultTy = Res;
682 break;
683 }
684 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
685 if (Record.size() != 1)
686 return Error("Invalid OPAQUE type record");
687
688 if (NumRecords >= TypeList.size())
689 return Error("invalid TYPE table");
690
691 // Check to see if this was forward referenced, if so fill in the temp.
692 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
693 if (Res) {
694 Res->setName(TypeName);
695 TypeList[NumRecords] = 0;
696 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000697 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000698 TypeName.clear();
699 ResultTy = Res;
700 break;
701 }
702 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
703 if (Record.size() < 2)
704 return Error("Invalid ARRAY type record");
705 if ((ResultTy = getTypeByID(Record[1])))
706 ResultTy = ArrayType::get(ResultTy, Record[0]);
707 else
708 return Error("Invalid ARRAY type element");
709 break;
710 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
711 if (Record.size() < 2)
712 return Error("Invalid VECTOR type record");
713 if ((ResultTy = getTypeByID(Record[1])))
714 ResultTy = VectorType::get(ResultTy, Record[0]);
715 else
716 return Error("Invalid ARRAY type element");
717 break;
718 }
719
720 if (NumRecords >= TypeList.size())
721 return Error("invalid TYPE table");
722 assert(ResultTy && "Didn't read a type?");
723 assert(TypeList[NumRecords] == 0 && "Already read type?");
724 TypeList[NumRecords++] = ResultTy;
725 }
726}
727
Chris Lattner86697142007-05-01 05:01:34 +0000728bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000729 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000730 return Error("Malformed block record");
731
732 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000733
Chris Lattner0b2482a2007-04-23 21:26:05 +0000734 // Read all the records for this value table.
735 SmallString<128> ValueName;
736 while (1) {
737 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000738 if (Code == bitc::END_BLOCK) {
739 if (Stream.ReadBlockEnd())
740 return Error("Error at end of value symbol table block");
741 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000742 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000743 if (Code == bitc::ENTER_SUBBLOCK) {
744 // No known subblocks, always skip them.
745 Stream.ReadSubBlockID();
746 if (Stream.SkipBlock())
747 return Error("Malformed block record");
748 continue;
749 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000750
Chris Lattner0b2482a2007-04-23 21:26:05 +0000751 if (Code == bitc::DEFINE_ABBREV) {
752 Stream.ReadAbbrevRecord();
753 continue;
754 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000755
Chris Lattner0b2482a2007-04-23 21:26:05 +0000756 // Read a record.
757 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000758 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000759 default: // Default behavior: unknown type.
760 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000761 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000762 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000763 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 unsigned ValueID = Record[0];
765 if (ValueID >= ValueList.size())
766 return Error("Invalid Value ID in VST_ENTRY record");
767 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000768
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000769 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000770 ValueName.clear();
771 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000772 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000773 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000774 if (ConvertToString(Record, 1, ValueName))
775 return Error("Invalid VST_BBENTRY record");
776 BasicBlock *BB = getBasicBlock(Record[0]);
777 if (BB == 0)
778 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000779
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000780 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000781 ValueName.clear();
782 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000783 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000784 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000785 }
786}
787
Devang Patele54abc92009-07-22 17:43:22 +0000788bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000789 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000790
791 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
792 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000793
Devang Patele54abc92009-07-22 17:43:22 +0000794 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Devang Patele54abc92009-07-22 17:43:22 +0000796 // Read all the records.
797 while (1) {
798 unsigned Code = Stream.ReadCode();
799 if (Code == bitc::END_BLOCK) {
800 if (Stream.ReadBlockEnd())
801 return Error("Error at end of PARAMATTR block");
802 return false;
803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000804
Devang Patele54abc92009-07-22 17:43:22 +0000805 if (Code == bitc::ENTER_SUBBLOCK) {
806 // No known subblocks, always skip them.
807 Stream.ReadSubBlockID();
808 if (Stream.SkipBlock())
809 return Error("Malformed block record");
810 continue;
811 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000812
Devang Patele54abc92009-07-22 17:43:22 +0000813 if (Code == bitc::DEFINE_ABBREV) {
814 Stream.ReadAbbrevRecord();
815 continue;
816 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000817
Victor Hernandez24e64df2010-01-10 07:14:18 +0000818 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000819 // Read a record.
820 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000821 Code = Stream.ReadRecord(Code, Record);
822 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000823 default: // Default behavior: ignore.
824 break;
Devang Patelaa993142009-07-29 22:34:41 +0000825 case bitc::METADATA_NAME: {
826 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000827 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000828 Record.clear();
829 Code = Stream.ReadCode();
830
Chris Lattner9d61dd92011-06-17 17:50:30 +0000831 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000832 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000833 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000834
835 // Read named metadata elements.
836 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000837 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000838 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000839 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
840 if (MD == 0)
841 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000842 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000843 }
Devang Patelaa993142009-07-29 22:34:41 +0000844 break;
845 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000846 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000847 IsFunctionLocal = true;
848 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000849 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000850 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000851 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000852
Devang Patel104cf9e2009-07-23 01:07:34 +0000853 unsigned Size = Record.size();
854 SmallVector<Value*, 8> Elts;
855 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000856 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000857 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000858 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000859 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000860 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000861 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
862 else
863 Elts.push_back(NULL);
864 }
Jay Foadec9186b2011-04-21 19:59:31 +0000865 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000866 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000867 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000868 break;
869 }
Devang Patele54abc92009-07-22 17:43:22 +0000870 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000871 SmallString<8> String(Record.begin(), Record.end());
872 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000873 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000874 break;
875 }
Devang Patele8e02132009-09-18 19:26:43 +0000876 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000877 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000878 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000879
Devang Patela2148402009-09-28 21:14:55 +0000880 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000881 SmallString<8> Name(Record.begin()+1, Record.end());
882
Chris Lattner08113472009-12-29 09:01:33 +0000883 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000884 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
885 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000886 break;
887 }
Devang Patele54abc92009-07-22 17:43:22 +0000888 }
889 }
890}
891
Chris Lattner0eef0802007-04-24 04:04:35 +0000892/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
893/// the LSB for dense VBR encoding.
894static uint64_t DecodeSignRotatedValue(uint64_t V) {
895 if ((V & 1) == 0)
896 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000897 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000898 return -(V >> 1);
899 // There is no such thing as -0 with integers. "-0" really means MININT.
900 return 1ULL << 63;
901}
902
Chris Lattner07d98b42007-04-26 02:46:40 +0000903/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
904/// values and aliases that we can.
905bool BitcodeReader::ResolveGlobalAndAliasInits() {
906 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
907 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000908
Chris Lattner07d98b42007-04-26 02:46:40 +0000909 GlobalInitWorklist.swap(GlobalInits);
910 AliasInitWorklist.swap(AliasInits);
911
912 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000913 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000914 if (ValID >= ValueList.size()) {
915 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000916 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000917 } else {
918 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
919 GlobalInitWorklist.back().first->setInitializer(C);
920 else
921 return Error("Global variable initializer is not a constant!");
922 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000923 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000924 }
925
926 while (!AliasInitWorklist.empty()) {
927 unsigned ValID = AliasInitWorklist.back().second;
928 if (ValID >= ValueList.size()) {
929 AliasInits.push_back(AliasInitWorklist.back());
930 } else {
931 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000932 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000933 else
934 return Error("Alias initializer is not a constant!");
935 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000936 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000937 }
938 return false;
939}
940
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000941static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
942 SmallVector<uint64_t, 8> Words(Vals.size());
943 std::transform(Vals.begin(), Vals.end(), Words.begin(),
944 DecodeSignRotatedValue);
945
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000946 return APInt(TypeBits, Words);
947}
948
Chris Lattner86697142007-05-01 05:01:34 +0000949bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000950 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000951 return Error("Malformed block record");
952
953 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000954
Chris Lattnere16504e2007-04-24 03:30:34 +0000955 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000956 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000957 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000958 while (1) {
959 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000960 if (Code == bitc::END_BLOCK)
961 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000962
Chris Lattnere16504e2007-04-24 03:30:34 +0000963 if (Code == bitc::ENTER_SUBBLOCK) {
964 // No known subblocks, always skip them.
965 Stream.ReadSubBlockID();
966 if (Stream.SkipBlock())
967 return Error("Malformed block record");
968 continue;
969 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000970
Chris Lattnere16504e2007-04-24 03:30:34 +0000971 if (Code == bitc::DEFINE_ABBREV) {
972 Stream.ReadAbbrevRecord();
973 continue;
974 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000975
Chris Lattnere16504e2007-04-24 03:30:34 +0000976 // Read a record.
977 Record.clear();
978 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000979 unsigned BitCode = Stream.ReadRecord(Code, Record);
980 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000981 default: // Default behavior: unknown constant
982 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000983 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000984 break;
985 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
986 if (Record.empty())
987 return Error("Malformed CST_SETTYPE record");
988 if (Record[0] >= TypeList.size())
989 return Error("Invalid Type ID in CST_SETTYPE record");
990 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000991 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000992 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000993 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 break;
995 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000996 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000997 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +0000998 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000999 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001000 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001001 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001002 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001003
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001004 APInt VInt = ReadWideAPInt(Record,
1005 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001006 V = ConstantInt::get(Context, VInt);
1007
Chris Lattner0eef0802007-04-24 04:04:35 +00001008 break;
1009 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001010 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001011 if (Record.empty())
1012 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001013 if (CurTy->isHalfTy())
1014 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1015 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001016 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001017 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001018 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001019 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001020 // Bits are not stored the same way as a normal i80 APInt, compensate.
1021 uint64_t Rearrange[2];
1022 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1023 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001024 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001025 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001026 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001027 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001028 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001029 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001030 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001031 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001032 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001033
Chris Lattner15e6d172007-05-04 19:11:41 +00001034 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1035 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001036 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001037
Chris Lattner15e6d172007-05-04 19:11:41 +00001038 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001039 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001040
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001041 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001042 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001043 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001044 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001045 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001046 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1047 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001048 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001049 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001050 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001051 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1052 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001053 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001054 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001055 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001056 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001057 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001058 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001059 break;
1060 }
Chris Lattner2237f842012-02-05 02:41:35 +00001061 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001062 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1063 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001064 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001065
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001066 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001067 V = ConstantDataArray::getString(Context, Elts,
1068 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001069 break;
1070 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001071 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1072 if (Record.empty())
1073 return Error("Invalid CST_DATA record");
1074
1075 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1076 unsigned Size = Record.size();
1077
1078 if (EltTy->isIntegerTy(8)) {
1079 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1080 if (isa<VectorType>(CurTy))
1081 V = ConstantDataVector::get(Context, Elts);
1082 else
1083 V = ConstantDataArray::get(Context, Elts);
1084 } else if (EltTy->isIntegerTy(16)) {
1085 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1086 if (isa<VectorType>(CurTy))
1087 V = ConstantDataVector::get(Context, Elts);
1088 else
1089 V = ConstantDataArray::get(Context, Elts);
1090 } else if (EltTy->isIntegerTy(32)) {
1091 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1092 if (isa<VectorType>(CurTy))
1093 V = ConstantDataVector::get(Context, Elts);
1094 else
1095 V = ConstantDataArray::get(Context, Elts);
1096 } else if (EltTy->isIntegerTy(64)) {
1097 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1098 if (isa<VectorType>(CurTy))
1099 V = ConstantDataVector::get(Context, Elts);
1100 else
1101 V = ConstantDataArray::get(Context, Elts);
1102 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001103 SmallVector<float, 16> Elts(Size);
1104 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001105 if (isa<VectorType>(CurTy))
1106 V = ConstantDataVector::get(Context, Elts);
1107 else
1108 V = ConstantDataArray::get(Context, Elts);
1109 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001110 SmallVector<double, 16> Elts(Size);
1111 std::transform(Record.begin(), Record.end(), Elts.begin(),
1112 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001113 if (isa<VectorType>(CurTy))
1114 V = ConstantDataVector::get(Context, Elts);
1115 else
1116 V = ConstantDataArray::get(Context, Elts);
1117 } else {
1118 return Error("Unknown element type in CE_DATA");
1119 }
1120 break;
1121 }
1122
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001123 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1124 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1125 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001126 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001127 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001128 } else {
1129 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1130 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001131 unsigned Flags = 0;
1132 if (Record.size() >= 4) {
1133 if (Opc == Instruction::Add ||
1134 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001135 Opc == Instruction::Mul ||
1136 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001137 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1138 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1139 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1140 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001141 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001142 Opc == Instruction::UDiv ||
1143 Opc == Instruction::LShr ||
1144 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001145 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001146 Flags |= SDivOperator::IsExact;
1147 }
1148 }
1149 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001150 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001151 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001152 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1154 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1155 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001156 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001157 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001159 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001160 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001161 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001162 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001163 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001164 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001165 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001166 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001167 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001168 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001170 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001171 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001172 if (!ElTy) return Error("Invalid CE_GEP record");
1173 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1174 }
Jay Foaddab3d292011-07-21 14:31:17 +00001175 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001176 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1177 BitCode ==
1178 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001179 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001180 }
1181 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1182 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001183 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001184 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001185 ValueList.getConstantFwdRef(Record[1],CurTy),
1186 ValueList.getConstantFwdRef(Record[2],CurTy));
1187 break;
1188 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1189 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001190 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001191 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1192 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1193 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001194 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001195 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001196 break;
1197 }
1198 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001199 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001200 if (Record.size() < 3 || OpTy == 0)
1201 return Error("Invalid CE_INSERTELT record");
1202 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1203 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1204 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001205 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001206 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001207 break;
1208 }
1209 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001210 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001211 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001212 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001213 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1214 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001215 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001216 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001217 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001218 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001219 break;
1220 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001221 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001222 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1223 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001224 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001225 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1226 return Error("Invalid CE_SHUFVEC_EX record");
1227 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1228 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001229 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001230 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001231 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001232 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001233 break;
1234 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001235 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1236 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001237 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001238 if (OpTy == 0) return Error("Invalid CE_CMP record");
1239 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1240 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1241
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001242 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001243 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001244 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001245 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001246 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001247 }
Chad Rosierf16ae582012-09-05 00:56:20 +00001248 // This maintains backward compatibility, pre-'nsdialect'.
Chad Rosier27b25c22012-09-05 06:28:52 +00001249 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001250 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001251 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1252 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001253 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001254 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001255 unsigned AsmStrSize = Record[1];
1256 if (2+AsmStrSize >= Record.size())
1257 return Error("Invalid INLINEASM record");
1258 unsigned ConstStrSize = Record[2+AsmStrSize];
1259 if (3+AsmStrSize+ConstStrSize > Record.size())
1260 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001261
Chris Lattner2bce93a2007-05-06 01:58:20 +00001262 for (unsigned i = 0; i != AsmStrSize; ++i)
1263 AsmStr += (char)Record[2+i];
1264 for (unsigned i = 0; i != ConstStrSize; ++i)
1265 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001266 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001267 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001268 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001269 break;
1270 }
Chad Rosierf16ae582012-09-05 00:56:20 +00001271 // This version adds support for the 'nsdialect' keyword.
1272 case bitc::CST_CODE_INLINEASM: {
1273 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1274 std::string AsmStr, ConstrStr;
1275 bool HasSideEffects = Record[0] & 1;
1276 bool IsAlignStack = (Record[0] >> 1) & 1;
1277 unsigned AsmDialect = Record[0] >> 2;
1278 unsigned AsmStrSize = Record[1];
1279 if (2+AsmStrSize >= Record.size())
1280 return Error("Invalid INLINEASM record");
1281 unsigned ConstStrSize = Record[2+AsmStrSize];
1282 if (3+AsmStrSize+ConstStrSize > Record.size())
1283 return Error("Invalid INLINEASM record");
1284
1285 for (unsigned i = 0; i != AsmStrSize; ++i)
1286 AsmStr += (char)Record[2+i];
1287 for (unsigned i = 0; i != ConstStrSize; ++i)
1288 ConstrStr += (char)Record[3+AsmStrSize+i];
1289 PointerType *PTy = cast<PointerType>(CurTy);
1290 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1291 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1292 AsmDialect);
1293 break;
1294 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001295 case bitc::CST_CODE_BLOCKADDRESS:{
1296 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001297 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001298 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1299 Function *Fn =
1300 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1301 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1302
1303 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1304 Type::getInt8Ty(Context),
1305 false, GlobalValue::InternalLinkage,
1306 0, "");
1307 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1308 V = FwdRef;
1309 break;
1310 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001312
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001313 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001314 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001316
Chris Lattnerea693df2008-08-21 02:34:16 +00001317 if (NextCstNo != ValueList.size())
1318 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001319
Chris Lattnerea693df2008-08-21 02:34:16 +00001320 if (Stream.ReadBlockEnd())
1321 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322
Chris Lattnerea693df2008-08-21 02:34:16 +00001323 // Once all the constants have been read, go through and resolve forward
1324 // references.
1325 ValueList.ResolveConstantForwardRefs();
1326 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001327}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001328
Chad Rosiercbbb0962011-12-07 21:44:12 +00001329bool BitcodeReader::ParseUseLists() {
1330 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1331 return Error("Malformed block record");
1332
1333 SmallVector<uint64_t, 64> Record;
1334
1335 // Read all the records.
1336 while (1) {
1337 unsigned Code = Stream.ReadCode();
1338 if (Code == bitc::END_BLOCK) {
1339 if (Stream.ReadBlockEnd())
1340 return Error("Error at end of use-list table block");
1341 return false;
1342 }
1343
1344 if (Code == bitc::ENTER_SUBBLOCK) {
1345 // No known subblocks, always skip them.
1346 Stream.ReadSubBlockID();
1347 if (Stream.SkipBlock())
1348 return Error("Malformed block record");
1349 continue;
1350 }
1351
1352 if (Code == bitc::DEFINE_ABBREV) {
1353 Stream.ReadAbbrevRecord();
1354 continue;
1355 }
1356
1357 // Read a use list record.
1358 Record.clear();
1359 switch (Stream.ReadRecord(Code, Record)) {
1360 default: // Default behavior: unknown type.
1361 break;
1362 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1363 unsigned RecordLength = Record.size();
1364 if (RecordLength < 1)
1365 return Error ("Invalid UseList reader!");
1366 UseListRecords.push_back(Record);
1367 break;
1368 }
1369 }
1370 }
1371}
1372
Chris Lattner980e5aa2007-05-01 05:52:21 +00001373/// RememberAndSkipFunctionBody - When we see the block for a function body,
1374/// remember where it is and then skip it. This lets us lazily deserialize the
1375/// functions.
1376bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001377 // Get the function we are talking about.
1378 if (FunctionsWithBodies.empty())
1379 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001380
Chris Lattner48f84872007-05-01 04:59:48 +00001381 Function *Fn = FunctionsWithBodies.back();
1382 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001383
Chris Lattner48f84872007-05-01 04:59:48 +00001384 // Save the current stream state.
1385 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001386 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387
Chris Lattner48f84872007-05-01 04:59:48 +00001388 // Skip over the function block for now.
1389 if (Stream.SkipBlock())
1390 return Error("Malformed block record");
1391 return false;
1392}
1393
Derek Schuff2ea93872012-02-06 22:30:29 +00001394bool BitcodeReader::GlobalCleanup() {
1395 // Patch the initializers for globals and aliases up.
1396 ResolveGlobalAndAliasInits();
1397 if (!GlobalInits.empty() || !AliasInits.empty())
1398 return Error("Malformed global initializer set");
1399
1400 // Look for intrinsic functions which need to be upgraded at some point
1401 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1402 FI != FE; ++FI) {
1403 Function *NewFn;
1404 if (UpgradeIntrinsicFunction(FI, NewFn))
1405 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1406 }
1407
1408 // Look for global variables which need to be renamed.
1409 for (Module::global_iterator
1410 GI = TheModule->global_begin(), GE = TheModule->global_end();
1411 GI != GE; ++GI)
1412 UpgradeGlobalVariable(GI);
1413 // Force deallocation of memory for these vectors to favor the client that
1414 // want lazy deserialization.
1415 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1416 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1417 return false;
1418}
1419
1420bool BitcodeReader::ParseModule(bool Resume) {
1421 if (Resume)
1422 Stream.JumpToBit(NextUnreadBit);
1423 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001424 return Error("Malformed block record");
1425
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001426 SmallVector<uint64_t, 64> Record;
1427 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001428 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001429
1430 // Read all the records for this module.
1431 while (!Stream.AtEndOfStream()) {
1432 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001433 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001434 if (Stream.ReadBlockEnd())
1435 return Error("Error at end of module block");
1436
Derek Schuff2ea93872012-02-06 22:30:29 +00001437 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001438 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001439
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001440 if (Code == bitc::ENTER_SUBBLOCK) {
1441 switch (Stream.ReadSubBlockID()) {
1442 default: // Skip unknown content.
1443 if (Stream.SkipBlock())
1444 return Error("Malformed block record");
1445 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001446 case bitc::BLOCKINFO_BLOCK_ID:
1447 if (Stream.ReadBlockInfoBlock())
1448 return Error("Malformed BlockInfoBlock");
1449 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001450 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001451 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001452 return true;
1453 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001454 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001455 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456 return true;
1457 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001458 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001459 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001460 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001461 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001462 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001463 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001464 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001465 return true;
1466 break;
Devang Patele54abc92009-07-22 17:43:22 +00001467 case bitc::METADATA_BLOCK_ID:
1468 if (ParseMetadata())
1469 return true;
1470 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001471 case bitc::FUNCTION_BLOCK_ID:
1472 // If this is the first function body we've seen, reverse the
1473 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001474 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001475 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001476 if (GlobalCleanup())
1477 return true;
1478 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001479 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001480
Chris Lattner980e5aa2007-05-01 05:52:21 +00001481 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001482 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001483 // For streaming bitcode, suspend parsing when we reach the function
1484 // bodies. Subsequent materialization calls will resume it when
1485 // necessary. For streaming, the function bodies must be at the end of
1486 // the bitcode. If the bitcode file is old, the symbol table will be
1487 // at the end instead and will not have been seen yet. In this case,
1488 // just finish the parse now.
1489 if (LazyStreamer && SeenValueSymbolTable) {
1490 NextUnreadBit = Stream.GetCurrentBitNo();
1491 return false;
1492 }
Chris Lattner48f84872007-05-01 04:59:48 +00001493 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001494 case bitc::USELIST_BLOCK_ID:
1495 if (ParseUseLists())
1496 return true;
1497 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001498 }
1499 continue;
1500 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001501
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001502 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001503 Stream.ReadAbbrevRecord();
1504 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001505 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001506
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001507 // Read a record.
1508 switch (Stream.ReadRecord(Code, Record)) {
1509 default: break; // Default behavior, ignore unknown content.
1510 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1511 if (Record.size() < 1)
1512 return Error("Malformed MODULE_CODE_VERSION");
1513 // Only version #0 is supported so far.
1514 if (Record[0] != 0)
1515 return Error("Unknown bitstream version!");
1516 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001517 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001518 std::string S;
1519 if (ConvertToString(Record, 0, S))
1520 return Error("Invalid MODULE_CODE_TRIPLE record");
1521 TheModule->setTargetTriple(S);
1522 break;
1523 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001524 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001525 std::string S;
1526 if (ConvertToString(Record, 0, S))
1527 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1528 TheModule->setDataLayout(S);
1529 break;
1530 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001531 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001532 std::string S;
1533 if (ConvertToString(Record, 0, S))
1534 return Error("Invalid MODULE_CODE_ASM record");
1535 TheModule->setModuleInlineAsm(S);
1536 break;
1537 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001538 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001539 std::string S;
1540 if (ConvertToString(Record, 0, S))
1541 return Error("Invalid MODULE_CODE_DEPLIB record");
1542 TheModule->addLibrary(S);
1543 break;
1544 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001545 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001546 std::string S;
1547 if (ConvertToString(Record, 0, S))
1548 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1549 SectionTable.push_back(S);
1550 break;
1551 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001552 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001553 std::string S;
1554 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001555 return Error("Invalid MODULE_CODE_GCNAME record");
1556 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001557 break;
1558 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001559 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001560 // linkage, alignment, section, visibility, threadlocal,
1561 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001562 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001563 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001564 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001565 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001566 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001567 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001568 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001569 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001570 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001571
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001572 bool isConstant = Record[1];
1573 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1574 unsigned Alignment = (1 << Record[4]) >> 1;
1575 std::string Section;
1576 if (Record[5]) {
1577 if (Record[5]-1 >= SectionTable.size())
1578 return Error("Invalid section ID");
1579 Section = SectionTable[Record[5]-1];
1580 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001581 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001582 if (Record.size() > 6)
1583 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001584
1585 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001586 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001587 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001588
Rafael Espindolabea46262011-01-08 16:42:36 +00001589 bool UnnamedAddr = false;
1590 if (Record.size() > 8)
1591 UnnamedAddr = Record[8];
1592
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001593 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001594 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001595 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001596 NewGV->setAlignment(Alignment);
1597 if (!Section.empty())
1598 NewGV->setSection(Section);
1599 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001600 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001601
Chris Lattner0b2482a2007-04-23 21:26:05 +00001602 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001603
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001604 // Remember which value to use for the global initializer.
1605 if (unsigned InitID = Record[2])
1606 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001607 break;
1608 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001609 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001610 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001611 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001612 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001613 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001614 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001615 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001616 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001617 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001618 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001619 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1620 if (!FTy)
1621 return Error("Function not a pointer to function type!");
1622
Gabor Greif051a9502008-04-06 20:25:17 +00001623 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1624 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001625
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001626 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001627 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001628 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001629 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001630
Chris Lattnera9bb7132007-05-08 05:38:01 +00001631 Func->setAlignment((1 << Record[5]) >> 1);
1632 if (Record[6]) {
1633 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001634 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001635 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001636 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001637 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001638 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001639 if (Record[8]-1 > GCTable.size())
1640 return Error("Invalid GC ID");
1641 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001642 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001643 bool UnnamedAddr = false;
1644 if (Record.size() > 9)
1645 UnnamedAddr = Record[9];
1646 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001647 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001648
Chris Lattner48f84872007-05-01 04:59:48 +00001649 // If this is a function with a body, remember the prototype we are
1650 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001651 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001652 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001653 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1654 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001655 break;
1656 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001657 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001658 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001659 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001660 if (Record.size() < 3)
1661 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001662 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001663 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001664 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001665 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001666
Chris Lattner07d98b42007-04-26 02:46:40 +00001667 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1668 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001669 // Old bitcode files didn't have visibility field.
1670 if (Record.size() > 3)
1671 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001672 ValueList.push_back(NewGA);
1673 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1674 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001675 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001676 /// MODULE_CODE_PURGEVALS: [numvals]
1677 case bitc::MODULE_CODE_PURGEVALS:
1678 // Trim down the value list to the specified size.
1679 if (Record.size() < 1 || Record[0] > ValueList.size())
1680 return Error("Invalid MODULE_PURGEVALS record");
1681 ValueList.shrinkTo(Record[0]);
1682 break;
1683 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001684 Record.clear();
1685 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001686
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001687 return Error("Premature end of bitstream");
1688}
1689
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001690bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001691 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001692
Derek Schuff2ea93872012-02-06 22:30:29 +00001693 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001694
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001695 // Sniff for the signature.
1696 if (Stream.Read(8) != 'B' ||
1697 Stream.Read(8) != 'C' ||
1698 Stream.Read(4) != 0x0 ||
1699 Stream.Read(4) != 0xC ||
1700 Stream.Read(4) != 0xE ||
1701 Stream.Read(4) != 0xD)
1702 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001703
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001704 // We expect a number of well-defined blocks, though we don't necessarily
1705 // need to understand them all.
1706 while (!Stream.AtEndOfStream()) {
1707 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Rafael Espindolac9687b32011-05-26 18:59:54 +00001709 if (Code != bitc::ENTER_SUBBLOCK) {
1710
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001711 // The ranlib in xcode 4 will align archive members by appending newlines
1712 // to the end of them. If this file size is a multiple of 4 but not 8, we
1713 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001714 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1715 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001716 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001717 return false;
1718
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001719 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001720 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001721
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001722 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001723
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001724 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001725 switch (BlockID) {
1726 case bitc::BLOCKINFO_BLOCK_ID:
1727 if (Stream.ReadBlockInfoBlock())
1728 return Error("Malformed BlockInfoBlock");
1729 break;
1730 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001731 // Reject multiple MODULE_BLOCK's in a single bitstream.
1732 if (TheModule)
1733 return Error("Multiple MODULE_BLOCKs in same stream");
1734 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001735 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001736 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001737 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001738 break;
1739 default:
1740 if (Stream.SkipBlock())
1741 return Error("Malformed block record");
1742 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001743 }
1744 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001745
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001746 return false;
1747}
Chris Lattnerc453f762007-04-29 07:54:31 +00001748
Bill Wendling34711742010-10-06 01:22:42 +00001749bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1750 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1751 return Error("Malformed block record");
1752
1753 SmallVector<uint64_t, 64> Record;
1754
1755 // Read all the records for this module.
1756 while (!Stream.AtEndOfStream()) {
1757 unsigned Code = Stream.ReadCode();
1758 if (Code == bitc::END_BLOCK) {
1759 if (Stream.ReadBlockEnd())
1760 return Error("Error at end of module block");
1761
1762 return false;
1763 }
1764
1765 if (Code == bitc::ENTER_SUBBLOCK) {
1766 switch (Stream.ReadSubBlockID()) {
1767 default: // Skip unknown content.
1768 if (Stream.SkipBlock())
1769 return Error("Malformed block record");
1770 break;
1771 }
1772 continue;
1773 }
1774
1775 if (Code == bitc::DEFINE_ABBREV) {
1776 Stream.ReadAbbrevRecord();
1777 continue;
1778 }
1779
1780 // Read a record.
1781 switch (Stream.ReadRecord(Code, Record)) {
1782 default: break; // Default behavior, ignore unknown content.
1783 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1784 if (Record.size() < 1)
1785 return Error("Malformed MODULE_CODE_VERSION");
1786 // Only version #0 is supported so far.
1787 if (Record[0] != 0)
1788 return Error("Unknown bitstream version!");
1789 break;
1790 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1791 std::string S;
1792 if (ConvertToString(Record, 0, S))
1793 return Error("Invalid MODULE_CODE_TRIPLE record");
1794 Triple = S;
1795 break;
1796 }
1797 }
1798 Record.clear();
1799 }
1800
1801 return Error("Premature end of bitstream");
1802}
1803
1804bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001805 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001806
1807 // Sniff for the signature.
1808 if (Stream.Read(8) != 'B' ||
1809 Stream.Read(8) != 'C' ||
1810 Stream.Read(4) != 0x0 ||
1811 Stream.Read(4) != 0xC ||
1812 Stream.Read(4) != 0xE ||
1813 Stream.Read(4) != 0xD)
1814 return Error("Invalid bitcode signature");
1815
1816 // We expect a number of well-defined blocks, though we don't necessarily
1817 // need to understand them all.
1818 while (!Stream.AtEndOfStream()) {
1819 unsigned Code = Stream.ReadCode();
1820
1821 if (Code != bitc::ENTER_SUBBLOCK)
1822 return Error("Invalid record at top-level");
1823
1824 unsigned BlockID = Stream.ReadSubBlockID();
1825
1826 // We only know the MODULE subblock ID.
1827 switch (BlockID) {
1828 case bitc::MODULE_BLOCK_ID:
1829 if (ParseModuleTriple(Triple))
1830 return true;
1831 break;
1832 default:
1833 if (Stream.SkipBlock())
1834 return Error("Malformed block record");
1835 break;
1836 }
1837 }
1838
1839 return false;
1840}
1841
Devang Patele8e02132009-09-18 19:26:43 +00001842/// ParseMetadataAttachment - Parse metadata attachments.
1843bool BitcodeReader::ParseMetadataAttachment() {
1844 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1845 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001846
Devang Patele8e02132009-09-18 19:26:43 +00001847 SmallVector<uint64_t, 64> Record;
1848 while(1) {
1849 unsigned Code = Stream.ReadCode();
1850 if (Code == bitc::END_BLOCK) {
1851 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001853 break;
1854 }
1855 if (Code == bitc::DEFINE_ABBREV) {
1856 Stream.ReadAbbrevRecord();
1857 continue;
1858 }
1859 // Read a metadata attachment record.
1860 Record.clear();
1861 switch (Stream.ReadRecord(Code, Record)) {
1862 default: // Default behavior: ignore.
1863 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001864 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001865 unsigned RecordLength = Record.size();
1866 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001867 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001868 Instruction *Inst = InstructionList[Record[0]];
1869 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001870 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001871 DenseMap<unsigned, unsigned>::iterator I =
1872 MDKindMap.find(Kind);
1873 if (I == MDKindMap.end())
1874 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001875 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001876 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001877 }
1878 break;
1879 }
1880 }
1881 }
1882 return false;
1883}
Chris Lattner48f84872007-05-01 04:59:48 +00001884
Chris Lattner980e5aa2007-05-01 05:52:21 +00001885/// ParseFunctionBody - Lazily parse the specified function body block.
1886bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001887 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001888 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001889
Nick Lewycky9a49f152010-02-25 08:30:17 +00001890 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001891 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001892 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001893
Chris Lattner980e5aa2007-05-01 05:52:21 +00001894 // Add all the function arguments to the value table.
1895 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1896 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001898 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001899 BasicBlock *CurBB = 0;
1900 unsigned CurBBNo = 0;
1901
Chris Lattnera6245242010-04-03 02:17:50 +00001902 DebugLoc LastLoc;
1903
Chris Lattner980e5aa2007-05-01 05:52:21 +00001904 // Read all the records.
1905 SmallVector<uint64_t, 64> Record;
1906 while (1) {
1907 unsigned Code = Stream.ReadCode();
1908 if (Code == bitc::END_BLOCK) {
1909 if (Stream.ReadBlockEnd())
1910 return Error("Error at end of function block");
1911 break;
1912 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913
Chris Lattner980e5aa2007-05-01 05:52:21 +00001914 if (Code == bitc::ENTER_SUBBLOCK) {
1915 switch (Stream.ReadSubBlockID()) {
1916 default: // Skip unknown content.
1917 if (Stream.SkipBlock())
1918 return Error("Malformed block record");
1919 break;
1920 case bitc::CONSTANTS_BLOCK_ID:
1921 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001922 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001923 break;
1924 case bitc::VALUE_SYMTAB_BLOCK_ID:
1925 if (ParseValueSymbolTable()) return true;
1926 break;
Devang Patele8e02132009-09-18 19:26:43 +00001927 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001928 if (ParseMetadataAttachment()) return true;
1929 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001930 case bitc::METADATA_BLOCK_ID:
1931 if (ParseMetadata()) return true;
1932 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001933 }
1934 continue;
1935 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001936
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 if (Code == bitc::DEFINE_ABBREV) {
1938 Stream.ReadAbbrevRecord();
1939 continue;
1940 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001941
Chris Lattner980e5aa2007-05-01 05:52:21 +00001942 // Read a record.
1943 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001944 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001945 unsigned BitCode = Stream.ReadRecord(Code, Record);
1946 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001947 default: // Default behavior: reject
1948 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001949 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001950 if (Record.size() < 1 || Record[0] == 0)
1951 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001952 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001953 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001954 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001955 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001956 CurBB = FunctionBBs[0];
1957 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001958
1959 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1960 // This record indicates that the last instruction is at the same
1961 // location as the previous instruction with a location.
1962 I = 0;
1963
1964 // Get the last instruction emitted.
1965 if (CurBB && !CurBB->empty())
1966 I = &CurBB->back();
1967 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1968 !FunctionBBs[CurBBNo-1]->empty())
1969 I = &FunctionBBs[CurBBNo-1]->back();
1970
1971 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1972 I->setDebugLoc(LastLoc);
1973 I = 0;
1974 continue;
1975
Chris Lattner4f6bab92011-06-17 18:17:37 +00001976 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001977 I = 0; // Get the last instruction emitted.
1978 if (CurBB && !CurBB->empty())
1979 I = &CurBB->back();
1980 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1981 !FunctionBBs[CurBBNo-1]->empty())
1982 I = &FunctionBBs[CurBBNo-1]->back();
1983 if (I == 0 || Record.size() < 4)
1984 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1985
1986 unsigned Line = Record[0], Col = Record[1];
1987 unsigned ScopeID = Record[2], IAID = Record[3];
1988
1989 MDNode *Scope = 0, *IA = 0;
1990 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1991 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1992 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1993 I->setDebugLoc(LastLoc);
1994 I = 0;
1995 continue;
1996 }
1997
Chris Lattnerabfbf852007-05-06 00:21:25 +00001998 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1999 unsigned OpNum = 0;
2000 Value *LHS, *RHS;
2001 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2002 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002003 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002004 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002005
Dan Gohman1224c382009-07-20 21:19:07 +00002006 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002007 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002008 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002009 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002010 if (OpNum < Record.size()) {
2011 if (Opc == Instruction::Add ||
2012 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002013 Opc == Instruction::Mul ||
2014 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002015 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002016 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002017 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002018 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002019 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002020 Opc == Instruction::UDiv ||
2021 Opc == Instruction::LShr ||
2022 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002023 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002024 cast<BinaryOperator>(I)->setIsExact(true);
2025 }
2026 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002027 break;
2028 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002029 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2030 unsigned OpNum = 0;
2031 Value *Op;
2032 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2033 OpNum+2 != Record.size())
2034 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002035
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002036 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002037 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2038 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002039 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002041 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002042 break;
2043 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002044 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002045 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002046 unsigned OpNum = 0;
2047 Value *BasePtr;
2048 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002049 return Error("Invalid GEP record");
2050
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002051 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002052 while (OpNum != Record.size()) {
2053 Value *Op;
2054 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002055 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002056 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002057 }
2058
Jay Foada9203102011-07-25 09:48:08 +00002059 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002060 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002061 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002062 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002063 break;
2064 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002065
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002066 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2067 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002068 unsigned OpNum = 0;
2069 Value *Agg;
2070 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2071 return Error("Invalid EXTRACTVAL record");
2072
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002073 SmallVector<unsigned, 4> EXTRACTVALIdx;
2074 for (unsigned RecSize = Record.size();
2075 OpNum != RecSize; ++OpNum) {
2076 uint64_t Index = Record[OpNum];
2077 if ((unsigned)Index != Index)
2078 return Error("Invalid EXTRACTVAL index");
2079 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002080 }
2081
Jay Foadfc6d3a42011-07-13 10:26:04 +00002082 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002083 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002084 break;
2085 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002086
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002087 case bitc::FUNC_CODE_INST_INSERTVAL: {
2088 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002089 unsigned OpNum = 0;
2090 Value *Agg;
2091 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2092 return Error("Invalid INSERTVAL record");
2093 Value *Val;
2094 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2095 return Error("Invalid INSERTVAL record");
2096
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002097 SmallVector<unsigned, 4> INSERTVALIdx;
2098 for (unsigned RecSize = Record.size();
2099 OpNum != RecSize; ++OpNum) {
2100 uint64_t Index = Record[OpNum];
2101 if ((unsigned)Index != Index)
2102 return Error("Invalid INSERTVAL index");
2103 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002104 }
2105
Jay Foadfc6d3a42011-07-13 10:26:04 +00002106 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002107 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002108 break;
2109 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Chris Lattnerabfbf852007-05-06 00:21:25 +00002111 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002112 // obsolete form of select
2113 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002114 unsigned OpNum = 0;
2115 Value *TrueVal, *FalseVal, *Cond;
2116 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2117 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002118 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002119 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002120
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002121 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002122 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002123 break;
2124 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002126 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2127 // new form of select
2128 // handles select i1 or select [N x i1]
2129 unsigned OpNum = 0;
2130 Value *TrueVal, *FalseVal, *Cond;
2131 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2132 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2133 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2134 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002135
2136 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002137 if (VectorType* vector_type =
2138 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002139 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002141 return Error("Invalid SELECT condition type");
2142 } else {
2143 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002144 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002145 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002146 }
2147
Gabor Greif051a9502008-04-06 20:25:17 +00002148 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002149 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002150 break;
2151 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002152
Chris Lattner01ff65f2007-05-02 05:16:49 +00002153 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002154 unsigned OpNum = 0;
2155 Value *Vec, *Idx;
2156 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002157 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002158 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002159 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002160 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002161 break;
2162 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163
Chris Lattner01ff65f2007-05-02 05:16:49 +00002164 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002165 unsigned OpNum = 0;
2166 Value *Vec, *Elt, *Idx;
2167 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002168 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002169 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002170 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002171 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002172 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002173 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002174 break;
2175 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002176
Chris Lattnerabfbf852007-05-06 00:21:25 +00002177 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2178 unsigned OpNum = 0;
2179 Value *Vec1, *Vec2, *Mask;
2180 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2181 getValue(Record, OpNum, Vec1->getType(), Vec2))
2182 return Error("Invalid SHUFFLEVEC record");
2183
Mon P Wangaeb06d22008-11-10 04:46:22 +00002184 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002185 return Error("Invalid SHUFFLEVEC record");
2186 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002187 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002188 break;
2189 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002190
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002191 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2192 // Old form of ICmp/FCmp returning bool
2193 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2194 // both legal on vectors but had different behaviour.
2195 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2196 // FCmp/ICmp returning bool or vector of bool
2197
Chris Lattner7337ab92007-05-06 00:00:00 +00002198 unsigned OpNum = 0;
2199 Value *LHS, *RHS;
2200 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2201 getValue(Record, OpNum, LHS->getType(), RHS) ||
2202 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002203 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002204
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002205 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002206 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002207 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002208 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002209 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002210 break;
2211 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002212
Chris Lattner231cbcb2007-05-02 04:27:25 +00002213 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002214 {
2215 unsigned Size = Record.size();
2216 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002217 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002218 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002219 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002220 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002221
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002222 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002223 Value *Op = NULL;
2224 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2225 return Error("Invalid RET record");
2226 if (OpNum != Record.size())
2227 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002228
Chris Lattner96a74c52011-06-17 18:09:11 +00002229 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002230 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002231 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002232 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002233 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002234 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002235 return Error("Invalid BR record");
2236 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2237 if (TrueDest == 0)
2238 return Error("Invalid BR record");
2239
Devang Patele8e02132009-09-18 19:26:43 +00002240 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002241 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002242 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002243 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002244 else {
2245 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002246 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002247 if (FalseDest == 0 || Cond == 0)
2248 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002249 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002250 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002251 }
2252 break;
2253 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002254 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002255 // Check magic
2256 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2257 // New SwitchInst format with case ranges.
2258
2259 Type *OpTy = getTypeByID(Record[1]);
2260 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2261
2262 Value *Cond = getFnValueByID(Record[2], OpTy);
2263 BasicBlock *Default = getBasicBlock(Record[3]);
2264 if (OpTy == 0 || Cond == 0 || Default == 0)
2265 return Error("Invalid SWITCH record");
2266
2267 unsigned NumCases = Record[4];
2268
2269 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2270 InstructionList.push_back(SI);
2271
2272 unsigned CurIdx = 5;
2273 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002274 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002275 unsigned NumItems = Record[CurIdx++];
2276 for (unsigned ci = 0; ci != NumItems; ++ci) {
2277 bool isSingleNumber = Record[CurIdx++];
2278
2279 APInt Low;
2280 unsigned ActiveWords = 1;
2281 if (ValueBitWidth > 64)
2282 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002283 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2284 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002285 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002286
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002287 if (!isSingleNumber) {
2288 ActiveWords = 1;
2289 if (ValueBitWidth > 64)
2290 ActiveWords = Record[CurIdx++];
2291 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002292 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2293 ValueBitWidth);
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002294
2295 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2296 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002297 CurIdx += ActiveWords;
2298 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002299 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002300 }
2301 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002302 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002303 SI->addCase(Case, DestBB);
2304 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002305 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002306 if (Hash != (Record[0] & 0xFFFF))
2307 return Error("Invalid SWITCH record");
2308 I = SI;
2309 break;
2310 }
2311
2312 // Old SwitchInst format without case ranges.
2313
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002314 if (Record.size() < 3 || (Record.size() & 1) == 0)
2315 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002316 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002317 Value *Cond = getFnValueByID(Record[1], OpTy);
2318 BasicBlock *Default = getBasicBlock(Record[2]);
2319 if (OpTy == 0 || Cond == 0 || Default == 0)
2320 return Error("Invalid SWITCH record");
2321 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002322 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002323 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002324 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002325 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002326 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2327 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2328 if (CaseVal == 0 || DestBB == 0) {
2329 delete SI;
2330 return Error("Invalid SWITCH record!");
2331 }
2332 SI->addCase(CaseVal, DestBB);
2333 }
2334 I = SI;
2335 break;
2336 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002337 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002338 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002339 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002340 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002341 Value *Address = getFnValueByID(Record[1], OpTy);
2342 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002343 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002344 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002345 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002346 InstructionList.push_back(IBI);
2347 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2348 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2349 IBI->addDestination(DestBB);
2350 } else {
2351 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002352 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002353 }
2354 }
2355 I = IBI;
2356 break;
2357 }
2358
Duncan Sandsdc024672007-11-27 13:23:08 +00002359 case bitc::FUNC_CODE_INST_INVOKE: {
2360 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002361 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002362 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002363 unsigned CCInfo = Record[1];
2364 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2365 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002366
Chris Lattnera9bb7132007-05-08 05:38:01 +00002367 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002368 Value *Callee;
2369 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002370 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002371
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002372 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2373 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002374 dyn_cast<FunctionType>(CalleeTy->getElementType());
2375
2376 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002377 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2378 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002379 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002380
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002381 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002382 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2383 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2384 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002385 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002386
Chris Lattner7337ab92007-05-06 00:00:00 +00002387 if (!FTy->isVarArg()) {
2388 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002389 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002390 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002391 // Read type/value pairs for varargs params.
2392 while (OpNum != Record.size()) {
2393 Value *Op;
2394 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2395 return Error("Invalid INVOKE record");
2396 Ops.push_back(Op);
2397 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002398 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002399
Jay Foada3efbb12011-07-15 08:37:34 +00002400 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002401 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002402 cast<InvokeInst>(I)->setCallingConv(
2403 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002404 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002405 break;
2406 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002407 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2408 unsigned Idx = 0;
2409 Value *Val = 0;
2410 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2411 return Error("Invalid RESUME record");
2412 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002413 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002414 break;
2415 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002416 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002417 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002418 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002419 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002420 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002421 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002422 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002423 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002424 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002425
Jay Foad3ecfc862011-03-30 11:28:46 +00002426 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002427 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002428
Chris Lattner15e6d172007-05-04 19:11:41 +00002429 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2430 Value *V = getFnValueByID(Record[1+i], Ty);
2431 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002432 if (!V || !BB) return Error("Invalid PHI record");
2433 PN->addIncoming(V, BB);
2434 }
2435 I = PN;
2436 break;
2437 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002438
Bill Wendlinge6e88262011-08-12 20:24:12 +00002439 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2440 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2441 unsigned Idx = 0;
2442 if (Record.size() < 4)
2443 return Error("Invalid LANDINGPAD record");
2444 Type *Ty = getTypeByID(Record[Idx++]);
2445 if (!Ty) return Error("Invalid LANDINGPAD record");
2446 Value *PersFn = 0;
2447 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2448 return Error("Invalid LANDINGPAD record");
2449
2450 bool IsCleanup = !!Record[Idx++];
2451 unsigned NumClauses = Record[Idx++];
2452 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2453 LP->setCleanup(IsCleanup);
2454 for (unsigned J = 0; J != NumClauses; ++J) {
2455 LandingPadInst::ClauseType CT =
2456 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2457 Value *Val;
2458
2459 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2460 delete LP;
2461 return Error("Invalid LANDINGPAD record");
2462 }
2463
2464 assert((CT != LandingPadInst::Catch ||
2465 !isa<ArrayType>(Val->getType())) &&
2466 "Catch clause has a invalid type!");
2467 assert((CT != LandingPadInst::Filter ||
2468 isa<ArrayType>(Val->getType())) &&
2469 "Filter clause has invalid type!");
2470 LP->addClause(Val);
2471 }
2472
2473 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002474 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002475 break;
2476 }
2477
Chris Lattner96a74c52011-06-17 18:09:11 +00002478 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2479 if (Record.size() != 4)
2480 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002481 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002482 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002483 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002484 Value *Size = getFnValueByID(Record[2], OpTy);
2485 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002486 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002487 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002488 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002489 break;
2490 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002491 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002492 unsigned OpNum = 0;
2493 Value *Op;
2494 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2495 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002496 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002497
Chris Lattner7337ab92007-05-06 00:00:00 +00002498 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002499 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002500 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002501 }
Eli Friedman21006d42011-08-09 23:02:53 +00002502 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2503 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2504 unsigned OpNum = 0;
2505 Value *Op;
2506 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2507 OpNum+4 != Record.size())
2508 return Error("Invalid LOADATOMIC record");
2509
2510
2511 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2512 if (Ordering == NotAtomic || Ordering == Release ||
2513 Ordering == AcquireRelease)
2514 return Error("Invalid LOADATOMIC record");
2515 if (Ordering != NotAtomic && Record[OpNum] == 0)
2516 return Error("Invalid LOADATOMIC record");
2517 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2518
2519 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2520 Ordering, SynchScope);
2521 InstructionList.push_back(I);
2522 break;
2523 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002524 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002525 unsigned OpNum = 0;
2526 Value *Val, *Ptr;
2527 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002528 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002529 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2530 OpNum+2 != Record.size())
2531 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002532
Christopher Lambfe63fb92007-12-11 08:59:05 +00002533 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002534 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002535 break;
2536 }
Eli Friedman21006d42011-08-09 23:02:53 +00002537 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2538 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2539 unsigned OpNum = 0;
2540 Value *Val, *Ptr;
2541 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2542 getValue(Record, OpNum,
2543 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2544 OpNum+4 != Record.size())
2545 return Error("Invalid STOREATOMIC record");
2546
2547 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002548 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002549 Ordering == AcquireRelease)
2550 return Error("Invalid STOREATOMIC record");
2551 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2552 if (Ordering != NotAtomic && Record[OpNum] == 0)
2553 return Error("Invalid STOREATOMIC record");
2554
2555 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2556 Ordering, SynchScope);
2557 InstructionList.push_back(I);
2558 break;
2559 }
Eli Friedmanff030482011-07-28 21:48:00 +00002560 case bitc::FUNC_CODE_INST_CMPXCHG: {
2561 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2562 unsigned OpNum = 0;
2563 Value *Ptr, *Cmp, *New;
2564 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2565 getValue(Record, OpNum,
2566 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2567 getValue(Record, OpNum,
2568 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2569 OpNum+3 != Record.size())
2570 return Error("Invalid CMPXCHG record");
2571 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002572 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002573 return Error("Invalid CMPXCHG record");
2574 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2575 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2576 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2577 InstructionList.push_back(I);
2578 break;
2579 }
2580 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2581 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2582 unsigned OpNum = 0;
2583 Value *Ptr, *Val;
2584 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2585 getValue(Record, OpNum,
2586 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2587 OpNum+4 != Record.size())
2588 return Error("Invalid ATOMICRMW record");
2589 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2590 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2591 Operation > AtomicRMWInst::LAST_BINOP)
2592 return Error("Invalid ATOMICRMW record");
2593 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002594 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002595 return Error("Invalid ATOMICRMW record");
2596 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2597 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2598 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2599 InstructionList.push_back(I);
2600 break;
2601 }
Eli Friedman47f35132011-07-25 23:16:38 +00002602 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2603 if (2 != Record.size())
2604 return Error("Invalid FENCE record");
2605 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2606 if (Ordering == NotAtomic || Ordering == Unordered ||
2607 Ordering == Monotonic)
2608 return Error("Invalid FENCE record");
2609 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2610 I = new FenceInst(Context, Ordering, SynchScope);
2611 InstructionList.push_back(I);
2612 break;
2613 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002614 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002615 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2616 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002617 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002618
Devang Patel05988662008-09-25 21:00:45 +00002619 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002620 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002621
Chris Lattnera9bb7132007-05-08 05:38:01 +00002622 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002623 Value *Callee;
2624 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2625 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002627 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2628 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002629 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002630 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002631 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002632
Chris Lattner0579f7f2007-05-03 22:04:19 +00002633 SmallVector<Value*, 16> Args;
2634 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002635 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002636 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002637 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002638 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002639 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002640 if (Args.back() == 0) return Error("Invalid CALL record");
2641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002642
Chris Lattner0579f7f2007-05-03 22:04:19 +00002643 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002644 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002645 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002646 return Error("Invalid CALL record");
2647 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002648 while (OpNum != Record.size()) {
2649 Value *Op;
2650 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2651 return Error("Invalid CALL record");
2652 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002653 }
2654 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002655
Jay Foada3efbb12011-07-15 08:37:34 +00002656 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002657 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002658 cast<CallInst>(I)->setCallingConv(
2659 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002660 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002661 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002662 break;
2663 }
2664 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2665 if (Record.size() < 3)
2666 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002667 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002668 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002669 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002670 if (!OpTy || !Op || !ResTy)
2671 return Error("Invalid VAARG record");
2672 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002673 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002674 break;
2675 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002676 }
2677
2678 // Add instruction to end of current BB. If there is no current BB, reject
2679 // this file.
2680 if (CurBB == 0) {
2681 delete I;
2682 return Error("Invalid instruction with no BB");
2683 }
2684 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002685
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002686 // If this was a terminator instruction, move to the next block.
2687 if (isa<TerminatorInst>(I)) {
2688 ++CurBBNo;
2689 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2690 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002691
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002692 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002693 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002694 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002695 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002696
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002697 // Check the function list for unresolved values.
2698 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2699 if (A->getParent() == 0) {
2700 // We found at least one unresolved value. Nuke them all to avoid leaks.
2701 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002702 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002703 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002704 delete A;
2705 }
2706 }
Chris Lattner35a04702007-05-04 03:50:29 +00002707 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002708 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002709 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002710
Dan Gohman064ff3e2010-08-25 20:23:38 +00002711 // FIXME: Check for unresolved forward-declared metadata references
2712 // and clean up leaks.
2713
Chris Lattner50b136d2009-10-28 05:53:48 +00002714 // See if anything took the address of blocks in this function. If so,
2715 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002716 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2717 BlockAddrFwdRefs.find(F);
2718 if (BAFRI != BlockAddrFwdRefs.end()) {
2719 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2720 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2721 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002722 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002723 return Error("Invalid blockaddress block #");
2724
2725 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002726 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002727 FwdRef->eraseFromParent();
2728 }
2729
2730 BlockAddrFwdRefs.erase(BAFRI);
2731 }
2732
Chris Lattner980e5aa2007-05-01 05:52:21 +00002733 // Trim the value list down to the size it was before we parsed this function.
2734 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002735 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002736 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002737 return false;
2738}
2739
Derek Schuff2ea93872012-02-06 22:30:29 +00002740/// FindFunctionInStream - Find the function body in the bitcode stream
2741bool BitcodeReader::FindFunctionInStream(Function *F,
2742 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2743 while (DeferredFunctionInfoIterator->second == 0) {
2744 if (Stream.AtEndOfStream())
2745 return Error("Could not find Function in stream");
2746 // ParseModule will parse the next body in the stream and set its
2747 // position in the DeferredFunctionInfo map.
2748 if (ParseModule(true)) return true;
2749 }
2750 return false;
2751}
2752
Chris Lattnerb348bb82007-05-18 04:02:46 +00002753//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002754// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002755//===----------------------------------------------------------------------===//
2756
2757
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002758bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2759 if (const Function *F = dyn_cast<Function>(GV)) {
2760 return F->isDeclaration() &&
2761 DeferredFunctionInfo.count(const_cast<Function*>(F));
2762 }
2763 return false;
2764}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002765
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002766bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2767 Function *F = dyn_cast<Function>(GV);
2768 // If it's not a function or is already material, ignore the request.
2769 if (!F || !F->isMaterializable()) return false;
2770
2771 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002772 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002773 // If its position is recorded as 0, its body is somewhere in the stream
2774 // but we haven't seen it yet.
2775 if (DFII->second == 0)
2776 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002777
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002778 // Move the bit stream to the saved position of the deferred function body.
2779 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002780
Chris Lattnerb348bb82007-05-18 04:02:46 +00002781 if (ParseFunctionBody(F)) {
2782 if (ErrInfo) *ErrInfo = ErrorString;
2783 return true;
2784 }
Chandler Carruth69940402007-08-04 01:51:18 +00002785
2786 // Upgrade any old intrinsic calls in the function.
2787 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2788 E = UpgradedIntrinsics.end(); I != E; ++I) {
2789 if (I->first != I->second) {
2790 for (Value::use_iterator UI = I->first->use_begin(),
2791 UE = I->first->use_end(); UI != UE; ) {
2792 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2793 UpgradeIntrinsicCall(CI, I->second);
2794 }
2795 }
2796 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerb348bb82007-05-18 04:02:46 +00002798 return false;
2799}
2800
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002801bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2802 const Function *F = dyn_cast<Function>(GV);
2803 if (!F || F->isDeclaration())
2804 return false;
2805 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2806}
2807
2808void BitcodeReader::Dematerialize(GlobalValue *GV) {
2809 Function *F = dyn_cast<Function>(GV);
2810 // If this function isn't dematerializable, this is a noop.
2811 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002812 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002813
Chris Lattnerb348bb82007-05-18 04:02:46 +00002814 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002815
Chris Lattnerb348bb82007-05-18 04:02:46 +00002816 // Just forget the function body, we can remat it later.
2817 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002818}
2819
2820
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002821bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2822 assert(M == TheModule &&
2823 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002824 // Iterate over the module, deserializing any functions that are still on
2825 // disk.
2826 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2827 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002828 if (F->isMaterializable() &&
2829 Materialize(F, ErrInfo))
2830 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002831
Derek Schuff0ffe6982012-02-29 00:07:09 +00002832 // At this point, if there are any function bodies, the current bit is
2833 // pointing to the END_BLOCK record after them. Now make sure the rest
2834 // of the bits in the module have been read.
2835 if (NextUnreadBit)
2836 ParseModule(true);
2837
Daniel Dunbara279bc32009-09-20 02:20:51 +00002838 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2839 // delete the old functions to clean up. We can't do this unless the entire
2840 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002841 // with calls to the old function.
2842 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2843 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2844 if (I->first != I->second) {
2845 for (Value::use_iterator UI = I->first->use_begin(),
2846 UE = I->first->use_end(); UI != UE; ) {
2847 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2848 UpgradeIntrinsicCall(CI, I->second);
2849 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002850 if (!I->first->use_empty())
2851 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002852 I->first->eraseFromParent();
2853 }
2854 }
2855 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002856
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002857 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002858}
2859
Derek Schuff2ea93872012-02-06 22:30:29 +00002860bool BitcodeReader::InitStream() {
2861 if (LazyStreamer) return InitLazyStream();
2862 return InitStreamFromBuffer();
2863}
2864
2865bool BitcodeReader::InitStreamFromBuffer() {
2866 const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2867 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2868
2869 if (Buffer->getBufferSize() & 3) {
2870 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2871 return Error("Invalid bitcode signature");
2872 else
2873 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2874 }
2875
2876 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2877 // The magic number is 0x0B17C0DE stored in little endian.
2878 if (isBitcodeWrapper(BufPtr, BufEnd))
2879 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2880 return Error("Invalid bitcode wrapper header");
2881
2882 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2883 Stream.init(*StreamFile);
2884
2885 return false;
2886}
2887
2888bool BitcodeReader::InitLazyStream() {
2889 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2890 // see it.
2891 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2892 StreamFile.reset(new BitstreamReader(Bytes));
2893 Stream.init(*StreamFile);
2894
2895 unsigned char buf[16];
2896 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2897 return Error("Bitcode stream must be at least 16 bytes in length");
2898
2899 if (!isBitcode(buf, buf + 16))
2900 return Error("Invalid bitcode signature");
2901
2902 if (isBitcodeWrapper(buf, buf + 4)) {
2903 const unsigned char *bitcodeStart = buf;
2904 const unsigned char *bitcodeEnd = buf + 16;
2905 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2906 Bytes->dropLeadingBytes(bitcodeStart - buf);
2907 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2908 }
2909 return false;
2910}
Chris Lattner48f84872007-05-01 04:59:48 +00002911
Chris Lattnerc453f762007-04-29 07:54:31 +00002912//===----------------------------------------------------------------------===//
2913// External interface
2914//===----------------------------------------------------------------------===//
2915
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002916/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002917///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002918Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2919 LLVMContext& Context,
2920 std::string *ErrMsg) {
2921 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002922 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002923 M->setMaterializer(R);
2924 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002925 if (ErrMsg)
2926 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002927
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002928 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002929 return 0;
2930 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002931 // Have the BitcodeReader dtor delete 'Buffer'.
2932 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002933
2934 R->materializeForwardReferencedFunctions();
2935
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002936 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002937}
2938
Derek Schuff2ea93872012-02-06 22:30:29 +00002939
2940Module *llvm::getStreamedBitcodeModule(const std::string &name,
2941 DataStreamer *streamer,
2942 LLVMContext &Context,
2943 std::string *ErrMsg) {
2944 Module *M = new Module(name, Context);
2945 BitcodeReader *R = new BitcodeReader(streamer, Context);
2946 M->setMaterializer(R);
2947 if (R->ParseBitcodeInto(M)) {
2948 if (ErrMsg)
2949 *ErrMsg = R->getErrorString();
2950 delete M; // Also deletes R.
2951 return 0;
2952 }
2953 R->setBufferOwned(false); // no buffer to delete
2954 return M;
2955}
2956
Chris Lattnerc453f762007-04-29 07:54:31 +00002957/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2958/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002959Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002960 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002961 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2962 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002963
2964 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2965 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002966 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002967
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002968 // Read in the entire module, and destroy the BitcodeReader.
2969 if (M->MaterializeAllPermanently(ErrMsg)) {
2970 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002971 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002972 }
Bill Wendling34711742010-10-06 01:22:42 +00002973
Chad Rosiercbbb0962011-12-07 21:44:12 +00002974 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2975 // written. We must defer until the Module has been fully materialized.
2976
Chris Lattnerc453f762007-04-29 07:54:31 +00002977 return M;
2978}
Bill Wendling34711742010-10-06 01:22:42 +00002979
2980std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2981 LLVMContext& Context,
2982 std::string *ErrMsg) {
2983 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2984 // Don't let the BitcodeReader dtor delete 'Buffer'.
2985 R->setBufferOwned(false);
2986
2987 std::string Triple("");
2988 if (R->ParseTriple(Triple))
2989 if (ErrMsg)
2990 *ErrMsg = R->getErrorString();
2991
2992 delete R;
2993 return Triple;
2994}