blob: 8860ef065c6aab4cbaab9276b62baf110f5baf69 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Devang Patele4b27562009-08-28 23:24:31 +000019#include "llvm/IntrinsicInst.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Dan Gohman1224c382009-07-20 21:19:07 +000021#include "llvm/Operator.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Devang Patelf4511cd2008-02-26 19:38:17 +000024#include "llvm/ADT/SmallVector.h"
Derek Schuff2ea93872012-02-06 22:30:29 +000025#include "llvm/Support/DataStream.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000027#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000029using namespace llvm;
30
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +000031enum {
32 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
Rafael Espindola47f79bb2012-01-02 07:49:53 +000035void BitcodeReader::materializeForwardReferencedFunctions() {
36 while (!BlockAddrFwdRefs.empty()) {
37 Function *F = BlockAddrFwdRefs.begin()->first;
38 F->Materialize();
39 }
40}
41
Chris Lattnerb348bb82007-05-18 04:02:46 +000042void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000043 if (BufferOwned)
44 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000045 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000046 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000047 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000048 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000049
Devang Patel19c87462008-09-26 22:53:05 +000050 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000051 std::vector<BasicBlock*>().swap(FunctionBBs);
52 std::vector<Function*>().swap(FunctionsWithBodies);
53 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000054 MDKindMap.clear();
Benjamin Kramer122f5e52012-09-21 14:34:31 +000055
56 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
Chris Lattnerc453f762007-04-29 07:54:31 +000057}
58
Chris Lattner48c85b82007-05-04 03:30:17 +000059//===----------------------------------------------------------------------===//
60// Helper functions to implement forward reference resolution, etc.
61//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000062
Chris Lattnercaee0dc2007-04-22 06:23:29 +000063/// ConvertToString - Convert a string from a record into an std::string, return
64/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000065template<typename StrTy>
Benjamin Kramerf52aea82012-05-28 14:10:31 +000066static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000067 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000068 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000069 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000070
Chris Lattner15e6d172007-05-04 19:11:41 +000071 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
72 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000073 return false;
74}
75
76static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77 switch (Val) {
78 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000079 case 0: return GlobalValue::ExternalLinkage;
80 case 1: return GlobalValue::WeakAnyLinkage;
81 case 2: return GlobalValue::AppendingLinkage;
82 case 3: return GlobalValue::InternalLinkage;
83 case 4: return GlobalValue::LinkOnceAnyLinkage;
84 case 5: return GlobalValue::DLLImportLinkage;
85 case 6: return GlobalValue::DLLExportLinkage;
86 case 7: return GlobalValue::ExternalWeakLinkage;
87 case 8: return GlobalValue::CommonLinkage;
88 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000089 case 10: return GlobalValue::WeakODRLinkage;
90 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000091 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000092 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000093 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling32811be2012-08-17 18:33:14 +000094 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000095 }
96}
97
98static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99 switch (Val) {
100 default: // Map unknown visibilities to default.
101 case 0: return GlobalValue::DefaultVisibility;
102 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000103 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000104 }
105}
106
Hans Wennborgce718ff2012-06-23 11:37:03 +0000107static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
108 switch (Val) {
109 case 0: return GlobalVariable::NotThreadLocal;
110 default: // Map unknown non-zero value to general dynamic.
111 case 1: return GlobalVariable::GeneralDynamicTLSModel;
112 case 2: return GlobalVariable::LocalDynamicTLSModel;
113 case 3: return GlobalVariable::InitialExecTLSModel;
114 case 4: return GlobalVariable::LocalExecTLSModel;
115 }
116}
117
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000118static int GetDecodedCastOpcode(unsigned Val) {
119 switch (Val) {
120 default: return -1;
121 case bitc::CAST_TRUNC : return Instruction::Trunc;
122 case bitc::CAST_ZEXT : return Instruction::ZExt;
123 case bitc::CAST_SEXT : return Instruction::SExt;
124 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
125 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
126 case bitc::CAST_UITOFP : return Instruction::UIToFP;
127 case bitc::CAST_SITOFP : return Instruction::SIToFP;
128 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
129 case bitc::CAST_FPEXT : return Instruction::FPExt;
130 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
131 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
132 case bitc::CAST_BITCAST : return Instruction::BitCast;
133 }
134}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000136 switch (Val) {
137 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000138 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000139 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000140 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000141 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000142 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000143 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000144 case bitc::BINOP_UDIV: return Instruction::UDiv;
145 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000146 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000147 case bitc::BINOP_UREM: return Instruction::URem;
148 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000149 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000150 case bitc::BINOP_SHL: return Instruction::Shl;
151 case bitc::BINOP_LSHR: return Instruction::LShr;
152 case bitc::BINOP_ASHR: return Instruction::AShr;
153 case bitc::BINOP_AND: return Instruction::And;
154 case bitc::BINOP_OR: return Instruction::Or;
155 case bitc::BINOP_XOR: return Instruction::Xor;
156 }
157}
158
Eli Friedmanff030482011-07-28 21:48:00 +0000159static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160 switch (Val) {
161 default: return AtomicRMWInst::BAD_BINOP;
162 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
163 case bitc::RMW_ADD: return AtomicRMWInst::Add;
164 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
165 case bitc::RMW_AND: return AtomicRMWInst::And;
166 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
167 case bitc::RMW_OR: return AtomicRMWInst::Or;
168 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
169 case bitc::RMW_MAX: return AtomicRMWInst::Max;
170 case bitc::RMW_MIN: return AtomicRMWInst::Min;
171 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
172 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
173 }
174}
175
Eli Friedman47f35132011-07-25 23:16:38 +0000176static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177 switch (Val) {
178 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
179 case bitc::ORDERING_UNORDERED: return Unordered;
180 case bitc::ORDERING_MONOTONIC: return Monotonic;
181 case bitc::ORDERING_ACQUIRE: return Acquire;
182 case bitc::ORDERING_RELEASE: return Release;
183 case bitc::ORDERING_ACQREL: return AcquireRelease;
184 default: // Map unknown orderings to sequentially-consistent.
185 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
186 }
187}
188
189static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190 switch (Val) {
191 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
192 default: // Map unknown scopes to cross-thread.
193 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
194 }
195}
196
Gabor Greifefe65362008-05-10 08:32:32 +0000197namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000198namespace {
199 /// @brief A class for maintaining the slot number definition
200 /// as a placeholder for the actual definition for forward constants defs.
201 class ConstantPlaceHolder : public ConstantExpr {
Craig Topper86a1c322012-09-15 17:09:36 +0000202 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
Gabor Greif051a9502008-04-06 20:25:17 +0000203 public:
204 // allocate space for exactly one operand
205 void *operator new(size_t s) {
206 return User::operator new(s, 1);
207 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000208 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000209 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000210 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000211 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000212
Chris Lattnerea693df2008-08-21 02:34:16 +0000213 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000214 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000215 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000216 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000217 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
218 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000219
220
Gabor Greifefe65362008-05-10 08:32:32 +0000221 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000222 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000223 };
224}
225
Chris Lattner46e77402009-03-31 22:55:09 +0000226// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000227template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000228struct OperandTraits<ConstantPlaceHolder> :
229 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000230};
Gabor Greifefe65362008-05-10 08:32:32 +0000231}
232
Chris Lattner46e77402009-03-31 22:55:09 +0000233
234void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
235 if (Idx == size()) {
236 push_back(V);
237 return;
238 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000239
Chris Lattner46e77402009-03-31 22:55:09 +0000240 if (Idx >= size())
241 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000242
Chris Lattner46e77402009-03-31 22:55:09 +0000243 WeakVH &OldV = ValuePtrs[Idx];
244 if (OldV == 0) {
245 OldV = V;
246 return;
247 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000248
Chris Lattner46e77402009-03-31 22:55:09 +0000249 // Handle constants and non-constants (e.g. instrs) differently for
250 // efficiency.
251 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
252 ResolveConstants.push_back(std::make_pair(PHC, Idx));
253 OldV = V;
254 } else {
255 // If there was a forward reference to this value, replace it.
256 Value *PrevVal = OldV;
257 OldV->replaceAllUsesWith(V);
258 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000259 }
260}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000261
Gabor Greifefe65362008-05-10 08:32:32 +0000262
Chris Lattner522b7b12007-04-24 05:48:56 +0000263Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000264 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000265 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000266 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000267
Chris Lattner46e77402009-03-31 22:55:09 +0000268 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000269 assert(Ty == V->getType() && "Type mismatch in constant table!");
270 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000271 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000272
273 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000274 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000275 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000276 return C;
277}
278
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000279Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000280 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000281 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000282
Chris Lattner46e77402009-03-31 22:55:09 +0000283 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000284 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
285 return V;
286 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287
Chris Lattner01ff65f2007-05-02 05:16:49 +0000288 // No type specified, must be invalid reference.
289 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000291 // Create and return a placeholder, which will later be RAUW'd.
292 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000293 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000294 return V;
295}
296
Chris Lattnerea693df2008-08-21 02:34:16 +0000297/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
298/// resolves any forward references. The idea behind this is that we sometimes
299/// get constants (such as large arrays) which reference *many* forward ref
300/// constants. Replacing each of these causes a lot of thrashing when
301/// building/reuniquing the constant. Instead of doing this, we look at all the
302/// uses and rewrite all the place holders at once for any constant that uses
303/// a placeholder.
304void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000305 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000306 // binary search.
307 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000308
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000310
Chris Lattnerea693df2008-08-21 02:34:16 +0000311 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000312 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000313 Constant *Placeholder = ResolveConstants.back().first;
314 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000315
Chris Lattnerea693df2008-08-21 02:34:16 +0000316 // Loop over all users of the placeholder, updating them to reference the
317 // new value. If they reference more than one placeholder, update them all
318 // at once.
319 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000320 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000321 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000322
Chris Lattnerea693df2008-08-21 02:34:16 +0000323 // If the using object isn't uniqued, just update the operands. This
324 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000325 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000326 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000327 continue;
328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Chris Lattnerea693df2008-08-21 02:34:16 +0000330 // Otherwise, we have a constant that uses the placeholder. Replace that
331 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000332 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000333 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
334 I != E; ++I) {
335 Value *NewOp;
336 if (!isa<ConstantPlaceHolder>(*I)) {
337 // Not a placeholder reference.
338 NewOp = *I;
339 } else if (*I == Placeholder) {
340 // Common case is that it just references this one placeholder.
341 NewOp = RealVal;
342 } else {
343 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000344 ResolveConstantsTy::iterator It =
345 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000346 std::pair<Constant*, unsigned>(cast<Constant>(*I),
347 0));
348 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000349 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 }
351
352 NewOps.push_back(cast<Constant>(NewOp));
353 }
354
355 // Make the new constant.
356 Constant *NewC;
357 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000358 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000359 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000360 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000361 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000362 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000363 } else {
364 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000365 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000366 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Chris Lattnerea693df2008-08-21 02:34:16 +0000368 UserC->replaceAllUsesWith(NewC);
369 UserC->destroyConstant();
370 NewOps.clear();
371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000372
Nick Lewyckycb337992009-05-10 20:57:05 +0000373 // Update all ValueHandles, they should be the only users at this point.
374 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000375 delete Placeholder;
376 }
377}
378
Devang Pateld5ac4042009-08-04 06:00:18 +0000379void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
380 if (Idx == size()) {
381 push_back(V);
382 return;
383 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000384
Devang Pateld5ac4042009-08-04 06:00:18 +0000385 if (Idx >= size())
386 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000387
Devang Pateld5ac4042009-08-04 06:00:18 +0000388 WeakVH &OldV = MDValuePtrs[Idx];
389 if (OldV == 0) {
390 OldV = V;
391 return;
392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000395 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000397 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000398 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
399 // value for Idx.
400 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000401}
402
403Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
404 if (Idx >= size())
405 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000406
Devang Pateld5ac4042009-08-04 06:00:18 +0000407 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000408 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000409 return V;
410 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000411
Devang Pateld5ac4042009-08-04 06:00:18 +0000412 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000413 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000414 MDValuePtrs[Idx] = V;
415 return V;
416}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000417
Chris Lattner1afcace2011-07-09 17:41:24 +0000418Type *BitcodeReader::getTypeByID(unsigned ID) {
419 // The type table size is always specified correctly.
420 if (ID >= TypeList.size())
421 return 0;
Derek Schufffccf0622012-02-06 19:03:04 +0000422
Chris Lattner1afcace2011-07-09 17:41:24 +0000423 if (Type *Ty = TypeList[ID])
424 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000425
Chris Lattner1afcace2011-07-09 17:41:24 +0000426 // If we have a forward reference, the only possible case is when it is to a
427 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000428 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429}
430
Chris Lattner1afcace2011-07-09 17:41:24 +0000431
Chris Lattner48c85b82007-05-04 03:30:17 +0000432//===----------------------------------------------------------------------===//
433// Functions for parsing blocks from the bitcode file
434//===----------------------------------------------------------------------===//
435
Devang Patel05988662008-09-25 21:00:45 +0000436bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000437 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000439
Devang Patel19c87462008-09-26 22:53:05 +0000440 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000441 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000442
Chris Lattner48c85b82007-05-04 03:30:17 +0000443 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000444
Devang Patel05988662008-09-25 21:00:45 +0000445 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000446
Chris Lattner48c85b82007-05-04 03:30:17 +0000447 // Read all the records.
448 while (1) {
449 unsigned Code = Stream.ReadCode();
450 if (Code == bitc::END_BLOCK) {
451 if (Stream.ReadBlockEnd())
452 return Error("Error at end of PARAMATTR block");
453 return false;
454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000455
Chris Lattner48c85b82007-05-04 03:30:17 +0000456 if (Code == bitc::ENTER_SUBBLOCK) {
457 // No known subblocks, always skip them.
458 Stream.ReadSubBlockID();
459 if (Stream.SkipBlock())
460 return Error("Malformed block record");
461 continue;
462 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000463
Chris Lattner48c85b82007-05-04 03:30:17 +0000464 if (Code == bitc::DEFINE_ABBREV) {
465 Stream.ReadAbbrevRecord();
466 continue;
467 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000468
Chris Lattner48c85b82007-05-04 03:30:17 +0000469 // Read a record.
470 Record.clear();
471 switch (Stream.ReadRecord(Code, Record)) {
472 default: // Default behavior: ignore.
473 break;
474 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
475 if (Record.size() & 1)
476 return Error("Invalid ENTRY record");
477
Chris Lattner48c85b82007-05-04 03:30:17 +0000478 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Meador Ingee99f8be2012-05-28 15:45:43 +0000479 Attributes ReconstitutedAttr =
Bill Wendling2039a8f2012-09-25 20:57:48 +0000480 Attributes::decodeLLVMAttributesForBitcode(Record[i+1]);
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000481 Record[i+1] = ReconstitutedAttr.Raw();
Chris Lattner48c85b82007-05-04 03:30:17 +0000482 }
Chris Lattner461edd92008-03-12 02:25:52 +0000483
Devang Patel19c87462008-09-26 22:53:05 +0000484 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling47a33952012-10-04 07:19:46 +0000485 if (Attributes(Record[i+1]).hasAttributes())
Kostya Serebryany164b86b2012-01-20 17:56:17 +0000486 Attrs.push_back(AttributeWithIndex::get(Record[i],
487 Attributes(Record[i+1])));
Devang Patel19c87462008-09-26 22:53:05 +0000488 }
Devang Patel19c87462008-09-26 22:53:05 +0000489
Chris Lattnerd509d0b2012-05-28 01:47:44 +0000490 MAttributes.push_back(AttrListPtr::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000491 Attrs.clear();
492 break;
493 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000494 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000495 }
496}
497
Chris Lattner86697142007-05-01 05:01:34 +0000498bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000499 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000500 return Error("Malformed block record");
Derek Schufffccf0622012-02-06 19:03:04 +0000501
Chris Lattner1afcace2011-07-09 17:41:24 +0000502 return ParseTypeTableBody();
503}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000504
Chris Lattner1afcace2011-07-09 17:41:24 +0000505bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000506 if (!TypeList.empty())
507 return Error("Multiple TYPE_BLOCKs found!");
508
509 SmallVector<uint64_t, 64> Record;
510 unsigned NumRecords = 0;
511
Chris Lattner1afcace2011-07-09 17:41:24 +0000512 SmallString<64> TypeName;
Derek Schufffccf0622012-02-06 19:03:04 +0000513
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000514 // Read all the records for this type table.
515 while (1) {
516 unsigned Code = Stream.ReadCode();
517 if (Code == bitc::END_BLOCK) {
518 if (NumRecords != TypeList.size())
519 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000520 if (Stream.ReadBlockEnd())
521 return Error("Error at end of type table block");
522 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000523 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000524
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000525 if (Code == bitc::ENTER_SUBBLOCK) {
526 // No known subblocks, always skip them.
527 Stream.ReadSubBlockID();
528 if (Stream.SkipBlock())
529 return Error("Malformed block record");
530 continue;
531 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000532
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000533 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000534 Stream.ReadAbbrevRecord();
535 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000537
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000538 // Read a record.
539 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000540 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000541 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000542 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000543 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
544 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
545 // type list. This allows us to reserve space.
546 if (Record.size() < 1)
547 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000548 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000549 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000550 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000551 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000552 break;
Dan Gohmance163392011-12-17 00:04:22 +0000553 case bitc::TYPE_CODE_HALF: // HALF
554 ResultTy = Type::getHalfTy(Context);
555 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000556 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 break;
559 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000561 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000562 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000564 break;
565 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000567 break;
568 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000569 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000570 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000572 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000573 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000574 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000575 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000576 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000577 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
578 ResultTy = Type::getX86_MMXTy(Context);
579 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
581 if (Record.size() < 1)
582 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000583
Owen Anderson1d0be152009-08-13 21:58:54 +0000584 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000585 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000586 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000587 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000588 if (Record.size() < 1)
589 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000590 unsigned AddressSpace = 0;
591 if (Record.size() == 2)
592 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000593 ResultTy = getTypeByID(Record[0]);
594 if (ResultTy == 0) return Error("invalid element type in pointer type");
595 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000596 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000597 }
Nuno Lopesee8100d2012-05-23 15:19:39 +0000598 case bitc::TYPE_CODE_FUNCTION_OLD: {
599 // FIXME: attrid is dead, remove it in LLVM 4.0
600 // FUNCTION: [vararg, attrid, retty, paramty x N]
601 if (Record.size() < 3)
602 return Error("Invalid FUNCTION type record");
603 SmallVector<Type*, 8> ArgTys;
604 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
605 if (Type *T = getTypeByID(Record[i]))
606 ArgTys.push_back(T);
607 else
608 break;
609 }
610
611 ResultTy = getTypeByID(Record[2]);
612 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
613 return Error("invalid type in function type");
614
615 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
616 break;
617 }
Chad Rosiercde54642011-11-03 00:14:01 +0000618 case bitc::TYPE_CODE_FUNCTION: {
619 // FUNCTION: [vararg, retty, paramty x N]
620 if (Record.size() < 2)
621 return Error("Invalid FUNCTION type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000622 SmallVector<Type*, 8> ArgTys;
Chad Rosiercde54642011-11-03 00:14:01 +0000623 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
624 if (Type *T = getTypeByID(Record[i]))
625 ArgTys.push_back(T);
626 else
627 break;
628 }
629
630 ResultTy = getTypeByID(Record[1]);
631 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
632 return Error("invalid type in function type");
633
634 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
635 break;
636 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000638 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000639 return Error("Invalid STRUCT type record");
Chris Lattnerd629efa2012-01-27 03:15:49 +0000640 SmallVector<Type*, 8> EltTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000641 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
642 if (Type *T = getTypeByID(Record[i]))
643 EltTys.push_back(T);
644 else
645 break;
646 }
647 if (EltTys.size() != Record.size()-1)
648 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000649 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000650 break;
651 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000652 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
653 if (ConvertToString(Record, 0, TypeName))
654 return Error("Invalid STRUCT_NAME record");
655 continue;
656
657 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
658 if (Record.size() < 1)
659 return Error("Invalid STRUCT type record");
660
661 if (NumRecords >= TypeList.size())
662 return Error("invalid TYPE table");
663
664 // Check to see if this was forward referenced, if so fill in the temp.
665 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
666 if (Res) {
667 Res->setName(TypeName);
668 TypeList[NumRecords] = 0;
669 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000670 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000671 TypeName.clear();
672
673 SmallVector<Type*, 8> EltTys;
674 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
675 if (Type *T = getTypeByID(Record[i]))
676 EltTys.push_back(T);
677 else
678 break;
679 }
680 if (EltTys.size() != Record.size()-1)
681 return Error("invalid STRUCT type record");
682 Res->setBody(EltTys, Record[0]);
683 ResultTy = Res;
684 break;
685 }
686 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
687 if (Record.size() != 1)
688 return Error("Invalid OPAQUE type record");
689
690 if (NumRecords >= TypeList.size())
691 return Error("invalid TYPE table");
692
693 // Check to see if this was forward referenced, if so fill in the temp.
694 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
695 if (Res) {
696 Res->setName(TypeName);
697 TypeList[NumRecords] = 0;
698 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000699 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000700 TypeName.clear();
701 ResultTy = Res;
702 break;
703 }
704 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
705 if (Record.size() < 2)
706 return Error("Invalid ARRAY type record");
707 if ((ResultTy = getTypeByID(Record[1])))
708 ResultTy = ArrayType::get(ResultTy, Record[0]);
709 else
710 return Error("Invalid ARRAY type element");
711 break;
712 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
713 if (Record.size() < 2)
714 return Error("Invalid VECTOR type record");
715 if ((ResultTy = getTypeByID(Record[1])))
716 ResultTy = VectorType::get(ResultTy, Record[0]);
717 else
718 return Error("Invalid ARRAY type element");
719 break;
720 }
721
722 if (NumRecords >= TypeList.size())
723 return Error("invalid TYPE table");
724 assert(ResultTy && "Didn't read a type?");
725 assert(TypeList[NumRecords] == 0 && "Already read type?");
726 TypeList[NumRecords++] = ResultTy;
727 }
728}
729
Chris Lattner86697142007-05-01 05:01:34 +0000730bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000731 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000732 return Error("Malformed block record");
733
734 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000735
Chris Lattner0b2482a2007-04-23 21:26:05 +0000736 // Read all the records for this value table.
737 SmallString<128> ValueName;
738 while (1) {
739 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000740 if (Code == bitc::END_BLOCK) {
741 if (Stream.ReadBlockEnd())
742 return Error("Error at end of value symbol table block");
743 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000744 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000745 if (Code == bitc::ENTER_SUBBLOCK) {
746 // No known subblocks, always skip them.
747 Stream.ReadSubBlockID();
748 if (Stream.SkipBlock())
749 return Error("Malformed block record");
750 continue;
751 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000752
Chris Lattner0b2482a2007-04-23 21:26:05 +0000753 if (Code == bitc::DEFINE_ABBREV) {
754 Stream.ReadAbbrevRecord();
755 continue;
756 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattner0b2482a2007-04-23 21:26:05 +0000758 // Read a record.
759 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000760 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000761 default: // Default behavior: unknown type.
762 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000763 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000764 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000765 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000766 unsigned ValueID = Record[0];
767 if (ValueID >= ValueList.size())
768 return Error("Invalid Value ID in VST_ENTRY record");
769 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000770
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000771 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000772 ValueName.clear();
773 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000774 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000775 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000776 if (ConvertToString(Record, 1, ValueName))
777 return Error("Invalid VST_BBENTRY record");
778 BasicBlock *BB = getBasicBlock(Record[0]);
779 if (BB == 0)
780 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000781
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000782 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000783 ValueName.clear();
784 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000785 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000786 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000787 }
788}
789
Devang Patele54abc92009-07-22 17:43:22 +0000790bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000791 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000792
793 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
794 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000795
Devang Patele54abc92009-07-22 17:43:22 +0000796 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000797
Devang Patele54abc92009-07-22 17:43:22 +0000798 // Read all the records.
799 while (1) {
800 unsigned Code = Stream.ReadCode();
801 if (Code == bitc::END_BLOCK) {
802 if (Stream.ReadBlockEnd())
803 return Error("Error at end of PARAMATTR block");
804 return false;
805 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000806
Devang Patele54abc92009-07-22 17:43:22 +0000807 if (Code == bitc::ENTER_SUBBLOCK) {
808 // No known subblocks, always skip them.
809 Stream.ReadSubBlockID();
810 if (Stream.SkipBlock())
811 return Error("Malformed block record");
812 continue;
813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000814
Devang Patele54abc92009-07-22 17:43:22 +0000815 if (Code == bitc::DEFINE_ABBREV) {
816 Stream.ReadAbbrevRecord();
817 continue;
818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Victor Hernandez24e64df2010-01-10 07:14:18 +0000820 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000821 // Read a record.
822 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000823 Code = Stream.ReadRecord(Code, Record);
824 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000825 default: // Default behavior: ignore.
826 break;
Devang Patelaa993142009-07-29 22:34:41 +0000827 case bitc::METADATA_NAME: {
828 // Read named of the named metadata.
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000829 SmallString<8> Name(Record.begin(), Record.end());
Devang Patelaa993142009-07-29 22:34:41 +0000830 Record.clear();
831 Code = Stream.ReadCode();
832
Chris Lattner9d61dd92011-06-17 17:50:30 +0000833 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000834 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000835 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000836
837 // Read named metadata elements.
838 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000839 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000840 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000841 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
842 if (MD == 0)
843 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000844 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000845 }
Devang Patelaa993142009-07-29 22:34:41 +0000846 break;
847 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000848 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000849 IsFunctionLocal = true;
850 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000851 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000852 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000853 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000854
Devang Patel104cf9e2009-07-23 01:07:34 +0000855 unsigned Size = Record.size();
856 SmallVector<Value*, 8> Elts;
857 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000858 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000859 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000860 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000861 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000862 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000863 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
864 else
865 Elts.push_back(NULL);
866 }
Jay Foadec9186b2011-04-21 19:59:31 +0000867 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000868 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000869 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000870 break;
871 }
Devang Patele54abc92009-07-22 17:43:22 +0000872 case bitc::METADATA_STRING: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000873 SmallString<8> String(Record.begin(), Record.end());
874 Value *V = MDString::get(Context, String);
Devang Patel23598502010-01-11 18:52:33 +0000875 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000876 break;
877 }
Devang Patele8e02132009-09-18 19:26:43 +0000878 case bitc::METADATA_KIND: {
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000879 if (Record.size() < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880 return Error("Invalid METADATA_KIND record");
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000881
Devang Patela2148402009-09-28 21:14:55 +0000882 unsigned Kind = Record[0];
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000883 SmallString<8> Name(Record.begin()+1, Record.end());
884
Chris Lattner08113472009-12-29 09:01:33 +0000885 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000886 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
887 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000888 break;
889 }
Devang Patele54abc92009-07-22 17:43:22 +0000890 }
891 }
892}
893
Chris Lattner0eef0802007-04-24 04:04:35 +0000894/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
895/// the LSB for dense VBR encoding.
896static uint64_t DecodeSignRotatedValue(uint64_t V) {
897 if ((V & 1) == 0)
898 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000899 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000900 return -(V >> 1);
901 // There is no such thing as -0 with integers. "-0" really means MININT.
902 return 1ULL << 63;
903}
904
Chris Lattner07d98b42007-04-26 02:46:40 +0000905/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
906/// values and aliases that we can.
907bool BitcodeReader::ResolveGlobalAndAliasInits() {
908 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
909 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000910
Chris Lattner07d98b42007-04-26 02:46:40 +0000911 GlobalInitWorklist.swap(GlobalInits);
912 AliasInitWorklist.swap(AliasInits);
913
914 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000915 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000916 if (ValID >= ValueList.size()) {
917 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000918 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000919 } else {
920 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
921 GlobalInitWorklist.back().first->setInitializer(C);
922 else
923 return Error("Global variable initializer is not a constant!");
924 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000925 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000926 }
927
928 while (!AliasInitWorklist.empty()) {
929 unsigned ValID = AliasInitWorklist.back().second;
930 if (ValID >= ValueList.size()) {
931 AliasInits.push_back(AliasInitWorklist.back());
932 } else {
933 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000934 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000935 else
936 return Error("Alias initializer is not a constant!");
937 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000938 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000939 }
940 return false;
941}
942
Benjamin Kramerf52aea82012-05-28 14:10:31 +0000943static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
944 SmallVector<uint64_t, 8> Words(Vals.size());
945 std::transform(Vals.begin(), Vals.end(), Words.begin(),
946 DecodeSignRotatedValue);
947
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +0000948 return APInt(TypeBits, Words);
949}
950
Chris Lattner86697142007-05-01 05:01:34 +0000951bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000952 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000953 return Error("Malformed block record");
954
955 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000956
Chris Lattnere16504e2007-04-24 03:30:34 +0000957 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000958 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000959 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000960 while (1) {
961 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000962 if (Code == bitc::END_BLOCK)
963 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000964
Chris Lattnere16504e2007-04-24 03:30:34 +0000965 if (Code == bitc::ENTER_SUBBLOCK) {
966 // No known subblocks, always skip them.
967 Stream.ReadSubBlockID();
968 if (Stream.SkipBlock())
969 return Error("Malformed block record");
970 continue;
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972
Chris Lattnere16504e2007-04-24 03:30:34 +0000973 if (Code == bitc::DEFINE_ABBREV) {
974 Stream.ReadAbbrevRecord();
975 continue;
976 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000977
Chris Lattnere16504e2007-04-24 03:30:34 +0000978 // Read a record.
979 Record.clear();
980 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +0000981 unsigned BitCode = Stream.ReadRecord(Code, Record);
982 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 default: // Default behavior: unknown constant
984 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000985 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000986 break;
987 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
988 if (Record.empty())
989 return Error("Malformed CST_SETTYPE record");
990 if (Record[0] >= TypeList.size())
991 return Error("Invalid Type ID in CST_SETTYPE record");
992 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000993 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000994 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +0000995 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000996 break;
997 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +0000998 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000999 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001000 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001001 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001002 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001003 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001004 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001005
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001006 APInt VInt = ReadWideAPInt(Record,
1007 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00001008 V = ConstantInt::get(Context, VInt);
1009
Chris Lattner0eef0802007-04-24 04:04:35 +00001010 break;
1011 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001012 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001013 if (Record.empty())
1014 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001015 if (CurTy->isHalfTy())
1016 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1017 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001018 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001019 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001020 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001021 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001022 // Bits are not stored the same way as a normal i80 APInt, compensate.
1023 uint64_t Rearrange[2];
1024 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1025 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001026 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001027 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001028 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001029 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001030 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001031 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001032 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001033 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001034 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001035
Chris Lattner15e6d172007-05-04 19:11:41 +00001036 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1037 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001038 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001039
Chris Lattner15e6d172007-05-04 19:11:41 +00001040 unsigned Size = Record.size();
Chris Lattnerd629efa2012-01-27 03:15:49 +00001041 SmallVector<Constant*, 16> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001042
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001043 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001044 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001045 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001046 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001047 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1049 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001050 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001051 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001052 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1054 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001055 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001056 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001057 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001058 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001059 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001060 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001061 break;
1062 }
Chris Lattner2237f842012-02-05 02:41:35 +00001063 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001064 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1065 if (Record.empty())
Chris Lattner2237f842012-02-05 02:41:35 +00001066 return Error("Invalid CST_STRING record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001067
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001068 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattner2237f842012-02-05 02:41:35 +00001069 V = ConstantDataArray::getString(Context, Elts,
1070 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001071 break;
1072 }
Chris Lattnerd408f062012-01-30 00:51:16 +00001073 case bitc::CST_CODE_DATA: {// DATA: [n x value]
1074 if (Record.empty())
1075 return Error("Invalid CST_DATA record");
1076
1077 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1078 unsigned Size = Record.size();
1079
1080 if (EltTy->isIntegerTy(8)) {
1081 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1082 if (isa<VectorType>(CurTy))
1083 V = ConstantDataVector::get(Context, Elts);
1084 else
1085 V = ConstantDataArray::get(Context, Elts);
1086 } else if (EltTy->isIntegerTy(16)) {
1087 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1088 if (isa<VectorType>(CurTy))
1089 V = ConstantDataVector::get(Context, Elts);
1090 else
1091 V = ConstantDataArray::get(Context, Elts);
1092 } else if (EltTy->isIntegerTy(32)) {
1093 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1094 if (isa<VectorType>(CurTy))
1095 V = ConstantDataVector::get(Context, Elts);
1096 else
1097 V = ConstantDataArray::get(Context, Elts);
1098 } else if (EltTy->isIntegerTy(64)) {
1099 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1100 if (isa<VectorType>(CurTy))
1101 V = ConstantDataVector::get(Context, Elts);
1102 else
1103 V = ConstantDataArray::get(Context, Elts);
1104 } else if (EltTy->isFloatTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001105 SmallVector<float, 16> Elts(Size);
1106 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattnerd408f062012-01-30 00:51:16 +00001107 if (isa<VectorType>(CurTy))
1108 V = ConstantDataVector::get(Context, Elts);
1109 else
1110 V = ConstantDataArray::get(Context, Elts);
1111 } else if (EltTy->isDoubleTy()) {
Benjamin Kramerf52aea82012-05-28 14:10:31 +00001112 SmallVector<double, 16> Elts(Size);
1113 std::transform(Record.begin(), Record.end(), Elts.begin(),
1114 BitsToDouble);
Chris Lattnerd408f062012-01-30 00:51:16 +00001115 if (isa<VectorType>(CurTy))
1116 V = ConstantDataVector::get(Context, Elts);
1117 else
1118 V = ConstantDataArray::get(Context, Elts);
1119 } else {
1120 return Error("Unknown element type in CE_DATA");
1121 }
1122 break;
1123 }
1124
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001125 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1126 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1127 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001128 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001129 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001130 } else {
1131 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1132 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001133 unsigned Flags = 0;
1134 if (Record.size() >= 4) {
1135 if (Opc == Instruction::Add ||
1136 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001137 Opc == Instruction::Mul ||
1138 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001139 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1140 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1141 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1142 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001143 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001144 Opc == Instruction::UDiv ||
1145 Opc == Instruction::LShr ||
1146 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001147 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001148 Flags |= SDivOperator::IsExact;
1149 }
1150 }
1151 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001152 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001153 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001154 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001155 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1156 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1157 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001158 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001159 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001160 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001161 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001162 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001163 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001164 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001165 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001166 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001167 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001168 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001169 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001170 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001171 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001172 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001173 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001174 if (!ElTy) return Error("Invalid CE_GEP record");
1175 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1176 }
Jay Foaddab3d292011-07-21 14:31:17 +00001177 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001178 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1179 BitCode ==
1180 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001181 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001182 }
1183 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1184 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001185 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001186 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001187 ValueList.getConstantFwdRef(Record[1],CurTy),
1188 ValueList.getConstantFwdRef(Record[2],CurTy));
1189 break;
1190 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1191 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001192 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001193 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1194 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1195 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001196 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001197 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001198 break;
1199 }
1200 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001201 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001202 if (Record.size() < 3 || OpTy == 0)
1203 return Error("Invalid CE_INSERTELT record");
1204 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1205 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1206 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001207 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001208 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001209 break;
1210 }
1211 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001212 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001213 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001214 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001215 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1216 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001217 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001218 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001219 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001220 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001221 break;
1222 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001223 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001224 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1225 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001226 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001227 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1228 return Error("Invalid CE_SHUFVEC_EX record");
1229 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1230 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001231 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001232 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001233 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001234 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001235 break;
1236 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001237 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1238 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001239 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001240 if (OpTy == 0) return Error("Invalid CE_CMP record");
1241 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1242 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1243
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001244 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001245 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001246 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001247 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001248 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001249 }
Chad Rosier581600b2012-09-05 19:00:49 +00001250 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier27b25c22012-09-05 06:28:52 +00001251 // FIXME: Remove with the 4.0 release.
Chad Rosierf16ae582012-09-05 00:56:20 +00001252 case bitc::CST_CODE_INLINEASM_OLD: {
Chris Lattner2bce93a2007-05-06 01:58:20 +00001253 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1254 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001255 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001256 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001257 unsigned AsmStrSize = Record[1];
1258 if (2+AsmStrSize >= Record.size())
1259 return Error("Invalid INLINEASM record");
1260 unsigned ConstStrSize = Record[2+AsmStrSize];
1261 if (3+AsmStrSize+ConstStrSize > Record.size())
1262 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001263
Chris Lattner2bce93a2007-05-06 01:58:20 +00001264 for (unsigned i = 0; i != AsmStrSize; ++i)
1265 AsmStr += (char)Record[2+i];
1266 for (unsigned i = 0; i != ConstStrSize; ++i)
1267 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001269 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001270 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001271 break;
1272 }
Chad Rosier581600b2012-09-05 19:00:49 +00001273 // This version adds support for the asm dialect keywords (e.g.,
1274 // inteldialect).
Chad Rosierf16ae582012-09-05 00:56:20 +00001275 case bitc::CST_CODE_INLINEASM: {
1276 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1277 std::string AsmStr, ConstrStr;
1278 bool HasSideEffects = Record[0] & 1;
1279 bool IsAlignStack = (Record[0] >> 1) & 1;
1280 unsigned AsmDialect = Record[0] >> 2;
1281 unsigned AsmStrSize = Record[1];
1282 if (2+AsmStrSize >= Record.size())
1283 return Error("Invalid INLINEASM record");
1284 unsigned ConstStrSize = Record[2+AsmStrSize];
1285 if (3+AsmStrSize+ConstStrSize > Record.size())
1286 return Error("Invalid INLINEASM record");
1287
1288 for (unsigned i = 0; i != AsmStrSize; ++i)
1289 AsmStr += (char)Record[2+i];
1290 for (unsigned i = 0; i != ConstStrSize; ++i)
1291 ConstrStr += (char)Record[3+AsmStrSize+i];
1292 PointerType *PTy = cast<PointerType>(CurTy);
1293 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1294 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosier581600b2012-09-05 19:00:49 +00001295 InlineAsm::AsmDialect(AsmDialect));
Chad Rosierf16ae582012-09-05 00:56:20 +00001296 break;
1297 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001298 case bitc::CST_CODE_BLOCKADDRESS:{
1299 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001300 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001301 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1302 Function *Fn =
1303 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1304 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001305
1306 // If the function is already parsed we can insert the block address right
1307 // away.
1308 if (!Fn->empty()) {
1309 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1310 for (size_t I = 0, E = Record[2]; I != E; ++I) {
1311 if (BBI == BBE)
1312 return Error("Invalid blockaddress block #");
1313 ++BBI;
1314 }
1315 V = BlockAddress::get(Fn, BBI);
1316 } else {
1317 // Otherwise insert a placeholder and remember it so it can be inserted
1318 // when the function is parsed.
1319 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1320 Type::getInt8Ty(Context),
Chris Lattner50b136d2009-10-28 05:53:48 +00001321 false, GlobalValue::InternalLinkage,
Benjamin Kramer122f5e52012-09-21 14:34:31 +00001322 0, "");
1323 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1324 V = FwdRef;
1325 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001326 break;
1327 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001328 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001329
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001330 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001331 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001332 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001333
Chris Lattnerea693df2008-08-21 02:34:16 +00001334 if (NextCstNo != ValueList.size())
1335 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001336
Chris Lattnerea693df2008-08-21 02:34:16 +00001337 if (Stream.ReadBlockEnd())
1338 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001339
Chris Lattnerea693df2008-08-21 02:34:16 +00001340 // Once all the constants have been read, go through and resolve forward
1341 // references.
1342 ValueList.ResolveConstantForwardRefs();
1343 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001344}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001345
Chad Rosiercbbb0962011-12-07 21:44:12 +00001346bool BitcodeReader::ParseUseLists() {
1347 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1348 return Error("Malformed block record");
1349
1350 SmallVector<uint64_t, 64> Record;
1351
1352 // Read all the records.
1353 while (1) {
1354 unsigned Code = Stream.ReadCode();
1355 if (Code == bitc::END_BLOCK) {
1356 if (Stream.ReadBlockEnd())
1357 return Error("Error at end of use-list table block");
1358 return false;
1359 }
1360
1361 if (Code == bitc::ENTER_SUBBLOCK) {
1362 // No known subblocks, always skip them.
1363 Stream.ReadSubBlockID();
1364 if (Stream.SkipBlock())
1365 return Error("Malformed block record");
1366 continue;
1367 }
1368
1369 if (Code == bitc::DEFINE_ABBREV) {
1370 Stream.ReadAbbrevRecord();
1371 continue;
1372 }
1373
1374 // Read a use list record.
1375 Record.clear();
1376 switch (Stream.ReadRecord(Code, Record)) {
1377 default: // Default behavior: unknown type.
1378 break;
1379 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1380 unsigned RecordLength = Record.size();
1381 if (RecordLength < 1)
1382 return Error ("Invalid UseList reader!");
1383 UseListRecords.push_back(Record);
1384 break;
1385 }
1386 }
1387 }
1388}
1389
Chris Lattner980e5aa2007-05-01 05:52:21 +00001390/// RememberAndSkipFunctionBody - When we see the block for a function body,
1391/// remember where it is and then skip it. This lets us lazily deserialize the
1392/// functions.
1393bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001394 // Get the function we are talking about.
1395 if (FunctionsWithBodies.empty())
1396 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001397
Chris Lattner48f84872007-05-01 04:59:48 +00001398 Function *Fn = FunctionsWithBodies.back();
1399 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001400
Chris Lattner48f84872007-05-01 04:59:48 +00001401 // Save the current stream state.
1402 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001403 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001404
Chris Lattner48f84872007-05-01 04:59:48 +00001405 // Skip over the function block for now.
1406 if (Stream.SkipBlock())
1407 return Error("Malformed block record");
1408 return false;
1409}
1410
Derek Schuff2ea93872012-02-06 22:30:29 +00001411bool BitcodeReader::GlobalCleanup() {
1412 // Patch the initializers for globals and aliases up.
1413 ResolveGlobalAndAliasInits();
1414 if (!GlobalInits.empty() || !AliasInits.empty())
1415 return Error("Malformed global initializer set");
1416
1417 // Look for intrinsic functions which need to be upgraded at some point
1418 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1419 FI != FE; ++FI) {
1420 Function *NewFn;
1421 if (UpgradeIntrinsicFunction(FI, NewFn))
1422 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1423 }
1424
1425 // Look for global variables which need to be renamed.
1426 for (Module::global_iterator
1427 GI = TheModule->global_begin(), GE = TheModule->global_end();
1428 GI != GE; ++GI)
1429 UpgradeGlobalVariable(GI);
1430 // Force deallocation of memory for these vectors to favor the client that
1431 // want lazy deserialization.
1432 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1433 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1434 return false;
1435}
1436
1437bool BitcodeReader::ParseModule(bool Resume) {
1438 if (Resume)
1439 Stream.JumpToBit(NextUnreadBit);
1440 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001441 return Error("Malformed block record");
1442
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001443 SmallVector<uint64_t, 64> Record;
1444 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001445 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001446
1447 // Read all the records for this module.
1448 while (!Stream.AtEndOfStream()) {
1449 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001450 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001451 if (Stream.ReadBlockEnd())
1452 return Error("Error at end of module block");
1453
Derek Schuff2ea93872012-02-06 22:30:29 +00001454 return GlobalCleanup();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001455 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001456
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001457 if (Code == bitc::ENTER_SUBBLOCK) {
1458 switch (Stream.ReadSubBlockID()) {
1459 default: // Skip unknown content.
1460 if (Stream.SkipBlock())
1461 return Error("Malformed block record");
1462 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001463 case bitc::BLOCKINFO_BLOCK_ID:
1464 if (Stream.ReadBlockInfoBlock())
1465 return Error("Malformed BlockInfoBlock");
1466 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001467 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001468 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001469 return true;
1470 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001471 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001472 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001473 return true;
1474 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001475 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001476 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001477 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001478 SeenValueSymbolTable = true;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001479 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001480 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001481 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001482 return true;
1483 break;
Devang Patele54abc92009-07-22 17:43:22 +00001484 case bitc::METADATA_BLOCK_ID:
1485 if (ParseMetadata())
1486 return true;
1487 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001488 case bitc::FUNCTION_BLOCK_ID:
1489 // If this is the first function body we've seen, reverse the
1490 // FunctionsWithBodies list.
Derek Schuff2ea93872012-02-06 22:30:29 +00001491 if (!SeenFirstFunctionBody) {
Chris Lattner48f84872007-05-01 04:59:48 +00001492 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Derek Schuff2ea93872012-02-06 22:30:29 +00001493 if (GlobalCleanup())
1494 return true;
1495 SeenFirstFunctionBody = true;
Chris Lattner48f84872007-05-01 04:59:48 +00001496 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001497
Chris Lattner980e5aa2007-05-01 05:52:21 +00001498 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001499 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001500 // For streaming bitcode, suspend parsing when we reach the function
1501 // bodies. Subsequent materialization calls will resume it when
1502 // necessary. For streaming, the function bodies must be at the end of
1503 // the bitcode. If the bitcode file is old, the symbol table will be
1504 // at the end instead and will not have been seen yet. In this case,
1505 // just finish the parse now.
1506 if (LazyStreamer && SeenValueSymbolTable) {
1507 NextUnreadBit = Stream.GetCurrentBitNo();
1508 return false;
1509 }
Chris Lattner48f84872007-05-01 04:59:48 +00001510 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001511 case bitc::USELIST_BLOCK_ID:
1512 if (ParseUseLists())
1513 return true;
1514 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001515 }
1516 continue;
1517 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001518
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001519 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001520 Stream.ReadAbbrevRecord();
1521 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001522 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001523
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001524 // Read a record.
1525 switch (Stream.ReadRecord(Code, Record)) {
1526 default: break; // Default behavior, ignore unknown content.
1527 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1528 if (Record.size() < 1)
1529 return Error("Malformed MODULE_CODE_VERSION");
1530 // Only version #0 is supported so far.
1531 if (Record[0] != 0)
1532 return Error("Unknown bitstream version!");
1533 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001534 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001535 std::string S;
1536 if (ConvertToString(Record, 0, S))
1537 return Error("Invalid MODULE_CODE_TRIPLE record");
1538 TheModule->setTargetTriple(S);
1539 break;
1540 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001541 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001542 std::string S;
1543 if (ConvertToString(Record, 0, S))
1544 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1545 TheModule->setDataLayout(S);
1546 break;
1547 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001548 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001549 std::string S;
1550 if (ConvertToString(Record, 0, S))
1551 return Error("Invalid MODULE_CODE_ASM record");
1552 TheModule->setModuleInlineAsm(S);
1553 break;
1554 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001555 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001556 std::string S;
1557 if (ConvertToString(Record, 0, S))
1558 return Error("Invalid MODULE_CODE_DEPLIB record");
1559 TheModule->addLibrary(S);
1560 break;
1561 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001562 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001563 std::string S;
1564 if (ConvertToString(Record, 0, S))
1565 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1566 SectionTable.push_back(S);
1567 break;
1568 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001569 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001570 std::string S;
1571 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001572 return Error("Invalid MODULE_CODE_GCNAME record");
1573 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001574 break;
1575 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001576 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001577 // linkage, alignment, section, visibility, threadlocal,
1578 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001579 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001580 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001581 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001582 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001583 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001584 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001585 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001586 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001587 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001588
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001589 bool isConstant = Record[1];
1590 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1591 unsigned Alignment = (1 << Record[4]) >> 1;
1592 std::string Section;
1593 if (Record[5]) {
1594 if (Record[5]-1 >= SectionTable.size())
1595 return Error("Invalid section ID");
1596 Section = SectionTable[Record[5]-1];
1597 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001598 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001599 if (Record.size() > 6)
1600 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgce718ff2012-06-23 11:37:03 +00001601
1602 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner5f32c012007-05-06 19:27:46 +00001603 if (Record.size() > 7)
Hans Wennborgce718ff2012-06-23 11:37:03 +00001604 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001605
Rafael Espindolabea46262011-01-08 16:42:36 +00001606 bool UnnamedAddr = false;
1607 if (Record.size() > 8)
1608 UnnamedAddr = Record[8];
1609
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001610 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001611 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Hans Wennborgce718ff2012-06-23 11:37:03 +00001612 TLM, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001613 NewGV->setAlignment(Alignment);
1614 if (!Section.empty())
1615 NewGV->setSection(Section);
1616 NewGV->setVisibility(Visibility);
Rafael Espindolabea46262011-01-08 16:42:36 +00001617 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001618
Chris Lattner0b2482a2007-04-23 21:26:05 +00001619 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001620
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001621 // Remember which value to use for the global initializer.
1622 if (unsigned InitID = Record[2])
1623 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001624 break;
1625 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001626 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001627 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001628 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001629 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001630 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001631 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001632 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001633 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001634 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001635 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001636 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1637 if (!FTy)
1638 return Error("Function not a pointer to function type!");
1639
Gabor Greif051a9502008-04-06 20:25:17 +00001640 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1641 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001642
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001643 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001644 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001645 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001646 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001647
Chris Lattnera9bb7132007-05-08 05:38:01 +00001648 Func->setAlignment((1 << Record[5]) >> 1);
1649 if (Record[6]) {
1650 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001651 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001652 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001653 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001654 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001655 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001656 if (Record[8]-1 > GCTable.size())
1657 return Error("Invalid GC ID");
1658 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001659 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001660 bool UnnamedAddr = false;
1661 if (Record.size() > 9)
1662 UnnamedAddr = Record[9];
1663 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001664 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Chris Lattner48f84872007-05-01 04:59:48 +00001666 // If this is a function with a body, remember the prototype we are
1667 // creating now, so that we can match up the body with them later.
Derek Schuff2ea93872012-02-06 22:30:29 +00001668 if (!isProto) {
Chris Lattner48f84872007-05-01 04:59:48 +00001669 FunctionsWithBodies.push_back(Func);
Derek Schuff2ea93872012-02-06 22:30:29 +00001670 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1671 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001672 break;
1673 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001674 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001675 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001676 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001677 if (Record.size() < 3)
1678 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001679 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001680 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001681 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001682 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001683
Chris Lattner07d98b42007-04-26 02:46:40 +00001684 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1685 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001686 // Old bitcode files didn't have visibility field.
1687 if (Record.size() > 3)
1688 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001689 ValueList.push_back(NewGA);
1690 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1691 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001692 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001693 /// MODULE_CODE_PURGEVALS: [numvals]
1694 case bitc::MODULE_CODE_PURGEVALS:
1695 // Trim down the value list to the specified size.
1696 if (Record.size() < 1 || Record[0] > ValueList.size())
1697 return Error("Invalid MODULE_PURGEVALS record");
1698 ValueList.shrinkTo(Record[0]);
1699 break;
1700 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001701 Record.clear();
1702 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001703
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001704 return Error("Premature end of bitstream");
1705}
1706
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001707bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001708 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001709
Derek Schuff2ea93872012-02-06 22:30:29 +00001710 if (InitStream()) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001711
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001712 // Sniff for the signature.
1713 if (Stream.Read(8) != 'B' ||
1714 Stream.Read(8) != 'C' ||
1715 Stream.Read(4) != 0x0 ||
1716 Stream.Read(4) != 0xC ||
1717 Stream.Read(4) != 0xE ||
1718 Stream.Read(4) != 0xD)
1719 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001720
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001721 // We expect a number of well-defined blocks, though we don't necessarily
1722 // need to understand them all.
1723 while (!Stream.AtEndOfStream()) {
1724 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001725
Rafael Espindolac9687b32011-05-26 18:59:54 +00001726 if (Code != bitc::ENTER_SUBBLOCK) {
1727
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001728 // The ranlib in xcode 4 will align archive members by appending newlines
1729 // to the end of them. If this file size is a multiple of 4 but not 8, we
1730 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001731 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1732 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling2127c9b2012-07-19 00:15:11 +00001733 Stream.AtEndOfStream())
Rafael Espindolac9687b32011-05-26 18:59:54 +00001734 return false;
1735
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001736 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001737 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001738
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001739 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001741 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001742 switch (BlockID) {
1743 case bitc::BLOCKINFO_BLOCK_ID:
1744 if (Stream.ReadBlockInfoBlock())
1745 return Error("Malformed BlockInfoBlock");
1746 break;
1747 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001748 // Reject multiple MODULE_BLOCK's in a single bitstream.
1749 if (TheModule)
1750 return Error("Multiple MODULE_BLOCKs in same stream");
1751 TheModule = M;
Derek Schuff2ea93872012-02-06 22:30:29 +00001752 if (ParseModule(false))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001753 return true;
Derek Schuff2ea93872012-02-06 22:30:29 +00001754 if (LazyStreamer) return false;
Chris Lattnere17b6582007-05-05 00:17:00 +00001755 break;
1756 default:
1757 if (Stream.SkipBlock())
1758 return Error("Malformed block record");
1759 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001760 }
1761 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001762
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001763 return false;
1764}
Chris Lattnerc453f762007-04-29 07:54:31 +00001765
Bill Wendling34711742010-10-06 01:22:42 +00001766bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1767 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1768 return Error("Malformed block record");
1769
1770 SmallVector<uint64_t, 64> Record;
1771
1772 // Read all the records for this module.
1773 while (!Stream.AtEndOfStream()) {
1774 unsigned Code = Stream.ReadCode();
1775 if (Code == bitc::END_BLOCK) {
1776 if (Stream.ReadBlockEnd())
1777 return Error("Error at end of module block");
1778
1779 return false;
1780 }
1781
1782 if (Code == bitc::ENTER_SUBBLOCK) {
1783 switch (Stream.ReadSubBlockID()) {
1784 default: // Skip unknown content.
1785 if (Stream.SkipBlock())
1786 return Error("Malformed block record");
1787 break;
1788 }
1789 continue;
1790 }
1791
1792 if (Code == bitc::DEFINE_ABBREV) {
1793 Stream.ReadAbbrevRecord();
1794 continue;
1795 }
1796
1797 // Read a record.
1798 switch (Stream.ReadRecord(Code, Record)) {
1799 default: break; // Default behavior, ignore unknown content.
1800 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1801 if (Record.size() < 1)
1802 return Error("Malformed MODULE_CODE_VERSION");
1803 // Only version #0 is supported so far.
1804 if (Record[0] != 0)
1805 return Error("Unknown bitstream version!");
1806 break;
1807 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1808 std::string S;
1809 if (ConvertToString(Record, 0, S))
1810 return Error("Invalid MODULE_CODE_TRIPLE record");
1811 Triple = S;
1812 break;
1813 }
1814 }
1815 Record.clear();
1816 }
1817
1818 return Error("Premature end of bitstream");
1819}
1820
1821bool BitcodeReader::ParseTriple(std::string &Triple) {
Derek Schuff2ea93872012-02-06 22:30:29 +00001822 if (InitStream()) return true;
Bill Wendling34711742010-10-06 01:22:42 +00001823
1824 // Sniff for the signature.
1825 if (Stream.Read(8) != 'B' ||
1826 Stream.Read(8) != 'C' ||
1827 Stream.Read(4) != 0x0 ||
1828 Stream.Read(4) != 0xC ||
1829 Stream.Read(4) != 0xE ||
1830 Stream.Read(4) != 0xD)
1831 return Error("Invalid bitcode signature");
1832
1833 // We expect a number of well-defined blocks, though we don't necessarily
1834 // need to understand them all.
1835 while (!Stream.AtEndOfStream()) {
1836 unsigned Code = Stream.ReadCode();
1837
1838 if (Code != bitc::ENTER_SUBBLOCK)
1839 return Error("Invalid record at top-level");
1840
1841 unsigned BlockID = Stream.ReadSubBlockID();
1842
1843 // We only know the MODULE subblock ID.
1844 switch (BlockID) {
1845 case bitc::MODULE_BLOCK_ID:
1846 if (ParseModuleTriple(Triple))
1847 return true;
1848 break;
1849 default:
1850 if (Stream.SkipBlock())
1851 return Error("Malformed block record");
1852 break;
1853 }
1854 }
1855
1856 return false;
1857}
1858
Devang Patele8e02132009-09-18 19:26:43 +00001859/// ParseMetadataAttachment - Parse metadata attachments.
1860bool BitcodeReader::ParseMetadataAttachment() {
1861 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1862 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001863
Devang Patele8e02132009-09-18 19:26:43 +00001864 SmallVector<uint64_t, 64> Record;
1865 while(1) {
1866 unsigned Code = Stream.ReadCode();
1867 if (Code == bitc::END_BLOCK) {
1868 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001869 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001870 break;
1871 }
1872 if (Code == bitc::DEFINE_ABBREV) {
1873 Stream.ReadAbbrevRecord();
1874 continue;
1875 }
1876 // Read a metadata attachment record.
1877 Record.clear();
1878 switch (Stream.ReadRecord(Code, Record)) {
1879 default: // Default behavior: ignore.
1880 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001881 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001882 unsigned RecordLength = Record.size();
1883 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001884 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001885 Instruction *Inst = InstructionList[Record[0]];
1886 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001887 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001888 DenseMap<unsigned, unsigned>::iterator I =
1889 MDKindMap.find(Kind);
1890 if (I == MDKindMap.end())
1891 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001892 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001893 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001894 }
1895 break;
1896 }
1897 }
1898 }
1899 return false;
1900}
Chris Lattner48f84872007-05-01 04:59:48 +00001901
Chris Lattner980e5aa2007-05-01 05:52:21 +00001902/// ParseFunctionBody - Lazily parse the specified function body block.
1903bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001904 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001905 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Nick Lewycky9a49f152010-02-25 08:30:17 +00001907 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001908 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001909 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001910
Chris Lattner980e5aa2007-05-01 05:52:21 +00001911 // Add all the function arguments to the value table.
1912 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1913 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001914
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001915 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001916 BasicBlock *CurBB = 0;
1917 unsigned CurBBNo = 0;
1918
Chris Lattnera6245242010-04-03 02:17:50 +00001919 DebugLoc LastLoc;
1920
Chris Lattner980e5aa2007-05-01 05:52:21 +00001921 // Read all the records.
1922 SmallVector<uint64_t, 64> Record;
1923 while (1) {
1924 unsigned Code = Stream.ReadCode();
1925 if (Code == bitc::END_BLOCK) {
1926 if (Stream.ReadBlockEnd())
1927 return Error("Error at end of function block");
1928 break;
1929 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001930
Chris Lattner980e5aa2007-05-01 05:52:21 +00001931 if (Code == bitc::ENTER_SUBBLOCK) {
1932 switch (Stream.ReadSubBlockID()) {
1933 default: // Skip unknown content.
1934 if (Stream.SkipBlock())
1935 return Error("Malformed block record");
1936 break;
1937 case bitc::CONSTANTS_BLOCK_ID:
1938 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001939 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001940 break;
1941 case bitc::VALUE_SYMTAB_BLOCK_ID:
1942 if (ParseValueSymbolTable()) return true;
1943 break;
Devang Patele8e02132009-09-18 19:26:43 +00001944 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001945 if (ParseMetadataAttachment()) return true;
1946 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001947 case bitc::METADATA_BLOCK_ID:
1948 if (ParseMetadata()) return true;
1949 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001950 }
1951 continue;
1952 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001953
Chris Lattner980e5aa2007-05-01 05:52:21 +00001954 if (Code == bitc::DEFINE_ABBREV) {
1955 Stream.ReadAbbrevRecord();
1956 continue;
1957 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001958
Chris Lattner980e5aa2007-05-01 05:52:21 +00001959 // Read a record.
1960 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001961 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001962 unsigned BitCode = Stream.ReadRecord(Code, Record);
1963 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001964 default: // Default behavior: reject
1965 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001966 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001967 if (Record.size() < 1 || Record[0] == 0)
1968 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001969 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001970 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001971 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001972 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001973 CurBB = FunctionBBs[0];
1974 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001975
1976 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1977 // This record indicates that the last instruction is at the same
1978 // location as the previous instruction with a location.
1979 I = 0;
1980
1981 // Get the last instruction emitted.
1982 if (CurBB && !CurBB->empty())
1983 I = &CurBB->back();
1984 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1985 !FunctionBBs[CurBBNo-1]->empty())
1986 I = &FunctionBBs[CurBBNo-1]->back();
1987
1988 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1989 I->setDebugLoc(LastLoc);
1990 I = 0;
1991 continue;
1992
Chris Lattner4f6bab92011-06-17 18:17:37 +00001993 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001994 I = 0; // Get the last instruction emitted.
1995 if (CurBB && !CurBB->empty())
1996 I = &CurBB->back();
1997 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1998 !FunctionBBs[CurBBNo-1]->empty())
1999 I = &FunctionBBs[CurBBNo-1]->back();
2000 if (I == 0 || Record.size() < 4)
2001 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2002
2003 unsigned Line = Record[0], Col = Record[1];
2004 unsigned ScopeID = Record[2], IAID = Record[3];
2005
2006 MDNode *Scope = 0, *IA = 0;
2007 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2008 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2009 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2010 I->setDebugLoc(LastLoc);
2011 I = 0;
2012 continue;
2013 }
2014
Chris Lattnerabfbf852007-05-06 00:21:25 +00002015 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
2016 unsigned OpNum = 0;
2017 Value *LHS, *RHS;
2018 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2019 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00002020 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002021 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002022
Dan Gohman1224c382009-07-20 21:19:07 +00002023 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00002024 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002025 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002026 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002027 if (OpNum < Record.size()) {
2028 if (Opc == Instruction::Add ||
2029 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002030 Opc == Instruction::Mul ||
2031 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002032 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002033 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002034 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002035 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002036 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002037 Opc == Instruction::UDiv ||
2038 Opc == Instruction::LShr ||
2039 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002040 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002041 cast<BinaryOperator>(I)->setIsExact(true);
2042 }
2043 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002044 break;
2045 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002046 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2047 unsigned OpNum = 0;
2048 Value *Op;
2049 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2050 OpNum+2 != Record.size())
2051 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002052
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002053 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002054 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2055 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002056 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002057 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002058 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002059 break;
2060 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002061 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002062 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002063 unsigned OpNum = 0;
2064 Value *BasePtr;
2065 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002066 return Error("Invalid GEP record");
2067
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002068 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002069 while (OpNum != Record.size()) {
2070 Value *Op;
2071 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002072 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002073 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002074 }
2075
Jay Foada9203102011-07-25 09:48:08 +00002076 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002077 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002078 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002079 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002080 break;
2081 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002082
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002083 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2084 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002085 unsigned OpNum = 0;
2086 Value *Agg;
2087 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2088 return Error("Invalid EXTRACTVAL record");
2089
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002090 SmallVector<unsigned, 4> EXTRACTVALIdx;
2091 for (unsigned RecSize = Record.size();
2092 OpNum != RecSize; ++OpNum) {
2093 uint64_t Index = Record[OpNum];
2094 if ((unsigned)Index != Index)
2095 return Error("Invalid EXTRACTVAL index");
2096 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002097 }
2098
Jay Foadfc6d3a42011-07-13 10:26:04 +00002099 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002100 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002101 break;
2102 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002103
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002104 case bitc::FUNC_CODE_INST_INSERTVAL: {
2105 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002106 unsigned OpNum = 0;
2107 Value *Agg;
2108 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2109 return Error("Invalid INSERTVAL record");
2110 Value *Val;
2111 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2112 return Error("Invalid INSERTVAL record");
2113
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002114 SmallVector<unsigned, 4> INSERTVALIdx;
2115 for (unsigned RecSize = Record.size();
2116 OpNum != RecSize; ++OpNum) {
2117 uint64_t Index = Record[OpNum];
2118 if ((unsigned)Index != Index)
2119 return Error("Invalid INSERTVAL index");
2120 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002121 }
2122
Jay Foadfc6d3a42011-07-13 10:26:04 +00002123 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002124 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002125 break;
2126 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002127
Chris Lattnerabfbf852007-05-06 00:21:25 +00002128 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002129 // obsolete form of select
2130 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002131 unsigned OpNum = 0;
2132 Value *TrueVal, *FalseVal, *Cond;
2133 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2134 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002135 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002136 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002138 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002139 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002140 break;
2141 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002142
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002143 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2144 // new form of select
2145 // handles select i1 or select [N x i1]
2146 unsigned OpNum = 0;
2147 Value *TrueVal, *FalseVal, *Cond;
2148 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2149 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2150 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2151 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002152
2153 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002154 if (VectorType* vector_type =
2155 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002156 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002157 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002158 return Error("Invalid SELECT condition type");
2159 } else {
2160 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002162 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002163 }
2164
Gabor Greif051a9502008-04-06 20:25:17 +00002165 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002166 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002167 break;
2168 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002169
Chris Lattner01ff65f2007-05-02 05:16:49 +00002170 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002171 unsigned OpNum = 0;
2172 Value *Vec, *Idx;
2173 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002174 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002175 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002176 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002177 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002178 break;
2179 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002180
Chris Lattner01ff65f2007-05-02 05:16:49 +00002181 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002182 unsigned OpNum = 0;
2183 Value *Vec, *Elt, *Idx;
2184 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002185 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002186 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002187 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002188 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002189 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002190 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002191 break;
2192 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002193
Chris Lattnerabfbf852007-05-06 00:21:25 +00002194 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2195 unsigned OpNum = 0;
2196 Value *Vec1, *Vec2, *Mask;
2197 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2198 getValue(Record, OpNum, Vec1->getType(), Vec2))
2199 return Error("Invalid SHUFFLEVEC record");
2200
Mon P Wangaeb06d22008-11-10 04:46:22 +00002201 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002202 return Error("Invalid SHUFFLEVEC record");
2203 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002204 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002205 break;
2206 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002207
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002208 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2209 // Old form of ICmp/FCmp returning bool
2210 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2211 // both legal on vectors but had different behaviour.
2212 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2213 // FCmp/ICmp returning bool or vector of bool
2214
Chris Lattner7337ab92007-05-06 00:00:00 +00002215 unsigned OpNum = 0;
2216 Value *LHS, *RHS;
2217 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2218 getValue(Record, OpNum, LHS->getType(), RHS) ||
2219 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002220 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002221
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002222 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002223 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002224 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002225 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002226 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002227 break;
2228 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002229
Chris Lattner231cbcb2007-05-02 04:27:25 +00002230 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002231 {
2232 unsigned Size = Record.size();
2233 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002234 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002235 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002236 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002237 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002238
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002239 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002240 Value *Op = NULL;
2241 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2242 return Error("Invalid RET record");
2243 if (OpNum != Record.size())
2244 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002245
Chris Lattner96a74c52011-06-17 18:09:11 +00002246 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002247 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002248 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002249 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002250 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002251 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002252 return Error("Invalid BR record");
2253 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2254 if (TrueDest == 0)
2255 return Error("Invalid BR record");
2256
Devang Patele8e02132009-09-18 19:26:43 +00002257 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002258 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002259 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002260 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002261 else {
2262 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002263 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002264 if (FalseDest == 0 || Cond == 0)
2265 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002266 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002267 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002268 }
2269 break;
2270 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002271 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002272 // Check magic
2273 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2274 // New SwitchInst format with case ranges.
2275
2276 Type *OpTy = getTypeByID(Record[1]);
2277 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2278
2279 Value *Cond = getFnValueByID(Record[2], OpTy);
2280 BasicBlock *Default = getBasicBlock(Record[3]);
2281 if (OpTy == 0 || Cond == 0 || Default == 0)
2282 return Error("Invalid SWITCH record");
2283
2284 unsigned NumCases = Record[4];
2285
2286 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2287 InstructionList.push_back(SI);
2288
2289 unsigned CurIdx = 5;
2290 for (unsigned i = 0; i != NumCases; ++i) {
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002291 IntegersSubsetToBB CaseBuilder;
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002292 unsigned NumItems = Record[CurIdx++];
2293 for (unsigned ci = 0; ci != NumItems; ++ci) {
2294 bool isSingleNumber = Record[CurIdx++];
2295
2296 APInt Low;
2297 unsigned ActiveWords = 1;
2298 if (ValueBitWidth > 64)
2299 ActiveWords = Record[CurIdx++];
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002300 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2301 ValueBitWidth);
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002302 CurIdx += ActiveWords;
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002303
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002304 if (!isSingleNumber) {
2305 ActiveWords = 1;
2306 if (ValueBitWidth > 64)
2307 ActiveWords = Record[CurIdx++];
2308 APInt High =
Benjamin Kramerf52aea82012-05-28 14:10:31 +00002309 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2310 ValueBitWidth);
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002311
2312 CaseBuilder.add(IntItem::fromType(OpTy, Low),
2313 IntItem::fromType(OpTy, High));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002314 CurIdx += ActiveWords;
2315 } else
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002316 CaseBuilder.add(IntItem::fromType(OpTy, Low));
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002317 }
2318 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Stepan Dyatkovskiy0aa32d52012-05-29 12:26:47 +00002319 IntegersSubset Case = CaseBuilder.getCase();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002320 SI->addCase(Case, DestBB);
2321 }
Stepan Dyatkovskiy734dde82012-05-14 08:26:31 +00002322 uint16_t Hash = SI->hash();
Stepan Dyatkovskiy1cce5bf2012-05-12 10:48:17 +00002323 if (Hash != (Record[0] & 0xFFFF))
2324 return Error("Invalid SWITCH record");
2325 I = SI;
2326 break;
2327 }
2328
2329 // Old SwitchInst format without case ranges.
2330
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002331 if (Record.size() < 3 || (Record.size() & 1) == 0)
2332 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002333 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002334 Value *Cond = getFnValueByID(Record[1], OpTy);
2335 BasicBlock *Default = getBasicBlock(Record[2]);
2336 if (OpTy == 0 || Cond == 0 || Default == 0)
2337 return Error("Invalid SWITCH record");
2338 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002339 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002340 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002341 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002342 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002343 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2344 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2345 if (CaseVal == 0 || DestBB == 0) {
2346 delete SI;
2347 return Error("Invalid SWITCH record!");
2348 }
2349 SI->addCase(CaseVal, DestBB);
2350 }
2351 I = SI;
2352 break;
2353 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002354 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002355 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002356 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002357 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002358 Value *Address = getFnValueByID(Record[1], OpTy);
2359 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002360 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002361 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002362 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002363 InstructionList.push_back(IBI);
2364 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2365 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2366 IBI->addDestination(DestBB);
2367 } else {
2368 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002369 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002370 }
2371 }
2372 I = IBI;
2373 break;
2374 }
2375
Duncan Sandsdc024672007-11-27 13:23:08 +00002376 case bitc::FUNC_CODE_INST_INVOKE: {
2377 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002378 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002379 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002380 unsigned CCInfo = Record[1];
2381 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2382 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002383
Chris Lattnera9bb7132007-05-08 05:38:01 +00002384 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002385 Value *Callee;
2386 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002387 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002389 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2390 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002391 dyn_cast<FunctionType>(CalleeTy->getElementType());
2392
2393 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002394 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2395 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002396 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002397
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002398 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002399 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2400 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2401 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002402 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002403
Chris Lattner7337ab92007-05-06 00:00:00 +00002404 if (!FTy->isVarArg()) {
2405 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002406 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002407 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002408 // Read type/value pairs for varargs params.
2409 while (OpNum != Record.size()) {
2410 Value *Op;
2411 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2412 return Error("Invalid INVOKE record");
2413 Ops.push_back(Op);
2414 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002415 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002416
Jay Foada3efbb12011-07-15 08:37:34 +00002417 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002418 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002419 cast<InvokeInst>(I)->setCallingConv(
2420 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002421 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002422 break;
2423 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002424 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2425 unsigned Idx = 0;
2426 Value *Val = 0;
2427 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2428 return Error("Invalid RESUME record");
2429 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002430 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002431 break;
2432 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002433 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002434 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002435 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002436 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002437 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002438 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002439 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002440 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002441 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002442
Jay Foad3ecfc862011-03-30 11:28:46 +00002443 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002444 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002445
Chris Lattner15e6d172007-05-04 19:11:41 +00002446 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2447 Value *V = getFnValueByID(Record[1+i], Ty);
2448 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002449 if (!V || !BB) return Error("Invalid PHI record");
2450 PN->addIncoming(V, BB);
2451 }
2452 I = PN;
2453 break;
2454 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002455
Bill Wendlinge6e88262011-08-12 20:24:12 +00002456 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2457 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2458 unsigned Idx = 0;
2459 if (Record.size() < 4)
2460 return Error("Invalid LANDINGPAD record");
2461 Type *Ty = getTypeByID(Record[Idx++]);
2462 if (!Ty) return Error("Invalid LANDINGPAD record");
2463 Value *PersFn = 0;
2464 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2465 return Error("Invalid LANDINGPAD record");
2466
2467 bool IsCleanup = !!Record[Idx++];
2468 unsigned NumClauses = Record[Idx++];
2469 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2470 LP->setCleanup(IsCleanup);
2471 for (unsigned J = 0; J != NumClauses; ++J) {
2472 LandingPadInst::ClauseType CT =
2473 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2474 Value *Val;
2475
2476 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2477 delete LP;
2478 return Error("Invalid LANDINGPAD record");
2479 }
2480
2481 assert((CT != LandingPadInst::Catch ||
2482 !isa<ArrayType>(Val->getType())) &&
2483 "Catch clause has a invalid type!");
2484 assert((CT != LandingPadInst::Filter ||
2485 isa<ArrayType>(Val->getType())) &&
2486 "Filter clause has invalid type!");
2487 LP->addClause(Val);
2488 }
2489
2490 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002491 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002492 break;
2493 }
2494
Chris Lattner96a74c52011-06-17 18:09:11 +00002495 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2496 if (Record.size() != 4)
2497 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002498 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002499 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002500 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002501 Value *Size = getFnValueByID(Record[2], OpTy);
2502 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002503 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002504 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002505 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002506 break;
2507 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002508 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002509 unsigned OpNum = 0;
2510 Value *Op;
2511 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2512 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002513 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002514
Chris Lattner7337ab92007-05-06 00:00:00 +00002515 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002516 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002517 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002518 }
Eli Friedman21006d42011-08-09 23:02:53 +00002519 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2520 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2521 unsigned OpNum = 0;
2522 Value *Op;
2523 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2524 OpNum+4 != Record.size())
2525 return Error("Invalid LOADATOMIC record");
2526
2527
2528 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2529 if (Ordering == NotAtomic || Ordering == Release ||
2530 Ordering == AcquireRelease)
2531 return Error("Invalid LOADATOMIC record");
2532 if (Ordering != NotAtomic && Record[OpNum] == 0)
2533 return Error("Invalid LOADATOMIC record");
2534 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2535
2536 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2537 Ordering, SynchScope);
2538 InstructionList.push_back(I);
2539 break;
2540 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002541 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002542 unsigned OpNum = 0;
2543 Value *Val, *Ptr;
2544 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002545 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002546 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2547 OpNum+2 != Record.size())
2548 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002549
Christopher Lambfe63fb92007-12-11 08:59:05 +00002550 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002551 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002552 break;
2553 }
Eli Friedman21006d42011-08-09 23:02:53 +00002554 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2555 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2556 unsigned OpNum = 0;
2557 Value *Val, *Ptr;
2558 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2559 getValue(Record, OpNum,
2560 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2561 OpNum+4 != Record.size())
2562 return Error("Invalid STOREATOMIC record");
2563
2564 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002565 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002566 Ordering == AcquireRelease)
2567 return Error("Invalid STOREATOMIC record");
2568 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2569 if (Ordering != NotAtomic && Record[OpNum] == 0)
2570 return Error("Invalid STOREATOMIC record");
2571
2572 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2573 Ordering, SynchScope);
2574 InstructionList.push_back(I);
2575 break;
2576 }
Eli Friedmanff030482011-07-28 21:48:00 +00002577 case bitc::FUNC_CODE_INST_CMPXCHG: {
2578 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2579 unsigned OpNum = 0;
2580 Value *Ptr, *Cmp, *New;
2581 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2582 getValue(Record, OpNum,
2583 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2584 getValue(Record, OpNum,
2585 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2586 OpNum+3 != Record.size())
2587 return Error("Invalid CMPXCHG record");
2588 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002589 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002590 return Error("Invalid CMPXCHG record");
2591 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2592 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2593 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2594 InstructionList.push_back(I);
2595 break;
2596 }
2597 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2598 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2599 unsigned OpNum = 0;
2600 Value *Ptr, *Val;
2601 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2602 getValue(Record, OpNum,
2603 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2604 OpNum+4 != Record.size())
2605 return Error("Invalid ATOMICRMW record");
2606 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2607 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2608 Operation > AtomicRMWInst::LAST_BINOP)
2609 return Error("Invalid ATOMICRMW record");
2610 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002611 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002612 return Error("Invalid ATOMICRMW record");
2613 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2614 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2615 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2616 InstructionList.push_back(I);
2617 break;
2618 }
Eli Friedman47f35132011-07-25 23:16:38 +00002619 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2620 if (2 != Record.size())
2621 return Error("Invalid FENCE record");
2622 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2623 if (Ordering == NotAtomic || Ordering == Unordered ||
2624 Ordering == Monotonic)
2625 return Error("Invalid FENCE record");
2626 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2627 I = new FenceInst(Context, Ordering, SynchScope);
2628 InstructionList.push_back(I);
2629 break;
2630 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002631 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002632 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2633 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002634 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002635
Devang Patel05988662008-09-25 21:00:45 +00002636 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002637 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002638
Chris Lattnera9bb7132007-05-08 05:38:01 +00002639 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002640 Value *Callee;
2641 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2642 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002643
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002644 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2645 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002646 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002647 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002648 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002649
Chris Lattner0579f7f2007-05-03 22:04:19 +00002650 SmallVector<Value*, 16> Args;
2651 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002652 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002653 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002654 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002655 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002656 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002657 if (Args.back() == 0) return Error("Invalid CALL record");
2658 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002659
Chris Lattner0579f7f2007-05-03 22:04:19 +00002660 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002661 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002662 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002663 return Error("Invalid CALL record");
2664 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002665 while (OpNum != Record.size()) {
2666 Value *Op;
2667 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2668 return Error("Invalid CALL record");
2669 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002670 }
2671 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002672
Jay Foada3efbb12011-07-15 08:37:34 +00002673 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002674 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002675 cast<CallInst>(I)->setCallingConv(
2676 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002677 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002678 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002679 break;
2680 }
2681 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2682 if (Record.size() < 3)
2683 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002684 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002685 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002686 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002687 if (!OpTy || !Op || !ResTy)
2688 return Error("Invalid VAARG record");
2689 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002690 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002691 break;
2692 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002693 }
2694
2695 // Add instruction to end of current BB. If there is no current BB, reject
2696 // this file.
2697 if (CurBB == 0) {
2698 delete I;
2699 return Error("Invalid instruction with no BB");
2700 }
2701 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002702
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002703 // If this was a terminator instruction, move to the next block.
2704 if (isa<TerminatorInst>(I)) {
2705 ++CurBBNo;
2706 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2707 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002708
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002709 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002710 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002711 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002712 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002713
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002714 // Check the function list for unresolved values.
2715 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2716 if (A->getParent() == 0) {
2717 // We found at least one unresolved value. Nuke them all to avoid leaks.
2718 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002719 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002720 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002721 delete A;
2722 }
2723 }
Chris Lattner35a04702007-05-04 03:50:29 +00002724 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002725 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002726 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002727
Dan Gohman064ff3e2010-08-25 20:23:38 +00002728 // FIXME: Check for unresolved forward-declared metadata references
2729 // and clean up leaks.
2730
Chris Lattner50b136d2009-10-28 05:53:48 +00002731 // See if anything took the address of blocks in this function. If so,
2732 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002733 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2734 BlockAddrFwdRefs.find(F);
2735 if (BAFRI != BlockAddrFwdRefs.end()) {
2736 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2737 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2738 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002739 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002740 return Error("Invalid blockaddress block #");
2741
2742 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002743 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002744 FwdRef->eraseFromParent();
2745 }
2746
2747 BlockAddrFwdRefs.erase(BAFRI);
2748 }
2749
Chris Lattner980e5aa2007-05-01 05:52:21 +00002750 // Trim the value list down to the size it was before we parsed this function.
2751 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002752 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002753 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002754 return false;
2755}
2756
Derek Schuff2ea93872012-02-06 22:30:29 +00002757/// FindFunctionInStream - Find the function body in the bitcode stream
2758bool BitcodeReader::FindFunctionInStream(Function *F,
2759 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2760 while (DeferredFunctionInfoIterator->second == 0) {
2761 if (Stream.AtEndOfStream())
2762 return Error("Could not find Function in stream");
2763 // ParseModule will parse the next body in the stream and set its
2764 // position in the DeferredFunctionInfo map.
2765 if (ParseModule(true)) return true;
2766 }
2767 return false;
2768}
2769
Chris Lattnerb348bb82007-05-18 04:02:46 +00002770//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002771// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002772//===----------------------------------------------------------------------===//
2773
2774
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002775bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2776 if (const Function *F = dyn_cast<Function>(GV)) {
2777 return F->isDeclaration() &&
2778 DeferredFunctionInfo.count(const_cast<Function*>(F));
2779 }
2780 return false;
2781}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002782
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002783bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2784 Function *F = dyn_cast<Function>(GV);
2785 // If it's not a function or is already material, ignore the request.
2786 if (!F || !F->isMaterializable()) return false;
2787
2788 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002789 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff2ea93872012-02-06 22:30:29 +00002790 // If its position is recorded as 0, its body is somewhere in the stream
2791 // but we haven't seen it yet.
2792 if (DFII->second == 0)
2793 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002794
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002795 // Move the bit stream to the saved position of the deferred function body.
2796 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797
Chris Lattnerb348bb82007-05-18 04:02:46 +00002798 if (ParseFunctionBody(F)) {
2799 if (ErrInfo) *ErrInfo = ErrorString;
2800 return true;
2801 }
Chandler Carruth69940402007-08-04 01:51:18 +00002802
2803 // Upgrade any old intrinsic calls in the function.
2804 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2805 E = UpgradedIntrinsics.end(); I != E; ++I) {
2806 if (I->first != I->second) {
2807 for (Value::use_iterator UI = I->first->use_begin(),
2808 UE = I->first->use_end(); UI != UE; ) {
2809 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2810 UpgradeIntrinsicCall(CI, I->second);
2811 }
2812 }
2813 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002814
Chris Lattnerb348bb82007-05-18 04:02:46 +00002815 return false;
2816}
2817
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002818bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2819 const Function *F = dyn_cast<Function>(GV);
2820 if (!F || F->isDeclaration())
2821 return false;
2822 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2823}
2824
2825void BitcodeReader::Dematerialize(GlobalValue *GV) {
2826 Function *F = dyn_cast<Function>(GV);
2827 // If this function isn't dematerializable, this is a noop.
2828 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002829 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002830
Chris Lattnerb348bb82007-05-18 04:02:46 +00002831 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002832
Chris Lattnerb348bb82007-05-18 04:02:46 +00002833 // Just forget the function body, we can remat it later.
2834 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002835}
2836
2837
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002838bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2839 assert(M == TheModule &&
2840 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002841 // Iterate over the module, deserializing any functions that are still on
2842 // disk.
2843 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2844 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002845 if (F->isMaterializable() &&
2846 Materialize(F, ErrInfo))
2847 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002848
Derek Schuff0ffe6982012-02-29 00:07:09 +00002849 // At this point, if there are any function bodies, the current bit is
2850 // pointing to the END_BLOCK record after them. Now make sure the rest
2851 // of the bits in the module have been read.
2852 if (NextUnreadBit)
2853 ParseModule(true);
2854
Daniel Dunbara279bc32009-09-20 02:20:51 +00002855 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2856 // delete the old functions to clean up. We can't do this unless the entire
2857 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002858 // with calls to the old function.
2859 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2860 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2861 if (I->first != I->second) {
2862 for (Value::use_iterator UI = I->first->use_begin(),
2863 UE = I->first->use_end(); UI != UE; ) {
2864 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2865 UpgradeIntrinsicCall(CI, I->second);
2866 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002867 if (!I->first->use_empty())
2868 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002869 I->first->eraseFromParent();
2870 }
2871 }
2872 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002873
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002874 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002875}
2876
Derek Schuff2ea93872012-02-06 22:30:29 +00002877bool BitcodeReader::InitStream() {
2878 if (LazyStreamer) return InitLazyStream();
2879 return InitStreamFromBuffer();
2880}
2881
2882bool BitcodeReader::InitStreamFromBuffer() {
Roman Divacky5177b3a2012-09-06 15:42:13 +00002883 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff2ea93872012-02-06 22:30:29 +00002884 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2885
2886 if (Buffer->getBufferSize() & 3) {
2887 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2888 return Error("Invalid bitcode signature");
2889 else
2890 return Error("Bitcode stream should be a multiple of 4 bytes in length");
2891 }
2892
2893 // If we have a wrapper header, parse it and ignore the non-bc file contents.
2894 // The magic number is 0x0B17C0DE stored in little endian.
2895 if (isBitcodeWrapper(BufPtr, BufEnd))
2896 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2897 return Error("Invalid bitcode wrapper header");
2898
2899 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2900 Stream.init(*StreamFile);
2901
2902 return false;
2903}
2904
2905bool BitcodeReader::InitLazyStream() {
2906 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2907 // see it.
2908 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2909 StreamFile.reset(new BitstreamReader(Bytes));
2910 Stream.init(*StreamFile);
2911
2912 unsigned char buf[16];
2913 if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2914 return Error("Bitcode stream must be at least 16 bytes in length");
2915
2916 if (!isBitcode(buf, buf + 16))
2917 return Error("Invalid bitcode signature");
2918
2919 if (isBitcodeWrapper(buf, buf + 4)) {
2920 const unsigned char *bitcodeStart = buf;
2921 const unsigned char *bitcodeEnd = buf + 16;
2922 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2923 Bytes->dropLeadingBytes(bitcodeStart - buf);
2924 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2925 }
2926 return false;
2927}
Chris Lattner48f84872007-05-01 04:59:48 +00002928
Chris Lattnerc453f762007-04-29 07:54:31 +00002929//===----------------------------------------------------------------------===//
2930// External interface
2931//===----------------------------------------------------------------------===//
2932
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002933/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002934///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002935Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2936 LLVMContext& Context,
2937 std::string *ErrMsg) {
2938 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002939 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002940 M->setMaterializer(R);
2941 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002942 if (ErrMsg)
2943 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002944
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002945 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002946 return 0;
2947 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002948 // Have the BitcodeReader dtor delete 'Buffer'.
2949 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002950
2951 R->materializeForwardReferencedFunctions();
2952
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002953 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002954}
2955
Derek Schuff2ea93872012-02-06 22:30:29 +00002956
2957Module *llvm::getStreamedBitcodeModule(const std::string &name,
2958 DataStreamer *streamer,
2959 LLVMContext &Context,
2960 std::string *ErrMsg) {
2961 Module *M = new Module(name, Context);
2962 BitcodeReader *R = new BitcodeReader(streamer, Context);
2963 M->setMaterializer(R);
2964 if (R->ParseBitcodeInto(M)) {
2965 if (ErrMsg)
2966 *ErrMsg = R->getErrorString();
2967 delete M; // Also deletes R.
2968 return 0;
2969 }
2970 R->setBufferOwned(false); // no buffer to delete
2971 return M;
2972}
2973
Chris Lattnerc453f762007-04-29 07:54:31 +00002974/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2975/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002976Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002977 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002978 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2979 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002980
2981 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2982 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002983 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002984
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002985 // Read in the entire module, and destroy the BitcodeReader.
2986 if (M->MaterializeAllPermanently(ErrMsg)) {
2987 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002988 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002989 }
Bill Wendling34711742010-10-06 01:22:42 +00002990
Chad Rosiercbbb0962011-12-07 21:44:12 +00002991 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2992 // written. We must defer until the Module has been fully materialized.
2993
Chris Lattnerc453f762007-04-29 07:54:31 +00002994 return M;
2995}
Bill Wendling34711742010-10-06 01:22:42 +00002996
2997std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2998 LLVMContext& Context,
2999 std::string *ErrMsg) {
3000 BitcodeReader *R = new BitcodeReader(Buffer, Context);
3001 // Don't let the BitcodeReader dtor delete 'Buffer'.
3002 R->setBufferOwned(false);
3003
3004 std::string Triple("");
3005 if (R->ParseTriple(Triple))
3006 if (ErrMsg)
3007 *ErrMsg = R->getErrorString();
3008
3009 delete R;
3010 return Triple;
3011}