blob: 9d10498943e0302539dbd24b1b8841751c2198ba [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"
Chris Lattner0eef0802007-04-24 04:04:35 +000025#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000026#include "llvm/Support/MemoryBuffer.h"
Gabor Greifefe65362008-05-10 08:32:32 +000027#include "llvm/OperandTraits.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000028using namespace llvm;
29
Rafael Espindola47f79bb2012-01-02 07:49:53 +000030void BitcodeReader::materializeForwardReferencedFunctions() {
31 while (!BlockAddrFwdRefs.empty()) {
32 Function *F = BlockAddrFwdRefs.begin()->first;
33 F->Materialize();
34 }
35}
36
Chris Lattnerb348bb82007-05-18 04:02:46 +000037void BitcodeReader::FreeState() {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000038 if (BufferOwned)
39 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000040 Buffer = 0;
Chris Lattner1afcace2011-07-09 17:41:24 +000041 std::vector<Type*>().swap(TypeList);
Chris Lattnerb348bb82007-05-18 04:02:46 +000042 ValueList.clear();
Devang Pateld5ac4042009-08-04 06:00:18 +000043 MDValueList.clear();
Daniel Dunbara279bc32009-09-20 02:20:51 +000044
Devang Patel19c87462008-09-26 22:53:05 +000045 std::vector<AttrListPtr>().swap(MAttributes);
Chris Lattnerb348bb82007-05-18 04:02:46 +000046 std::vector<BasicBlock*>().swap(FunctionBBs);
47 std::vector<Function*>().swap(FunctionsWithBodies);
48 DeferredFunctionInfo.clear();
Dan Gohman19538d12010-07-20 21:42:28 +000049 MDKindMap.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000050}
51
Chris Lattner48c85b82007-05-04 03:30:17 +000052//===----------------------------------------------------------------------===//
53// Helper functions to implement forward reference resolution, etc.
54//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000055
Chris Lattnercaee0dc2007-04-22 06:23:29 +000056/// ConvertToString - Convert a string from a record into an std::string, return
57/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000058template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000059static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000060 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000061 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000062 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +000063
Chris Lattner15e6d172007-05-04 19:11:41 +000064 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
65 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000066 return false;
67}
68
69static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
70 switch (Val) {
71 default: // Map unknown/new linkages to external
Bill Wendling3d10a5a2009-07-20 01:03:30 +000072 case 0: return GlobalValue::ExternalLinkage;
73 case 1: return GlobalValue::WeakAnyLinkage;
74 case 2: return GlobalValue::AppendingLinkage;
75 case 3: return GlobalValue::InternalLinkage;
76 case 4: return GlobalValue::LinkOnceAnyLinkage;
77 case 5: return GlobalValue::DLLImportLinkage;
78 case 6: return GlobalValue::DLLExportLinkage;
79 case 7: return GlobalValue::ExternalWeakLinkage;
80 case 8: return GlobalValue::CommonLinkage;
81 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands667d4b82009-03-07 15:45:40 +000082 case 10: return GlobalValue::WeakODRLinkage;
83 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner266c7bb2009-04-13 05:44:34 +000084 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling3d10a5a2009-07-20 01:03:30 +000085 case 13: return GlobalValue::LinkerPrivateLinkage;
Bill Wendling5e721d72010-07-01 21:55:59 +000086 case 14: return GlobalValue::LinkerPrivateWeakLinkage;
Bill Wendling55ae5152010-08-20 22:05:50 +000087 case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000088 }
89}
90
91static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
92 switch (Val) {
93 default: // Map unknown visibilities to default.
94 case 0: return GlobalValue::DefaultVisibility;
95 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000096 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000097 }
98}
99
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000100static int GetDecodedCastOpcode(unsigned Val) {
101 switch (Val) {
102 default: return -1;
103 case bitc::CAST_TRUNC : return Instruction::Trunc;
104 case bitc::CAST_ZEXT : return Instruction::ZExt;
105 case bitc::CAST_SEXT : return Instruction::SExt;
106 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
107 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
108 case bitc::CAST_UITOFP : return Instruction::UIToFP;
109 case bitc::CAST_SITOFP : return Instruction::SIToFP;
110 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
111 case bitc::CAST_FPEXT : return Instruction::FPExt;
112 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
113 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
114 case bitc::CAST_BITCAST : return Instruction::BitCast;
115 }
116}
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000117static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000118 switch (Val) {
119 default: return -1;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000120 case bitc::BINOP_ADD:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000121 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000122 case bitc::BINOP_SUB:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000123 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000124 case bitc::BINOP_MUL:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000125 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000126 case bitc::BINOP_UDIV: return Instruction::UDiv;
127 case bitc::BINOP_SDIV:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000128 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000129 case bitc::BINOP_UREM: return Instruction::URem;
130 case bitc::BINOP_SREM:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000131 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000132 case bitc::BINOP_SHL: return Instruction::Shl;
133 case bitc::BINOP_LSHR: return Instruction::LShr;
134 case bitc::BINOP_ASHR: return Instruction::AShr;
135 case bitc::BINOP_AND: return Instruction::And;
136 case bitc::BINOP_OR: return Instruction::Or;
137 case bitc::BINOP_XOR: return Instruction::Xor;
138 }
139}
140
Eli Friedmanff030482011-07-28 21:48:00 +0000141static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
142 switch (Val) {
143 default: return AtomicRMWInst::BAD_BINOP;
144 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
145 case bitc::RMW_ADD: return AtomicRMWInst::Add;
146 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
147 case bitc::RMW_AND: return AtomicRMWInst::And;
148 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
149 case bitc::RMW_OR: return AtomicRMWInst::Or;
150 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
151 case bitc::RMW_MAX: return AtomicRMWInst::Max;
152 case bitc::RMW_MIN: return AtomicRMWInst::Min;
153 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
154 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
155 }
156}
157
Eli Friedman47f35132011-07-25 23:16:38 +0000158static AtomicOrdering GetDecodedOrdering(unsigned Val) {
159 switch (Val) {
160 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
161 case bitc::ORDERING_UNORDERED: return Unordered;
162 case bitc::ORDERING_MONOTONIC: return Monotonic;
163 case bitc::ORDERING_ACQUIRE: return Acquire;
164 case bitc::ORDERING_RELEASE: return Release;
165 case bitc::ORDERING_ACQREL: return AcquireRelease;
166 default: // Map unknown orderings to sequentially-consistent.
167 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
168 }
169}
170
171static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
172 switch (Val) {
173 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
174 default: // Map unknown scopes to cross-thread.
175 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
176 }
177}
178
Gabor Greifefe65362008-05-10 08:32:32 +0000179namespace llvm {
Chris Lattner522b7b12007-04-24 05:48:56 +0000180namespace {
181 /// @brief A class for maintaining the slot number definition
182 /// as a placeholder for the actual definition for forward constants defs.
183 class ConstantPlaceHolder : public ConstantExpr {
Argyrios Kyrtzidis8c8b9ee2010-08-15 10:27:23 +0000184 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greif051a9502008-04-06 20:25:17 +0000185 public:
186 // allocate space for exactly one operand
187 void *operator new(size_t s) {
188 return User::operator new(s, 1);
189 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000190 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greifefe65362008-05-10 08:32:32 +0000191 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000192 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner522b7b12007-04-24 05:48:56 +0000193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000194
Chris Lattnerea693df2008-08-21 02:34:16 +0000195 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner17aa6802010-09-04 18:12:00 +0000196 //static inline bool classof(const ConstantPlaceHolder *) { return true; }
Chris Lattnerea693df2008-08-21 02:34:16 +0000197 static bool classof(const Value *V) {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000198 return isa<ConstantExpr>(V) &&
Chris Lattnerea693df2008-08-21 02:34:16 +0000199 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
200 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000201
202
Gabor Greifefe65362008-05-10 08:32:32 +0000203 /// Provide fast operand accessors
Chris Lattner46e77402009-03-31 22:55:09 +0000204 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner522b7b12007-04-24 05:48:56 +0000205 };
206}
207
Chris Lattner46e77402009-03-31 22:55:09 +0000208// FIXME: can we inherit this from ConstantExpr?
Gabor Greifefe65362008-05-10 08:32:32 +0000209template <>
Jay Foad67c619b2011-01-11 15:07:38 +0000210struct OperandTraits<ConstantPlaceHolder> :
211 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greifefe65362008-05-10 08:32:32 +0000212};
Gabor Greifefe65362008-05-10 08:32:32 +0000213}
214
Chris Lattner46e77402009-03-31 22:55:09 +0000215
216void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
217 if (Idx == size()) {
218 push_back(V);
219 return;
220 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000221
Chris Lattner46e77402009-03-31 22:55:09 +0000222 if (Idx >= size())
223 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000224
Chris Lattner46e77402009-03-31 22:55:09 +0000225 WeakVH &OldV = ValuePtrs[Idx];
226 if (OldV == 0) {
227 OldV = V;
228 return;
229 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000230
Chris Lattner46e77402009-03-31 22:55:09 +0000231 // Handle constants and non-constants (e.g. instrs) differently for
232 // efficiency.
233 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
234 ResolveConstants.push_back(std::make_pair(PHC, Idx));
235 OldV = V;
236 } else {
237 // If there was a forward reference to this value, replace it.
238 Value *PrevVal = OldV;
239 OldV->replaceAllUsesWith(V);
240 delete PrevVal;
Gabor Greifefe65362008-05-10 08:32:32 +0000241 }
242}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000243
Gabor Greifefe65362008-05-10 08:32:32 +0000244
Chris Lattner522b7b12007-04-24 05:48:56 +0000245Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000246 Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000247 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000248 resize(Idx + 1);
Chris Lattner522b7b12007-04-24 05:48:56 +0000249
Chris Lattner46e77402009-03-31 22:55:09 +0000250 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000251 assert(Ty == V->getType() && "Type mismatch in constant table!");
252 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000253 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000254
255 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson74a77812009-07-07 20:18:58 +0000256 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner46e77402009-03-31 22:55:09 +0000257 ValuePtrs[Idx] = C;
Chris Lattner522b7b12007-04-24 05:48:56 +0000258 return C;
259}
260
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner46e77402009-03-31 22:55:09 +0000262 if (Idx >= size())
Gabor Greifefe65362008-05-10 08:32:32 +0000263 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000264
Chris Lattner46e77402009-03-31 22:55:09 +0000265 if (Value *V = ValuePtrs[Idx]) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000266 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
267 return V;
268 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000269
Chris Lattner01ff65f2007-05-02 05:16:49 +0000270 // No type specified, must be invalid reference.
271 if (Ty == 0) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000272
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000273 // Create and return a placeholder, which will later be RAUW'd.
274 Value *V = new Argument(Ty);
Chris Lattner46e77402009-03-31 22:55:09 +0000275 ValuePtrs[Idx] = V;
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000276 return V;
277}
278
Chris Lattnerea693df2008-08-21 02:34:16 +0000279/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
280/// resolves any forward references. The idea behind this is that we sometimes
281/// get constants (such as large arrays) which reference *many* forward ref
282/// constants. Replacing each of these causes a lot of thrashing when
283/// building/reuniquing the constant. Instead of doing this, we look at all the
284/// uses and rewrite all the place holders at once for any constant that uses
285/// a placeholder.
286void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbara279bc32009-09-20 02:20:51 +0000287 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattnerea693df2008-08-21 02:34:16 +0000288 // binary search.
289 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000290
Chris Lattnerea693df2008-08-21 02:34:16 +0000291 SmallVector<Constant*, 64> NewOps;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000292
Chris Lattnerea693df2008-08-21 02:34:16 +0000293 while (!ResolveConstants.empty()) {
Chris Lattner46e77402009-03-31 22:55:09 +0000294 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000295 Constant *Placeholder = ResolveConstants.back().first;
296 ResolveConstants.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000297
Chris Lattnerea693df2008-08-21 02:34:16 +0000298 // Loop over all users of the placeholder, updating them to reference the
299 // new value. If they reference more than one placeholder, update them all
300 // at once.
301 while (!Placeholder->use_empty()) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000302 Value::use_iterator UI = Placeholder->use_begin();
Gabor Greifc654d1b2010-07-09 16:01:21 +0000303 User *U = *UI;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000304
Chris Lattnerea693df2008-08-21 02:34:16 +0000305 // If the using object isn't uniqued, just update the operands. This
306 // handles instructions and initializers for global variables.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000307 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattnerb6135a02008-08-21 17:31:45 +0000308 UI.getUse().set(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000309 continue;
310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000311
Chris Lattnerea693df2008-08-21 02:34:16 +0000312 // Otherwise, we have a constant that uses the placeholder. Replace that
313 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greifc654d1b2010-07-09 16:01:21 +0000314 Constant *UserC = cast<Constant>(U);
Chris Lattnerea693df2008-08-21 02:34:16 +0000315 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
316 I != E; ++I) {
317 Value *NewOp;
318 if (!isa<ConstantPlaceHolder>(*I)) {
319 // Not a placeholder reference.
320 NewOp = *I;
321 } else if (*I == Placeholder) {
322 // Common case is that it just references this one placeholder.
323 NewOp = RealVal;
324 } else {
325 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000326 ResolveConstantsTy::iterator It =
327 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattnerea693df2008-08-21 02:34:16 +0000328 std::pair<Constant*, unsigned>(cast<Constant>(*I),
329 0));
330 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner46e77402009-03-31 22:55:09 +0000331 NewOp = operator[](It->second);
Chris Lattnerea693df2008-08-21 02:34:16 +0000332 }
333
334 NewOps.push_back(cast<Constant>(NewOp));
335 }
336
337 // Make the new constant.
338 Constant *NewC;
339 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad26701082011-06-22 09:24:39 +0000340 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000341 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000342 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000343 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000344 NewC = ConstantVector::get(NewOps);
Nick Lewyckycb337992009-05-10 20:57:05 +0000345 } else {
346 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foadb81e4572011-04-13 13:46:01 +0000347 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattnerea693df2008-08-21 02:34:16 +0000348 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000349
Chris Lattnerea693df2008-08-21 02:34:16 +0000350 UserC->replaceAllUsesWith(NewC);
351 UserC->destroyConstant();
352 NewOps.clear();
353 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Nick Lewyckycb337992009-05-10 20:57:05 +0000355 // Update all ValueHandles, they should be the only users at this point.
356 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattnerea693df2008-08-21 02:34:16 +0000357 delete Placeholder;
358 }
359}
360
Devang Pateld5ac4042009-08-04 06:00:18 +0000361void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
362 if (Idx == size()) {
363 push_back(V);
364 return;
365 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000366
Devang Pateld5ac4042009-08-04 06:00:18 +0000367 if (Idx >= size())
368 resize(Idx+1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000369
Devang Pateld5ac4042009-08-04 06:00:18 +0000370 WeakVH &OldV = MDValuePtrs[Idx];
371 if (OldV == 0) {
372 OldV = V;
373 return;
374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000375
Devang Pateld5ac4042009-08-04 06:00:18 +0000376 // If there was a forward reference to this value, replace it.
Dan Gohman489b29b2010-08-20 22:02:26 +0000377 MDNode *PrevVal = cast<MDNode>(OldV);
Devang Pateld5ac4042009-08-04 06:00:18 +0000378 OldV->replaceAllUsesWith(V);
Dan Gohman489b29b2010-08-20 22:02:26 +0000379 MDNode::deleteTemporary(PrevVal);
Devang Patelc0ff8c82009-09-03 01:38:02 +0000380 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
381 // value for Idx.
382 MDValuePtrs[Idx] = V;
Devang Pateld5ac4042009-08-04 06:00:18 +0000383}
384
385Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
386 if (Idx >= size())
387 resize(Idx + 1);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000388
Devang Pateld5ac4042009-08-04 06:00:18 +0000389 if (Value *V = MDValuePtrs[Idx]) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000390 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
Devang Pateld5ac4042009-08-04 06:00:18 +0000391 return V;
392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000393
Devang Pateld5ac4042009-08-04 06:00:18 +0000394 // Create and return a placeholder, which will later be RAUW'd.
Jay Foadec9186b2011-04-21 19:59:31 +0000395 Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
Devang Pateld5ac4042009-08-04 06:00:18 +0000396 MDValuePtrs[Idx] = V;
397 return V;
398}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000399
Chris Lattner1afcace2011-07-09 17:41:24 +0000400Type *BitcodeReader::getTypeByID(unsigned ID) {
401 // The type table size is always specified correctly.
402 if (ID >= TypeList.size())
403 return 0;
404
405 if (Type *Ty = TypeList[ID])
406 return Ty;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000407
Chris Lattner1afcace2011-07-09 17:41:24 +0000408 // If we have a forward reference, the only possible case is when it is to a
409 // named struct. Just create a placeholder for now.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000410 return TypeList[ID] = StructType::create(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000411}
412
Chris Lattner1afcace2011-07-09 17:41:24 +0000413
Chris Lattner48c85b82007-05-04 03:30:17 +0000414//===----------------------------------------------------------------------===//
415// Functions for parsing blocks from the bitcode file
416//===----------------------------------------------------------------------===//
417
Devang Patel05988662008-09-25 21:00:45 +0000418bool BitcodeReader::ParseAttributeBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000419 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000420 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000421
Devang Patel19c87462008-09-26 22:53:05 +0000422 if (!MAttributes.empty())
Chris Lattner48c85b82007-05-04 03:30:17 +0000423 return Error("Multiple PARAMATTR blocks found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000424
Chris Lattner48c85b82007-05-04 03:30:17 +0000425 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000426
Devang Patel05988662008-09-25 21:00:45 +0000427 SmallVector<AttributeWithIndex, 8> Attrs;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000428
Chris Lattner48c85b82007-05-04 03:30:17 +0000429 // Read all the records.
430 while (1) {
431 unsigned Code = Stream.ReadCode();
432 if (Code == bitc::END_BLOCK) {
433 if (Stream.ReadBlockEnd())
434 return Error("Error at end of PARAMATTR block");
435 return false;
436 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000437
Chris Lattner48c85b82007-05-04 03:30:17 +0000438 if (Code == bitc::ENTER_SUBBLOCK) {
439 // No known subblocks, always skip them.
440 Stream.ReadSubBlockID();
441 if (Stream.SkipBlock())
442 return Error("Malformed block record");
443 continue;
444 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000445
Chris Lattner48c85b82007-05-04 03:30:17 +0000446 if (Code == bitc::DEFINE_ABBREV) {
447 Stream.ReadAbbrevRecord();
448 continue;
449 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000450
Chris Lattner48c85b82007-05-04 03:30:17 +0000451 // Read a record.
452 Record.clear();
453 switch (Stream.ReadRecord(Code, Record)) {
454 default: // Default behavior: ignore.
455 break;
456 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
457 if (Record.size() & 1)
458 return Error("Invalid ENTRY record");
459
Chris Lattner9a6cb152008-10-05 18:22:09 +0000460 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patel19c87462008-09-26 22:53:05 +0000461 // If Function attributes are using index 0 then transfer them
Chris Lattner9a6cb152008-10-05 18:22:09 +0000462 // to index ~0. Index 0 is used for return value attributes but used to be
463 // used for function attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000464 Attributes RetAttribute = Attribute::None;
465 Attributes FnAttribute = Attribute::None;
Chris Lattner48c85b82007-05-04 03:30:17 +0000466 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky73ddd4f2008-12-19 09:38:31 +0000467 // FIXME: remove in LLVM 3.0
468 // The alignment is stored as a 16-bit raw value from bits 31--16.
469 // We shift the bits above 31 down by 11 bits.
470
471 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
472 if (Alignment && !isPowerOf2_32(Alignment))
473 return Error("Alignment is not a power of two.");
474
475 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
476 if (Alignment)
477 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
478 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
479 Record[i+1] = ReconstitutedAttr;
480
Devang Patel19c87462008-09-26 22:53:05 +0000481 if (Record[i] == 0)
482 RetAttribute = Record[i+1];
483 else if (Record[i] == ~0U)
484 FnAttribute = Record[i+1];
485 }
Chris Lattner9a6cb152008-10-05 18:22:09 +0000486
487 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
488 Attribute::ReadOnly|Attribute::ReadNone);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000489
Chris Lattner9a6cb152008-10-05 18:22:09 +0000490 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
491 (RetAttribute & OldRetAttrs) != 0) {
492 if (FnAttribute == Attribute::None) { // add a slot so they get added.
493 Record.push_back(~0U);
494 Record.push_back(0);
Devang Patel19c87462008-09-26 22:53:05 +0000495 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000496
Chris Lattner9a6cb152008-10-05 18:22:09 +0000497 FnAttribute |= RetAttribute & OldRetAttrs;
498 RetAttribute &= ~OldRetAttrs;
Chris Lattner48c85b82007-05-04 03:30:17 +0000499 }
Chris Lattner461edd92008-03-12 02:25:52 +0000500
Devang Patel19c87462008-09-26 22:53:05 +0000501 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner9a6cb152008-10-05 18:22:09 +0000502 if (Record[i] == 0) {
503 if (RetAttribute != Attribute::None)
504 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
505 } else if (Record[i] == ~0U) {
506 if (FnAttribute != Attribute::None)
507 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
508 } else if (Record[i+1] != Attribute::None)
Devang Patel19c87462008-09-26 22:53:05 +0000509 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
510 }
Devang Patel19c87462008-09-26 22:53:05 +0000511
512 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Chris Lattner48c85b82007-05-04 03:30:17 +0000513 Attrs.clear();
514 break;
515 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000516 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000517 }
518}
519
Chris Lattner86697142007-05-01 05:01:34 +0000520bool BitcodeReader::ParseTypeTable() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000521 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000522 return Error("Malformed block record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000523
524 return ParseTypeTableBody();
525}
Daniel Dunbara279bc32009-09-20 02:20:51 +0000526
Chris Lattner1afcace2011-07-09 17:41:24 +0000527bool BitcodeReader::ParseTypeTableBody() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000528 if (!TypeList.empty())
529 return Error("Multiple TYPE_BLOCKs found!");
530
531 SmallVector<uint64_t, 64> Record;
532 unsigned NumRecords = 0;
533
Chris Lattner1afcace2011-07-09 17:41:24 +0000534 SmallString<64> TypeName;
535
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000536 // Read all the records for this type table.
537 while (1) {
538 unsigned Code = Stream.ReadCode();
539 if (Code == bitc::END_BLOCK) {
540 if (NumRecords != TypeList.size())
541 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000542 if (Stream.ReadBlockEnd())
543 return Error("Error at end of type table block");
544 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000545 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000546
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000547 if (Code == bitc::ENTER_SUBBLOCK) {
548 // No known subblocks, always skip them.
549 Stream.ReadSubBlockID();
550 if (Stream.SkipBlock())
551 return Error("Malformed block record");
552 continue;
553 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000554
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000555 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000556 Stream.ReadAbbrevRecord();
557 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000558 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000559
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000560 // Read a record.
561 Record.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000562 Type *ResultTy = 0;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000563 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000564 default: return Error("unknown type in type table");
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000565 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
566 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
567 // type list. This allows us to reserve space.
568 if (Record.size() < 1)
569 return Error("Invalid TYPE_CODE_NUMENTRY record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000570 TypeList.resize(Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000571 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000572 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson1d0be152009-08-13 21:58:54 +0000573 ResultTy = Type::getVoidTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000574 break;
Dan Gohmance163392011-12-17 00:04:22 +0000575 case bitc::TYPE_CODE_HALF: // HALF
576 ResultTy = Type::getHalfTy(Context);
577 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000578 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson1d0be152009-08-13 21:58:54 +0000579 ResultTy = Type::getFloatTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000580 break;
581 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson1d0be152009-08-13 21:58:54 +0000582 ResultTy = Type::getDoubleTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000583 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000584 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson1d0be152009-08-13 21:58:54 +0000585 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000586 break;
587 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000588 ResultTy = Type::getFP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000589 break;
590 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson1d0be152009-08-13 21:58:54 +0000591 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000592 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000593 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson1d0be152009-08-13 21:58:54 +0000594 ResultTy = Type::getLabelTy(Context);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000595 break;
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000596 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson1d0be152009-08-13 21:58:54 +0000597 ResultTy = Type::getMetadataTy(Context);
Nick Lewycky7a0370f2009-05-30 05:06:04 +0000598 break;
Dale Johannesenbb811a22010-09-10 20:55:01 +0000599 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
600 ResultTy = Type::getX86_MMXTy(Context);
601 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000602 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
603 if (Record.size() < 1)
604 return Error("Invalid Integer type record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000605
Owen Anderson1d0be152009-08-13 21:58:54 +0000606 ResultTy = IntegerType::get(Context, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000607 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000608 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lambfe63fb92007-12-11 08:59:05 +0000609 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000610 if (Record.size() < 1)
611 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000612 unsigned AddressSpace = 0;
613 if (Record.size() == 2)
614 AddressSpace = Record[1];
Chris Lattner1afcace2011-07-09 17:41:24 +0000615 ResultTy = getTypeByID(Record[0]);
616 if (ResultTy == 0) return Error("invalid element type in pointer type");
617 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000618 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000619 }
Chad Rosiercde54642011-11-03 00:14:01 +0000620 case bitc::TYPE_CODE_FUNCTION_OLD: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000621 // FIXME: attrid is dead, remove it in LLVM 3.0
622 // FUNCTION: [vararg, attrid, retty, paramty x N]
623 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000624 return Error("Invalid FUNCTION type record");
Jay Foad5fdd6c82011-07-12 14:06:48 +0000625 std::vector<Type*> ArgTys;
Chris Lattner1afcace2011-07-09 17:41:24 +0000626 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
627 if (Type *T = getTypeByID(Record[i]))
628 ArgTys.push_back(T);
629 else
630 break;
631 }
632
633 ResultTy = getTypeByID(Record[2]);
634 if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
635 return Error("invalid type in function type");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000636
Chris Lattner1afcace2011-07-09 17:41:24 +0000637 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000638 break;
639 }
Chad Rosiercde54642011-11-03 00:14:01 +0000640 case bitc::TYPE_CODE_FUNCTION: {
641 // FUNCTION: [vararg, retty, paramty x N]
642 if (Record.size() < 2)
643 return Error("Invalid FUNCTION type record");
644 std::vector<Type*> ArgTys;
645 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
646 if (Type *T = getTypeByID(Record[i]))
647 ArgTys.push_back(T);
648 else
649 break;
650 }
651
652 ResultTy = getTypeByID(Record[1]);
653 if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
654 return Error("invalid type in function type");
655
656 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
657 break;
658 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000659 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000660 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000661 return Error("Invalid STRUCT type record");
Chris Lattner1afcace2011-07-09 17:41:24 +0000662 std::vector<Type*> EltTys;
663 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
664 if (Type *T = getTypeByID(Record[i]))
665 EltTys.push_back(T);
666 else
667 break;
668 }
669 if (EltTys.size() != Record.size()-1)
670 return Error("invalid type in struct type");
Owen Andersond7f2a6c2009-08-05 23:16:16 +0000671 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000672 break;
673 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000674 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
675 if (ConvertToString(Record, 0, TypeName))
676 return Error("Invalid STRUCT_NAME record");
677 continue;
678
679 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
680 if (Record.size() < 1)
681 return Error("Invalid STRUCT type record");
682
683 if (NumRecords >= TypeList.size())
684 return Error("invalid TYPE table");
685
686 // Check to see if this was forward referenced, if so fill in the temp.
687 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
688 if (Res) {
689 Res->setName(TypeName);
690 TypeList[NumRecords] = 0;
691 } else // Otherwise, create a new struct.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000692 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000693 TypeName.clear();
694
695 SmallVector<Type*, 8> EltTys;
696 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
697 if (Type *T = getTypeByID(Record[i]))
698 EltTys.push_back(T);
699 else
700 break;
701 }
702 if (EltTys.size() != Record.size()-1)
703 return Error("invalid STRUCT type record");
704 Res->setBody(EltTys, Record[0]);
705 ResultTy = Res;
706 break;
707 }
708 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
709 if (Record.size() != 1)
710 return Error("Invalid OPAQUE type record");
711
712 if (NumRecords >= TypeList.size())
713 return Error("invalid TYPE table");
714
715 // Check to see if this was forward referenced, if so fill in the temp.
716 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
717 if (Res) {
718 Res->setName(TypeName);
719 TypeList[NumRecords] = 0;
720 } else // Otherwise, create a new struct with no body.
Chris Lattner3ebb6492011-08-12 18:06:37 +0000721 Res = StructType::create(Context, TypeName);
Chris Lattner1afcace2011-07-09 17:41:24 +0000722 TypeName.clear();
723 ResultTy = Res;
724 break;
725 }
726 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
727 if (Record.size() < 2)
728 return Error("Invalid ARRAY type record");
729 if ((ResultTy = getTypeByID(Record[1])))
730 ResultTy = ArrayType::get(ResultTy, Record[0]);
731 else
732 return Error("Invalid ARRAY type element");
733 break;
734 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
735 if (Record.size() < 2)
736 return Error("Invalid VECTOR type record");
737 if ((ResultTy = getTypeByID(Record[1])))
738 ResultTy = VectorType::get(ResultTy, Record[0]);
739 else
740 return Error("Invalid ARRAY type element");
741 break;
742 }
743
744 if (NumRecords >= TypeList.size())
745 return Error("invalid TYPE table");
746 assert(ResultTy && "Didn't read a type?");
747 assert(TypeList[NumRecords] == 0 && "Already read type?");
748 TypeList[NumRecords++] = ResultTy;
749 }
750}
751
Chris Lattner86697142007-05-01 05:01:34 +0000752bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000753 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000754 return Error("Malformed block record");
755
756 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000757
Chris Lattner0b2482a2007-04-23 21:26:05 +0000758 // Read all the records for this value table.
759 SmallString<128> ValueName;
760 while (1) {
761 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000762 if (Code == bitc::END_BLOCK) {
763 if (Stream.ReadBlockEnd())
764 return Error("Error at end of value symbol table block");
765 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000766 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000767 if (Code == bitc::ENTER_SUBBLOCK) {
768 // No known subblocks, always skip them.
769 Stream.ReadSubBlockID();
770 if (Stream.SkipBlock())
771 return Error("Malformed block record");
772 continue;
773 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000774
Chris Lattner0b2482a2007-04-23 21:26:05 +0000775 if (Code == bitc::DEFINE_ABBREV) {
776 Stream.ReadAbbrevRecord();
777 continue;
778 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000779
Chris Lattner0b2482a2007-04-23 21:26:05 +0000780 // Read a record.
781 Record.clear();
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000782 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattner0b2482a2007-04-23 21:26:05 +0000783 default: // Default behavior: unknown type.
784 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000785 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000786 if (ConvertToString(Record, 1, ValueName))
Nick Lewycky88b72932009-05-31 06:07:28 +0000787 return Error("Invalid VST_ENTRY record");
Chris Lattner0b2482a2007-04-23 21:26:05 +0000788 unsigned ValueID = Record[0];
789 if (ValueID >= ValueList.size())
790 return Error("Invalid Value ID in VST_ENTRY record");
791 Value *V = ValueList[ValueID];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000792
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000793 V->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner0b2482a2007-04-23 21:26:05 +0000794 ValueName.clear();
795 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000796 }
Bill Wendling5d7a5a42011-04-10 23:18:04 +0000797 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000798 if (ConvertToString(Record, 1, ValueName))
799 return Error("Invalid VST_BBENTRY record");
800 BasicBlock *BB = getBasicBlock(Record[0]);
801 if (BB == 0)
802 return Error("Invalid BB ID in VST_BBENTRY record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000803
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000804 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattnere825ed52007-05-03 22:18:21 +0000805 ValueName.clear();
806 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000807 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000808 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000809 }
810}
811
Devang Patele54abc92009-07-22 17:43:22 +0000812bool BitcodeReader::ParseMetadata() {
Devang Patel23598502010-01-11 18:52:33 +0000813 unsigned NextMDValueNo = MDValueList.size();
Devang Patele54abc92009-07-22 17:43:22 +0000814
815 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
816 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000817
Devang Patele54abc92009-07-22 17:43:22 +0000818 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000819
Devang Patele54abc92009-07-22 17:43:22 +0000820 // Read all the records.
821 while (1) {
822 unsigned Code = Stream.ReadCode();
823 if (Code == bitc::END_BLOCK) {
824 if (Stream.ReadBlockEnd())
825 return Error("Error at end of PARAMATTR block");
826 return false;
827 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000828
Devang Patele54abc92009-07-22 17:43:22 +0000829 if (Code == bitc::ENTER_SUBBLOCK) {
830 // No known subblocks, always skip them.
831 Stream.ReadSubBlockID();
832 if (Stream.SkipBlock())
833 return Error("Malformed block record");
834 continue;
835 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000836
Devang Patele54abc92009-07-22 17:43:22 +0000837 if (Code == bitc::DEFINE_ABBREV) {
838 Stream.ReadAbbrevRecord();
839 continue;
840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000841
Victor Hernandez24e64df2010-01-10 07:14:18 +0000842 bool IsFunctionLocal = false;
Devang Patele54abc92009-07-22 17:43:22 +0000843 // Read a record.
844 Record.clear();
Dan Gohman9b10dfb2010-09-13 18:00:48 +0000845 Code = Stream.ReadRecord(Code, Record);
846 switch (Code) {
Devang Patele54abc92009-07-22 17:43:22 +0000847 default: // Default behavior: ignore.
848 break;
Devang Patelaa993142009-07-29 22:34:41 +0000849 case bitc::METADATA_NAME: {
850 // Read named of the named metadata.
851 unsigned NameLength = Record.size();
852 SmallString<8> Name;
853 Name.resize(NameLength);
854 for (unsigned i = 0; i != NameLength; ++i)
855 Name[i] = Record[i];
856 Record.clear();
857 Code = Stream.ReadCode();
858
Chris Lattner9d61dd92011-06-17 17:50:30 +0000859 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Dan Gohman70c2fc02010-09-09 23:12:39 +0000860 unsigned NextBitCode = Stream.ReadRecord(Code, Record);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000861 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patelaa993142009-07-29 22:34:41 +0000862
863 // Read named metadata elements.
864 unsigned Size = Record.size();
Dan Gohman17aa92c2010-07-21 23:38:33 +0000865 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patelaa993142009-07-29 22:34:41 +0000866 for (unsigned i = 0; i != Size; ++i) {
Chris Lattner70644e92010-01-09 02:02:37 +0000867 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
868 if (MD == 0)
869 return Error("Malformed metadata record");
Dan Gohman17aa92c2010-07-21 23:38:33 +0000870 NMD->addOperand(MD);
Devang Patelaa993142009-07-29 22:34:41 +0000871 }
Devang Patelaa993142009-07-29 22:34:41 +0000872 break;
873 }
Chris Lattner9d61dd92011-06-17 17:50:30 +0000874 case bitc::METADATA_FN_NODE:
Victor Hernandez24e64df2010-01-10 07:14:18 +0000875 IsFunctionLocal = true;
876 // fall-through
Chris Lattner9d61dd92011-06-17 17:50:30 +0000877 case bitc::METADATA_NODE: {
Dan Gohmanac809752010-07-13 19:33:27 +0000878 if (Record.size() % 2 == 1)
Chris Lattner9d61dd92011-06-17 17:50:30 +0000879 return Error("Invalid METADATA_NODE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +0000880
Devang Patel104cf9e2009-07-23 01:07:34 +0000881 unsigned Size = Record.size();
882 SmallVector<Value*, 8> Elts;
883 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000884 Type *Ty = getTypeByID(Record[i]);
Chris Lattner9d61dd92011-06-17 17:50:30 +0000885 if (!Ty) return Error("Invalid METADATA_NODE record");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000886 if (Ty->isMetadataTy())
Devang Pateld5ac4042009-08-04 06:00:18 +0000887 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Benjamin Kramerf0127052010-01-05 13:12:22 +0000888 else if (!Ty->isVoidTy())
Devang Patel104cf9e2009-07-23 01:07:34 +0000889 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
890 else
891 Elts.push_back(NULL);
892 }
Jay Foadec9186b2011-04-21 19:59:31 +0000893 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000894 IsFunctionLocal = false;
Devang Patel23598502010-01-11 18:52:33 +0000895 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patel104cf9e2009-07-23 01:07:34 +0000896 break;
897 }
Devang Patele54abc92009-07-22 17:43:22 +0000898 case bitc::METADATA_STRING: {
899 unsigned MDStringLength = Record.size();
900 SmallString<8> String;
901 String.resize(MDStringLength);
902 for (unsigned i = 0; i != MDStringLength; ++i)
903 String[i] = Record[i];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000904 Value *V = MDString::get(Context,
Owen Anderson647e3012009-07-31 21:35:40 +0000905 StringRef(String.data(), String.size()));
Devang Patel23598502010-01-11 18:52:33 +0000906 MDValueList.AssignValue(V, NextMDValueNo++);
Devang Patele54abc92009-07-22 17:43:22 +0000907 break;
908 }
Devang Patele8e02132009-09-18 19:26:43 +0000909 case bitc::METADATA_KIND: {
910 unsigned RecordLength = Record.size();
911 if (Record.empty() || RecordLength < 2)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000912 return Error("Invalid METADATA_KIND record");
Devang Patele8e02132009-09-18 19:26:43 +0000913 SmallString<8> Name;
914 Name.resize(RecordLength-1);
Devang Patela2148402009-09-28 21:14:55 +0000915 unsigned Kind = Record[0];
Devang Patele8e02132009-09-18 19:26:43 +0000916 for (unsigned i = 1; i != RecordLength; ++i)
Daniel Dunbara279bc32009-09-20 02:20:51 +0000917 Name[i-1] = Record[i];
Chris Lattner0eb41982009-12-28 20:45:51 +0000918
Chris Lattner08113472009-12-29 09:01:33 +0000919 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman19538d12010-07-20 21:42:28 +0000920 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
921 return Error("Conflicting METADATA_KIND records");
Devang Patele8e02132009-09-18 19:26:43 +0000922 break;
923 }
Devang Patele54abc92009-07-22 17:43:22 +0000924 }
925 }
926}
927
Chris Lattner0eef0802007-04-24 04:04:35 +0000928/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
929/// the LSB for dense VBR encoding.
930static uint64_t DecodeSignRotatedValue(uint64_t V) {
931 if ((V & 1) == 0)
932 return V >> 1;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000933 if (V != 1)
Chris Lattner0eef0802007-04-24 04:04:35 +0000934 return -(V >> 1);
935 // There is no such thing as -0 with integers. "-0" really means MININT.
936 return 1ULL << 63;
937}
938
Chris Lattner07d98b42007-04-26 02:46:40 +0000939/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
940/// values and aliases that we can.
941bool BitcodeReader::ResolveGlobalAndAliasInits() {
942 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
943 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000944
Chris Lattner07d98b42007-04-26 02:46:40 +0000945 GlobalInitWorklist.swap(GlobalInits);
946 AliasInitWorklist.swap(AliasInits);
947
948 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000949 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000950 if (ValID >= ValueList.size()) {
951 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000952 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000953 } else {
954 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
955 GlobalInitWorklist.back().first->setInitializer(C);
956 else
957 return Error("Global variable initializer is not a constant!");
958 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000959 GlobalInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000960 }
961
962 while (!AliasInitWorklist.empty()) {
963 unsigned ValID = AliasInitWorklist.back().second;
964 if (ValID >= ValueList.size()) {
965 AliasInits.push_back(AliasInitWorklist.back());
966 } else {
967 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000968 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000969 else
970 return Error("Alias initializer is not a constant!");
971 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000972 AliasInitWorklist.pop_back();
Chris Lattner07d98b42007-04-26 02:46:40 +0000973 }
974 return false;
975}
976
Chris Lattner86697142007-05-01 05:01:34 +0000977bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000978 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000979 return Error("Malformed block record");
980
981 SmallVector<uint64_t, 64> Record;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000982
Chris Lattnere16504e2007-04-24 03:30:34 +0000983 // Read all the records for this value table.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000984 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner522b7b12007-04-24 05:48:56 +0000985 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000986 while (1) {
987 unsigned Code = Stream.ReadCode();
Chris Lattnerea693df2008-08-21 02:34:16 +0000988 if (Code == bitc::END_BLOCK)
989 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000990
Chris Lattnere16504e2007-04-24 03:30:34 +0000991 if (Code == bitc::ENTER_SUBBLOCK) {
992 // No known subblocks, always skip them.
993 Stream.ReadSubBlockID();
994 if (Stream.SkipBlock())
995 return Error("Malformed block record");
996 continue;
997 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000998
Chris Lattnere16504e2007-04-24 03:30:34 +0000999 if (Code == bitc::DEFINE_ABBREV) {
1000 Stream.ReadAbbrevRecord();
1001 continue;
1002 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001003
Chris Lattnere16504e2007-04-24 03:30:34 +00001004 // Read a record.
1005 Record.clear();
1006 Value *V = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001007 unsigned BitCode = Stream.ReadRecord(Code, Record);
1008 switch (BitCode) {
Chris Lattnere16504e2007-04-24 03:30:34 +00001009 default: // Default behavior: unknown constant
1010 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001011 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001012 break;
1013 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1014 if (Record.empty())
1015 return Error("Malformed CST_SETTYPE record");
1016 if (Record[0] >= TypeList.size())
1017 return Error("Invalid Type ID in CST_SETTYPE record");
1018 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +00001019 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +00001020 case bitc::CST_CODE_NULL: // NULL
Owen Andersona7235ea2009-07-31 20:28:14 +00001021 V = Constant::getNullValue(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001022 break;
1023 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001024 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001025 return Error("Invalid CST_INTEGER record");
Owen Andersoneed707b2009-07-24 23:12:02 +00001026 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +00001027 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001028 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands1df98592010-02-16 11:11:14 +00001029 if (!CurTy->isIntegerTy() || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +00001030 return Error("Invalid WIDE_INTEGER record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001031
Chris Lattner15e6d172007-05-04 19:11:41 +00001032 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +00001033 SmallVector<uint64_t, 8> Words;
1034 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +00001035 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001036 Words[i] = DecodeSignRotatedValue(Record[i]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001037 V = ConstantInt::get(Context,
Owen Andersoneed707b2009-07-24 23:12:02 +00001038 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001039 Words));
Chris Lattner0eef0802007-04-24 04:04:35 +00001040 break;
1041 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001042 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +00001043 if (Record.empty())
1044 return Error("Invalid FLOAT record");
Dan Gohmance163392011-12-17 00:04:22 +00001045 if (CurTy->isHalfTy())
1046 V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1047 else if (CurTy->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001048 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001049 else if (CurTy->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001050 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001051 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen1b25cb22009-03-23 21:16:53 +00001052 // Bits are not stored the same way as a normal i80 APInt, compensate.
1053 uint64_t Rearrange[2];
1054 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1055 Rearrange[1] = Record[0] >> 48;
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001056 V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001057 } else if (CurTy->isFP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001058 V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001059 else if (CurTy->isPPC_FP128Ty())
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001060 V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
Chris Lattnere16504e2007-04-24 03:30:34 +00001061 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001062 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +00001063 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00001064 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001065
Chris Lattner15e6d172007-05-04 19:11:41 +00001066 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1067 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +00001068 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001069
Chris Lattner15e6d172007-05-04 19:11:41 +00001070 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +00001071 std::vector<Constant*> Elts;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001072
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001073 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner522b7b12007-04-24 05:48:56 +00001074 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001075 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +00001076 STy->getElementType(i)));
Owen Anderson8fa33382009-07-27 22:29:26 +00001077 V = ConstantStruct::get(STy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001078 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1079 Type *EltTy = ATy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001080 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001081 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001082 V = ConstantArray::get(ATy, Elts);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001083 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1084 Type *EltTy = VTy->getElementType();
Chris Lattner522b7b12007-04-24 05:48:56 +00001085 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +00001086 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00001087 V = ConstantVector::get(Elts);
Chris Lattner522b7b12007-04-24 05:48:56 +00001088 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001089 V = UndefValue::get(CurTy);
Chris Lattner522b7b12007-04-24 05:48:56 +00001090 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001091 break;
1092 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001093 case bitc::CST_CODE_STRING: { // STRING: [values]
1094 if (Record.empty())
1095 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001096
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001097 ArrayType *ATy = cast<ArrayType>(CurTy);
1098 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001099
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001100 unsigned Size = Record.size();
1101 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001102 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001103 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +00001104 V = ConstantArray::get(ATy, Elts);
Chris Lattnerff7fc5d2007-05-06 00:35:24 +00001105 break;
1106 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001107 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1108 if (Record.empty())
1109 return Error("Invalid CST_AGGREGATE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001110
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001111 ArrayType *ATy = cast<ArrayType>(CurTy);
1112 Type *EltTy = ATy->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001113
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001114 unsigned Size = Record.size();
1115 std::vector<Constant*> Elts;
1116 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneed707b2009-07-24 23:12:02 +00001117 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Andersona7235ea2009-07-31 20:28:14 +00001118 Elts.push_back(Constant::getNullValue(EltTy));
Owen Anderson1fd70962009-07-28 18:32:17 +00001119 V = ConstantArray::get(ATy, Elts);
Chris Lattnercb3d91b2007-05-06 00:53:07 +00001120 break;
1121 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001122 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
1123 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1124 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001125 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001126 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001127 } else {
1128 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1129 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001130 unsigned Flags = 0;
1131 if (Record.size() >= 4) {
1132 if (Opc == Instruction::Add ||
1133 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001134 Opc == Instruction::Mul ||
1135 Opc == Instruction::Shl) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001136 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1137 Flags |= OverflowingBinaryOperator::NoSignedWrap;
1138 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1139 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35bda892011-02-06 21:44:57 +00001140 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001141 Opc == Instruction::UDiv ||
1142 Opc == Instruction::LShr ||
1143 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00001144 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001145 Flags |= SDivOperator::IsExact;
1146 }
1147 }
1148 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001149 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001150 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001151 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001152 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
1153 if (Record.size() < 3) return Error("Invalid CE_CAST record");
1154 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001155 if (Opc < 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001156 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001157 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001158 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +00001159 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001160 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001161 V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001162 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001163 break;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001164 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00001165 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001166 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +00001167 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001168 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +00001169 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001170 Type *ElTy = getTypeByID(Record[i]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001171 if (!ElTy) return Error("Invalid CE_GEP record");
1172 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1173 }
Jay Foaddab3d292011-07-21 14:31:17 +00001174 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad4b5e2072011-07-21 15:15:37 +00001175 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1176 BitCode ==
1177 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001178 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001179 }
1180 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1181 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Andersonbaf3c402009-07-29 18:55:55 +00001182 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
Owen Anderson1d0be152009-08-13 21:58:54 +00001183 Type::getInt1Ty(Context)),
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001184 ValueList.getConstantFwdRef(Record[1],CurTy),
1185 ValueList.getConstantFwdRef(Record[2],CurTy));
1186 break;
1187 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1188 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001189 VectorType *OpTy =
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001190 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1191 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1192 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson1d0be152009-08-13 21:58:54 +00001193 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001194 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001195 break;
1196 }
1197 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001198 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001199 if (Record.size() < 3 || OpTy == 0)
1200 return Error("Invalid CE_INSERTELT record");
1201 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1202 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1203 OpTy->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001204 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001205 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001206 break;
1207 }
1208 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001209 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001210 if (Record.size() < 3 || OpTy == 0)
Nate Begeman0f123cf2009-02-12 21:28:33 +00001211 return Error("Invalid CE_SHUFFLEVEC record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001212 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1213 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001214 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001215 OpTy->getNumElements());
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001216 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001217 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001218 break;
1219 }
Nate Begeman0f123cf2009-02-12 21:28:33 +00001220 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001221 VectorType *RTy = dyn_cast<VectorType>(CurTy);
1222 VectorType *OpTy =
Duncan Sandsf22b7462010-10-28 15:47:26 +00001223 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Nate Begeman0f123cf2009-02-12 21:28:33 +00001224 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1225 return Error("Invalid CE_SHUFVEC_EX record");
1226 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1227 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001228 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Anderson74a77812009-07-07 20:18:58 +00001229 RTy->getNumElements());
Nate Begeman0f123cf2009-02-12 21:28:33 +00001230 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001231 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman0f123cf2009-02-12 21:28:33 +00001232 break;
1233 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001234 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1235 if (Record.size() < 4) return Error("Invalid CE_CMP record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001236 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001237 if (OpTy == 0) return Error("Invalid CE_CMP record");
1238 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1239 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1240
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001241 if (OpTy->isFPOrFPVectorTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001242 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemanac80ade2008-05-12 19:01:56 +00001243 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001244 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattnerf581c3b2007-04-24 07:07:11 +00001245 break;
Chris Lattner522b7b12007-04-24 05:48:56 +00001246 }
Chris Lattner2bce93a2007-05-06 01:58:20 +00001247 case bitc::CST_CODE_INLINEASM: {
1248 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1249 std::string AsmStr, ConstrStr;
Dale Johannesen43602982009-10-13 20:46:56 +00001250 bool HasSideEffects = Record[0] & 1;
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001251 bool IsAlignStack = Record[0] >> 1;
Chris Lattner2bce93a2007-05-06 01:58:20 +00001252 unsigned AsmStrSize = Record[1];
1253 if (2+AsmStrSize >= Record.size())
1254 return Error("Invalid INLINEASM record");
1255 unsigned ConstStrSize = Record[2+AsmStrSize];
1256 if (3+AsmStrSize+ConstStrSize > Record.size())
1257 return Error("Invalid INLINEASM record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001258
Chris Lattner2bce93a2007-05-06 01:58:20 +00001259 for (unsigned i = 0; i != AsmStrSize; ++i)
1260 AsmStr += (char)Record[2+i];
1261 for (unsigned i = 0; i != ConstStrSize; ++i)
1262 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001263 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001264 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen8ba2d5b2009-10-21 23:28:00 +00001265 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattner2bce93a2007-05-06 01:58:20 +00001266 break;
1267 }
Chris Lattner50b136d2009-10-28 05:53:48 +00001268 case bitc::CST_CODE_BLOCKADDRESS:{
1269 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001270 Type *FnTy = getTypeByID(Record[0]);
Chris Lattner50b136d2009-10-28 05:53:48 +00001271 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1272 Function *Fn =
1273 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1274 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1275
1276 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1277 Type::getInt8Ty(Context),
1278 false, GlobalValue::InternalLinkage,
1279 0, "");
1280 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1281 V = FwdRef;
1282 break;
1283 }
Chris Lattnere16504e2007-04-24 03:30:34 +00001284 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001285
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001286 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +00001287 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +00001288 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001289
Chris Lattnerea693df2008-08-21 02:34:16 +00001290 if (NextCstNo != ValueList.size())
1291 return Error("Invalid constant reference!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001292
Chris Lattnerea693df2008-08-21 02:34:16 +00001293 if (Stream.ReadBlockEnd())
1294 return Error("Error at end of constants block");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001295
Chris Lattnerea693df2008-08-21 02:34:16 +00001296 // Once all the constants have been read, go through and resolve forward
1297 // references.
1298 ValueList.ResolveConstantForwardRefs();
1299 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +00001300}
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001301
Chad Rosiercbbb0962011-12-07 21:44:12 +00001302bool BitcodeReader::ParseUseLists() {
1303 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1304 return Error("Malformed block record");
1305
1306 SmallVector<uint64_t, 64> Record;
1307
1308 // Read all the records.
1309 while (1) {
1310 unsigned Code = Stream.ReadCode();
1311 if (Code == bitc::END_BLOCK) {
1312 if (Stream.ReadBlockEnd())
1313 return Error("Error at end of use-list table block");
1314 return false;
1315 }
1316
1317 if (Code == bitc::ENTER_SUBBLOCK) {
1318 // No known subblocks, always skip them.
1319 Stream.ReadSubBlockID();
1320 if (Stream.SkipBlock())
1321 return Error("Malformed block record");
1322 continue;
1323 }
1324
1325 if (Code == bitc::DEFINE_ABBREV) {
1326 Stream.ReadAbbrevRecord();
1327 continue;
1328 }
1329
1330 // Read a use list record.
1331 Record.clear();
1332 switch (Stream.ReadRecord(Code, Record)) {
1333 default: // Default behavior: unknown type.
1334 break;
1335 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1336 unsigned RecordLength = Record.size();
1337 if (RecordLength < 1)
1338 return Error ("Invalid UseList reader!");
1339 UseListRecords.push_back(Record);
1340 break;
1341 }
1342 }
1343 }
1344}
1345
Chris Lattner980e5aa2007-05-01 05:52:21 +00001346/// RememberAndSkipFunctionBody - When we see the block for a function body,
1347/// remember where it is and then skip it. This lets us lazily deserialize the
1348/// functions.
1349bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +00001350 // Get the function we are talking about.
1351 if (FunctionsWithBodies.empty())
1352 return Error("Insufficient function protos");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001353
Chris Lattner48f84872007-05-01 04:59:48 +00001354 Function *Fn = FunctionsWithBodies.back();
1355 FunctionsWithBodies.pop_back();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001356
Chris Lattner48f84872007-05-01 04:59:48 +00001357 // Save the current stream state.
1358 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001359 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001360
Chris Lattner48f84872007-05-01 04:59:48 +00001361 // Skip over the function block for now.
1362 if (Stream.SkipBlock())
1363 return Error("Malformed block record");
1364 return false;
1365}
1366
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001367bool BitcodeReader::ParseModule() {
Chris Lattnere17b6582007-05-05 00:17:00 +00001368 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001369 return Error("Malformed block record");
1370
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001371 SmallVector<uint64_t, 64> Record;
1372 std::vector<std::string> SectionTable;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001373 std::vector<std::string> GCTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001374
1375 // Read all the records for this module.
1376 while (!Stream.AtEndOfStream()) {
1377 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +00001378 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +00001379 if (Stream.ReadBlockEnd())
1380 return Error("Error at end of module block");
1381
1382 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +00001383 ResolveGlobalAndAliasInits();
1384 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +00001385 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +00001386 if (!FunctionsWithBodies.empty())
1387 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001388
Chandler Carruth69940402007-08-04 01:51:18 +00001389 // Look for intrinsic functions which need to be upgraded at some point
1390 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1391 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +00001392 Function* NewFn;
1393 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +00001394 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1395 }
1396
Bill Wendlingde49f362010-09-10 18:51:56 +00001397 // Look for global variables which need to be renamed.
1398 for (Module::global_iterator
1399 GI = TheModule->global_begin(), GE = TheModule->global_end();
1400 GI != GE; ++GI)
1401 UpgradeGlobalVariable(GI);
1402
Chris Lattner980e5aa2007-05-01 05:52:21 +00001403 // Force deallocation of memory for these vectors to favor the client that
1404 // want lazy deserialization.
1405 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1406 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1407 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +00001408 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +00001409 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001410
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001411 if (Code == bitc::ENTER_SUBBLOCK) {
1412 switch (Stream.ReadSubBlockID()) {
1413 default: // Skip unknown content.
1414 if (Stream.SkipBlock())
1415 return Error("Malformed block record");
1416 break;
Chris Lattner3f799802007-05-05 18:57:30 +00001417 case bitc::BLOCKINFO_BLOCK_ID:
1418 if (Stream.ReadBlockInfoBlock())
1419 return Error("Malformed BlockInfoBlock");
1420 break;
Chris Lattner48c85b82007-05-04 03:30:17 +00001421 case bitc::PARAMATTR_BLOCK_ID:
Devang Patel05988662008-09-25 21:00:45 +00001422 if (ParseAttributeBlock())
Chris Lattner48c85b82007-05-04 03:30:17 +00001423 return true;
1424 break;
Chris Lattner1afcace2011-07-09 17:41:24 +00001425 case bitc::TYPE_BLOCK_ID_NEW:
Chris Lattner86697142007-05-01 05:01:34 +00001426 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001427 return true;
1428 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +00001429 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001430 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +00001431 return true;
1432 break;
Chris Lattnere16504e2007-04-24 03:30:34 +00001433 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001434 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +00001435 return true;
1436 break;
Devang Patele54abc92009-07-22 17:43:22 +00001437 case bitc::METADATA_BLOCK_ID:
1438 if (ParseMetadata())
1439 return true;
1440 break;
Chris Lattner48f84872007-05-01 04:59:48 +00001441 case bitc::FUNCTION_BLOCK_ID:
1442 // If this is the first function body we've seen, reverse the
1443 // FunctionsWithBodies list.
1444 if (!HasReversedFunctionsWithBodies) {
1445 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1446 HasReversedFunctionsWithBodies = true;
1447 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001448
Chris Lattner980e5aa2007-05-01 05:52:21 +00001449 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +00001450 return true;
1451 break;
Chad Rosiercbbb0962011-12-07 21:44:12 +00001452 case bitc::USELIST_BLOCK_ID:
1453 if (ParseUseLists())
1454 return true;
1455 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001456 }
1457 continue;
1458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001460 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +00001461 Stream.ReadAbbrevRecord();
1462 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001463 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001464
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001465 // Read a record.
1466 switch (Stream.ReadRecord(Code, Record)) {
1467 default: break; // Default behavior, ignore unknown content.
1468 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1469 if (Record.size() < 1)
1470 return Error("Malformed MODULE_CODE_VERSION");
1471 // Only version #0 is supported so far.
1472 if (Record[0] != 0)
1473 return Error("Unknown bitstream version!");
1474 break;
Chris Lattner15e6d172007-05-04 19:11:41 +00001475 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001476 std::string S;
1477 if (ConvertToString(Record, 0, S))
1478 return Error("Invalid MODULE_CODE_TRIPLE record");
1479 TheModule->setTargetTriple(S);
1480 break;
1481 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001482 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001483 std::string S;
1484 if (ConvertToString(Record, 0, S))
1485 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1486 TheModule->setDataLayout(S);
1487 break;
1488 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001489 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001490 std::string S;
1491 if (ConvertToString(Record, 0, S))
1492 return Error("Invalid MODULE_CODE_ASM record");
1493 TheModule->setModuleInlineAsm(S);
1494 break;
1495 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001496 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001497 std::string S;
1498 if (ConvertToString(Record, 0, S))
1499 return Error("Invalid MODULE_CODE_DEPLIB record");
1500 TheModule->addLibrary(S);
1501 break;
1502 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001503 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001504 std::string S;
1505 if (ConvertToString(Record, 0, S))
1506 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1507 SectionTable.push_back(S);
1508 break;
1509 }
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001510 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001511 std::string S;
1512 if (ConvertToString(Record, 0, S))
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001513 return Error("Invalid MODULE_CODE_GCNAME record");
1514 GCTable.push_back(S);
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001515 break;
1516 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001517 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindolabea46262011-01-08 16:42:36 +00001518 // linkage, alignment, section, visibility, threadlocal,
1519 // unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001520 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001521 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001522 return Error("Invalid MODULE_CODE_GLOBALVAR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001523 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001524 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
Duncan Sands1df98592010-02-16 11:11:14 +00001525 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001526 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001527 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001528 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001529
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001530 bool isConstant = Record[1];
1531 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1532 unsigned Alignment = (1 << Record[4]) >> 1;
1533 std::string Section;
1534 if (Record[5]) {
1535 if (Record[5]-1 >= SectionTable.size())
1536 return Error("Invalid section ID");
1537 Section = SectionTable[Record[5]-1];
1538 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001539 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001540 if (Record.size() > 6)
1541 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001542 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001543 if (Record.size() > 7)
1544 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001545
Rafael Espindolabea46262011-01-08 16:42:36 +00001546 bool UnnamedAddr = false;
1547 if (Record.size() > 8)
1548 UnnamedAddr = Record[8];
1549
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001550 GlobalVariable *NewGV =
Daniel Dunbara279bc32009-09-20 02:20:51 +00001551 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lambfe63fb92007-12-11 08:59:05 +00001552 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001553 NewGV->setAlignment(Alignment);
1554 if (!Section.empty())
1555 NewGV->setSection(Section);
1556 NewGV->setVisibility(Visibility);
1557 NewGV->setThreadLocal(isThreadLocal);
Rafael Espindolabea46262011-01-08 16:42:36 +00001558 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001559
Chris Lattner0b2482a2007-04-23 21:26:05 +00001560 ValueList.push_back(NewGV);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001561
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001562 // Remember which value to use for the global initializer.
1563 if (unsigned InitID = Record[2])
1564 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001565 break;
1566 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001567 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Rafael Espindolabea46262011-01-08 16:42:36 +00001568 // alignment, section, visibility, gc, unnamed_addr]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001569 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001570 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001571 return Error("Invalid MODULE_CODE_FUNCTION record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001572 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001573 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
Duncan Sands1df98592010-02-16 11:11:14 +00001574 if (!Ty->isPointerTy())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001575 return Error("Function not a pointer type!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001576 FunctionType *FTy =
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001577 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1578 if (!FTy)
1579 return Error("Function not a pointer to function type!");
1580
Gabor Greif051a9502008-04-06 20:25:17 +00001581 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1582 "", TheModule);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001583
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001584 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner48f84872007-05-01 04:59:48 +00001585 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001586 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Patel05988662008-09-25 21:00:45 +00001587 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001588
Chris Lattnera9bb7132007-05-08 05:38:01 +00001589 Func->setAlignment((1 << Record[5]) >> 1);
1590 if (Record[6]) {
1591 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001592 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001593 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001594 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001595 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001596 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00001597 if (Record[8]-1 > GCTable.size())
1598 return Error("Invalid GC ID");
1599 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001600 }
Rafael Espindolabea46262011-01-08 16:42:36 +00001601 bool UnnamedAddr = false;
1602 if (Record.size() > 9)
1603 UnnamedAddr = Record[9];
1604 Func->setUnnamedAddr(UnnamedAddr);
Chris Lattner0b2482a2007-04-23 21:26:05 +00001605 ValueList.push_back(Func);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001606
Chris Lattner48f84872007-05-01 04:59:48 +00001607 // If this is a function with a body, remember the prototype we are
1608 // creating now, so that we can match up the body with them later.
1609 if (!isProto)
1610 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001611 break;
1612 }
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001613 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikovf8342b92008-03-11 21:40:17 +00001614 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Chris Lattner198f34a2007-04-26 03:27:58 +00001615 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001616 if (Record.size() < 3)
1617 return Error("Invalid MODULE_ALIAS record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001618 Type *Ty = getTypeByID(Record[0]);
Duncan Sandsf22b7462010-10-28 15:47:26 +00001619 if (!Ty) return Error("Invalid MODULE_ALIAS record");
Duncan Sands1df98592010-02-16 11:11:14 +00001620 if (!Ty->isPointerTy())
Chris Lattner07d98b42007-04-26 02:46:40 +00001621 return Error("Function not a pointer type!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001622
Chris Lattner07d98b42007-04-26 02:46:40 +00001623 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1624 "", 0, TheModule);
Anton Korobeynikov91342d82008-03-12 00:49:19 +00001625 // Old bitcode files didn't have visibility field.
1626 if (Record.size() > 3)
1627 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Chris Lattner07d98b42007-04-26 02:46:40 +00001628 ValueList.push_back(NewGA);
1629 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1630 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001631 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001632 /// MODULE_CODE_PURGEVALS: [numvals]
1633 case bitc::MODULE_CODE_PURGEVALS:
1634 // Trim down the value list to the specified size.
1635 if (Record.size() < 1 || Record[0] > ValueList.size())
1636 return Error("Invalid MODULE_PURGEVALS record");
1637 ValueList.shrinkTo(Record[0]);
1638 break;
1639 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001640 Record.clear();
1641 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001642
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001643 return Error("Premature end of bitstream");
1644}
1645
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001646bool BitcodeReader::ParseBitcodeInto(Module *M) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001647 TheModule = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001648
Chris Lattnerc453f762007-04-29 07:54:31 +00001649 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner6fa6a322008-07-09 05:14:23 +00001650 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001651
Dan Gohmana4ae3a12010-04-02 00:03:51 +00001652 if (Buffer->getBufferSize() & 3) {
1653 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1654 return Error("Invalid bitcode signature");
1655 else
1656 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1657 }
1658
Chris Lattner6fa6a322008-07-09 05:14:23 +00001659 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1660 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnere2a466b2009-04-06 20:54:32 +00001661 if (isBitcodeWrapper(BufPtr, BufEnd))
1662 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner6fa6a322008-07-09 05:14:23 +00001663 return Error("Invalid bitcode wrapper header");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattner962dde32009-04-26 20:59:02 +00001665 StreamFile.init(BufPtr, BufEnd);
1666 Stream.init(StreamFile);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001667
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001668 // Sniff for the signature.
1669 if (Stream.Read(8) != 'B' ||
1670 Stream.Read(8) != 'C' ||
1671 Stream.Read(4) != 0x0 ||
1672 Stream.Read(4) != 0xC ||
1673 Stream.Read(4) != 0xE ||
1674 Stream.Read(4) != 0xD)
1675 return Error("Invalid bitcode signature");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001677 // We expect a number of well-defined blocks, though we don't necessarily
1678 // need to understand them all.
1679 while (!Stream.AtEndOfStream()) {
1680 unsigned Code = Stream.ReadCode();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Rafael Espindolac9687b32011-05-26 18:59:54 +00001682 if (Code != bitc::ENTER_SUBBLOCK) {
1683
Chad Rosier6ff9aa22011-08-09 22:23:40 +00001684 // The ranlib in xcode 4 will align archive members by appending newlines
1685 // to the end of them. If this file size is a multiple of 4 but not 8, we
1686 // have to read and ignore these final 4 bytes :-(
Rafael Espindolac9687b32011-05-26 18:59:54 +00001687 if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1688 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1689 Stream.AtEndOfStream())
1690 return false;
1691
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001692 return Error("Invalid record at top-level");
Rafael Espindolac9687b32011-05-26 18:59:54 +00001693 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001694
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001695 unsigned BlockID = Stream.ReadSubBlockID();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001697 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001698 switch (BlockID) {
1699 case bitc::BLOCKINFO_BLOCK_ID:
1700 if (Stream.ReadBlockInfoBlock())
1701 return Error("Malformed BlockInfoBlock");
1702 break;
1703 case bitc::MODULE_BLOCK_ID:
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001704 // Reject multiple MODULE_BLOCK's in a single bitstream.
1705 if (TheModule)
1706 return Error("Multiple MODULE_BLOCKs in same stream");
1707 TheModule = M;
1708 if (ParseModule())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001709 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001710 break;
1711 default:
1712 if (Stream.SkipBlock())
1713 return Error("Malformed block record");
1714 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001715 }
1716 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001717
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001718 return false;
1719}
Chris Lattnerc453f762007-04-29 07:54:31 +00001720
Bill Wendling34711742010-10-06 01:22:42 +00001721bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1722 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1723 return Error("Malformed block record");
1724
1725 SmallVector<uint64_t, 64> Record;
1726
1727 // Read all the records for this module.
1728 while (!Stream.AtEndOfStream()) {
1729 unsigned Code = Stream.ReadCode();
1730 if (Code == bitc::END_BLOCK) {
1731 if (Stream.ReadBlockEnd())
1732 return Error("Error at end of module block");
1733
1734 return false;
1735 }
1736
1737 if (Code == bitc::ENTER_SUBBLOCK) {
1738 switch (Stream.ReadSubBlockID()) {
1739 default: // Skip unknown content.
1740 if (Stream.SkipBlock())
1741 return Error("Malformed block record");
1742 break;
1743 }
1744 continue;
1745 }
1746
1747 if (Code == bitc::DEFINE_ABBREV) {
1748 Stream.ReadAbbrevRecord();
1749 continue;
1750 }
1751
1752 // Read a record.
1753 switch (Stream.ReadRecord(Code, Record)) {
1754 default: break; // Default behavior, ignore unknown content.
1755 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1756 if (Record.size() < 1)
1757 return Error("Malformed MODULE_CODE_VERSION");
1758 // Only version #0 is supported so far.
1759 if (Record[0] != 0)
1760 return Error("Unknown bitstream version!");
1761 break;
1762 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1763 std::string S;
1764 if (ConvertToString(Record, 0, S))
1765 return Error("Invalid MODULE_CODE_TRIPLE record");
1766 Triple = S;
1767 break;
1768 }
1769 }
1770 Record.clear();
1771 }
1772
1773 return Error("Premature end of bitstream");
1774}
1775
1776bool BitcodeReader::ParseTriple(std::string &Triple) {
1777 if (Buffer->getBufferSize() & 3)
1778 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1779
1780 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1781 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1782
1783 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1784 // The magic number is 0x0B17C0DE stored in little endian.
1785 if (isBitcodeWrapper(BufPtr, BufEnd))
1786 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1787 return Error("Invalid bitcode wrapper header");
1788
1789 StreamFile.init(BufPtr, BufEnd);
1790 Stream.init(StreamFile);
1791
1792 // Sniff for the signature.
1793 if (Stream.Read(8) != 'B' ||
1794 Stream.Read(8) != 'C' ||
1795 Stream.Read(4) != 0x0 ||
1796 Stream.Read(4) != 0xC ||
1797 Stream.Read(4) != 0xE ||
1798 Stream.Read(4) != 0xD)
1799 return Error("Invalid bitcode signature");
1800
1801 // We expect a number of well-defined blocks, though we don't necessarily
1802 // need to understand them all.
1803 while (!Stream.AtEndOfStream()) {
1804 unsigned Code = Stream.ReadCode();
1805
1806 if (Code != bitc::ENTER_SUBBLOCK)
1807 return Error("Invalid record at top-level");
1808
1809 unsigned BlockID = Stream.ReadSubBlockID();
1810
1811 // We only know the MODULE subblock ID.
1812 switch (BlockID) {
1813 case bitc::MODULE_BLOCK_ID:
1814 if (ParseModuleTriple(Triple))
1815 return true;
1816 break;
1817 default:
1818 if (Stream.SkipBlock())
1819 return Error("Malformed block record");
1820 break;
1821 }
1822 }
1823
1824 return false;
1825}
1826
Devang Patele8e02132009-09-18 19:26:43 +00001827/// ParseMetadataAttachment - Parse metadata attachments.
1828bool BitcodeReader::ParseMetadataAttachment() {
1829 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1830 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001831
Devang Patele8e02132009-09-18 19:26:43 +00001832 SmallVector<uint64_t, 64> Record;
1833 while(1) {
1834 unsigned Code = Stream.ReadCode();
1835 if (Code == bitc::END_BLOCK) {
1836 if (Stream.ReadBlockEnd())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001837 return Error("Error at end of PARAMATTR block");
Devang Patele8e02132009-09-18 19:26:43 +00001838 break;
1839 }
1840 if (Code == bitc::DEFINE_ABBREV) {
1841 Stream.ReadAbbrevRecord();
1842 continue;
1843 }
1844 // Read a metadata attachment record.
1845 Record.clear();
1846 switch (Stream.ReadRecord(Code, Record)) {
1847 default: // Default behavior: ignore.
1848 break;
Chris Lattner9d61dd92011-06-17 17:50:30 +00001849 case bitc::METADATA_ATTACHMENT: {
Devang Patele8e02132009-09-18 19:26:43 +00001850 unsigned RecordLength = Record.size();
1851 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Daniel Dunbara279bc32009-09-20 02:20:51 +00001852 return Error ("Invalid METADATA_ATTACHMENT reader!");
Devang Patele8e02132009-09-18 19:26:43 +00001853 Instruction *Inst = InstructionList[Record[0]];
1854 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patela2148402009-09-28 21:14:55 +00001855 unsigned Kind = Record[i];
Dan Gohman19538d12010-07-20 21:42:28 +00001856 DenseMap<unsigned, unsigned>::iterator I =
1857 MDKindMap.find(Kind);
1858 if (I == MDKindMap.end())
1859 return Error("Invalid metadata kind ID");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001860 Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
Dan Gohman19538d12010-07-20 21:42:28 +00001861 Inst->setMetadata(I->second, cast<MDNode>(Node));
Devang Patele8e02132009-09-18 19:26:43 +00001862 }
1863 break;
1864 }
1865 }
1866 }
1867 return false;
1868}
Chris Lattner48f84872007-05-01 04:59:48 +00001869
Chris Lattner980e5aa2007-05-01 05:52:21 +00001870/// ParseFunctionBody - Lazily parse the specified function body block.
1871bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001872 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001873 return Error("Malformed block record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001874
Nick Lewycky9a49f152010-02-25 08:30:17 +00001875 InstructionList.clear();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001876 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman69813832010-08-25 20:22:53 +00001877 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001878
Chris Lattner980e5aa2007-05-01 05:52:21 +00001879 // Add all the function arguments to the value table.
1880 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1881 ValueList.push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001882
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001883 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001884 BasicBlock *CurBB = 0;
1885 unsigned CurBBNo = 0;
1886
Chris Lattnera6245242010-04-03 02:17:50 +00001887 DebugLoc LastLoc;
1888
Chris Lattner980e5aa2007-05-01 05:52:21 +00001889 // Read all the records.
1890 SmallVector<uint64_t, 64> Record;
1891 while (1) {
1892 unsigned Code = Stream.ReadCode();
1893 if (Code == bitc::END_BLOCK) {
1894 if (Stream.ReadBlockEnd())
1895 return Error("Error at end of function block");
1896 break;
1897 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001898
Chris Lattner980e5aa2007-05-01 05:52:21 +00001899 if (Code == bitc::ENTER_SUBBLOCK) {
1900 switch (Stream.ReadSubBlockID()) {
1901 default: // Skip unknown content.
1902 if (Stream.SkipBlock())
1903 return Error("Malformed block record");
1904 break;
1905 case bitc::CONSTANTS_BLOCK_ID:
1906 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001907 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001908 break;
1909 case bitc::VALUE_SYMTAB_BLOCK_ID:
1910 if (ParseValueSymbolTable()) return true;
1911 break;
Devang Patele8e02132009-09-18 19:26:43 +00001912 case bitc::METADATA_ATTACHMENT_ID:
Daniel Dunbara279bc32009-09-20 02:20:51 +00001913 if (ParseMetadataAttachment()) return true;
1914 break;
Victor Hernandezfab9e99c2010-01-13 19:34:08 +00001915 case bitc::METADATA_BLOCK_ID:
1916 if (ParseMetadata()) return true;
1917 break;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001918 }
1919 continue;
1920 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001921
Chris Lattner980e5aa2007-05-01 05:52:21 +00001922 if (Code == bitc::DEFINE_ABBREV) {
1923 Stream.ReadAbbrevRecord();
1924 continue;
1925 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001926
Chris Lattner980e5aa2007-05-01 05:52:21 +00001927 // Read a record.
1928 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001929 Instruction *I = 0;
Dan Gohman1224c382009-07-20 21:19:07 +00001930 unsigned BitCode = Stream.ReadRecord(Code, Record);
1931 switch (BitCode) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001932 default: // Default behavior: reject
1933 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001934 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001935 if (Record.size() < 1 || Record[0] == 0)
1936 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001937 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001938 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001939 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +00001940 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001941 CurBB = FunctionBBs[0];
1942 continue;
Chris Lattnera6245242010-04-03 02:17:50 +00001943
1944 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
1945 // This record indicates that the last instruction is at the same
1946 // location as the previous instruction with a location.
1947 I = 0;
1948
1949 // Get the last instruction emitted.
1950 if (CurBB && !CurBB->empty())
1951 I = &CurBB->back();
1952 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1953 !FunctionBBs[CurBBNo-1]->empty())
1954 I = &FunctionBBs[CurBBNo-1]->back();
1955
1956 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1957 I->setDebugLoc(LastLoc);
1958 I = 0;
1959 continue;
1960
Chris Lattner4f6bab92011-06-17 18:17:37 +00001961 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Chris Lattnera6245242010-04-03 02:17:50 +00001962 I = 0; // Get the last instruction emitted.
1963 if (CurBB && !CurBB->empty())
1964 I = &CurBB->back();
1965 else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1966 !FunctionBBs[CurBBNo-1]->empty())
1967 I = &FunctionBBs[CurBBNo-1]->back();
1968 if (I == 0 || Record.size() < 4)
1969 return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1970
1971 unsigned Line = Record[0], Col = Record[1];
1972 unsigned ScopeID = Record[2], IAID = Record[3];
1973
1974 MDNode *Scope = 0, *IA = 0;
1975 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1976 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1977 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1978 I->setDebugLoc(LastLoc);
1979 I = 0;
1980 continue;
1981 }
1982
Chris Lattnerabfbf852007-05-06 00:21:25 +00001983 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1984 unsigned OpNum = 0;
1985 Value *LHS, *RHS;
1986 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1987 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman1224c382009-07-20 21:19:07 +00001988 OpNum+1 > Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001989 return Error("Invalid BINOP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001990
Dan Gohman1224c382009-07-20 21:19:07 +00001991 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Chris Lattnerabfbf852007-05-06 00:21:25 +00001992 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001993 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00001994 InstructionList.push_back(I);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001995 if (OpNum < Record.size()) {
1996 if (Opc == Instruction::Add ||
1997 Opc == Instruction::Sub ||
Chris Lattnerf067d582011-02-07 16:40:21 +00001998 Opc == Instruction::Mul ||
1999 Opc == Instruction::Shl) {
Dan Gohman26793ed2010-01-25 21:55:39 +00002000 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002001 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman26793ed2010-01-25 21:55:39 +00002002 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002003 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35bda892011-02-06 21:44:57 +00002004 } else if (Opc == Instruction::SDiv ||
Chris Lattnerf067d582011-02-07 16:40:21 +00002005 Opc == Instruction::UDiv ||
2006 Opc == Instruction::LShr ||
2007 Opc == Instruction::AShr) {
Chris Lattner35bda892011-02-06 21:44:57 +00002008 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002009 cast<BinaryOperator>(I)->setIsExact(true);
2010 }
2011 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00002012 break;
2013 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00002014 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
2015 unsigned OpNum = 0;
2016 Value *Op;
2017 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2018 OpNum+2 != Record.size())
2019 return Error("Invalid CAST record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002020
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002021 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnerabfbf852007-05-06 00:21:25 +00002022 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2023 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00002024 return Error("Invalid CAST record");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002025 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002026 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002027 break;
2028 }
Dan Gohmandd8004d2009-07-27 21:53:46 +00002029 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Chris Lattner15e6d172007-05-04 19:11:41 +00002030 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00002031 unsigned OpNum = 0;
2032 Value *BasePtr;
2033 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002034 return Error("Invalid GEP record");
2035
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002036 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00002037 while (OpNum != Record.size()) {
2038 Value *Op;
2039 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002040 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00002041 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002042 }
2043
Jay Foada9203102011-07-25 09:48:08 +00002044 I = GetElementPtrInst::Create(BasePtr, GEPIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002045 InstructionList.push_back(I);
Dan Gohmandd8004d2009-07-27 21:53:46 +00002046 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002047 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002048 break;
2049 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002050
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002051 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2052 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002053 unsigned OpNum = 0;
2054 Value *Agg;
2055 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2056 return Error("Invalid EXTRACTVAL record");
2057
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002058 SmallVector<unsigned, 4> EXTRACTVALIdx;
2059 for (unsigned RecSize = Record.size();
2060 OpNum != RecSize; ++OpNum) {
2061 uint64_t Index = Record[OpNum];
2062 if ((unsigned)Index != Index)
2063 return Error("Invalid EXTRACTVAL index");
2064 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002065 }
2066
Jay Foadfc6d3a42011-07-13 10:26:04 +00002067 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002068 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002069 break;
2070 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002071
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002072 case bitc::FUNC_CODE_INST_INSERTVAL: {
2073 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane4977cf2008-05-23 01:55:30 +00002074 unsigned OpNum = 0;
2075 Value *Agg;
2076 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2077 return Error("Invalid INSERTVAL record");
2078 Value *Val;
2079 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2080 return Error("Invalid INSERTVAL record");
2081
Dan Gohman81a0c0b2008-05-31 00:58:22 +00002082 SmallVector<unsigned, 4> INSERTVALIdx;
2083 for (unsigned RecSize = Record.size();
2084 OpNum != RecSize; ++OpNum) {
2085 uint64_t Index = Record[OpNum];
2086 if ((unsigned)Index != Index)
2087 return Error("Invalid INSERTVAL index");
2088 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002089 }
2090
Jay Foadfc6d3a42011-07-13 10:26:04 +00002091 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patele8e02132009-09-18 19:26:43 +00002092 InstructionList.push_back(I);
Dan Gohmane4977cf2008-05-23 01:55:30 +00002093 break;
2094 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002095
Chris Lattnerabfbf852007-05-06 00:21:25 +00002096 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002097 // obsolete form of select
2098 // handles select i1 ... in old bitcode
Chris Lattnerabfbf852007-05-06 00:21:25 +00002099 unsigned OpNum = 0;
2100 Value *TrueVal, *FalseVal, *Cond;
2101 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2102 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002103 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002104 return Error("Invalid SELECT record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002105
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002106 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002107 InstructionList.push_back(I);
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002108 break;
2109 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002110
Dan Gohmanfb2bbbe2008-09-16 01:01:33 +00002111 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2112 // new form of select
2113 // handles select i1 or select [N x i1]
2114 unsigned OpNum = 0;
2115 Value *TrueVal, *FalseVal, *Cond;
2116 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2117 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2118 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2119 return Error("Invalid SELECT record");
Dan Gohmanf72fb672008-09-09 01:02:47 +00002120
2121 // select condition can be either i1 or [N x i1]
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002122 if (VectorType* vector_type =
2123 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanf72fb672008-09-09 01:02:47 +00002124 // expect <n x i1>
Daniel Dunbara279bc32009-09-20 02:20:51 +00002125 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002126 return Error("Invalid SELECT condition type");
2127 } else {
2128 // expect i1
Daniel Dunbara279bc32009-09-20 02:20:51 +00002129 if (Cond->getType() != Type::getInt1Ty(Context))
Dan Gohmanf72fb672008-09-09 01:02:47 +00002130 return Error("Invalid SELECT condition type");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002131 }
2132
Gabor Greif051a9502008-04-06 20:25:17 +00002133 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patele8e02132009-09-18 19:26:43 +00002134 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002135 break;
2136 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137
Chris Lattner01ff65f2007-05-02 05:16:49 +00002138 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002139 unsigned OpNum = 0;
2140 Value *Vec, *Idx;
2141 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002142 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002143 return Error("Invalid EXTRACTELT record");
Eric Christophera3500da2009-07-25 02:28:41 +00002144 I = ExtractElementInst::Create(Vec, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002145 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002146 break;
2147 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148
Chris Lattner01ff65f2007-05-02 05:16:49 +00002149 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00002150 unsigned OpNum = 0;
2151 Value *Vec, *Elt, *Idx;
2152 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002153 getValue(Record, OpNum,
Chris Lattnerabfbf852007-05-06 00:21:25 +00002154 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00002155 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002156 return Error("Invalid INSERTELT record");
Gabor Greif051a9502008-04-06 20:25:17 +00002157 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patele8e02132009-09-18 19:26:43 +00002158 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002159 break;
2160 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161
Chris Lattnerabfbf852007-05-06 00:21:25 +00002162 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2163 unsigned OpNum = 0;
2164 Value *Vec1, *Vec2, *Mask;
2165 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2166 getValue(Record, OpNum, Vec1->getType(), Vec2))
2167 return Error("Invalid SHUFFLEVEC record");
2168
Mon P Wangaeb06d22008-11-10 04:46:22 +00002169 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00002170 return Error("Invalid SHUFFLEVEC record");
2171 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patele8e02132009-09-18 19:26:43 +00002172 InstructionList.push_back(I);
Chris Lattner01ff65f2007-05-02 05:16:49 +00002173 break;
2174 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002175
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002176 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
2177 // Old form of ICmp/FCmp returning bool
2178 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2179 // both legal on vectors but had different behaviour.
2180 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2181 // FCmp/ICmp returning bool or vector of bool
2182
Chris Lattner7337ab92007-05-06 00:00:00 +00002183 unsigned OpNum = 0;
2184 Value *LHS, *RHS;
2185 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2186 getValue(Record, OpNum, LHS->getType(), RHS) ||
2187 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00002188 return Error("Invalid CMP record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002189
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002190 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002191 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002192 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002193 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patele8e02132009-09-18 19:26:43 +00002194 InstructionList.push_back(I);
Dan Gohmanf72fb672008-09-09 01:02:47 +00002195 break;
2196 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002197
Chris Lattner231cbcb2007-05-02 04:27:25 +00002198 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Pateld9d99ff2008-02-26 01:29:32 +00002199 {
2200 unsigned Size = Record.size();
2201 if (Size == 0) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002202 I = ReturnInst::Create(Context);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002203 InstructionList.push_back(I);
Devang Pateld9d99ff2008-02-26 01:29:32 +00002204 break;
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002205 }
Devang Pateld9d99ff2008-02-26 01:29:32 +00002206
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002207 unsigned OpNum = 0;
Chris Lattner96a74c52011-06-17 18:09:11 +00002208 Value *Op = NULL;
2209 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2210 return Error("Invalid RET record");
2211 if (OpNum != Record.size())
2212 return Error("Invalid RET record");
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002213
Chris Lattner96a74c52011-06-17 18:09:11 +00002214 I = ReturnInst::Create(Context, Op);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002215 InstructionList.push_back(I);
Dan Gohmanfc74abf2008-07-23 00:34:11 +00002216 break;
Chris Lattner231cbcb2007-05-02 04:27:25 +00002217 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002218 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00002219 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002220 return Error("Invalid BR record");
2221 BasicBlock *TrueDest = getBasicBlock(Record[0]);
2222 if (TrueDest == 0)
2223 return Error("Invalid BR record");
2224
Devang Patele8e02132009-09-18 19:26:43 +00002225 if (Record.size() == 1) {
Gabor Greif051a9502008-04-06 20:25:17 +00002226 I = BranchInst::Create(TrueDest);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002227 InstructionList.push_back(I);
Devang Patele8e02132009-09-18 19:26:43 +00002228 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002229 else {
2230 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Owen Anderson1d0be152009-08-13 21:58:54 +00002231 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002232 if (FalseDest == 0 || Cond == 0)
2233 return Error("Invalid BR record");
Gabor Greif051a9502008-04-06 20:25:17 +00002234 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002235 InstructionList.push_back(I);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002236 }
2237 break;
2238 }
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002239 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002240 if (Record.size() < 3 || (Record.size() & 1) == 0)
2241 return Error("Invalid SWITCH record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002242 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002243 Value *Cond = getFnValueByID(Record[1], OpTy);
2244 BasicBlock *Default = getBasicBlock(Record[2]);
2245 if (OpTy == 0 || Cond == 0 || Default == 0)
2246 return Error("Invalid SWITCH record");
2247 unsigned NumCases = (Record.size()-3)/2;
Gabor Greif051a9502008-04-06 20:25:17 +00002248 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patele8e02132009-09-18 19:26:43 +00002249 InstructionList.push_back(SI);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002250 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00002251 ConstantInt *CaseVal =
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002252 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2253 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2254 if (CaseVal == 0 || DestBB == 0) {
2255 delete SI;
2256 return Error("Invalid SWITCH record!");
2257 }
2258 SI->addCase(CaseVal, DestBB);
2259 }
2260 I = SI;
2261 break;
2262 }
Chris Lattnerab21db72009-10-28 00:19:10 +00002263 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002264 if (Record.size() < 2)
Chris Lattnerab21db72009-10-28 00:19:10 +00002265 return Error("Invalid INDIRECTBR record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002266 Type *OpTy = getTypeByID(Record[0]);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002267 Value *Address = getFnValueByID(Record[1], OpTy);
2268 if (OpTy == 0 || Address == 0)
Chris Lattnerab21db72009-10-28 00:19:10 +00002269 return Error("Invalid INDIRECTBR record");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002270 unsigned NumDests = Record.size()-2;
Chris Lattnerab21db72009-10-28 00:19:10 +00002271 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002272 InstructionList.push_back(IBI);
2273 for (unsigned i = 0, e = NumDests; i != e; ++i) {
2274 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2275 IBI->addDestination(DestBB);
2276 } else {
2277 delete IBI;
Chris Lattnerab21db72009-10-28 00:19:10 +00002278 return Error("Invalid INDIRECTBR record!");
Chris Lattnerf9be95f2009-10-27 19:13:16 +00002279 }
2280 }
2281 I = IBI;
2282 break;
2283 }
2284
Duncan Sandsdc024672007-11-27 13:23:08 +00002285 case bitc::FUNC_CODE_INST_INVOKE: {
2286 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00002287 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Patel05988662008-09-25 21:00:45 +00002288 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002289 unsigned CCInfo = Record[1];
2290 BasicBlock *NormalBB = getBasicBlock(Record[2]);
2291 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002292
Chris Lattnera9bb7132007-05-08 05:38:01 +00002293 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00002294 Value *Callee;
2295 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002296 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002297
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002298 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2299 FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002300 dyn_cast<FunctionType>(CalleeTy->getElementType());
2301
2302 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00002303 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2304 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002305 return Error("Invalid INVOKE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002306
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002307 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00002308 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2309 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2310 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002311 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002312
Chris Lattner7337ab92007-05-06 00:00:00 +00002313 if (!FTy->isVarArg()) {
2314 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002315 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002316 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002317 // Read type/value pairs for varargs params.
2318 while (OpNum != Record.size()) {
2319 Value *Op;
2320 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2321 return Error("Invalid INVOKE record");
2322 Ops.push_back(Op);
2323 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002324 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002325
Jay Foada3efbb12011-07-15 08:37:34 +00002326 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patele8e02132009-09-18 19:26:43 +00002327 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002328 cast<InvokeInst>(I)->setCallingConv(
2329 static_cast<CallingConv::ID>(CCInfo));
Devang Patel05988662008-09-25 21:00:45 +00002330 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00002331 break;
2332 }
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002333 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2334 unsigned Idx = 0;
2335 Value *Val = 0;
2336 if (getValueTypePair(Record, Idx, NextValueNo, Val))
2337 return Error("Invalid RESUME record");
2338 I = ResumeInst::Create(Val);
Bill Wendling35726bf2011-09-01 00:50:20 +00002339 InstructionList.push_back(I);
Bill Wendlingdccc03b2011-07-31 06:30:59 +00002340 break;
2341 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00002342 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
Owen Anderson1d0be152009-08-13 21:58:54 +00002343 I = new UnwindInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002344 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002345 break;
2346 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson1d0be152009-08-13 21:58:54 +00002347 I = new UnreachableInst(Context);
Devang Patele8e02132009-09-18 19:26:43 +00002348 InstructionList.push_back(I);
Chris Lattner231cbcb2007-05-02 04:27:25 +00002349 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00002350 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00002351 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00002352 return Error("Invalid PHI record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002353 Type *Ty = getTypeByID(Record[0]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002354 if (!Ty) return Error("Invalid PHI record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002355
Jay Foad3ecfc862011-03-30 11:28:46 +00002356 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patele8e02132009-09-18 19:26:43 +00002357 InstructionList.push_back(PN);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002358
Chris Lattner15e6d172007-05-04 19:11:41 +00002359 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2360 Value *V = getFnValueByID(Record[1+i], Ty);
2361 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002362 if (!V || !BB) return Error("Invalid PHI record");
2363 PN->addIncoming(V, BB);
2364 }
2365 I = PN;
2366 break;
2367 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002368
Bill Wendlinge6e88262011-08-12 20:24:12 +00002369 case bitc::FUNC_CODE_INST_LANDINGPAD: {
2370 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2371 unsigned Idx = 0;
2372 if (Record.size() < 4)
2373 return Error("Invalid LANDINGPAD record");
2374 Type *Ty = getTypeByID(Record[Idx++]);
2375 if (!Ty) return Error("Invalid LANDINGPAD record");
2376 Value *PersFn = 0;
2377 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2378 return Error("Invalid LANDINGPAD record");
2379
2380 bool IsCleanup = !!Record[Idx++];
2381 unsigned NumClauses = Record[Idx++];
2382 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2383 LP->setCleanup(IsCleanup);
2384 for (unsigned J = 0; J != NumClauses; ++J) {
2385 LandingPadInst::ClauseType CT =
2386 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2387 Value *Val;
2388
2389 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2390 delete LP;
2391 return Error("Invalid LANDINGPAD record");
2392 }
2393
2394 assert((CT != LandingPadInst::Catch ||
2395 !isa<ArrayType>(Val->getType())) &&
2396 "Catch clause has a invalid type!");
2397 assert((CT != LandingPadInst::Filter ||
2398 isa<ArrayType>(Val->getType())) &&
2399 "Filter clause has invalid type!");
2400 LP->addClause(Val);
2401 }
2402
2403 I = LP;
Bill Wendling35726bf2011-09-01 00:50:20 +00002404 InstructionList.push_back(I);
Bill Wendlinge6e88262011-08-12 20:24:12 +00002405 break;
2406 }
2407
Chris Lattner96a74c52011-06-17 18:09:11 +00002408 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2409 if (Record.size() != 4)
2410 return Error("Invalid ALLOCA record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002411 PointerType *Ty =
Chris Lattner2a98cca2007-05-03 18:58:09 +00002412 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002413 Type *OpTy = getTypeByID(Record[1]);
Chris Lattner96a74c52011-06-17 18:09:11 +00002414 Value *Size = getFnValueByID(Record[2], OpTy);
2415 unsigned Align = Record[3];
Chris Lattner2a98cca2007-05-03 18:58:09 +00002416 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson50dead02009-07-15 23:53:25 +00002417 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002418 InstructionList.push_back(I);
Chris Lattner2a98cca2007-05-03 18:58:09 +00002419 break;
2420 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00002421 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00002422 unsigned OpNum = 0;
2423 Value *Op;
2424 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2425 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00002426 return Error("Invalid LOAD record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002427
Chris Lattner7337ab92007-05-06 00:00:00 +00002428 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002429 InstructionList.push_back(I);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002430 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002431 }
Eli Friedman21006d42011-08-09 23:02:53 +00002432 case bitc::FUNC_CODE_INST_LOADATOMIC: {
2433 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2434 unsigned OpNum = 0;
2435 Value *Op;
2436 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2437 OpNum+4 != Record.size())
2438 return Error("Invalid LOADATOMIC record");
2439
2440
2441 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2442 if (Ordering == NotAtomic || Ordering == Release ||
2443 Ordering == AcquireRelease)
2444 return Error("Invalid LOADATOMIC record");
2445 if (Ordering != NotAtomic && Record[OpNum] == 0)
2446 return Error("Invalid LOADATOMIC record");
2447 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2448
2449 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2450 Ordering, SynchScope);
2451 InstructionList.push_back(I);
2452 break;
2453 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002454 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00002455 unsigned OpNum = 0;
2456 Value *Val, *Ptr;
2457 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Daniel Dunbara279bc32009-09-20 02:20:51 +00002458 getValue(Record, OpNum,
Christopher Lambfe63fb92007-12-11 08:59:05 +00002459 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2460 OpNum+2 != Record.size())
2461 return Error("Invalid STORE record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002462
Christopher Lambfe63fb92007-12-11 08:59:05 +00002463 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Devang Patele8e02132009-09-18 19:26:43 +00002464 InstructionList.push_back(I);
Christopher Lambfe63fb92007-12-11 08:59:05 +00002465 break;
2466 }
Eli Friedman21006d42011-08-09 23:02:53 +00002467 case bitc::FUNC_CODE_INST_STOREATOMIC: {
2468 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2469 unsigned OpNum = 0;
2470 Value *Val, *Ptr;
2471 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2472 getValue(Record, OpNum,
2473 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2474 OpNum+4 != Record.size())
2475 return Error("Invalid STOREATOMIC record");
2476
2477 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedmanc3d35982011-09-19 19:41:28 +00002478 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman21006d42011-08-09 23:02:53 +00002479 Ordering == AcquireRelease)
2480 return Error("Invalid STOREATOMIC record");
2481 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2482 if (Ordering != NotAtomic && Record[OpNum] == 0)
2483 return Error("Invalid STOREATOMIC record");
2484
2485 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2486 Ordering, SynchScope);
2487 InstructionList.push_back(I);
2488 break;
2489 }
Eli Friedmanff030482011-07-28 21:48:00 +00002490 case bitc::FUNC_CODE_INST_CMPXCHG: {
2491 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2492 unsigned OpNum = 0;
2493 Value *Ptr, *Cmp, *New;
2494 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2495 getValue(Record, OpNum,
2496 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2497 getValue(Record, OpNum,
2498 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2499 OpNum+3 != Record.size())
2500 return Error("Invalid CMPXCHG record");
2501 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
Eli Friedman21006d42011-08-09 23:02:53 +00002502 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002503 return Error("Invalid CMPXCHG record");
2504 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2505 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2506 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2507 InstructionList.push_back(I);
2508 break;
2509 }
2510 case bitc::FUNC_CODE_INST_ATOMICRMW: {
2511 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2512 unsigned OpNum = 0;
2513 Value *Ptr, *Val;
2514 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2515 getValue(Record, OpNum,
2516 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2517 OpNum+4 != Record.size())
2518 return Error("Invalid ATOMICRMW record");
2519 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2520 if (Operation < AtomicRMWInst::FIRST_BINOP ||
2521 Operation > AtomicRMWInst::LAST_BINOP)
2522 return Error("Invalid ATOMICRMW record");
2523 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman21006d42011-08-09 23:02:53 +00002524 if (Ordering == NotAtomic || Ordering == Unordered)
Eli Friedmanff030482011-07-28 21:48:00 +00002525 return Error("Invalid ATOMICRMW record");
2526 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2527 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2528 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2529 InstructionList.push_back(I);
2530 break;
2531 }
Eli Friedman47f35132011-07-25 23:16:38 +00002532 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2533 if (2 != Record.size())
2534 return Error("Invalid FENCE record");
2535 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2536 if (Ordering == NotAtomic || Ordering == Unordered ||
2537 Ordering == Monotonic)
2538 return Error("Invalid FENCE record");
2539 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2540 I = new FenceInst(Context, Ordering, SynchScope);
2541 InstructionList.push_back(I);
2542 break;
2543 }
Chris Lattner4f6bab92011-06-17 18:17:37 +00002544 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsdc024672007-11-27 13:23:08 +00002545 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2546 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002547 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002548
Devang Patel05988662008-09-25 21:00:45 +00002549 AttrListPtr PAL = getAttributes(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00002550 unsigned CCInfo = Record[1];
Daniel Dunbara279bc32009-09-20 02:20:51 +00002551
Chris Lattnera9bb7132007-05-08 05:38:01 +00002552 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00002553 Value *Callee;
2554 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2555 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002556
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002557 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2558 FunctionType *FTy = 0;
Chris Lattner0579f7f2007-05-03 22:04:19 +00002559 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00002560 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00002561 return Error("Invalid CALL record");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002562
Chris Lattner0579f7f2007-05-03 22:04:19 +00002563 SmallVector<Value*, 16> Args;
2564 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00002565 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002566 if (FTy->getParamType(i)->isLabelTy())
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002567 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohman9b10dfb2010-09-13 18:00:48 +00002568 else
Dale Johanneseneb57ea72007-11-05 21:20:28 +00002569 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00002570 if (Args.back() == 0) return Error("Invalid CALL record");
2571 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002572
Chris Lattner0579f7f2007-05-03 22:04:19 +00002573 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00002574 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00002575 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00002576 return Error("Invalid CALL record");
2577 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00002578 while (OpNum != Record.size()) {
2579 Value *Op;
2580 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2581 return Error("Invalid CALL record");
2582 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002583 }
2584 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002585
Jay Foada3efbb12011-07-15 08:37:34 +00002586 I = CallInst::Create(Callee, Args);
Devang Patele8e02132009-09-18 19:26:43 +00002587 InstructionList.push_back(I);
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00002588 cast<CallInst>(I)->setCallingConv(
2589 static_cast<CallingConv::ID>(CCInfo>>1));
Chris Lattner76520192007-05-03 22:34:03 +00002590 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Patel05988662008-09-25 21:00:45 +00002591 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002592 break;
2593 }
2594 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2595 if (Record.size() < 3)
2596 return Error("Invalid VAARG record");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002597 Type *OpTy = getTypeByID(Record[0]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002598 Value *Op = getFnValueByID(Record[1], OpTy);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002599 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002600 if (!OpTy || !Op || !ResTy)
2601 return Error("Invalid VAARG record");
2602 I = new VAArgInst(Op, ResTy);
Devang Patele8e02132009-09-18 19:26:43 +00002603 InstructionList.push_back(I);
Chris Lattner0579f7f2007-05-03 22:04:19 +00002604 break;
2605 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002606 }
2607
2608 // Add instruction to end of current BB. If there is no current BB, reject
2609 // this file.
2610 if (CurBB == 0) {
2611 delete I;
2612 return Error("Invalid instruction with no BB");
2613 }
2614 CurBB->getInstList().push_back(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002615
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002616 // If this was a terminator instruction, move to the next block.
2617 if (isa<TerminatorInst>(I)) {
2618 ++CurBBNo;
2619 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2620 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002621
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002622 // Non-void values get registered in the value table for future use.
Benjamin Kramerf0127052010-01-05 13:12:22 +00002623 if (I && !I->getType()->isVoidTy())
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002624 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002625 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002626
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002627 // Check the function list for unresolved values.
2628 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2629 if (A->getParent() == 0) {
2630 // We found at least one unresolved value. Nuke them all to avoid leaks.
2631 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Dan Gohman56e2a572010-08-25 20:20:21 +00002632 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002633 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002634 delete A;
2635 }
2636 }
Chris Lattner35a04702007-05-04 03:50:29 +00002637 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002638 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00002639 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002640
Dan Gohman064ff3e2010-08-25 20:23:38 +00002641 // FIXME: Check for unresolved forward-declared metadata references
2642 // and clean up leaks.
2643
Chris Lattner50b136d2009-10-28 05:53:48 +00002644 // See if anything took the address of blocks in this function. If so,
2645 // resolve them now.
Chris Lattner50b136d2009-10-28 05:53:48 +00002646 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2647 BlockAddrFwdRefs.find(F);
2648 if (BAFRI != BlockAddrFwdRefs.end()) {
2649 std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2650 for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2651 unsigned BlockIdx = RefList[i].first;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002652 if (BlockIdx >= FunctionBBs.size())
Chris Lattner50b136d2009-10-28 05:53:48 +00002653 return Error("Invalid blockaddress block #");
2654
2655 GlobalVariable *FwdRef = RefList[i].second;
Chris Lattnercdfc9402009-11-01 01:27:45 +00002656 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
Chris Lattner50b136d2009-10-28 05:53:48 +00002657 FwdRef->eraseFromParent();
2658 }
2659
2660 BlockAddrFwdRefs.erase(BAFRI);
2661 }
2662
Chris Lattner980e5aa2007-05-01 05:52:21 +00002663 // Trim the value list down to the size it was before we parsed this function.
2664 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman69813832010-08-25 20:22:53 +00002665 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner980e5aa2007-05-01 05:52:21 +00002666 std::vector<BasicBlock*>().swap(FunctionBBs);
Chris Lattner48f84872007-05-01 04:59:48 +00002667 return false;
2668}
2669
Chris Lattnerb348bb82007-05-18 04:02:46 +00002670//===----------------------------------------------------------------------===//
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002671// GVMaterializer implementation
Chris Lattnerb348bb82007-05-18 04:02:46 +00002672//===----------------------------------------------------------------------===//
2673
2674
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002675bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2676 if (const Function *F = dyn_cast<Function>(GV)) {
2677 return F->isDeclaration() &&
2678 DeferredFunctionInfo.count(const_cast<Function*>(F));
2679 }
2680 return false;
2681}
Daniel Dunbara279bc32009-09-20 02:20:51 +00002682
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002683bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2684 Function *F = dyn_cast<Function>(GV);
2685 // If it's not a function or is already material, ignore the request.
2686 if (!F || !F->isMaterializable()) return false;
2687
2688 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattnerb348bb82007-05-18 04:02:46 +00002689 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002690
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002691 // Move the bit stream to the saved position of the deferred function body.
2692 Stream.JumpToBit(DFII->second);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002693
Chris Lattnerb348bb82007-05-18 04:02:46 +00002694 if (ParseFunctionBody(F)) {
2695 if (ErrInfo) *ErrInfo = ErrorString;
2696 return true;
2697 }
Chandler Carruth69940402007-08-04 01:51:18 +00002698
2699 // Upgrade any old intrinsic calls in the function.
2700 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2701 E = UpgradedIntrinsics.end(); I != E; ++I) {
2702 if (I->first != I->second) {
2703 for (Value::use_iterator UI = I->first->use_begin(),
2704 UE = I->first->use_end(); UI != UE; ) {
2705 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2706 UpgradeIntrinsicCall(CI, I->second);
2707 }
2708 }
2709 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002710
Chris Lattnerb348bb82007-05-18 04:02:46 +00002711 return false;
2712}
2713
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002714bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2715 const Function *F = dyn_cast<Function>(GV);
2716 if (!F || F->isDeclaration())
2717 return false;
2718 return DeferredFunctionInfo.count(const_cast<Function*>(F));
2719}
2720
2721void BitcodeReader::Dematerialize(GlobalValue *GV) {
2722 Function *F = dyn_cast<Function>(GV);
2723 // If this function isn't dematerializable, this is a noop.
2724 if (!F || !isDematerializable(F))
Chris Lattnerb348bb82007-05-18 04:02:46 +00002725 return;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002726
Chris Lattnerb348bb82007-05-18 04:02:46 +00002727 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbara279bc32009-09-20 02:20:51 +00002728
Chris Lattnerb348bb82007-05-18 04:02:46 +00002729 // Just forget the function body, we can remat it later.
2730 F->deleteBody();
Chris Lattnerb348bb82007-05-18 04:02:46 +00002731}
2732
2733
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002734bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2735 assert(M == TheModule &&
2736 "Can only Materialize the Module this BitcodeReader is attached to.");
Chris Lattner714fa952009-06-16 05:15:21 +00002737 // Iterate over the module, deserializing any functions that are still on
2738 // disk.
2739 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2740 F != E; ++F)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002741 if (F->isMaterializable() &&
2742 Materialize(F, ErrInfo))
2743 return true;
Chandler Carruth69940402007-08-04 01:51:18 +00002744
Daniel Dunbara279bc32009-09-20 02:20:51 +00002745 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2746 // delete the old functions to clean up. We can't do this unless the entire
2747 // module is materialized because there could always be another function body
Chandler Carruth69940402007-08-04 01:51:18 +00002748 // with calls to the old function.
2749 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2750 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2751 if (I->first != I->second) {
2752 for (Value::use_iterator UI = I->first->use_begin(),
2753 UE = I->first->use_end(); UI != UE; ) {
2754 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2755 UpgradeIntrinsicCall(CI, I->second);
2756 }
Chris Lattner7d9eb582009-04-01 01:43:03 +00002757 if (!I->first->use_empty())
2758 I->first->replaceAllUsesWith(I->second);
Chandler Carruth69940402007-08-04 01:51:18 +00002759 I->first->eraseFromParent();
2760 }
2761 }
2762 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patele4b27562009-08-28 23:24:31 +00002763
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002764 return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002765}
2766
Chris Lattner48f84872007-05-01 04:59:48 +00002767
Chris Lattnerc453f762007-04-29 07:54:31 +00002768//===----------------------------------------------------------------------===//
2769// External interface
2770//===----------------------------------------------------------------------===//
2771
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002772/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
Chris Lattnerc453f762007-04-29 07:54:31 +00002773///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002774Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2775 LLVMContext& Context,
2776 std::string *ErrMsg) {
2777 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Owen Anderson8b477ed2009-07-01 16:58:40 +00002778 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002779 M->setMaterializer(R);
2780 if (R->ParseBitcodeInto(M)) {
Chris Lattnerc453f762007-04-29 07:54:31 +00002781 if (ErrMsg)
2782 *ErrMsg = R->getErrorString();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002783
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002784 delete M; // Also deletes R.
Chris Lattnerc453f762007-04-29 07:54:31 +00002785 return 0;
2786 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002787 // Have the BitcodeReader dtor delete 'Buffer'.
2788 R->setBufferOwned(true);
Rafael Espindola47f79bb2012-01-02 07:49:53 +00002789
2790 R->materializeForwardReferencedFunctions();
2791
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002792 return M;
Chris Lattnerc453f762007-04-29 07:54:31 +00002793}
2794
2795/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2796/// If an error occurs, return null and fill in *ErrMsg if non-null.
Daniel Dunbara279bc32009-09-20 02:20:51 +00002797Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson8b477ed2009-07-01 16:58:40 +00002798 std::string *ErrMsg){
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002799 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2800 if (!M) return 0;
Chris Lattnerb348bb82007-05-18 04:02:46 +00002801
2802 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2803 // there was an error.
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002804 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002805
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002806 // Read in the entire module, and destroy the BitcodeReader.
2807 if (M->MaterializeAllPermanently(ErrMsg)) {
2808 delete M;
Bill Wendling34711742010-10-06 01:22:42 +00002809 return 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00002810 }
Bill Wendling34711742010-10-06 01:22:42 +00002811
Chad Rosiercbbb0962011-12-07 21:44:12 +00002812 // TODO: Restore the use-lists to the in-memory state when the bitcode was
2813 // written. We must defer until the Module has been fully materialized.
2814
Chris Lattnerc453f762007-04-29 07:54:31 +00002815 return M;
2816}
Bill Wendling34711742010-10-06 01:22:42 +00002817
2818std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2819 LLVMContext& Context,
2820 std::string *ErrMsg) {
2821 BitcodeReader *R = new BitcodeReader(Buffer, Context);
2822 // Don't let the BitcodeReader dtor delete 'Buffer'.
2823 R->setBufferOwned(false);
2824
2825 std::string Triple("");
2826 if (R->ParseTriple(Triple))
2827 if (ErrMsg)
2828 *ErrMsg = R->getErrorString();
2829
2830 delete R;
2831 return Triple;
2832}