blob: 374fdd721b3fe3661b157a6b104fdb1dd1ec83a0 [file] [log] [blame]
Chris Lattner72bc70d2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002//
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.
Owen Anderson1ad2cb72007-07-24 17:55:58 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
John Criswell090c0a22009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman845f5242008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Anderson1ad2cb72007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Chris Lattnera53cfd12009-12-28 21:28:46 +000020#include "llvm/GlobalVariable.h"
Devang Patelc64bc162009-03-06 02:59:27 +000021#include "llvm/IntrinsicInst.h"
Dan Gohmanf4177aa2010-12-15 23:53:55 +000022#include "llvm/LLVMContext.h"
Owen Andersonb388ca92007-10-18 19:39:33 +000023#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnerbc9a28d2009-12-06 05:29:56 +000024#include "llvm/Analysis/ConstantFolding.h"
25#include "llvm/Analysis/Dominators.h"
Duncan Sands88c3df72010-11-12 21:10:24 +000026#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohmandd9344f2010-05-28 16:19:17 +000027#include "llvm/Analysis/Loads.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000029#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattner05e15f82009-12-09 01:59:31 +000030#include "llvm/Analysis/PHITransAddr.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000031#include "llvm/Analysis/ValueTracking.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000032#include "llvm/Assembly/Writer.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000033#include "llvm/Target/TargetData.h"
Chad Rosier618c1db2011-12-01 03:08:23 +000034#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000036#include "llvm/Transforms/Utils/SSAUpdater.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000039#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Statistic.h"
Owen Andersona04a0642010-11-18 18:32:40 +000041#include "llvm/Support/Allocator.h"
Owen Andersonaa0b6342008-06-19 19:57:25 +000042#include "llvm/Support/CommandLine.h"
Chris Lattner9f8a6a72008-03-29 04:36:18 +000043#include "llvm/Support/Debug.h"
Chris Lattnerfaf815b2009-12-06 01:57:02 +000044#include "llvm/Support/IRBuilder.h"
Duncan Sands02b5e722011-10-05 14:28:49 +000045#include "llvm/Support/PatternMatch.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000046using namespace llvm;
Duncan Sands02b5e722011-10-05 14:28:49 +000047using namespace PatternMatch;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000048
Bill Wendling70ded192008-12-22 22:14:07 +000049STATISTIC(NumGVNInstr, "Number of instructions deleted");
50STATISTIC(NumGVNLoad, "Number of loads deleted");
51STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson961edc82008-07-15 16:28:06 +000052STATISTIC(NumGVNBlocks, "Number of blocks merged");
Duncan Sands02b5e722011-10-05 14:28:49 +000053STATISTIC(NumGVNSimpl, "Number of instructions simplified");
54STATISTIC(NumGVNEqProp, "Number of equalities propagated");
Bill Wendling70ded192008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattnerd27290d2008-03-22 04:13:49 +000056
Evan Cheng88d11c02008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonc2b856e2008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohmanc915c952009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersonaa0b6342008-06-19 19:57:25 +000060
Owen Anderson1ad2cb72007-07-24 17:55:58 +000061//===----------------------------------------------------------------------===//
62// ValueTable Class
63//===----------------------------------------------------------------------===//
64
65/// This class holds the mapping between values and value numbers. It is used
66/// as an efficient mechanism to determine the expression-wise equivalence of
67/// two values.
68namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000069 struct Expression {
Owen Anderson30f4a552011-01-03 19:00:11 +000070 uint32_t opcode;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000071 Type *type;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000072 SmallVector<uint32_t, 4> varargs;
Daniel Dunbara279bc32009-09-20 02:20:51 +000073
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000074 Expression(uint32_t o = ~2U) : opcode(o) { }
Daniel Dunbara279bc32009-09-20 02:20:51 +000075
Owen Anderson1ad2cb72007-07-24 17:55:58 +000076 bool operator==(const Expression &other) const {
77 if (opcode != other.opcode)
78 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000079 if (opcode == ~0U || opcode == ~1U)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000080 return true;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000081 if (type != other.type)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000082 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000083 if (varargs != other.varargs)
Benjamin Krameraad94aa2010-12-21 21:30:19 +000084 return false;
85 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000086 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +000087 };
Daniel Dunbara279bc32009-09-20 02:20:51 +000088
Chris Lattner3e8b6632009-09-02 06:11:42 +000089 class ValueTable {
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000090 DenseMap<Value*, uint32_t> valueNumbering;
91 DenseMap<Expression, uint32_t> expressionNumbering;
92 AliasAnalysis *AA;
93 MemoryDependenceAnalysis *MD;
94 DominatorTree *DT;
Daniel Dunbara279bc32009-09-20 02:20:51 +000095
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000096 uint32_t nextValueNumber;
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000098 Expression create_expression(Instruction* I);
Lang Hames1fb09552011-07-08 01:50:54 +000099 Expression create_extractvalue_expression(ExtractValueInst* EI);
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000100 uint32_t lookup_or_add_call(CallInst* C);
101 public:
102 ValueTable() : nextValueNumber(1) { }
103 uint32_t lookup_or_add(Value *V);
104 uint32_t lookup(Value *V) const;
105 void add(Value *V, uint32_t num);
106 void clear();
107 void erase(Value *v);
108 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
109 AliasAnalysis *getAliasAnalysis() const { return AA; }
110 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
111 void setDomTree(DominatorTree* D) { DT = D; }
112 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
113 void verifyRemoved(const Value *) const;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000114 };
115}
116
117namespace llvm {
Chris Lattner76c1b972007-09-17 18:34:04 +0000118template <> struct DenseMapInfo<Expression> {
Owen Anderson830db6a2007-08-02 18:16:06 +0000119 static inline Expression getEmptyKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000120 return ~0U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Owen Anderson830db6a2007-08-02 18:16:06 +0000123 static inline Expression getTombstoneKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000124 return ~1U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000125 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000126
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000127 static unsigned getHashValue(const Expression e) {
128 unsigned hash = e.opcode;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000129
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000130 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
Owen Andersond41ed4e2009-10-19 22:14:22 +0000131 (unsigned)((uintptr_t)e.type >> 9));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000132
Owen Anderson830db6a2007-08-02 18:16:06 +0000133 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
134 E = e.varargs.end(); I != E; ++I)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000135 hash = *I + hash * 37;
Owen Anderson30f4a552011-01-03 19:00:11 +0000136
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000137 return hash;
138 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000139 static bool isEqual(const Expression &LHS, const Expression &RHS) {
140 return LHS == RHS;
141 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000142};
Chris Lattner4bbf4ee2009-12-15 07:26:43 +0000143
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000144}
145
146//===----------------------------------------------------------------------===//
147// ValueTable Internal Functions
148//===----------------------------------------------------------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000149
Owen Anderson30f4a552011-01-03 19:00:11 +0000150Expression ValueTable::create_expression(Instruction *I) {
151 Expression e;
152 e.type = I->getType();
153 e.opcode = I->getOpcode();
154 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
155 OI != OE; ++OI)
156 e.varargs.push_back(lookup_or_add(*OI));
157
Lang Hames1fb09552011-07-08 01:50:54 +0000158 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
Owen Anderson30f4a552011-01-03 19:00:11 +0000159 e.opcode = (C->getOpcode() << 8) | C->getPredicate();
Owen Anderson30f4a552011-01-03 19:00:11 +0000160 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
161 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
162 II != IE; ++II)
163 e.varargs.push_back(*II);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000164 }
Owen Anderson30f4a552011-01-03 19:00:11 +0000165
Owen Andersond41ed4e2009-10-19 22:14:22 +0000166 return e;
167}
168
Lang Hames1fb09552011-07-08 01:50:54 +0000169Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
170 assert(EI != 0 && "Not an ExtractValueInst?");
171 Expression e;
172 e.type = EI->getType();
173 e.opcode = 0;
174
175 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
176 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
177 // EI might be an extract from one of our recognised intrinsics. If it
178 // is we'll synthesize a semantically equivalent expression instead on
179 // an extract value expression.
180 switch (I->getIntrinsicID()) {
Lang Hamesbd1828c2011-07-09 00:25:11 +0000181 case Intrinsic::sadd_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000182 case Intrinsic::uadd_with_overflow:
183 e.opcode = Instruction::Add;
184 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000185 case Intrinsic::ssub_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000186 case Intrinsic::usub_with_overflow:
187 e.opcode = Instruction::Sub;
188 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000189 case Intrinsic::smul_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000190 case Intrinsic::umul_with_overflow:
191 e.opcode = Instruction::Mul;
192 break;
193 default:
194 break;
195 }
196
197 if (e.opcode != 0) {
198 // Intrinsic recognized. Grab its args to finish building the expression.
199 assert(I->getNumArgOperands() == 2 &&
200 "Expect two args for recognised intrinsics.");
201 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
202 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
203 return e;
204 }
205 }
206
207 // Not a recognised intrinsic. Fall back to producing an extract value
208 // expression.
209 e.opcode = EI->getOpcode();
210 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
211 OI != OE; ++OI)
212 e.varargs.push_back(lookup_or_add(*OI));
213
214 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
215 II != IE; ++II)
216 e.varargs.push_back(*II);
217
218 return e;
219}
220
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000221//===----------------------------------------------------------------------===//
222// ValueTable External Functions
223//===----------------------------------------------------------------------===//
224
Owen Andersonb2303722008-06-18 21:41:49 +0000225/// add - Insert a value into the table with a specified value number.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000226void ValueTable::add(Value *V, uint32_t num) {
Owen Andersonb2303722008-06-18 21:41:49 +0000227 valueNumbering.insert(std::make_pair(V, num));
228}
229
Owen Andersond41ed4e2009-10-19 22:14:22 +0000230uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
231 if (AA->doesNotAccessMemory(C)) {
232 Expression exp = create_expression(C);
233 uint32_t& e = expressionNumbering[exp];
234 if (!e) e = nextValueNumber++;
235 valueNumbering[C] = e;
236 return e;
237 } else if (AA->onlyReadsMemory(C)) {
238 Expression exp = create_expression(C);
239 uint32_t& e = expressionNumbering[exp];
240 if (!e) {
241 e = nextValueNumber++;
242 valueNumbering[C] = e;
243 return e;
244 }
Dan Gohman4ec01b22009-11-14 02:27:51 +0000245 if (!MD) {
246 e = nextValueNumber++;
247 valueNumbering[C] = e;
248 return e;
249 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000250
251 MemDepResult local_dep = MD->getDependency(C);
252
253 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
254 valueNumbering[C] = nextValueNumber;
255 return nextValueNumber++;
256 }
257
258 if (local_dep.isDef()) {
259 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
260
Gabor Greif237e1da2010-06-30 09:17:53 +0000261 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000262 valueNumbering[C] = nextValueNumber;
263 return nextValueNumber++;
264 }
265
Gabor Greifd883a9d2010-06-24 10:17:17 +0000266 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
267 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
268 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000269 if (c_vn != cd_vn) {
270 valueNumbering[C] = nextValueNumber;
271 return nextValueNumber++;
272 }
273 }
274
275 uint32_t v = lookup_or_add(local_cdep);
276 valueNumbering[C] = v;
277 return v;
278 }
279
280 // Non-local case.
281 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
282 MD->getNonLocalCallDependency(CallSite(C));
Eli Friedmana990e072011-06-15 00:47:34 +0000283 // FIXME: Move the checking logic to MemDep!
Owen Andersond41ed4e2009-10-19 22:14:22 +0000284 CallInst* cdep = 0;
285
286 // Check to see if we have a single dominating call instruction that is
287 // identical to C.
288 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +0000289 const NonLocalDepEntry *I = &deps[i];
Chris Lattnere18b9712009-12-09 07:08:01 +0000290 if (I->getResult().isNonLocal())
Owen Andersond41ed4e2009-10-19 22:14:22 +0000291 continue;
292
Eli Friedmana990e072011-06-15 00:47:34 +0000293 // We don't handle non-definitions. If we already have a call, reject
Owen Andersond41ed4e2009-10-19 22:14:22 +0000294 // instruction dependencies.
Eli Friedmana990e072011-06-15 00:47:34 +0000295 if (!I->getResult().isDef() || cdep != 0) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000296 cdep = 0;
297 break;
298 }
299
Chris Lattnere18b9712009-12-09 07:08:01 +0000300 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
Owen Andersond41ed4e2009-10-19 22:14:22 +0000301 // FIXME: All duplicated with non-local case.
Chris Lattnere18b9712009-12-09 07:08:01 +0000302 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
Owen Andersond41ed4e2009-10-19 22:14:22 +0000303 cdep = NonLocalDepCall;
304 continue;
305 }
306
307 cdep = 0;
308 break;
309 }
310
311 if (!cdep) {
312 valueNumbering[C] = nextValueNumber;
313 return nextValueNumber++;
314 }
315
Gabor Greif237e1da2010-06-30 09:17:53 +0000316 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000317 valueNumbering[C] = nextValueNumber;
318 return nextValueNumber++;
319 }
Gabor Greifd883a9d2010-06-24 10:17:17 +0000320 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
321 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
322 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000323 if (c_vn != cd_vn) {
324 valueNumbering[C] = nextValueNumber;
325 return nextValueNumber++;
326 }
327 }
328
329 uint32_t v = lookup_or_add(cdep);
330 valueNumbering[C] = v;
331 return v;
332
333 } else {
334 valueNumbering[C] = nextValueNumber;
335 return nextValueNumber++;
336 }
337}
338
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000339/// lookup_or_add - Returns the value number for the specified value, assigning
340/// it a new number if it did not have one before.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000341uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000342 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
343 if (VI != valueNumbering.end())
344 return VI->second;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000345
Owen Andersond41ed4e2009-10-19 22:14:22 +0000346 if (!isa<Instruction>(V)) {
Owen Anderson158d86e2009-10-19 21:14:57 +0000347 valueNumbering[V] = nextValueNumber;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000348 return nextValueNumber++;
349 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000350
351 Instruction* I = cast<Instruction>(V);
352 Expression exp;
353 switch (I->getOpcode()) {
354 case Instruction::Call:
355 return lookup_or_add_call(cast<CallInst>(I));
356 case Instruction::Add:
357 case Instruction::FAdd:
358 case Instruction::Sub:
359 case Instruction::FSub:
360 case Instruction::Mul:
361 case Instruction::FMul:
362 case Instruction::UDiv:
363 case Instruction::SDiv:
364 case Instruction::FDiv:
365 case Instruction::URem:
366 case Instruction::SRem:
367 case Instruction::FRem:
368 case Instruction::Shl:
369 case Instruction::LShr:
370 case Instruction::AShr:
371 case Instruction::And:
372 case Instruction::Or :
373 case Instruction::Xor:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000374 case Instruction::ICmp:
375 case Instruction::FCmp:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000376 case Instruction::Trunc:
377 case Instruction::ZExt:
378 case Instruction::SExt:
379 case Instruction::FPToUI:
380 case Instruction::FPToSI:
381 case Instruction::UIToFP:
382 case Instruction::SIToFP:
383 case Instruction::FPTrunc:
384 case Instruction::FPExt:
385 case Instruction::PtrToInt:
386 case Instruction::IntToPtr:
387 case Instruction::BitCast:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000388 case Instruction::Select:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000389 case Instruction::ExtractElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000390 case Instruction::InsertElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000391 case Instruction::ShuffleVector:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000392 case Instruction::InsertValue:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000393 case Instruction::GetElementPtr:
Owen Anderson30f4a552011-01-03 19:00:11 +0000394 exp = create_expression(I);
Owen Andersond41ed4e2009-10-19 22:14:22 +0000395 break;
Lang Hames1fb09552011-07-08 01:50:54 +0000396 case Instruction::ExtractValue:
397 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
398 break;
Owen Andersond41ed4e2009-10-19 22:14:22 +0000399 default:
400 valueNumbering[V] = nextValueNumber;
401 return nextValueNumber++;
402 }
403
404 uint32_t& e = expressionNumbering[exp];
405 if (!e) e = nextValueNumber++;
406 valueNumbering[V] = e;
407 return e;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000408}
409
410/// lookup - Returns the value number of the specified value. Fails if
411/// the value has not yet been numbered.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000412uint32_t ValueTable::lookup(Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000413 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Chris Lattner88365bb2008-03-21 21:14:38 +0000414 assert(VI != valueNumbering.end() && "Value not numbered?");
415 return VI->second;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000416}
417
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000418/// clear - Remove all entries from the ValueTable.
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000419void ValueTable::clear() {
420 valueNumbering.clear();
421 expressionNumbering.clear();
422 nextValueNumber = 1;
423}
424
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000425/// erase - Remove a value from the value numbering.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000426void ValueTable::erase(Value *V) {
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000427 valueNumbering.erase(V);
428}
429
Bill Wendling246dbbb2008-12-22 21:36:08 +0000430/// verifyRemoved - Verify that the value is removed from all internal data
431/// structures.
432void ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000433 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling246dbbb2008-12-22 21:36:08 +0000434 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
435 assert(I->first != V && "Inst still occurs in value numbering map!");
436 }
437}
438
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000439//===----------------------------------------------------------------------===//
Bill Wendling30788b82008-12-22 22:32:22 +0000440// GVN Pass
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000441//===----------------------------------------------------------------------===//
442
443namespace {
444
Chris Lattner3e8b6632009-09-02 06:11:42 +0000445 class GVN : public FunctionPass {
Dan Gohman4ec01b22009-11-14 02:27:51 +0000446 bool NoLoads;
Chris Lattner663e4412008-12-01 00:40:32 +0000447 MemoryDependenceAnalysis *MD;
448 DominatorTree *DT;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000449 const TargetData *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000450 const TargetLibraryInfo *TLI;
451
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000452 ValueTable VN;
Owen Andersona04a0642010-11-18 18:32:40 +0000453
Owen Andersonb1602ab2011-01-04 19:29:46 +0000454 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
Owen Anderson7a75d612011-01-04 19:13:25 +0000455 /// have that value number. Use findLeader to query it.
456 struct LeaderTableEntry {
Owen Andersonf0568382010-12-21 23:54:34 +0000457 Value *Val;
458 BasicBlock *BB;
Owen Anderson7a75d612011-01-04 19:13:25 +0000459 LeaderTableEntry *Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000460 };
Owen Andersonb1602ab2011-01-04 19:29:46 +0000461 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
Owen Andersona04a0642010-11-18 18:32:40 +0000462 BumpPtrAllocator TableAllocator;
Owen Anderson68c26392010-11-19 22:48:40 +0000463
Chris Lattnerf07054d2011-04-28 16:18:52 +0000464 SmallVector<Instruction*, 8> InstrsToErase;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000465 public:
466 static char ID; // Pass identification, replacement for typeid
467 explicit GVN(bool noloads = false)
468 : FunctionPass(ID), NoLoads(noloads), MD(0) {
469 initializeGVNPass(*PassRegistry::getPassRegistry());
470 }
471
472 bool runOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000473
Chris Lattner4756ecb2011-04-28 16:36:48 +0000474 /// markInstructionForDeletion - This removes the specified instruction from
475 /// our various maps and marks it for deletion.
476 void markInstructionForDeletion(Instruction *I) {
477 VN.erase(I);
478 InstrsToErase.push_back(I);
479 }
480
481 const TargetData *getTargetData() const { return TD; }
482 DominatorTree &getDominatorTree() const { return *DT; }
483 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000484 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000485 private:
Owen Andersonb1602ab2011-01-04 19:29:46 +0000486 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
Owen Anderson68c26392010-11-19 22:48:40 +0000487 /// its value number.
Owen Anderson7a75d612011-01-04 19:13:25 +0000488 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000489 LeaderTableEntry &Curr = LeaderTable[N];
Owen Andersonf0568382010-12-21 23:54:34 +0000490 if (!Curr.Val) {
491 Curr.Val = V;
492 Curr.BB = BB;
Owen Andersona04a0642010-11-18 18:32:40 +0000493 return;
494 }
495
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000496 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
Owen Andersonf0568382010-12-21 23:54:34 +0000497 Node->Val = V;
498 Node->BB = BB;
499 Node->Next = Curr.Next;
500 Curr.Next = Node;
Owen Andersona04a0642010-11-18 18:32:40 +0000501 }
502
Owen Andersonb1602ab2011-01-04 19:29:46 +0000503 /// removeFromLeaderTable - Scan the list of values corresponding to a given
504 /// value number, and remove the given value if encountered.
Owen Anderson7a75d612011-01-04 19:13:25 +0000505 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
506 LeaderTableEntry* Prev = 0;
Owen Andersonb1602ab2011-01-04 19:29:46 +0000507 LeaderTableEntry* Curr = &LeaderTable[N];
Owen Andersona04a0642010-11-18 18:32:40 +0000508
Owen Andersonf0568382010-12-21 23:54:34 +0000509 while (Curr->Val != V || Curr->BB != BB) {
Owen Andersona04a0642010-11-18 18:32:40 +0000510 Prev = Curr;
Owen Andersonf0568382010-12-21 23:54:34 +0000511 Curr = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000512 }
513
514 if (Prev) {
Owen Andersonf0568382010-12-21 23:54:34 +0000515 Prev->Next = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000516 } else {
Owen Andersonf0568382010-12-21 23:54:34 +0000517 if (!Curr->Next) {
518 Curr->Val = 0;
519 Curr->BB = 0;
Owen Andersona04a0642010-11-18 18:32:40 +0000520 } else {
Owen Anderson7a75d612011-01-04 19:13:25 +0000521 LeaderTableEntry* Next = Curr->Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000522 Curr->Val = Next->Val;
523 Curr->BB = Next->BB;
Owen Anderson680ac4f2011-01-04 19:10:54 +0000524 Curr->Next = Next->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000525 }
526 }
527 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000528
Bob Wilson484d4a32010-02-16 19:51:59 +0000529 // List of critical edges to be split between iterations.
530 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
531
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000532 // This transformation requires dominator postdominator info
533 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000534 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000535 AU.addRequired<TargetLibraryInfo>();
Dan Gohman4ec01b22009-11-14 02:27:51 +0000536 if (!NoLoads)
537 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000538 AU.addRequired<AliasAnalysis>();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000539
Owen Andersonb70a5712008-06-23 17:49:45 +0000540 AU.addPreserved<DominatorTree>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000541 AU.addPreserved<AliasAnalysis>();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000542 }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000543
Daniel Dunbara279bc32009-09-20 02:20:51 +0000544
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000545 // Helper fuctions
546 // FIXME: eliminate or document these better
Chris Lattnerf07054d2011-04-28 16:18:52 +0000547 bool processLoad(LoadInst *L);
548 bool processInstruction(Instruction *I);
549 bool processNonLocalLoad(LoadInst *L);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000550 bool processBlock(BasicBlock *BB);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000551 void dump(DenseMap<uint32_t, Value*> &d);
Owen Anderson3e75a422007-08-14 18:04:11 +0000552 bool iterateOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000553 bool performPRE(Function &F);
Owen Anderson7a75d612011-01-04 19:13:25 +0000554 Value *findLeader(BasicBlock *BB, uint32_t num);
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +0000555 void cleanupGlobalSets();
Bill Wendling246dbbb2008-12-22 21:36:08 +0000556 void verifyRemoved(const Instruction *I) const;
Bob Wilson484d4a32010-02-16 19:51:59 +0000557 bool splitCriticalEdges();
Duncan Sands02b5e722011-10-05 14:28:49 +0000558 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
559 BasicBlock *Root);
560 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000561 };
Daniel Dunbara279bc32009-09-20 02:20:51 +0000562
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000563 char GVN::ID = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000564}
565
566// createGVNPass - The public interface to this file...
Bob Wilsonb29d7d22010-02-28 05:34:05 +0000567FunctionPass *llvm::createGVNPass(bool NoLoads) {
568 return new GVN(NoLoads);
Dan Gohman4ec01b22009-11-14 02:27:51 +0000569}
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000570
Owen Anderson2ab36d32010-10-12 19:48:12 +0000571INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
572INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
573INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000574INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000575INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
576INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000577
Owen Andersonb2303722008-06-18 21:41:49 +0000578void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000579 errs() << "{\n";
Owen Andersonb2303722008-06-18 21:41:49 +0000580 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson0cd32032007-07-25 19:57:03 +0000581 E = d.end(); I != E; ++I) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000582 errs() << I->first << "\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000583 I->second->dump();
584 }
Dan Gohmanad12b262009-12-18 03:25:51 +0000585 errs() << "}\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000586}
587
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000588/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
589/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner72bc70d2008-12-05 07:49:08 +0000590/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
591/// map is actually a tri-state map with the following values:
592/// 0) we know the block *is not* fully available.
593/// 1) we know the block *is* fully available.
594/// 2) we do not know whether the block is fully available or not, but we are
595/// currently speculating that it will be.
596/// 3) we are speculating for this block and have used that to speculate for
597/// other blocks.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000598static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner72bc70d2008-12-05 07:49:08 +0000599 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000600 // Optimistically assume that the block is fully available and check to see
601 // if we already know about this block in one lookup.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000602 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner72bc70d2008-12-05 07:49:08 +0000603 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000604
605 // If the entry already existed for this block, return the precomputed value.
Chris Lattner72bc70d2008-12-05 07:49:08 +0000606 if (!IV.second) {
607 // If this is a speculative "available" value, mark it as being used for
608 // speculation of other blocks.
609 if (IV.first->second == 2)
610 IV.first->second = 3;
611 return IV.first->second != 0;
612 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000613
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000614 // Otherwise, see if it is fully available in all predecessors.
615 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000616
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000617 // If this block has no predecessors, it isn't live-in here.
618 if (PI == PE)
Chris Lattner72bc70d2008-12-05 07:49:08 +0000619 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000620
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000621 for (; PI != PE; ++PI)
622 // If the value isn't fully available in one of our predecessors, then it
623 // isn't fully available in this block either. Undo our previous
624 // optimistic assumption and bail out.
625 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner72bc70d2008-12-05 07:49:08 +0000626 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000627
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000628 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000629
Chris Lattner72bc70d2008-12-05 07:49:08 +0000630// SpeculationFailure - If we get here, we found out that this is not, after
631// all, a fully-available block. We have a problem if we speculated on this and
632// used the speculation to mark other blocks as available.
633SpeculationFailure:
634 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattner72bc70d2008-12-05 07:49:08 +0000636 // If we didn't speculate on this, just return with it set to false.
637 if (BBVal == 2) {
638 BBVal = 0;
639 return false;
640 }
641
642 // If we did speculate on this value, we could have blocks set to 1 that are
643 // incorrect. Walk the (transitive) successors of this block and mark them as
644 // 0 if set to one.
645 SmallVector<BasicBlock*, 32> BBWorklist;
646 BBWorklist.push_back(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000647
Dan Gohman321a8132010-01-05 16:27:25 +0000648 do {
Chris Lattner72bc70d2008-12-05 07:49:08 +0000649 BasicBlock *Entry = BBWorklist.pop_back_val();
650 // Note that this sets blocks to 0 (unavailable) if they happen to not
651 // already be in FullyAvailableBlocks. This is safe.
652 char &EntryVal = FullyAvailableBlocks[Entry];
653 if (EntryVal == 0) continue; // Already unavailable.
654
655 // Mark as unavailable.
656 EntryVal = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657
Chris Lattner72bc70d2008-12-05 07:49:08 +0000658 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
659 BBWorklist.push_back(*I);
Dan Gohman321a8132010-01-05 16:27:25 +0000660 } while (!BBWorklist.empty());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000661
Chris Lattner72bc70d2008-12-05 07:49:08 +0000662 return false;
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000663}
664
Chris Lattner771a5422009-09-20 20:09:34 +0000665
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000666/// CanCoerceMustAliasedValueToLoad - Return true if
667/// CoerceAvailableValueToLoadType will succeed.
668static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000669 Type *LoadTy,
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000670 const TargetData &TD) {
671 // If the loaded or stored value is an first class array or struct, don't try
672 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000673 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
674 StoredVal->getType()->isStructTy() ||
675 StoredVal->getType()->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000676 return false;
677
678 // The store has to be at least as big as the load.
679 if (TD.getTypeSizeInBits(StoredVal->getType()) <
680 TD.getTypeSizeInBits(LoadTy))
681 return false;
682
683 return true;
684}
685
686
Chris Lattner771a5422009-09-20 20:09:34 +0000687/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
688/// then a load from a must-aliased pointer of a different type, try to coerce
689/// the stored value. LoadedTy is the type of the load we want to replace and
690/// InsertPt is the place to insert new instructions.
691///
692/// If we can't do it, return null.
693static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000694 Type *LoadedTy,
Chris Lattner771a5422009-09-20 20:09:34 +0000695 Instruction *InsertPt,
696 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000697 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
698 return 0;
699
Chris Lattner4034e142011-04-28 07:29:08 +0000700 // If this is already the right type, just return it.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000701 Type *StoredValTy = StoredVal->getType();
Chris Lattner771a5422009-09-20 20:09:34 +0000702
Jakub Staszak8cec7592011-09-02 14:57:37 +0000703 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
704 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
Chris Lattner771a5422009-09-20 20:09:34 +0000705
706 // If the store and reload are the same size, we can always reuse it.
707 if (StoreSize == LoadSize) {
Chris Lattner1f821512011-04-26 01:21:15 +0000708 // Pointer to Pointer -> use bitcast.
709 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000710 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
Chris Lattner771a5422009-09-20 20:09:34 +0000711
712 // Convert source pointers to integers, which can be bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +0000713 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000714 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
715 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
716 }
717
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000718 Type *TypeToCastTo = LoadedTy;
Duncan Sands1df98592010-02-16 11:11:14 +0000719 if (TypeToCastTo->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000720 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
721
722 if (StoredValTy != TypeToCastTo)
723 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
724
725 // Cast to pointer if the load needs a pointer type.
Duncan Sands1df98592010-02-16 11:11:14 +0000726 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000727 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
728
729 return StoredVal;
730 }
731
732 // If the loaded value is smaller than the available value, then we can
733 // extract out a piece from it. If the available value is too small, then we
734 // can't do anything.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000735 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattner771a5422009-09-20 20:09:34 +0000736
737 // Convert source pointers to integers, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000738 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000739 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
740 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
741 }
742
743 // Convert vectors and fp to integer, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000744 if (!StoredValTy->isIntegerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000745 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
746 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
747 }
748
749 // If this is a big-endian system, we need to shift the value down to the low
750 // bits so that a truncate will work.
751 if (TD.isBigEndian()) {
752 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
753 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
754 }
755
756 // Truncate the integer to the right size now.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000757 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
Chris Lattner771a5422009-09-20 20:09:34 +0000758 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
759
760 if (LoadedTy == NewIntTy)
761 return StoredVal;
762
763 // If the result is a pointer, inttoptr.
Duncan Sands1df98592010-02-16 11:11:14 +0000764 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000765 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
766
767 // Otherwise, bitcast.
768 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
769}
770
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000771/// AnalyzeLoadFromClobberingWrite - This function is called when we have a
772/// memdep query of a load that ends up being a clobbering memory write (store,
773/// memset, memcpy, memmove). This means that the write *may* provide bits used
774/// by the load but we can't be sure because the pointers don't mustalias.
775///
776/// Check this case to see if there is anything more we can do before we give
777/// up. This returns -1 if we have to give up, or a byte number in the stored
778/// value of the piece that feeds the load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000779static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000780 Value *WritePtr,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000781 uint64_t WriteSizeInBits,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000782 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000783 // If the loaded or stored value is an first class array or struct, don't try
784 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000785 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000786 return -1;
787
Chris Lattnerca749402009-09-21 06:24:16 +0000788 int64_t StoreOffset = 0, LoadOffset = 0;
Chris Lattnered58a6f2010-11-30 22:25:26 +0000789 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
790 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
Chris Lattnerca749402009-09-21 06:24:16 +0000791 if (StoreBase != LoadBase)
792 return -1;
793
794 // If the load and store are to the exact same address, they should have been
795 // a must alias. AA must have gotten confused.
Chris Lattner219d7742010-03-25 05:58:19 +0000796 // FIXME: Study to see if/when this happens. One case is forwarding a memset
797 // to a load from the base of the memset.
Chris Lattnerca749402009-09-21 06:24:16 +0000798#if 0
Chris Lattner219d7742010-03-25 05:58:19 +0000799 if (LoadOffset == StoreOffset) {
David Greenebf7f78e2010-01-05 01:27:17 +0000800 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000801 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000802 << "Store Ptr = " << *WritePtr << "\n"
803 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000804 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000805 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000806 }
Chris Lattner219d7742010-03-25 05:58:19 +0000807#endif
Chris Lattnerca749402009-09-21 06:24:16 +0000808
809 // If the load and store don't overlap at all, the store doesn't provide
810 // anything to the load. In this case, they really don't alias at all, AA
811 // must have gotten confused.
Chris Lattner03f17da2009-12-09 07:34:10 +0000812 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
Chris Lattnerca749402009-09-21 06:24:16 +0000813
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000814 if ((WriteSizeInBits & 7) | (LoadSize & 7))
Chris Lattnerca749402009-09-21 06:24:16 +0000815 return -1;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000816 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
Chris Lattnerca749402009-09-21 06:24:16 +0000817 LoadSize >>= 3;
818
819
820 bool isAAFailure = false;
Chris Lattner219d7742010-03-25 05:58:19 +0000821 if (StoreOffset < LoadOffset)
Chris Lattnerca749402009-09-21 06:24:16 +0000822 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000823 else
Chris Lattnerca749402009-09-21 06:24:16 +0000824 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000825
Chris Lattnerca749402009-09-21 06:24:16 +0000826 if (isAAFailure) {
827#if 0
David Greenebf7f78e2010-01-05 01:27:17 +0000828 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000829 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000830 << "Store Ptr = " << *WritePtr << "\n"
831 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000832 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000833 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000834#endif
835 return -1;
836 }
837
838 // If the Load isn't completely contained within the stored bits, we don't
839 // have all the bits to feed it. We could do something crazy in the future
840 // (issue a smaller load then merge the bits in) but this seems unlikely to be
841 // valuable.
842 if (StoreOffset > LoadOffset ||
843 StoreOffset+StoreSize < LoadOffset+LoadSize)
844 return -1;
845
846 // Okay, we can do this transformation. Return the number of bytes into the
847 // store that the load is.
848 return LoadOffset-StoreOffset;
849}
850
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000851/// AnalyzeLoadFromClobberingStore - This function is called when we have a
852/// memdep query of a load that ends up being a clobbering store.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000853static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000854 StoreInst *DepSI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000855 const TargetData &TD) {
856 // Cannot handle reading from store of first-class aggregate yet.
Dan Gohman3355c4e2010-11-10 19:03:33 +0000857 if (DepSI->getValueOperand()->getType()->isStructTy() ||
858 DepSI->getValueOperand()->getType()->isArrayTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000859 return -1;
860
861 Value *StorePtr = DepSI->getPointerOperand();
Dan Gohman3355c4e2010-11-10 19:03:33 +0000862 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000863 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000864 StorePtr, StoreSize, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000865}
866
Chris Lattner1f821512011-04-26 01:21:15 +0000867/// AnalyzeLoadFromClobberingLoad - This function is called when we have a
868/// memdep query of a load that ends up being clobbered by another load. See if
869/// the other load can feed into the second load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000870static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
Chris Lattner1f821512011-04-26 01:21:15 +0000871 LoadInst *DepLI, const TargetData &TD){
872 // Cannot handle reading from store of first-class aggregate yet.
873 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
874 return -1;
875
876 Value *DepPtr = DepLI->getPointerOperand();
877 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
Chris Lattner4034e142011-04-28 07:29:08 +0000878 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
879 if (R != -1) return R;
880
881 // If we have a load/load clobber an DepLI can be widened to cover this load,
882 // then we should widen it!
883 int64_t LoadOffs = 0;
884 const Value *LoadBase =
885 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
886 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
887
888 unsigned Size = MemoryDependenceAnalysis::
889 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
890 if (Size == 0) return -1;
891
892 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
Chris Lattner1f821512011-04-26 01:21:15 +0000893}
894
895
896
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000897static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000898 MemIntrinsic *MI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000899 const TargetData &TD) {
900 // If the mem operation is a non-constant size, we can't handle it.
901 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
902 if (SizeCst == 0) return -1;
903 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000904
905 // If this is memset, we just need to see if the offset is valid in the size
906 // of the memset..
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000907 if (MI->getIntrinsicID() == Intrinsic::memset)
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000908 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
909 MemSizeInBits, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000910
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000911 // If we have a memcpy/memmove, the only case we can handle is if this is a
912 // copy from constant memory. In that case, we can read directly from the
913 // constant memory.
914 MemTransferInst *MTI = cast<MemTransferInst>(MI);
915
916 Constant *Src = dyn_cast<Constant>(MTI->getSource());
917 if (Src == 0) return -1;
918
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000919 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000920 if (GV == 0 || !GV->isConstant()) return -1;
921
922 // See if the access is within the bounds of the transfer.
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000923 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
924 MI->getDest(), MemSizeInBits, TD);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000925 if (Offset == -1)
926 return Offset;
927
928 // Otherwise, see if we can constant fold a load from the constant with the
929 // offset applied as appropriate.
930 Src = ConstantExpr::getBitCast(Src,
931 llvm::Type::getInt8PtrTy(Src->getContext()));
932 Constant *OffsetCst =
933 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +0000934 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000935 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000936 if (ConstantFoldLoadFromConstPtr(Src, &TD))
937 return Offset;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000938 return -1;
939}
940
Chris Lattnerca749402009-09-21 06:24:16 +0000941
942/// GetStoreValueForLoad - This function is called when we have a
943/// memdep query of a load that ends up being a clobbering store. This means
Chris Lattner4034e142011-04-28 07:29:08 +0000944/// that the store provides bits used by the load but we the pointers don't
945/// mustalias. Check this case to see if there is anything more we can do
946/// before we give up.
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000947static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000948 Type *LoadTy,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000949 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerca749402009-09-21 06:24:16 +0000950 LLVMContext &Ctx = SrcVal->getType()->getContext();
951
Chris Lattner7944c212010-05-08 20:01:44 +0000952 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
953 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
Chris Lattnerca749402009-09-21 06:24:16 +0000954
Chris Lattnerb2c6ae82009-12-09 18:13:28 +0000955 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +0000956
957 // Compute which bits of the stored value are being used by the load. Convert
958 // to an integer type to start with.
Duncan Sands1df98592010-02-16 11:11:14 +0000959 if (SrcVal->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000960 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
Duncan Sands1df98592010-02-16 11:11:14 +0000961 if (!SrcVal->getType()->isIntegerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000962 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +0000963
964 // Shift the bits to the least significant depending on endianness.
965 unsigned ShiftAmt;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000966 if (TD.isLittleEndian())
Chris Lattnerca749402009-09-21 06:24:16 +0000967 ShiftAmt = Offset*8;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000968 else
Chris Lattner19ad7842009-09-21 17:55:47 +0000969 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerca749402009-09-21 06:24:16 +0000970
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000971 if (ShiftAmt)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000972 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
Chris Lattnerca749402009-09-21 06:24:16 +0000973
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000974 if (LoadSize != StoreSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000975 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +0000976
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000977 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerca749402009-09-21 06:24:16 +0000978}
979
Chris Lattner4034e142011-04-28 07:29:08 +0000980/// GetStoreValueForLoad - This function is called when we have a
981/// memdep query of a load that ends up being a clobbering load. This means
982/// that the load *may* provide bits used by the load but we can't be sure
983/// because the pointers don't mustalias. Check this case to see if there is
984/// anything more we can do before we give up.
985static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000986 Type *LoadTy, Instruction *InsertPt,
Chris Lattner4756ecb2011-04-28 16:36:48 +0000987 GVN &gvn) {
988 const TargetData &TD = *gvn.getTargetData();
Chris Lattner4034e142011-04-28 07:29:08 +0000989 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
990 // widen SrcVal out to a larger load.
991 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
992 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
993 if (Offset+LoadSize > SrcValSize) {
Eli Friedman56efe242011-08-17 22:22:24 +0000994 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
995 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
Chris Lattner4034e142011-04-28 07:29:08 +0000996 // If we have a load/load clobber an DepLI can be widened to cover this
997 // load, then we should widen it to the next power of 2 size big enough!
998 unsigned NewLoadSize = Offset+LoadSize;
999 if (!isPowerOf2_32(NewLoadSize))
1000 NewLoadSize = NextPowerOf2(NewLoadSize);
1001
1002 Value *PtrVal = SrcVal->getPointerOperand();
1003
Chris Lattner0a9e3d62011-04-28 18:15:47 +00001004 // Insert the new load after the old load. This ensures that subsequent
1005 // memdep queries will find the new load. We can't easily remove the old
1006 // load completely because it is already in the value numbering table.
1007 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001008 Type *DestPTy =
Chris Lattner4034e142011-04-28 07:29:08 +00001009 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1010 DestPTy = PointerType::get(DestPTy,
1011 cast<PointerType>(PtrVal->getType())->getAddressSpace());
Devang Patel0f18d972011-05-04 23:58:50 +00001012 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
Chris Lattner4034e142011-04-28 07:29:08 +00001013 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1014 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1015 NewLoad->takeName(SrcVal);
1016 NewLoad->setAlignment(SrcVal->getAlignment());
Devang Patel0f18d972011-05-04 23:58:50 +00001017
Chris Lattner4034e142011-04-28 07:29:08 +00001018 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1019 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1020
1021 // Replace uses of the original load with the wider load. On a big endian
1022 // system, we need to shift down to get the relevant bits.
1023 Value *RV = NewLoad;
1024 if (TD.isBigEndian())
1025 RV = Builder.CreateLShr(RV,
1026 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1027 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1028 SrcVal->replaceAllUsesWith(RV);
Chris Lattner1e4f44b2011-04-28 20:02:57 +00001029
1030 // We would like to use gvn.markInstructionForDeletion here, but we can't
1031 // because the load is already memoized into the leader map table that GVN
1032 // tracks. It is potentially possible to remove the load from the table,
1033 // but then there all of the operations based on it would need to be
1034 // rehashed. Just leave the dead load around.
Chris Lattnerad3ba6a2011-04-28 18:08:21 +00001035 gvn.getMemDep().removeInstruction(SrcVal);
Chris Lattner4034e142011-04-28 07:29:08 +00001036 SrcVal = NewLoad;
1037 }
1038
1039 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1040}
1041
1042
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001043/// GetMemInstValueForLoad - This function is called when we have a
1044/// memdep query of a load that ends up being a clobbering mem intrinsic.
1045static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001046 Type *LoadTy, Instruction *InsertPt,
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001047 const TargetData &TD){
1048 LLVMContext &Ctx = LoadTy->getContext();
1049 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1050
1051 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1052
1053 // We know that this method is only called when the mem transfer fully
1054 // provides the bits for the load.
1055 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1056 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1057 // independently of what the offset is.
1058 Value *Val = MSI->getValue();
1059 if (LoadSize != 1)
1060 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1061
1062 Value *OneElt = Val;
1063
1064 // Splat the value out to the right number of bits.
1065 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1066 // If we can double the number of bytes set, do it.
1067 if (NumBytesSet*2 <= LoadSize) {
1068 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1069 Val = Builder.CreateOr(Val, ShVal);
1070 NumBytesSet <<= 1;
1071 continue;
1072 }
1073
1074 // Otherwise insert one byte at a time.
1075 Value *ShVal = Builder.CreateShl(Val, 1*8);
1076 Val = Builder.CreateOr(OneElt, ShVal);
1077 ++NumBytesSet;
1078 }
1079
1080 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1081 }
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001082
1083 // Otherwise, this is a memcpy/memmove from a constant global.
1084 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1085 Constant *Src = cast<Constant>(MTI->getSource());
1086
1087 // Otherwise, see if we can constant fold a load from the constant with the
1088 // offset applied as appropriate.
1089 Src = ConstantExpr::getBitCast(Src,
1090 llvm::Type::getInt8PtrTy(Src->getContext()));
1091 Constant *OffsetCst =
1092 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +00001093 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001094 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1095 return ConstantFoldLoadFromConstPtr(Src, &TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001096}
1097
Dan Gohmanb3579832010-04-15 17:08:50 +00001098namespace {
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001099
Chris Lattner87913512009-09-21 06:30:24 +00001100struct AvailableValueInBlock {
1101 /// BB - The basic block in question.
1102 BasicBlock *BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001103 enum ValType {
1104 SimpleVal, // A simple offsetted value that is accessed.
Chris Lattner4034e142011-04-28 07:29:08 +00001105 LoadVal, // A value produced by a load.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001106 MemIntrin // A memory intrinsic which is loaded from.
1107 };
1108
Chris Lattner87913512009-09-21 06:30:24 +00001109 /// V - The value that is live out of the block.
Chris Lattner4034e142011-04-28 07:29:08 +00001110 PointerIntPair<Value *, 2, ValType> Val;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001111
1112 /// Offset - The byte offset in Val that is interesting for the load query.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001113 unsigned Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001114
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001115 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1116 unsigned Offset = 0) {
Chris Lattner87913512009-09-21 06:30:24 +00001117 AvailableValueInBlock Res;
1118 Res.BB = BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001119 Res.Val.setPointer(V);
1120 Res.Val.setInt(SimpleVal);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001121 Res.Offset = Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001122 return Res;
1123 }
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001124
1125 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1126 unsigned Offset = 0) {
1127 AvailableValueInBlock Res;
1128 Res.BB = BB;
1129 Res.Val.setPointer(MI);
1130 Res.Val.setInt(MemIntrin);
1131 Res.Offset = Offset;
1132 return Res;
1133 }
1134
Chris Lattner4034e142011-04-28 07:29:08 +00001135 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1136 unsigned Offset = 0) {
1137 AvailableValueInBlock Res;
1138 Res.BB = BB;
1139 Res.Val.setPointer(LI);
1140 Res.Val.setInt(LoadVal);
1141 Res.Offset = Offset;
1142 return Res;
1143 }
1144
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001145 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
Chris Lattner4034e142011-04-28 07:29:08 +00001146 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1147 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1148
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001149 Value *getSimpleValue() const {
1150 assert(isSimpleValue() && "Wrong accessor");
1151 return Val.getPointer();
1152 }
1153
Chris Lattner4034e142011-04-28 07:29:08 +00001154 LoadInst *getCoercedLoadValue() const {
1155 assert(isCoercedLoadValue() && "Wrong accessor");
1156 return cast<LoadInst>(Val.getPointer());
1157 }
1158
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001159 MemIntrinsic *getMemIntrinValue() const {
Chris Lattner4034e142011-04-28 07:29:08 +00001160 assert(isMemIntrinValue() && "Wrong accessor");
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001161 return cast<MemIntrinsic>(Val.getPointer());
1162 }
Chris Lattner5362c542009-12-21 23:04:33 +00001163
1164 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1165 /// defined here to the specified type. This handles various coercion cases.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001166 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
Chris Lattner5362c542009-12-21 23:04:33 +00001167 Value *Res;
1168 if (isSimpleValue()) {
1169 Res = getSimpleValue();
1170 if (Res->getType() != LoadTy) {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001171 const TargetData *TD = gvn.getTargetData();
Chris Lattner5362c542009-12-21 23:04:33 +00001172 assert(TD && "Need target data to handle type mismatch case");
1173 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1174 *TD);
1175
Chris Lattner4034e142011-04-28 07:29:08 +00001176 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
Chris Lattner5362c542009-12-21 23:04:33 +00001177 << *getSimpleValue() << '\n'
1178 << *Res << '\n' << "\n\n\n");
1179 }
Chris Lattner4034e142011-04-28 07:29:08 +00001180 } else if (isCoercedLoadValue()) {
1181 LoadInst *Load = getCoercedLoadValue();
1182 if (Load->getType() == LoadTy && Offset == 0) {
1183 Res = Load;
1184 } else {
Chris Lattner4034e142011-04-28 07:29:08 +00001185 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
Chris Lattner4756ecb2011-04-28 16:36:48 +00001186 gvn);
Chris Lattner4034e142011-04-28 07:29:08 +00001187
1188 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1189 << *getCoercedLoadValue() << '\n'
1190 << *Res << '\n' << "\n\n\n");
1191 }
Chris Lattner5362c542009-12-21 23:04:33 +00001192 } else {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001193 const TargetData *TD = gvn.getTargetData();
1194 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner5362c542009-12-21 23:04:33 +00001195 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1196 LoadTy, BB->getTerminator(), *TD);
Chris Lattner4034e142011-04-28 07:29:08 +00001197 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
Chris Lattner5362c542009-12-21 23:04:33 +00001198 << " " << *getMemIntrinValue() << '\n'
1199 << *Res << '\n' << "\n\n\n");
1200 }
1201 return Res;
1202 }
Chris Lattner87913512009-09-21 06:30:24 +00001203};
1204
Chris Lattner4034e142011-04-28 07:29:08 +00001205} // end anonymous namespace
Dan Gohmanb3579832010-04-15 17:08:50 +00001206
Chris Lattnera09fbf02009-10-10 23:50:30 +00001207/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1208/// construct SSA form, allowing us to eliminate LI. This returns the value
1209/// that should be used at LI's definition site.
1210static Value *ConstructSSAForLoadSet(LoadInst *LI,
1211 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
Chris Lattner4756ecb2011-04-28 16:36:48 +00001212 GVN &gvn) {
Chris Lattnerd2191e52009-12-21 23:15:48 +00001213 // Check for the fully redundant, dominating load case. In this case, we can
1214 // just use the dominating value directly.
1215 if (ValuesPerBlock.size() == 1 &&
Chris Lattner4756ecb2011-04-28 16:36:48 +00001216 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1217 LI->getParent()))
1218 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
Chris Lattnerd2191e52009-12-21 23:15:48 +00001219
1220 // Otherwise, we have to construct SSA form.
Chris Lattnera09fbf02009-10-10 23:50:30 +00001221 SmallVector<PHINode*, 8> NewPHIs;
1222 SSAUpdater SSAUpdate(&NewPHIs);
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001223 SSAUpdate.Initialize(LI->getType(), LI->getName());
Chris Lattnera09fbf02009-10-10 23:50:30 +00001224
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001225 Type *LoadTy = LI->getType();
Chris Lattnera09fbf02009-10-10 23:50:30 +00001226
Chris Lattner771a5422009-09-20 20:09:34 +00001227 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001228 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1229 BasicBlock *BB = AV.BB;
Chris Lattner771a5422009-09-20 20:09:34 +00001230
Chris Lattnera09fbf02009-10-10 23:50:30 +00001231 if (SSAUpdate.HasValueForBlock(BB))
1232 continue;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001233
Chris Lattner4756ecb2011-04-28 16:36:48 +00001234 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
Chris Lattner771a5422009-09-20 20:09:34 +00001235 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001236
1237 // Perform PHI construction.
1238 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1239
1240 // If new PHI nodes were created, notify alias analysis.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001241 if (V->getType()->isPointerTy()) {
1242 AliasAnalysis *AA = gvn.getAliasAnalysis();
1243
Chris Lattnera09fbf02009-10-10 23:50:30 +00001244 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1245 AA->copyValue(LI, NewPHIs[i]);
Owen Anderson392249f2011-01-03 23:51:43 +00001246
1247 // Now that we've copied information to the new PHIs, scan through
1248 // them again and inform alias analysis that we've added potentially
1249 // escaping uses to any values that are operands to these PHIs.
1250 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1251 PHINode *P = NewPHIs[i];
Jay Foadc1371202011-06-20 14:18:48 +00001252 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1253 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1254 AA->addEscapingUse(P->getOperandUse(jj));
1255 }
Owen Anderson392249f2011-01-03 23:51:43 +00001256 }
Chris Lattner4756ecb2011-04-28 16:36:48 +00001257 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001258
1259 return V;
Chris Lattner771a5422009-09-20 20:09:34 +00001260}
1261
Gabor Greifea3eec92010-04-09 10:57:00 +00001262static bool isLifetimeStart(const Instruction *Inst) {
1263 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
Owen Anderson9ff5a232009-12-02 07:35:19 +00001264 return II->getIntrinsicID() == Intrinsic::lifetime_start;
Chris Lattner720e7902009-12-02 06:44:58 +00001265 return false;
1266}
1267
Owen Anderson62bc33c2007-08-16 22:02:55 +00001268/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1269/// non-local by performing PHI construction.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001270bool GVN::processNonLocalLoad(LoadInst *LI) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001271 // Find the non-local dependencies of the load.
Chris Lattner0ee443d2009-12-22 04:25:02 +00001272 SmallVector<NonLocalDepResult, 64> Deps;
Dan Gohman6d8eb152010-11-11 21:50:19 +00001273 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1274 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
David Greenebf7f78e2010-01-05 01:27:17 +00001275 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
Dan Gohman2a298992009-07-31 20:24:18 +00001276 // << Deps.size() << *LI << '\n');
Daniel Dunbara279bc32009-09-20 02:20:51 +00001277
Owen Anderson516eb1c2008-08-26 22:07:42 +00001278 // If we had to process more than one hundred blocks to find the
1279 // dependencies, this load isn't worth worrying about. Optimizing
1280 // it will be too expensive.
Chris Lattner91bcf642008-12-09 19:25:07 +00001281 if (Deps.size() > 100)
Owen Anderson516eb1c2008-08-26 22:07:42 +00001282 return false;
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001283
1284 // If we had a phi translation failure, we'll have a single entry which is a
1285 // clobber in the current block. Reject this early.
Eli Friedmanb4141422011-10-13 22:14:57 +00001286 if (Deps.size() == 1
1287 && !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber())
1288 {
Torok Edwin4306b1a2009-06-17 18:48:18 +00001289 DEBUG(
David Greenebf7f78e2010-01-05 01:27:17 +00001290 dbgs() << "GVN: non-local load ";
1291 WriteAsOperand(dbgs(), LI);
Eli Friedmana990e072011-06-15 00:47:34 +00001292 dbgs() << " has unknown dependencies\n";
Torok Edwin4306b1a2009-06-17 18:48:18 +00001293 );
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001294 return false;
Torok Edwin4306b1a2009-06-17 18:48:18 +00001295 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001296
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001297 // Filter out useless results (non-locals, etc). Keep track of the blocks
1298 // where we have a value available in repl, also keep track of whether we see
1299 // dependencies that produce an unknown value for the load (such as a call
1300 // that could potentially clobber the load).
Chris Lattner87913512009-09-21 06:30:24 +00001301 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001302 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001303
Chris Lattner91bcf642008-12-09 19:25:07 +00001304 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +00001305 BasicBlock *DepBB = Deps[i].getBB();
1306 MemDepResult DepInfo = Deps[i].getResult();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001307
Eli Friedmanb4141422011-10-13 22:14:57 +00001308 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001309 UnavailableBlocks.push_back(DepBB);
1310 continue;
1311 }
1312
Chris Lattnerb51deb92008-12-05 21:04:20 +00001313 if (DepInfo.isClobber()) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001314 // The address being loaded in this non-local block may not be the same as
1315 // the pointer operand of the load if PHI translation occurs. Make sure
1316 // to consider the right address.
1317 Value *Address = Deps[i].getAddress();
1318
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001319 // If the dependence is to a store that writes to a superset of the bits
1320 // read by the load, we can extract the bits we need for the load from the
1321 // stored value.
1322 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001323 if (TD && Address) {
1324 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001325 DepSI, *TD);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001326 if (Offset != -1) {
1327 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001328 DepSI->getValueOperand(),
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001329 Offset));
1330 continue;
1331 }
1332 }
1333 }
Chris Lattner1f821512011-04-26 01:21:15 +00001334
1335 // Check to see if we have something like this:
1336 // load i32* P
1337 // load i8* (P+1)
1338 // if we have this, replace the later with an extraction from the former.
1339 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1340 // If this is a clobber and L is the first instruction in its block, then
1341 // we have the first instruction in the entry block.
1342 if (DepLI != LI && Address && TD) {
1343 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1344 LI->getPointerOperand(),
1345 DepLI, *TD);
1346
1347 if (Offset != -1) {
Chris Lattner4034e142011-04-28 07:29:08 +00001348 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1349 Offset));
Chris Lattner1f821512011-04-26 01:21:15 +00001350 continue;
1351 }
1352 }
1353 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001354
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001355 // If the clobbering value is a memset/memcpy/memmove, see if we can
1356 // forward a value on from it.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001357 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001358 if (TD && Address) {
1359 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001360 DepMI, *TD);
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001361 if (Offset != -1) {
1362 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1363 Offset));
1364 continue;
1365 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001366 }
1367 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001368
Chris Lattnerb51deb92008-12-05 21:04:20 +00001369 UnavailableBlocks.push_back(DepBB);
1370 continue;
1371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001372
Eli Friedmanb4141422011-10-13 22:14:57 +00001373 // DepInfo.isDef() here
Eli Friedmana990e072011-06-15 00:47:34 +00001374
Chris Lattnerb51deb92008-12-05 21:04:20 +00001375 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001376
Chris Lattnerb51deb92008-12-05 21:04:20 +00001377 // Loading the allocation -> undef.
Chris Lattner720e7902009-12-02 06:44:58 +00001378 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
Owen Anderson9ff5a232009-12-02 07:35:19 +00001379 // Loading immediately after lifetime begin -> undef.
1380 isLifetimeStart(DepInst)) {
Chris Lattner87913512009-09-21 06:30:24 +00001381 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1382 UndefValue::get(LI->getType())));
Chris Lattnerbf145d62008-12-01 01:15:42 +00001383 continue;
1384 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001385
Chris Lattner87913512009-09-21 06:30:24 +00001386 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387 // Reject loads and stores that are to the same address but are of
Chris Lattner771a5422009-09-20 20:09:34 +00001388 // different types if we have to.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001389 if (S->getValueOperand()->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001390 // If the stored value is larger or equal to the loaded value, we can
1391 // reuse it.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001392 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001393 LI->getType(), *TD)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001394 UnavailableBlocks.push_back(DepBB);
1395 continue;
1396 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001397 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001398
Chris Lattner87913512009-09-21 06:30:24 +00001399 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001400 S->getValueOperand()));
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001401 continue;
1402 }
1403
1404 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001405 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001406 if (LD->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001407 // If the stored value is larger or equal to the loaded value, we can
1408 // reuse it.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001409 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattner771a5422009-09-20 20:09:34 +00001410 UnavailableBlocks.push_back(DepBB);
1411 continue;
1412 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001413 }
Chris Lattner4034e142011-04-28 07:29:08 +00001414 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001415 continue;
Owen Anderson0cd32032007-07-25 19:57:03 +00001416 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001417
1418 UnavailableBlocks.push_back(DepBB);
1419 continue;
Chris Lattner88365bb2008-03-21 21:14:38 +00001420 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001421
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001422 // If we have no predecessors that produce a known value for this load, exit
1423 // early.
1424 if (ValuesPerBlock.empty()) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001425
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001426 // If all of the instructions we depend on produce a known value for this
1427 // load, then it is fully redundant and we can use PHI insertion to compute
1428 // its value. Insert PHIs and remove the fully redundant value now.
1429 if (UnavailableBlocks.empty()) {
David Greenebf7f78e2010-01-05 01:27:17 +00001430 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattner771a5422009-09-20 20:09:34 +00001431
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001432 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001433 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001434 LI->replaceAllUsesWith(V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001435
Chris Lattner771a5422009-09-20 20:09:34 +00001436 if (isa<PHINode>(V))
1437 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001438 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001439 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001440 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001441 ++NumGVNLoad;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001442 return true;
1443 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001444
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001445 if (!EnablePRE || !EnableLoadPRE)
1446 return false;
1447
1448 // Okay, we have *some* definitions of the value. This means that the value
1449 // is available in some of our (transitive) predecessors. Lets think about
1450 // doing PRE of this load. This will involve inserting a new load into the
1451 // predecessor when it's not available. We could do this in general, but
1452 // prefer to not increase code size. As such, we only do this when we know
1453 // that we only have to insert *one* load (which means we're basically moving
1454 // the load, not inserting a new one).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001455
Owen Anderson88554df2009-05-31 09:03:40 +00001456 SmallPtrSet<BasicBlock *, 4> Blockers;
1457 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1458 Blockers.insert(UnavailableBlocks[i]);
1459
Bill Wendling795cf5e2011-08-17 21:32:02 +00001460 // Let's find the first basic block with more than one predecessor. Walk
1461 // backwards through predecessors if needed.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001462 BasicBlock *LoadBB = LI->getParent();
Owen Anderson88554df2009-05-31 09:03:40 +00001463 BasicBlock *TmpBB = LoadBB;
1464
1465 bool isSinglePred = false;
Dale Johannesen42c3f552009-06-17 20:48:23 +00001466 bool allSingleSucc = true;
Owen Anderson88554df2009-05-31 09:03:40 +00001467 while (TmpBB->getSinglePredecessor()) {
1468 isSinglePred = true;
1469 TmpBB = TmpBB->getSinglePredecessor();
Owen Anderson88554df2009-05-31 09:03:40 +00001470 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1471 return false;
1472 if (Blockers.count(TmpBB))
1473 return false;
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001474
1475 // If any of these blocks has more than one successor (i.e. if the edge we
1476 // just traversed was critical), then there are other paths through this
1477 // block along which the load may not be anticipated. Hoisting the load
1478 // above this block would be adding the load to execution paths along
1479 // which it was not previously executed.
Dale Johannesen42c3f552009-06-17 20:48:23 +00001480 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001481 return false;
Owen Anderson88554df2009-05-31 09:03:40 +00001482 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001483
Owen Anderson88554df2009-05-31 09:03:40 +00001484 assert(TmpBB);
1485 LoadBB = TmpBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001486
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001487 // FIXME: It is extremely unclear what this loop is doing, other than
1488 // artificially restricting loadpre.
Owen Anderson88554df2009-05-31 09:03:40 +00001489 if (isSinglePred) {
1490 bool isHot = false;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001491 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1492 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1493 if (AV.isSimpleValue())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001494 // "Hot" Instruction is in some loop (because it dominates its dep.
1495 // instruction).
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001496 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1497 if (DT->dominates(LI, I)) {
1498 isHot = true;
1499 break;
1500 }
1501 }
Owen Anderson88554df2009-05-31 09:03:40 +00001502
1503 // We are interested only in "hot" instructions. We don't want to do any
1504 // mis-optimizations here.
1505 if (!isHot)
1506 return false;
1507 }
1508
Bob Wilson6cad4172010-02-01 21:17:14 +00001509 // Check to see how many predecessors have the loaded value fully
1510 // available.
1511 DenseMap<BasicBlock*, Value*> PredLoads;
Chris Lattner72bc70d2008-12-05 07:49:08 +00001512 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001513 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001514 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001515 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1516 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1517
Bob Wilson34414a62010-05-04 20:03:21 +00001518 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001519 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1520 PI != E; ++PI) {
Bob Wilson6cad4172010-02-01 21:17:14 +00001521 BasicBlock *Pred = *PI;
1522 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001523 continue;
Bob Wilson6cad4172010-02-01 21:17:14 +00001524 }
1525 PredLoads[Pred] = 0;
Bob Wilson484d4a32010-02-16 19:51:59 +00001526
Bob Wilson6cad4172010-02-01 21:17:14 +00001527 if (Pred->getTerminator()->getNumSuccessors() != 1) {
Bob Wilson484d4a32010-02-16 19:51:59 +00001528 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1529 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1530 << Pred->getName() << "': " << *LI << '\n');
1531 return false;
1532 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001533
1534 if (LoadBB->isLandingPad()) {
1535 DEBUG(dbgs()
1536 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1537 << Pred->getName() << "': " << *LI << '\n');
1538 return false;
1539 }
1540
Bob Wilsonae23daf2010-02-16 21:06:42 +00001541 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
Bob Wilson34414a62010-05-04 20:03:21 +00001542 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
Bob Wilson6cad4172010-02-01 21:17:14 +00001543 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001544 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001545
Bob Wilson34414a62010-05-04 20:03:21 +00001546 if (!NeedToSplit.empty()) {
Bob Wilsonbc786532010-05-05 20:44:15 +00001547 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
Bob Wilson70704972010-03-01 23:37:32 +00001548 return false;
Bob Wilson34414a62010-05-04 20:03:21 +00001549 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001550
Bob Wilson6cad4172010-02-01 21:17:14 +00001551 // Decide whether PRE is profitable for this load.
1552 unsigned NumUnavailablePreds = PredLoads.size();
1553 assert(NumUnavailablePreds != 0 &&
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001554 "Fully available value should be eliminated above!");
Owen Anderson7267e142010-10-01 20:02:55 +00001555
1556 // If this load is unavailable in multiple predecessors, reject it.
1557 // FIXME: If we could restructure the CFG, we could make a common pred with
1558 // all the preds that don't have an available LI and insert a new load into
1559 // that one block.
1560 if (NumUnavailablePreds != 1)
Bob Wilson6cad4172010-02-01 21:17:14 +00001561 return false;
Bob Wilson6cad4172010-02-01 21:17:14 +00001562
1563 // Check if the load can safely be moved to all the unavailable predecessors.
1564 bool CanDoPRE = true;
Chris Lattnerdd696052009-11-28 15:39:14 +00001565 SmallVector<Instruction*, 8> NewInsts;
Bob Wilson6cad4172010-02-01 21:17:14 +00001566 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1567 E = PredLoads.end(); I != E; ++I) {
1568 BasicBlock *UnavailablePred = I->first;
1569
1570 // Do PHI translation to get its value in the predecessor if necessary. The
1571 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1572
1573 // If all preds have a single successor, then we know it is safe to insert
1574 // the load on the pred (?!?), so we can insert code to materialize the
1575 // pointer if it is not available.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001576 PHITransAddr Address(LI->getPointerOperand(), TD);
Bob Wilson6cad4172010-02-01 21:17:14 +00001577 Value *LoadPtr = 0;
1578 if (allSingleSucc) {
1579 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1580 *DT, NewInsts);
1581 } else {
Daniel Dunbar6d8f2ca2010-02-24 08:48:04 +00001582 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
Bob Wilson6cad4172010-02-01 21:17:14 +00001583 LoadPtr = Address.getAddr();
Bob Wilson6cad4172010-02-01 21:17:14 +00001584 }
1585
1586 // If we couldn't find or insert a computation of this phi translated value,
1587 // we fail PRE.
1588 if (LoadPtr == 0) {
1589 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
Dan Gohman3355c4e2010-11-10 19:03:33 +00001590 << *LI->getPointerOperand() << "\n");
Bob Wilson6cad4172010-02-01 21:17:14 +00001591 CanDoPRE = false;
1592 break;
1593 }
1594
1595 // Make sure it is valid to move this load here. We have to watch out for:
1596 // @1 = getelementptr (i8* p, ...
1597 // test p and branch if == 0
1598 // load @1
Owen Andersonb1602ab2011-01-04 19:29:46 +00001599 // It is valid to have the getelementptr before the test, even if p can
1600 // be 0, as getelementptr only does address arithmetic.
Bob Wilson6cad4172010-02-01 21:17:14 +00001601 // If we are not pushing the value through any multiple-successor blocks
1602 // we do not have this case. Otherwise, check that the load is safe to
1603 // put anywhere; this can be improved, but should be conservatively safe.
1604 if (!allSingleSucc &&
1605 // FIXME: REEVALUTE THIS.
1606 !isSafeToLoadUnconditionally(LoadPtr,
1607 UnavailablePred->getTerminator(),
1608 LI->getAlignment(), TD)) {
1609 CanDoPRE = false;
1610 break;
1611 }
1612
1613 I->second = LoadPtr;
Chris Lattner05e15f82009-12-09 01:59:31 +00001614 }
1615
Bob Wilson6cad4172010-02-01 21:17:14 +00001616 if (!CanDoPRE) {
Chris Lattner3077ca92011-01-11 08:19:16 +00001617 while (!NewInsts.empty()) {
1618 Instruction *I = NewInsts.pop_back_val();
1619 if (MD) MD->removeInstruction(I);
1620 I->eraseFromParent();
1621 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001622 return false;
Chris Lattner0c264b12009-11-28 16:08:18 +00001623 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001624
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001625 // Okay, we can eliminate this load by inserting a reload in the predecessor
1626 // and using PHI construction to get the value in the other predecessors, do
1627 // it.
David Greenebf7f78e2010-01-05 01:27:17 +00001628 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner0c264b12009-11-28 16:08:18 +00001629 DEBUG(if (!NewInsts.empty())
David Greenebf7f78e2010-01-05 01:27:17 +00001630 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
Chris Lattner0c264b12009-11-28 16:08:18 +00001631 << *NewInsts.back() << '\n');
1632
Bob Wilson6cad4172010-02-01 21:17:14 +00001633 // Assign value numbers to the new instructions.
1634 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1635 // FIXME: We really _ought_ to insert these value numbers into their
1636 // parent's availability map. However, in doing so, we risk getting into
1637 // ordering issues. If a block hasn't been processed yet, we would be
1638 // marking a value as AVAIL-IN, which isn't what we intend.
1639 VN.lookup_or_add(NewInsts[i]);
1640 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001641
Bob Wilson6cad4172010-02-01 21:17:14 +00001642 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1643 E = PredLoads.end(); I != E; ++I) {
1644 BasicBlock *UnavailablePred = I->first;
1645 Value *LoadPtr = I->second;
1646
Dan Gohmanf4177aa2010-12-15 23:53:55 +00001647 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1648 LI->getAlignment(),
1649 UnavailablePred->getTerminator());
1650
1651 // Transfer the old load's TBAA tag to the new load.
1652 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1653 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
Bob Wilson6cad4172010-02-01 21:17:14 +00001654
Devang Pateld9b49962011-05-17 19:43:38 +00001655 // Transfer DebugLoc.
1656 NewLoad->setDebugLoc(LI->getDebugLoc());
1657
Bob Wilson6cad4172010-02-01 21:17:14 +00001658 // Add the newly created load.
1659 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1660 NewLoad));
Bob Wilson188f4282010-02-23 05:55:00 +00001661 MD->invalidateCachedPointerInfo(LoadPtr);
1662 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
Bob Wilson6cad4172010-02-01 21:17:14 +00001663 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001664
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001665 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001666 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001667 LI->replaceAllUsesWith(V);
1668 if (isa<PHINode>(V))
1669 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001670 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001671 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001672 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001673 ++NumPRELoad;
Owen Anderson0cd32032007-07-25 19:57:03 +00001674 return true;
1675}
1676
Owen Anderson62bc33c2007-08-16 22:02:55 +00001677/// processLoad - Attempt to eliminate a load, first by eliminating it
1678/// locally, and then attempting non-local elimination if that fails.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001679bool GVN::processLoad(LoadInst *L) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00001680 if (!MD)
1681 return false;
1682
Eli Friedman56efe242011-08-17 22:22:24 +00001683 if (!L->isSimple())
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001684 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001685
Chris Lattner9e7bc052011-05-22 07:03:34 +00001686 if (L->use_empty()) {
1687 markInstructionForDeletion(L);
1688 return true;
1689 }
1690
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001691 // ... to a pointer that has been loaded from before...
Chris Lattnerb2412a82009-09-21 02:42:51 +00001692 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattner1f821512011-04-26 01:21:15 +00001694 // If we have a clobber and target data is around, see if this is a clobber
1695 // that we can fix up through code synthesis.
1696 if (Dep.isClobber() && TD) {
Chris Lattnereed919b2009-09-21 05:57:11 +00001697 // Check to see if we have something like this:
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001698 // store i32 123, i32* %P
1699 // %A = bitcast i32* %P to i8*
1700 // %B = gep i8* %A, i32 1
1701 // %C = load i8* %B
1702 //
1703 // We could do that by recognizing if the clobber instructions are obviously
1704 // a common base + constant offset, and if the previous store (or memset)
1705 // completely covers this load. This sort of thing can happen in bitfield
1706 // access code.
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001707 Value *AvailVal = 0;
Chris Lattner1f821512011-04-26 01:21:15 +00001708 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1709 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1710 L->getPointerOperand(),
1711 DepSI, *TD);
1712 if (Offset != -1)
1713 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1714 L->getType(), L, *TD);
1715 }
1716
1717 // Check to see if we have something like this:
1718 // load i32* P
1719 // load i8* (P+1)
1720 // if we have this, replace the later with an extraction from the former.
1721 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1722 // If this is a clobber and L is the first instruction in its block, then
1723 // we have the first instruction in the entry block.
1724 if (DepLI == L)
1725 return false;
1726
1727 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1728 L->getPointerOperand(),
1729 DepLI, *TD);
1730 if (Offset != -1)
Chris Lattner4756ecb2011-04-28 16:36:48 +00001731 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
Chris Lattner1f821512011-04-26 01:21:15 +00001732 }
Chris Lattnereed919b2009-09-21 05:57:11 +00001733
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001734 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1735 // a value on from it.
1736 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
Chris Lattner1f821512011-04-26 01:21:15 +00001737 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1738 L->getPointerOperand(),
1739 DepMI, *TD);
1740 if (Offset != -1)
1741 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001742 }
1743
1744 if (AvailVal) {
David Greenebf7f78e2010-01-05 01:27:17 +00001745 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001746 << *AvailVal << '\n' << *L << "\n\n\n");
1747
1748 // Replace the load!
1749 L->replaceAllUsesWith(AvailVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001750 if (AvailVal->getType()->isPointerTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001751 MD->invalidateCachedPointerInfo(AvailVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001752 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001753 ++NumGVNLoad;
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001754 return true;
1755 }
Chris Lattner1f821512011-04-26 01:21:15 +00001756 }
1757
1758 // If the value isn't available, don't do anything!
1759 if (Dep.isClobber()) {
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001760 DEBUG(
Chris Lattner1f821512011-04-26 01:21:15 +00001761 // fast print dep, using operator<< on instruction is too slow.
David Greenebf7f78e2010-01-05 01:27:17 +00001762 dbgs() << "GVN: load ";
1763 WriteAsOperand(dbgs(), L);
Chris Lattnerb2412a82009-09-21 02:42:51 +00001764 Instruction *I = Dep.getInst();
David Greenebf7f78e2010-01-05 01:27:17 +00001765 dbgs() << " is clobbered by " << *I << '\n';
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001766 );
Chris Lattnerb51deb92008-12-05 21:04:20 +00001767 return false;
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001768 }
Chris Lattnerb51deb92008-12-05 21:04:20 +00001769
Eli Friedmanb4141422011-10-13 22:14:57 +00001770 // If it is defined in another block, try harder.
1771 if (Dep.isNonLocal())
1772 return processNonLocalLoad(L);
1773
1774 if (!Dep.isDef()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001775 DEBUG(
1776 // fast print dep, using operator<< on instruction is too slow.
1777 dbgs() << "GVN: load ";
1778 WriteAsOperand(dbgs(), L);
1779 dbgs() << " has unknown dependence\n";
1780 );
1781 return false;
1782 }
1783
Chris Lattnerb2412a82009-09-21 02:42:51 +00001784 Instruction *DepInst = Dep.getInst();
Chris Lattnerb51deb92008-12-05 21:04:20 +00001785 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Dan Gohman3355c4e2010-11-10 19:03:33 +00001786 Value *StoredVal = DepSI->getValueOperand();
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001787
1788 // The store and load are to a must-aliased pointer, but they may not
1789 // actually have the same type. See if we know how to reuse the stored
1790 // value (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001791 if (StoredVal->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001792 if (TD) {
Chris Lattnera52fce42009-10-21 04:11:19 +00001793 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1794 L, *TD);
1795 if (StoredVal == 0)
1796 return false;
1797
David Greenebf7f78e2010-01-05 01:27:17 +00001798 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001799 << '\n' << *L << "\n\n\n");
1800 }
1801 else
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001802 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001803 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001804
Chris Lattnerb51deb92008-12-05 21:04:20 +00001805 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001806 L->replaceAllUsesWith(StoredVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001807 if (StoredVal->getType()->isPointerTy())
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001808 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001809 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001810 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001811 return true;
1812 }
1813
1814 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001815 Value *AvailableVal = DepLI;
1816
1817 // The loads are of a must-aliased pointer, but they may not actually have
1818 // the same type. See if we know how to reuse the previously loaded value
1819 // (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001820 if (DepLI->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001821 if (TD) {
Chris Lattner1f821512011-04-26 01:21:15 +00001822 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1823 L, *TD);
Chris Lattnera52fce42009-10-21 04:11:19 +00001824 if (AvailableVal == 0)
1825 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001826
David Greenebf7f78e2010-01-05 01:27:17 +00001827 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001828 << "\n" << *L << "\n\n\n");
1829 }
1830 else
1831 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001832 }
1833
Chris Lattnerb51deb92008-12-05 21:04:20 +00001834 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001835 L->replaceAllUsesWith(AvailableVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001836 if (DepLI->getType()->isPointerTy())
Chris Lattnerbc99be12008-12-09 22:06:23 +00001837 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001838 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001839 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001840 return true;
1841 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001842
Chris Lattner237a8282008-11-30 01:39:32 +00001843 // If this load really doesn't depend on anything, then we must be loading an
1844 // undef value. This can happen when loading for a fresh allocation with no
1845 // intervening stores, for example.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001846 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001847 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001848 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001849 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001850 return true;
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001851 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001852
Owen Anderson9ff5a232009-12-02 07:35:19 +00001853 // If this load occurs either right after a lifetime begin,
Owen Andersonb62f7922009-10-28 07:05:35 +00001854 // then the loaded value is undefined.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001855 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
Owen Anderson9ff5a232009-12-02 07:35:19 +00001856 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
Owen Andersonb62f7922009-10-28 07:05:35 +00001857 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001858 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001859 ++NumGVNLoad;
Owen Andersonb62f7922009-10-28 07:05:35 +00001860 return true;
1861 }
1862 }
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001863
Chris Lattnerb51deb92008-12-05 21:04:20 +00001864 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001865}
1866
Owen Anderson7a75d612011-01-04 19:13:25 +00001867// findLeader - In order to find a leader for a given value number at a
Owen Anderson68c26392010-11-19 22:48:40 +00001868// specific basic block, we first obtain the list of all Values for that number,
1869// and then scan the list to find one whose block dominates the block in
1870// question. This is fast because dominator tree queries consist of only
1871// a few comparisons of DFS numbers.
Owen Anderson7a75d612011-01-04 19:13:25 +00001872Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
Owen Andersonb1602ab2011-01-04 19:29:46 +00001873 LeaderTableEntry Vals = LeaderTable[num];
Owen Andersonf0568382010-12-21 23:54:34 +00001874 if (!Vals.Val) return 0;
Owen Andersona04a0642010-11-18 18:32:40 +00001875
Owen Andersonf0568382010-12-21 23:54:34 +00001876 Value *Val = 0;
1877 if (DT->dominates(Vals.BB, BB)) {
1878 Val = Vals.Val;
1879 if (isa<Constant>(Val)) return Val;
1880 }
1881
Owen Anderson7a75d612011-01-04 19:13:25 +00001882 LeaderTableEntry* Next = Vals.Next;
Owen Andersona04a0642010-11-18 18:32:40 +00001883 while (Next) {
Owen Andersonf0568382010-12-21 23:54:34 +00001884 if (DT->dominates(Next->BB, BB)) {
1885 if (isa<Constant>(Next->Val)) return Next->Val;
1886 if (!Val) Val = Next->Val;
1887 }
Owen Andersona04a0642010-11-18 18:32:40 +00001888
Owen Andersonf0568382010-12-21 23:54:34 +00001889 Next = Next->Next;
Owen Anderson6fafe842008-06-20 01:15:47 +00001890 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001891
Owen Andersonf0568382010-12-21 23:54:34 +00001892 return Val;
Owen Anderson6fafe842008-06-20 01:15:47 +00001893}
1894
Duncan Sands02b5e722011-10-05 14:28:49 +00001895/// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1896/// use is dominated by the given basic block. Returns the number of uses that
1897/// were replaced.
1898unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1899 BasicBlock *Root) {
1900 unsigned Count = 0;
1901 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1902 UI != UE; ) {
1903 Instruction *User = cast<Instruction>(*UI);
1904 unsigned OpNum = UI.getOperandNo();
1905 ++UI;
1906
1907 if (DT->dominates(Root, User->getParent())) {
1908 User->setOperand(OpNum, To);
1909 ++Count;
1910 }
1911 }
1912 return Count;
1913}
1914
1915/// propagateEquality - The given values are known to be equal in every block
1916/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1917/// 'RHS' everywhere in the scope. Returns whether a change was made.
1918bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1919 if (LHS == RHS) return false;
1920 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1921
1922 // Don't try to propagate equalities between constants.
1923 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1924 return false;
1925
1926 // Make sure that any constants are on the right-hand side. In general the
1927 // best results are obtained by placing the longest lived value on the RHS.
1928 if (isa<Constant>(LHS))
1929 std::swap(LHS, RHS);
1930
1931 // If neither term is constant then bail out. This is not for correctness,
1932 // it's just that the non-constant case is much less useful: it occurs just
1933 // as often as the constant case but handling it hardly ever results in an
1934 // improvement.
1935 if (!isa<Constant>(RHS))
1936 return false;
1937
1938 // If value numbering later deduces that an instruction in the scope is equal
1939 // to 'LHS' then ensure it will be turned into 'RHS'.
1940 addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
1941
Duncan Sands1673b152011-10-15 11:13:42 +00001942 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1943 // LHS always has at least one use that is not dominated by Root, this will
1944 // never do anything if LHS has only one use.
1945 bool Changed = false;
1946 if (!LHS->hasOneUse()) {
1947 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
1948 Changed |= NumReplacements > 0;
1949 NumGVNEqProp += NumReplacements;
1950 }
Duncan Sands02b5e722011-10-05 14:28:49 +00001951
1952 // Now try to deduce additional equalities from this one. For example, if the
1953 // known equality was "(A != B)" == "false" then it follows that A and B are
1954 // equal in the scope. Only boolean equalities with an explicit true or false
1955 // RHS are currently supported.
1956 if (!RHS->getType()->isIntegerTy(1))
1957 // Not a boolean equality - bail out.
1958 return Changed;
1959 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1960 if (!CI)
1961 // RHS neither 'true' nor 'false' - bail out.
1962 return Changed;
1963 // Whether RHS equals 'true'. Otherwise it equals 'false'.
1964 bool isKnownTrue = CI->isAllOnesValue();
1965 bool isKnownFalse = !isKnownTrue;
1966
1967 // If "A && B" is known true then both A and B are known true. If "A || B"
1968 // is known false then both A and B are known false.
1969 Value *A, *B;
1970 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1971 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1972 Changed |= propagateEquality(A, RHS, Root);
1973 Changed |= propagateEquality(B, RHS, Root);
1974 return Changed;
1975 }
1976
1977 // If we are propagating an equality like "(A == B)" == "true" then also
1978 // propagate the equality A == B.
1979 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
1980 // Only equality comparisons are supported.
1981 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1982 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE)) {
1983 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1984 Changed |= propagateEquality(Op0, Op1, Root);
1985 }
1986 return Changed;
1987 }
1988
1989 return Changed;
1990}
Owen Anderson255dafc2008-12-15 02:03:00 +00001991
Duncan Sands3f329cb2011-10-07 08:29:06 +00001992/// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
1993/// true if every path from the entry block to 'Dst' passes via this edge. In
1994/// particular 'Dst' must not be reachable via another edge from 'Src'.
1995static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
1996 DominatorTree *DT) {
1997 // First off, there must not be more than one edge from Src to Dst, there
1998 // should be exactly one. So keep track of the number of times Src occurs
1999 // as a predecessor of Dst and fail if it's more than once. Secondly, any
2000 // other predecessors of Dst should be dominated by Dst (see logic below).
2001 bool SawEdgeFromSrc = false;
2002 for (pred_iterator PI = pred_begin(Dst), PE = pred_end(Dst); PI != PE; ++PI) {
2003 BasicBlock *Pred = *PI;
2004 if (Pred == Src) {
2005 // An edge from Src to Dst.
2006 if (SawEdgeFromSrc)
2007 // There are multiple edges from Src to Dst - fail.
2008 return false;
2009 SawEdgeFromSrc = true;
2010 continue;
2011 }
2012 // If the predecessor is not dominated by Dst, then it must be possible to
2013 // reach it either without passing through Src (and thus not via the edge)
2014 // or by passing through Src but taking a different edge out of Src. Either
2015 // way it is possible to reach Dst without passing via the edge, so fail.
2016 if (!DT->dominates(Dst, *PI))
2017 return false;
2018 }
2019 assert(SawEdgeFromSrc && "No edge between these basic blocks!");
2020
2021 // Every path from the entry block to Dst must at some point pass to Dst from
2022 // a predecessor that is not dominated by Dst. This predecessor can only be
2023 // Src, since all others are dominated by Dst. As there is only one edge from
2024 // Src to Dst, the path passes by this edge.
2025 return true;
2026}
2027
Owen Anderson36057c72007-08-14 18:16:29 +00002028/// processInstruction - When calculating availability, handle an instruction
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002029/// by inserting it into the appropriate sets
Chris Lattnerf07054d2011-04-28 16:18:52 +00002030bool GVN::processInstruction(Instruction *I) {
Devang Patelbe905e22010-02-11 00:20:49 +00002031 // Ignore dbg info intrinsics.
2032 if (isa<DbgInfoIntrinsic>(I))
2033 return false;
2034
Duncan Sands88c3df72010-11-12 21:10:24 +00002035 // If the instruction can be easily simplified then do so now in preference
2036 // to value numbering it. Value numbering often exposes redundancies, for
2037 // example if it determines that %y is equal to %x then the instruction
2038 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
Chad Rosier618c1db2011-12-01 03:08:23 +00002039 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
Duncan Sands88c3df72010-11-12 21:10:24 +00002040 I->replaceAllUsesWith(V);
2041 if (MD && V->getType()->isPointerTy())
2042 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002043 markInstructionForDeletion(I);
Duncan Sands02b5e722011-10-05 14:28:49 +00002044 ++NumGVNSimpl;
Duncan Sands88c3df72010-11-12 21:10:24 +00002045 return true;
2046 }
2047
Chris Lattnerb2412a82009-09-21 02:42:51 +00002048 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002049 if (processLoad(LI))
2050 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002051
Chris Lattnerf07054d2011-04-28 16:18:52 +00002052 unsigned Num = VN.lookup_or_add(LI);
2053 addToLeaderTable(Num, LI, LI->getParent());
2054 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002055 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002056
Duncan Sands02b5e722011-10-05 14:28:49 +00002057 // For conditional branches, we can perform simple conditional propagation on
Owen Andersonf0568382010-12-21 23:54:34 +00002058 // the condition value itself.
2059 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Owen Andersonf0568382010-12-21 23:54:34 +00002060 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2061 return false;
Duncan Sands02b5e722011-10-05 14:28:49 +00002062
Owen Andersonf0568382010-12-21 23:54:34 +00002063 Value *BranchCond = BI->getCondition();
Duncan Sands02b5e722011-10-05 14:28:49 +00002064
Owen Andersonf0568382010-12-21 23:54:34 +00002065 BasicBlock *TrueSucc = BI->getSuccessor(0);
2066 BasicBlock *FalseSucc = BI->getSuccessor(1);
Duncan Sands452c58f2011-10-05 14:17:01 +00002067 BasicBlock *Parent = BI->getParent();
Duncan Sands3f329cb2011-10-07 08:29:06 +00002068 bool Changed = false;
Duncan Sands452c58f2011-10-05 14:17:01 +00002069
Duncan Sands3f329cb2011-10-07 08:29:06 +00002070 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2071 Changed |= propagateEquality(BranchCond,
Duncan Sands02b5e722011-10-05 14:28:49 +00002072 ConstantInt::getTrue(TrueSucc->getContext()),
Duncan Sands3f329cb2011-10-07 08:29:06 +00002073 TrueSucc);
2074
2075 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2076 Changed |= propagateEquality(BranchCond,
2077 ConstantInt::getFalse(FalseSucc->getContext()),
2078 FalseSucc);
2079
2080 return Changed;
Owen Andersonf0568382010-12-21 23:54:34 +00002081 }
Duncan Sands3f329cb2011-10-07 08:29:06 +00002082
2083 // For switches, propagate the case values into the case destinations.
2084 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2085 Value *SwitchCond = SI->getCondition();
2086 BasicBlock *Parent = SI->getParent();
2087 bool Changed = false;
2088 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
2089 BasicBlock *Dst = SI->getSuccessor(i);
2090 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2091 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2092 }
2093 return Changed;
2094 }
2095
Owen Anderson2cf75372011-01-04 22:15:21 +00002096 // Instructions with void type don't return a value, so there's
2097 // no point in trying to find redudancies in them.
2098 if (I->getType()->isVoidTy()) return false;
2099
Owen Andersonc2146a62011-01-04 18:54:18 +00002100 uint32_t NextNum = VN.getNextUnusedValueNumber();
2101 unsigned Num = VN.lookup_or_add(I);
2102
Owen Andersone5ffa902008-04-07 09:59:07 +00002103 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbara279bc32009-09-20 02:20:51 +00002104 // by fast failing them.
Chris Lattner459f4f82010-12-19 20:24:28 +00002105 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002106 addToLeaderTable(Num, I, I->getParent());
Owen Andersone5ffa902008-04-07 09:59:07 +00002107 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002108 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002109
Owen Anderson0ae33ef2008-07-03 17:44:33 +00002110 // If the number we were assigned was a brand new VN, then we don't
2111 // need to do a lookup to see if the number already exists
2112 // somewhere in the domtree: it can't!
Chris Lattner459f4f82010-12-19 20:24:28 +00002113 if (Num == NextNum) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002114 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002115 return false;
2116 }
2117
Owen Anderson255dafc2008-12-15 02:03:00 +00002118 // Perform fast-path value-number based elimination of values inherited from
2119 // dominators.
Owen Anderson7a75d612011-01-04 19:13:25 +00002120 Value *repl = findLeader(I->getParent(), Num);
Chris Lattner459f4f82010-12-19 20:24:28 +00002121 if (repl == 0) {
2122 // Failure, just remember this instance for future use.
Owen Anderson7a75d612011-01-04 19:13:25 +00002123 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002124 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002125 }
Chris Lattner459f4f82010-12-19 20:24:28 +00002126
2127 // Remove it!
Chris Lattner459f4f82010-12-19 20:24:28 +00002128 I->replaceAllUsesWith(repl);
2129 if (MD && repl->getType()->isPointerTy())
2130 MD->invalidateCachedPointerInfo(repl);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002131 markInstructionForDeletion(I);
Chris Lattner459f4f82010-12-19 20:24:28 +00002132 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002133}
2134
Bill Wendling30788b82008-12-22 22:32:22 +00002135/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson3e75a422007-08-14 18:04:11 +00002136bool GVN::runOnFunction(Function& F) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00002137 if (!NoLoads)
2138 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner663e4412008-12-01 00:40:32 +00002139 DT = &getAnalysis<DominatorTree>();
Duncan Sands88c3df72010-11-12 21:10:24 +00002140 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier618c1db2011-12-01 03:08:23 +00002141 TLI = &getAnalysis<TargetLibraryInfo>();
Owen Andersona472c4a2008-05-12 20:15:55 +00002142 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner663e4412008-12-01 00:40:32 +00002143 VN.setMemDep(MD);
2144 VN.setDomTree(DT);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002145
Chris Lattnerb2412a82009-09-21 02:42:51 +00002146 bool Changed = false;
2147 bool ShouldContinue = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148
Owen Anderson5d0af032008-07-16 17:52:31 +00002149 // Merge unconditional branches, allowing PRE to catch more
2150 // optimization opportunities.
2151 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerb5b79972011-01-11 08:13:40 +00002152 BasicBlock *BB = FI++;
2153
Owen Andersonb31b06d2008-07-17 00:01:40 +00002154 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
Dan Gohmanfe601042010-06-22 15:08:57 +00002155 if (removedBlock) ++NumGVNBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002156
Chris Lattnerb2412a82009-09-21 02:42:51 +00002157 Changed |= removedBlock;
Owen Anderson5d0af032008-07-16 17:52:31 +00002158 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002159
Chris Lattnerae199312008-12-09 19:21:47 +00002160 unsigned Iteration = 0;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002161 while (ShouldContinue) {
David Greenebf7f78e2010-01-05 01:27:17 +00002162 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002163 ShouldContinue = iterateOnFunction(F);
Bob Wilson484d4a32010-02-16 19:51:59 +00002164 if (splitCriticalEdges())
2165 ShouldContinue = true;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002166 Changed |= ShouldContinue;
Chris Lattnerae199312008-12-09 19:21:47 +00002167 ++Iteration;
Owen Anderson3e75a422007-08-14 18:04:11 +00002168 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002169
Owen Andersone98c54c2008-07-18 18:03:38 +00002170 if (EnablePRE) {
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002171 bool PREChanged = true;
2172 while (PREChanged) {
2173 PREChanged = performPRE(F);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002174 Changed |= PREChanged;
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002175 }
Owen Andersone98c54c2008-07-18 18:03:38 +00002176 }
Chris Lattnerae199312008-12-09 19:21:47 +00002177 // FIXME: Should perform GVN again after PRE does something. PRE can move
2178 // computations into blocks where they become fully redundant. Note that
2179 // we can't do this until PRE's critical edge splitting updates memdep.
2180 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002181
2182 cleanupGlobalSets();
2183
Chris Lattnerb2412a82009-09-21 02:42:51 +00002184 return Changed;
Owen Anderson3e75a422007-08-14 18:04:11 +00002185}
2186
2187
Chris Lattnerb2412a82009-09-21 02:42:51 +00002188bool GVN::processBlock(BasicBlock *BB) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002189 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2190 // (and incrementing BI before processing an instruction).
2191 assert(InstrsToErase.empty() &&
2192 "We expect InstrsToErase to be empty across iterations");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002193 bool ChangedFunction = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002194
Owen Andersonaf4240a2008-06-12 19:25:32 +00002195 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2196 BI != BE;) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002197 ChangedFunction |= processInstruction(BI);
2198 if (InstrsToErase.empty()) {
Owen Andersonaf4240a2008-06-12 19:25:32 +00002199 ++BI;
2200 continue;
2201 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002202
Owen Andersonaf4240a2008-06-12 19:25:32 +00002203 // If we need some instructions deleted, do it now.
Chris Lattnerf07054d2011-04-28 16:18:52 +00002204 NumGVNInstr += InstrsToErase.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002205
Owen Andersonaf4240a2008-06-12 19:25:32 +00002206 // Avoid iterator invalidation.
2207 bool AtStart = BI == BB->begin();
2208 if (!AtStart)
2209 --BI;
2210
Chris Lattnerf07054d2011-04-28 16:18:52 +00002211 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2212 E = InstrsToErase.end(); I != E; ++I) {
David Greenebf7f78e2010-01-05 01:27:17 +00002213 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002214 if (MD) MD->removeInstruction(*I);
Owen Andersonaf4240a2008-06-12 19:25:32 +00002215 (*I)->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002216 DEBUG(verifyRemoved(*I));
Chris Lattner663e4412008-12-01 00:40:32 +00002217 }
Chris Lattnerf07054d2011-04-28 16:18:52 +00002218 InstrsToErase.clear();
Owen Andersonaf4240a2008-06-12 19:25:32 +00002219
2220 if (AtStart)
2221 BI = BB->begin();
2222 else
2223 ++BI;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002224 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225
Chris Lattnerb2412a82009-09-21 02:42:51 +00002226 return ChangedFunction;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002227}
2228
Owen Andersonb2303722008-06-18 21:41:49 +00002229/// performPRE - Perform a purely local form of PRE that looks for diamond
2230/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002231bool GVN::performPRE(Function &F) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002232 bool Changed = false;
Chris Lattner09713792008-12-01 07:29:03 +00002233 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersonb2303722008-06-18 21:41:49 +00002234 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2235 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002236 BasicBlock *CurrentBlock = *DI;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002237
Owen Andersonb2303722008-06-18 21:41:49 +00002238 // Nothing to PRE in the entry block.
2239 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002240
Bill Wendling795cf5e2011-08-17 21:32:02 +00002241 // Don't perform PRE on a landing pad.
2242 if (CurrentBlock->isLandingPad()) continue;
2243
Owen Andersonb2303722008-06-18 21:41:49 +00002244 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2245 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002246 Instruction *CurInst = BI++;
Duncan Sands7af1c782009-05-06 06:49:50 +00002247
Victor Hernandez7b929da2009-10-23 21:09:37 +00002248 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00002249 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel9674d152009-10-14 17:29:00 +00002250 CurInst->getType()->isVoidTy() ||
Duncan Sands7af1c782009-05-06 06:49:50 +00002251 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell090c0a22009-03-10 15:04:53 +00002252 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002253 continue;
Owen Anderson5015b342010-08-07 00:20:35 +00002254
2255 // We don't currently value number ANY inline asm calls.
2256 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2257 if (CallI->isInlineAsm())
2258 continue;
Duncan Sands7af1c782009-05-06 06:49:50 +00002259
Chris Lattnerb2412a82009-09-21 02:42:51 +00002260 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002261
Owen Andersonb2303722008-06-18 21:41:49 +00002262 // Look for the predecessors for PRE opportunities. We're
2263 // only trying to solve the basic diamond case, where
2264 // a value is computed in the successor and one predecessor,
2265 // but not the other. We also explicitly disallow cases
2266 // where the successor is its own predecessor, because they're
2267 // more complicated to get right.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002268 unsigned NumWith = 0;
2269 unsigned NumWithout = 0;
2270 BasicBlock *PREPred = 0;
Chris Lattner09713792008-12-01 07:29:03 +00002271 predMap.clear();
2272
Owen Andersonb2303722008-06-18 21:41:49 +00002273 for (pred_iterator PI = pred_begin(CurrentBlock),
2274 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
Gabor Greif08149852010-07-09 14:36:49 +00002275 BasicBlock *P = *PI;
Owen Andersonb2303722008-06-18 21:41:49 +00002276 // We're not interested in PRE where the block is its
Bob Wilsone7b635f2010-02-03 00:33:21 +00002277 // own predecessor, or in blocks with predecessors
Owen Anderson6fafe842008-06-20 01:15:47 +00002278 // that are not reachable.
Gabor Greif08149852010-07-09 14:36:49 +00002279 if (P == CurrentBlock) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002280 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002281 break;
Owen Andersona04a0642010-11-18 18:32:40 +00002282 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002283 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002284 break;
2285 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002286
Owen Anderson7a75d612011-01-04 19:13:25 +00002287 Value* predV = findLeader(P, ValNo);
Owen Andersona04a0642010-11-18 18:32:40 +00002288 if (predV == 0) {
Gabor Greif08149852010-07-09 14:36:49 +00002289 PREPred = P;
Dan Gohmanfe601042010-06-22 15:08:57 +00002290 ++NumWithout;
Owen Andersona04a0642010-11-18 18:32:40 +00002291 } else if (predV == CurInst) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002292 NumWithout = 2;
Owen Andersonb2303722008-06-18 21:41:49 +00002293 } else {
Owen Andersona04a0642010-11-18 18:32:40 +00002294 predMap[P] = predV;
Dan Gohmanfe601042010-06-22 15:08:57 +00002295 ++NumWith;
Owen Andersonb2303722008-06-18 21:41:49 +00002296 }
2297 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002298
Owen Andersonb2303722008-06-18 21:41:49 +00002299 // Don't do PRE when it might increase code size, i.e. when
2300 // we would need to insert instructions in more than one pred.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002301 if (NumWithout != 1 || NumWith == 0)
Owen Andersonb2303722008-06-18 21:41:49 +00002302 continue;
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002303
2304 // Don't do PRE across indirect branch.
2305 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2306 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002307
Owen Anderson5c274ee2008-06-19 19:54:19 +00002308 // We can't do PRE safely on a critical edge, so instead we schedule
2309 // the edge to be split and perform the PRE the next time we iterate
2310 // on the function.
Bob Wilsonae23daf2010-02-16 21:06:42 +00002311 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002312 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2313 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Anderson5c274ee2008-06-19 19:54:19 +00002314 continue;
2315 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002316
Bob Wilsone7b635f2010-02-03 00:33:21 +00002317 // Instantiate the expression in the predecessor that lacked it.
Owen Andersonb2303722008-06-18 21:41:49 +00002318 // Because we are going top-down through the block, all value numbers
2319 // will be available in the predecessor by the time we need them. Any
Bob Wilsone7b635f2010-02-03 00:33:21 +00002320 // that weren't originally present will have been instantiated earlier
Owen Andersonb2303722008-06-18 21:41:49 +00002321 // in this loop.
Nick Lewycky67760642009-09-27 07:38:41 +00002322 Instruction *PREInstr = CurInst->clone();
Owen Andersonb2303722008-06-18 21:41:49 +00002323 bool success = true;
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002324 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2325 Value *Op = PREInstr->getOperand(i);
2326 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2327 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002328
Owen Anderson7a75d612011-01-04 19:13:25 +00002329 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002330 PREInstr->setOperand(i, V);
2331 } else {
2332 success = false;
2333 break;
Owen Andersonc45996b2008-07-11 20:05:13 +00002334 }
Owen Andersonb2303722008-06-18 21:41:49 +00002335 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002336
Owen Andersonb2303722008-06-18 21:41:49 +00002337 // Fail out if we encounter an operand that is not available in
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338 // the PRE predecessor. This is typically because of loads which
Owen Andersonb2303722008-06-18 21:41:49 +00002339 // are not value numbered precisely.
2340 if (!success) {
2341 delete PREInstr;
Bill Wendling70ded192008-12-22 22:14:07 +00002342 DEBUG(verifyRemoved(PREInstr));
Owen Andersonb2303722008-06-18 21:41:49 +00002343 continue;
2344 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002345
Owen Andersonb2303722008-06-18 21:41:49 +00002346 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002347 PREInstr->setName(CurInst->getName() + ".pre");
Devang Patelde985682011-05-17 20:00:02 +00002348 PREInstr->setDebugLoc(CurInst->getDebugLoc());
Owen Anderson6fafe842008-06-20 01:15:47 +00002349 predMap[PREPred] = PREInstr;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002350 VN.add(PREInstr, ValNo);
Dan Gohmanfe601042010-06-22 15:08:57 +00002351 ++NumGVNPRE;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002352
Owen Andersonb2303722008-06-18 21:41:49 +00002353 // Update the availability map to include the new instruction.
Owen Anderson7a75d612011-01-04 19:13:25 +00002354 addToLeaderTable(ValNo, PREInstr, PREPred);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002355
Owen Andersonb2303722008-06-18 21:41:49 +00002356 // Create a PHI to make the value available in this block.
Jay Foadd8b4fb42011-03-30 11:19:20 +00002357 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
Jay Foad3ecfc862011-03-30 11:28:46 +00002358 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002359 CurInst->getName() + ".pre-phi",
Owen Andersonb2303722008-06-18 21:41:49 +00002360 CurrentBlock->begin());
Jay Foadd8b4fb42011-03-30 11:19:20 +00002361 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif1d3ae022010-07-09 14:48:08 +00002362 BasicBlock *P = *PI;
2363 Phi->addIncoming(predMap[P], P);
2364 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002365
Chris Lattnerb2412a82009-09-21 02:42:51 +00002366 VN.add(Phi, ValNo);
Owen Anderson7a75d612011-01-04 19:13:25 +00002367 addToLeaderTable(ValNo, Phi, CurrentBlock);
Devang Patel0f18d972011-05-04 23:58:50 +00002368 Phi->setDebugLoc(CurInst->getDebugLoc());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002369 CurInst->replaceAllUsesWith(Phi);
Owen Anderson392249f2011-01-03 23:51:43 +00002370 if (Phi->getType()->isPointerTy()) {
2371 // Because we have added a PHI-use of the pointer value, it has now
2372 // "escaped" from alias analysis' perspective. We need to inform
2373 // AA of this.
Jay Foadc1371202011-06-20 14:18:48 +00002374 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2375 ++ii) {
2376 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2377 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2378 }
Owen Anderson392249f2011-01-03 23:51:43 +00002379
2380 if (MD)
2381 MD->invalidateCachedPointerInfo(Phi);
2382 }
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002383 VN.erase(CurInst);
Owen Anderson7a75d612011-01-04 19:13:25 +00002384 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002385
David Greenebf7f78e2010-01-05 01:27:17 +00002386 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002387 if (MD) MD->removeInstruction(CurInst);
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002388 CurInst->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002389 DEBUG(verifyRemoved(CurInst));
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002390 Changed = true;
Owen Andersonb2303722008-06-18 21:41:49 +00002391 }
2392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002393
Bob Wilson484d4a32010-02-16 19:51:59 +00002394 if (splitCriticalEdges())
2395 Changed = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002396
Bob Wilson484d4a32010-02-16 19:51:59 +00002397 return Changed;
2398}
2399
2400/// splitCriticalEdges - Split critical edges found during the previous
2401/// iteration that may enable further optimization.
2402bool GVN::splitCriticalEdges() {
2403 if (toSplit.empty())
2404 return false;
2405 do {
2406 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2407 SplitCriticalEdge(Edge.first, Edge.second, this);
2408 } while (!toSplit.empty());
Evan Cheng19d417c2010-03-01 22:23:12 +00002409 if (MD) MD->invalidateCachedPredecessors();
Bob Wilson484d4a32010-02-16 19:51:59 +00002410 return true;
Owen Andersonb2303722008-06-18 21:41:49 +00002411}
2412
Bill Wendling30788b82008-12-22 22:32:22 +00002413/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson3e75a422007-08-14 18:04:11 +00002414bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002415 cleanupGlobalSets();
Owen Andersona04a0642010-11-18 18:32:40 +00002416
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002417 // Top-down walk of the dominator tree
Chris Lattnerb2412a82009-09-21 02:42:51 +00002418 bool Changed = false;
Owen Andersonc34d1122008-12-15 03:52:17 +00002419#if 0
2420 // Needed for value numbering with phi construction to work.
Owen Anderson255dafc2008-12-15 02:03:00 +00002421 ReversePostOrderTraversal<Function*> RPOT(&F);
2422 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2423 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002424 Changed |= processBlock(*RI);
Owen Andersonc34d1122008-12-15 03:52:17 +00002425#else
2426 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2427 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002428 Changed |= processBlock(DI->getBlock());
Owen Andersonc34d1122008-12-15 03:52:17 +00002429#endif
2430
Chris Lattnerb2412a82009-09-21 02:42:51 +00002431 return Changed;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002432}
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002433
2434void GVN::cleanupGlobalSets() {
2435 VN.clear();
Owen Andersonb1602ab2011-01-04 19:29:46 +00002436 LeaderTable.clear();
Owen Andersona04a0642010-11-18 18:32:40 +00002437 TableAllocator.Reset();
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002438}
Bill Wendling246dbbb2008-12-22 21:36:08 +00002439
2440/// verifyRemoved - Verify that the specified instruction does not occur in our
2441/// internal data structures.
Bill Wendling6d463f22008-12-22 22:28:56 +00002442void GVN::verifyRemoved(const Instruction *Inst) const {
2443 VN.verifyRemoved(Inst);
Bill Wendling70ded192008-12-22 22:14:07 +00002444
Bill Wendling6d463f22008-12-22 22:28:56 +00002445 // Walk through the value number scope to make sure the instruction isn't
2446 // ferreted away in it.
Owen Anderson7a75d612011-01-04 19:13:25 +00002447 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
Owen Andersonb1602ab2011-01-04 19:29:46 +00002448 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002449 const LeaderTableEntry *Node = &I->second;
Owen Andersonf0568382010-12-21 23:54:34 +00002450 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Owen Andersona04a0642010-11-18 18:32:40 +00002451
Owen Andersonf0568382010-12-21 23:54:34 +00002452 while (Node->Next) {
2453 Node = Node->Next;
2454 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Bill Wendling70ded192008-12-22 22:14:07 +00002455 }
2456 }
Bill Wendling246dbbb2008-12-22 21:36:08 +00002457}