blob: a7b38056ad1ca6f113deda9a02ad5e1834dc0f0e [file] [log] [blame]
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
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//
Matthijs Kooijman845f5242008-06-05 07:55:49 +000013// Note that this pass does the value numbering itself, it does not use the
14// 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"
Owen Anderson0cd32032007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Anderson45537912007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Anderson45537912007-07-26 18:26:51 +000023#include "llvm/Function.h"
24#include "llvm/Instructions.h"
25#include "llvm/Value.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Owen Andersonb388ca92007-10-18 19:39:33 +000031#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000033#include "llvm/Analysis/MemoryDependenceAnalysis.h"
34#include "llvm/Support/CFG.h"
Owen Andersonaa0b6342008-06-19 19:57:25 +000035#include "llvm/Support/CommandLine.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000036#include "llvm/Support/Compiler.h"
Chris Lattner9f8a6a72008-03-29 04:36:18 +000037#include "llvm/Support/Debug.h"
Owen Anderson5c274ee2008-06-19 19:54:19 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Duncan Sands4520dd22008-10-08 07:23:46 +000039#include <cstdio>
Owen Anderson1ad2cb72007-07-24 17:55:58 +000040using namespace llvm;
41
Chris Lattnerd27290d2008-03-22 04:13:49 +000042STATISTIC(NumGVNInstr, "Number of instructions deleted");
43STATISTIC(NumGVNLoad, "Number of loads deleted");
Owen Andersonb2303722008-06-18 21:41:49 +000044STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson961edc82008-07-15 16:28:06 +000045STATISTIC(NumGVNBlocks, "Number of blocks merged");
Chris Lattnerd27290d2008-03-22 04:13:49 +000046
Evan Cheng88d11c02008-06-20 01:01:07 +000047static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonc2b856e2008-07-17 19:41:00 +000048 cl::init(true), cl::Hidden);
Owen Andersonaa0b6342008-06-19 19:57:25 +000049
Owen Anderson1ad2cb72007-07-24 17:55:58 +000050//===----------------------------------------------------------------------===//
51// ValueTable Class
52//===----------------------------------------------------------------------===//
53
54/// This class holds the mapping between values and value numbers. It is used
55/// as an efficient mechanism to determine the expression-wise equivalence of
56/// two values.
57namespace {
58 struct VISIBILITY_HIDDEN Expression {
59 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
60 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
61 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
62 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
63 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
64 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
65 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
66 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
67 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson3b3f58c2008-05-13 08:17:22 +000068 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Anderson3cd8eb32008-06-19 17:25:39 +000069 EMPTY, TOMBSTONE };
Owen Anderson1ad2cb72007-07-24 17:55:58 +000070
71 ExpressionOpcode opcode;
72 const Type* type;
73 uint32_t firstVN;
74 uint32_t secondVN;
75 uint32_t thirdVN;
76 SmallVector<uint32_t, 4> varargs;
Owen Andersonb388ca92007-10-18 19:39:33 +000077 Value* function;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000078
79 Expression() { }
80 Expression(ExpressionOpcode o) : opcode(o) { }
81
82 bool operator==(const Expression &other) const {
83 if (opcode != other.opcode)
84 return false;
85 else if (opcode == EMPTY || opcode == TOMBSTONE)
86 return true;
87 else if (type != other.type)
88 return false;
Owen Andersonb388ca92007-10-18 19:39:33 +000089 else if (function != other.function)
90 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000091 else if (firstVN != other.firstVN)
92 return false;
93 else if (secondVN != other.secondVN)
94 return false;
95 else if (thirdVN != other.thirdVN)
96 return false;
97 else {
98 if (varargs.size() != other.varargs.size())
99 return false;
100
101 for (size_t i = 0; i < varargs.size(); ++i)
102 if (varargs[i] != other.varargs[i])
103 return false;
104
105 return true;
106 }
107 }
108
109 bool operator!=(const Expression &other) const {
110 if (opcode != other.opcode)
111 return true;
112 else if (opcode == EMPTY || opcode == TOMBSTONE)
113 return false;
114 else if (type != other.type)
115 return true;
Owen Andersonb388ca92007-10-18 19:39:33 +0000116 else if (function != other.function)
117 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000118 else if (firstVN != other.firstVN)
119 return true;
120 else if (secondVN != other.secondVN)
121 return true;
122 else if (thirdVN != other.thirdVN)
123 return true;
124 else {
125 if (varargs.size() != other.varargs.size())
126 return true;
127
128 for (size_t i = 0; i < varargs.size(); ++i)
129 if (varargs[i] != other.varargs[i])
130 return true;
131
132 return false;
133 }
134 }
135 };
136
137 class VISIBILITY_HIDDEN ValueTable {
138 private:
139 DenseMap<Value*, uint32_t> valueNumbering;
140 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersona472c4a2008-05-12 20:15:55 +0000141 AliasAnalysis* AA;
142 MemoryDependenceAnalysis* MD;
143 DominatorTree* DT;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000144
145 uint32_t nextValueNumber;
146
147 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148 Expression::ExpressionOpcode getOpcode(CmpInst* C);
149 Expression::ExpressionOpcode getOpcode(CastInst* C);
150 Expression create_expression(BinaryOperator* BO);
151 Expression create_expression(CmpInst* C);
152 Expression create_expression(ShuffleVectorInst* V);
153 Expression create_expression(ExtractElementInst* C);
154 Expression create_expression(InsertElementInst* V);
155 Expression create_expression(SelectInst* V);
156 Expression create_expression(CastInst* C);
157 Expression create_expression(GetElementPtrInst* G);
Owen Andersonb388ca92007-10-18 19:39:33 +0000158 Expression create_expression(CallInst* C);
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000159 Expression create_expression(Constant* C);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000160 public:
Owen Andersonb388ca92007-10-18 19:39:33 +0000161 ValueTable() : nextValueNumber(1) { }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000162 uint32_t lookup_or_add(Value* V);
163 uint32_t lookup(Value* V) const;
164 void add(Value* V, uint32_t num);
165 void clear();
166 void erase(Value* v);
167 unsigned size();
Owen Andersona472c4a2008-05-12 20:15:55 +0000168 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner663e4412008-12-01 00:40:32 +0000169 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersona472c4a2008-05-12 20:15:55 +0000170 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
171 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson0ae33ef2008-07-03 17:44:33 +0000172 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000173 };
174}
175
176namespace llvm {
Chris Lattner76c1b972007-09-17 18:34:04 +0000177template <> struct DenseMapInfo<Expression> {
Owen Anderson830db6a2007-08-02 18:16:06 +0000178 static inline Expression getEmptyKey() {
179 return Expression(Expression::EMPTY);
180 }
181
182 static inline Expression getTombstoneKey() {
183 return Expression(Expression::TOMBSTONE);
184 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000185
186 static unsigned getHashValue(const Expression e) {
187 unsigned hash = e.opcode;
188
189 hash = e.firstVN + hash * 37;
190 hash = e.secondVN + hash * 37;
191 hash = e.thirdVN + hash * 37;
192
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000193 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
194 (unsigned)((uintptr_t)e.type >> 9)) +
195 hash * 37;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000196
Owen Anderson830db6a2007-08-02 18:16:06 +0000197 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
198 E = e.varargs.end(); I != E; ++I)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000199 hash = *I + hash * 37;
200
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000201 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
202 (unsigned)((uintptr_t)e.function >> 9)) +
203 hash * 37;
Owen Andersonb388ca92007-10-18 19:39:33 +0000204
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000205 return hash;
206 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000207 static bool isEqual(const Expression &LHS, const Expression &RHS) {
208 return LHS == RHS;
209 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000210 static bool isPod() { return true; }
211};
212}
213
214//===----------------------------------------------------------------------===//
215// ValueTable Internal Functions
216//===----------------------------------------------------------------------===//
Chris Lattner88365bb2008-03-21 21:14:38 +0000217Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000218 switch(BO->getOpcode()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000219 default: // THIS SHOULD NEVER HAPPEN
220 assert(0 && "Binary operator with unknown opcode?");
221 case Instruction::Add: return Expression::ADD;
222 case Instruction::Sub: return Expression::SUB;
223 case Instruction::Mul: return Expression::MUL;
224 case Instruction::UDiv: return Expression::UDIV;
225 case Instruction::SDiv: return Expression::SDIV;
226 case Instruction::FDiv: return Expression::FDIV;
227 case Instruction::URem: return Expression::UREM;
228 case Instruction::SRem: return Expression::SREM;
229 case Instruction::FRem: return Expression::FREM;
230 case Instruction::Shl: return Expression::SHL;
231 case Instruction::LShr: return Expression::LSHR;
232 case Instruction::AShr: return Expression::ASHR;
233 case Instruction::And: return Expression::AND;
234 case Instruction::Or: return Expression::OR;
235 case Instruction::Xor: return Expression::XOR;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000236 }
237}
238
239Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nate Begeman1d6e4092008-05-18 19:49:05 +0000240 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000241 switch (C->getPredicate()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000242 default: // THIS SHOULD NEVER HAPPEN
243 assert(0 && "Comparison with unknown predicate?");
244 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
245 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
246 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
247 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
248 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
249 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
250 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
251 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
252 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
253 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000254 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000255 }
Nate Begeman1d6e4092008-05-18 19:49:05 +0000256 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
Chris Lattner88365bb2008-03-21 21:14:38 +0000257 switch (C->getPredicate()) {
258 default: // THIS SHOULD NEVER HAPPEN
259 assert(0 && "Comparison with unknown predicate?");
260 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
261 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
262 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
263 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
264 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
265 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
266 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
267 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
268 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
269 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
270 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
271 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
272 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
273 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000274 }
275}
276
Chris Lattner88365bb2008-03-21 21:14:38 +0000277Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000278 switch(C->getOpcode()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000279 default: // THIS SHOULD NEVER HAPPEN
280 assert(0 && "Cast operator with unknown opcode?");
281 case Instruction::Trunc: return Expression::TRUNC;
282 case Instruction::ZExt: return Expression::ZEXT;
283 case Instruction::SExt: return Expression::SEXT;
284 case Instruction::FPToUI: return Expression::FPTOUI;
285 case Instruction::FPToSI: return Expression::FPTOSI;
286 case Instruction::UIToFP: return Expression::UITOFP;
287 case Instruction::SIToFP: return Expression::SITOFP;
288 case Instruction::FPTrunc: return Expression::FPTRUNC;
289 case Instruction::FPExt: return Expression::FPEXT;
290 case Instruction::PtrToInt: return Expression::PTRTOINT;
291 case Instruction::IntToPtr: return Expression::INTTOPTR;
292 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000293 }
294}
295
Owen Andersonb388ca92007-10-18 19:39:33 +0000296Expression ValueTable::create_expression(CallInst* C) {
297 Expression e;
298
299 e.type = C->getType();
300 e.firstVN = 0;
301 e.secondVN = 0;
302 e.thirdVN = 0;
303 e.function = C->getCalledFunction();
304 e.opcode = Expression::CALL;
305
306 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
307 I != E; ++I)
Owen Anderson8f46c782008-04-11 05:11:49 +0000308 e.varargs.push_back(lookup_or_add(*I));
Owen Andersonb388ca92007-10-18 19:39:33 +0000309
310 return e;
311}
312
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000313Expression ValueTable::create_expression(BinaryOperator* BO) {
314 Expression e;
315
Owen Anderson8f46c782008-04-11 05:11:49 +0000316 e.firstVN = lookup_or_add(BO->getOperand(0));
317 e.secondVN = lookup_or_add(BO->getOperand(1));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000318 e.thirdVN = 0;
Owen Andersonb388ca92007-10-18 19:39:33 +0000319 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000320 e.type = BO->getType();
321 e.opcode = getOpcode(BO);
322
323 return e;
324}
325
326Expression ValueTable::create_expression(CmpInst* C) {
327 Expression e;
328
Owen Anderson8f46c782008-04-11 05:11:49 +0000329 e.firstVN = lookup_or_add(C->getOperand(0));
330 e.secondVN = lookup_or_add(C->getOperand(1));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000331 e.thirdVN = 0;
Owen Andersonb388ca92007-10-18 19:39:33 +0000332 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000333 e.type = C->getType();
334 e.opcode = getOpcode(C);
335
336 return e;
337}
338
339Expression ValueTable::create_expression(CastInst* C) {
340 Expression e;
341
Owen Anderson8f46c782008-04-11 05:11:49 +0000342 e.firstVN = lookup_or_add(C->getOperand(0));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000343 e.secondVN = 0;
344 e.thirdVN = 0;
Owen Andersonb388ca92007-10-18 19:39:33 +0000345 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000346 e.type = C->getType();
347 e.opcode = getOpcode(C);
348
349 return e;
350}
351
352Expression ValueTable::create_expression(ShuffleVectorInst* S) {
353 Expression e;
354
Owen Anderson8f46c782008-04-11 05:11:49 +0000355 e.firstVN = lookup_or_add(S->getOperand(0));
356 e.secondVN = lookup_or_add(S->getOperand(1));
357 e.thirdVN = lookup_or_add(S->getOperand(2));
Owen Andersonb388ca92007-10-18 19:39:33 +0000358 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000359 e.type = S->getType();
360 e.opcode = Expression::SHUFFLE;
361
362 return e;
363}
364
365Expression ValueTable::create_expression(ExtractElementInst* E) {
366 Expression e;
367
Owen Anderson8f46c782008-04-11 05:11:49 +0000368 e.firstVN = lookup_or_add(E->getOperand(0));
369 e.secondVN = lookup_or_add(E->getOperand(1));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000370 e.thirdVN = 0;
Owen Andersonb388ca92007-10-18 19:39:33 +0000371 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000372 e.type = E->getType();
373 e.opcode = Expression::EXTRACT;
374
375 return e;
376}
377
378Expression ValueTable::create_expression(InsertElementInst* I) {
379 Expression e;
380
Owen Anderson8f46c782008-04-11 05:11:49 +0000381 e.firstVN = lookup_or_add(I->getOperand(0));
382 e.secondVN = lookup_or_add(I->getOperand(1));
383 e.thirdVN = lookup_or_add(I->getOperand(2));
Owen Andersonb388ca92007-10-18 19:39:33 +0000384 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000385 e.type = I->getType();
386 e.opcode = Expression::INSERT;
387
388 return e;
389}
390
391Expression ValueTable::create_expression(SelectInst* I) {
392 Expression e;
393
Owen Anderson8f46c782008-04-11 05:11:49 +0000394 e.firstVN = lookup_or_add(I->getCondition());
395 e.secondVN = lookup_or_add(I->getTrueValue());
396 e.thirdVN = lookup_or_add(I->getFalseValue());
Owen Andersonb388ca92007-10-18 19:39:33 +0000397 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000398 e.type = I->getType();
399 e.opcode = Expression::SELECT;
400
401 return e;
402}
403
404Expression ValueTable::create_expression(GetElementPtrInst* G) {
405 Expression e;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000406
Owen Anderson8f46c782008-04-11 05:11:49 +0000407 e.firstVN = lookup_or_add(G->getPointerOperand());
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000408 e.secondVN = 0;
409 e.thirdVN = 0;
Owen Andersonb388ca92007-10-18 19:39:33 +0000410 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000411 e.type = G->getType();
412 e.opcode = Expression::GEP;
413
414 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
415 I != E; ++I)
Owen Anderson8f46c782008-04-11 05:11:49 +0000416 e.varargs.push_back(lookup_or_add(*I));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000417
418 return e;
419}
420
421//===----------------------------------------------------------------------===//
422// ValueTable External Functions
423//===----------------------------------------------------------------------===//
424
Owen Andersonb2303722008-06-18 21:41:49 +0000425/// add - Insert a value into the table with a specified value number.
426void ValueTable::add(Value* V, uint32_t num) {
427 valueNumbering.insert(std::make_pair(V, num));
428}
429
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000430/// lookup_or_add - Returns the value number for the specified value, assigning
431/// it a new number if it did not have one before.
432uint32_t ValueTable::lookup_or_add(Value* V) {
433 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
434 if (VI != valueNumbering.end())
435 return VI->second;
436
Owen Andersonb388ca92007-10-18 19:39:33 +0000437 if (CallInst* C = dyn_cast<CallInst>(V)) {
Owen Anderson8f46c782008-04-11 05:11:49 +0000438 if (AA->doesNotAccessMemory(C)) {
Owen Andersonb388ca92007-10-18 19:39:33 +0000439 Expression e = create_expression(C);
440
441 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442 if (EI != expressionNumbering.end()) {
443 valueNumbering.insert(std::make_pair(V, EI->second));
444 return EI->second;
445 } else {
446 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448
449 return nextValueNumber++;
450 }
Owen Anderson241f6532008-04-17 05:36:50 +0000451 } else if (AA->onlyReadsMemory(C)) {
452 Expression e = create_expression(C);
453
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000454 if (expressionNumbering.find(e) == expressionNumbering.end()) {
Owen Anderson241f6532008-04-17 05:36:50 +0000455 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
456 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000457 return nextValueNumber++;
458 }
Owen Anderson241f6532008-04-17 05:36:50 +0000459
Chris Lattner4c724002008-11-29 02:29:27 +0000460 MemDepResult local_dep = MD->getDependency(C);
Owen Andersonc4f406e2008-05-13 23:18:30 +0000461
Chris Lattner4c724002008-11-29 02:29:27 +0000462 if (local_dep.isNone()) {
Owen Andersonc4f406e2008-05-13 23:18:30 +0000463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
Chris Lattner1440ac52008-11-30 23:39:23 +0000465 }
466
467 if (Instruction *LocalDepInst = local_dep.getInst()) {
Chris Lattner4c724002008-11-29 02:29:27 +0000468 if (!isa<CallInst>(LocalDepInst)) {
Owen Andersonc4f406e2008-05-13 23:18:30 +0000469 valueNumbering.insert(std::make_pair(V, nextValueNumber));
470 return nextValueNumber++;
471 }
472
Chris Lattner4c724002008-11-29 02:29:27 +0000473 CallInst* local_cdep = cast<CallInst>(LocalDepInst);
Owen Andersonc4f406e2008-05-13 23:18:30 +0000474
475 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
476 local_cdep->getNumOperands() != C->getNumOperands()) {
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478 return nextValueNumber++;
Chris Lattner1440ac52008-11-30 23:39:23 +0000479 }
480
481 if (!C->getCalledFunction()) {
Owen Andersonc4f406e2008-05-13 23:18:30 +0000482 valueNumbering.insert(std::make_pair(V, nextValueNumber));
483 return nextValueNumber++;
Owen Andersonc4f406e2008-05-13 23:18:30 +0000484 }
Chris Lattner1440ac52008-11-30 23:39:23 +0000485
486 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
487 uint32_t c_vn = lookup_or_add(C->getOperand(i));
488 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
489 if (c_vn != cd_vn) {
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491 return nextValueNumber++;
492 }
493 }
494
495 uint32_t v = lookup_or_add(local_cdep);
496 valueNumbering.insert(std::make_pair(V, v));
497 return v;
Owen Andersonc4f406e2008-05-13 23:18:30 +0000498 }
499
500
Chris Lattner396a4a52008-11-29 21:33:22 +0000501 SmallVector<std::pair<BasicBlock*, MemDepResult>, 32> deps;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000502 MD->getNonLocalDependency(C, deps);
Owen Anderson16db1f72008-05-13 13:41:23 +0000503 CallInst* cdep = 0;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000504
Chris Lattner1440ac52008-11-30 23:39:23 +0000505 // Check to see if we have a single dominating call instruction that is
506 // identical to C.
Chris Lattner396a4a52008-11-29 21:33:22 +0000507 for (SmallVector<std::pair<BasicBlock*, MemDepResult>, 32>
Chris Lattner39f372e2008-11-29 01:43:36 +0000508 ::iterator I = deps.begin(), E = deps.end(); I != E; ++I) {
Chris Lattner1440ac52008-11-30 23:39:23 +0000509 // Ignore non-local dependencies.
510 if (I->second.isNonLocal())
511 continue;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000512
Chris Lattner1440ac52008-11-30 23:39:23 +0000513 // We don't handle non-depedencies. If we already have a call, reject
514 // instruction dependencies.
515 if (I->second.isNone() || cdep != 0) {
516 cdep = 0;
517 break;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000518 }
Chris Lattner1440ac52008-11-30 23:39:23 +0000519
520 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
521 // FIXME: All duplicated with non-local case.
522 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
523 cdep = NonLocalDepCall;
524 continue;
525 }
526
527 cdep = 0;
528 break;
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000529 }
530
Owen Anderson16db1f72008-05-13 13:41:23 +0000531 if (!cdep) {
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000532 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson241f6532008-04-17 05:36:50 +0000533 return nextValueNumber++;
534 }
535
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000536 if (cdep->getCalledFunction() != C->getCalledFunction() ||
537 cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson241f6532008-04-17 05:36:50 +0000538 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000539 return nextValueNumber++;
Chris Lattner1440ac52008-11-30 23:39:23 +0000540 }
541 if (!C->getCalledFunction()) {
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson241f6532008-04-17 05:36:50 +0000543 return nextValueNumber++;
Owen Anderson241f6532008-04-17 05:36:50 +0000544 }
Chris Lattner1440ac52008-11-30 23:39:23 +0000545 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
546 uint32_t c_vn = lookup_or_add(C->getOperand(i));
547 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
548 if (c_vn != cd_vn) {
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
550 return nextValueNumber++;
551 }
552 }
553
554 uint32_t v = lookup_or_add(cdep);
555 valueNumbering.insert(std::make_pair(V, v));
556 return v;
Owen Anderson241f6532008-04-17 05:36:50 +0000557
Owen Andersonb388ca92007-10-18 19:39:33 +0000558 } else {
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
560 return nextValueNumber++;
561 }
562 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000563 Expression e = create_expression(BO);
564
565 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
566 if (EI != expressionNumbering.end()) {
567 valueNumbering.insert(std::make_pair(V, EI->second));
568 return EI->second;
569 } else {
570 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
571 valueNumbering.insert(std::make_pair(V, nextValueNumber));
572
573 return nextValueNumber++;
574 }
575 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
576 Expression e = create_expression(C);
577
578 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
579 if (EI != expressionNumbering.end()) {
580 valueNumbering.insert(std::make_pair(V, EI->second));
581 return EI->second;
582 } else {
583 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
584 valueNumbering.insert(std::make_pair(V, nextValueNumber));
585
586 return nextValueNumber++;
587 }
588 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
589 Expression e = create_expression(U);
590
591 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
592 if (EI != expressionNumbering.end()) {
593 valueNumbering.insert(std::make_pair(V, EI->second));
594 return EI->second;
595 } else {
596 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
597 valueNumbering.insert(std::make_pair(V, nextValueNumber));
598
599 return nextValueNumber++;
600 }
601 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
602 Expression e = create_expression(U);
603
604 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
605 if (EI != expressionNumbering.end()) {
606 valueNumbering.insert(std::make_pair(V, EI->second));
607 return EI->second;
608 } else {
609 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
610 valueNumbering.insert(std::make_pair(V, nextValueNumber));
611
612 return nextValueNumber++;
613 }
614 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
615 Expression e = create_expression(U);
616
617 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
618 if (EI != expressionNumbering.end()) {
619 valueNumbering.insert(std::make_pair(V, EI->second));
620 return EI->second;
621 } else {
622 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
623 valueNumbering.insert(std::make_pair(V, nextValueNumber));
624
625 return nextValueNumber++;
626 }
627 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
628 Expression e = create_expression(U);
629
630 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
631 if (EI != expressionNumbering.end()) {
632 valueNumbering.insert(std::make_pair(V, EI->second));
633 return EI->second;
634 } else {
635 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
636 valueNumbering.insert(std::make_pair(V, nextValueNumber));
637
638 return nextValueNumber++;
639 }
640 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
641 Expression e = create_expression(U);
642
643 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
644 if (EI != expressionNumbering.end()) {
645 valueNumbering.insert(std::make_pair(V, EI->second));
646 return EI->second;
647 } else {
648 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
649 valueNumbering.insert(std::make_pair(V, nextValueNumber));
650
651 return nextValueNumber++;
652 }
653 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
654 Expression e = create_expression(U);
655
656 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
657 if (EI != expressionNumbering.end()) {
658 valueNumbering.insert(std::make_pair(V, EI->second));
659 return EI->second;
660 } else {
661 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
662 valueNumbering.insert(std::make_pair(V, nextValueNumber));
663
664 return nextValueNumber++;
665 }
666 } else {
667 valueNumbering.insert(std::make_pair(V, nextValueNumber));
668 return nextValueNumber++;
669 }
670}
671
672/// lookup - Returns the value number of the specified value. Fails if
673/// the value has not yet been numbered.
674uint32_t ValueTable::lookup(Value* V) const {
675 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner88365bb2008-03-21 21:14:38 +0000676 assert(VI != valueNumbering.end() && "Value not numbered?");
677 return VI->second;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000678}
679
680/// clear - Remove all entries from the ValueTable
681void ValueTable::clear() {
682 valueNumbering.clear();
683 expressionNumbering.clear();
684 nextValueNumber = 1;
685}
686
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000687/// erase - Remove a value from the value numbering
688void ValueTable::erase(Value* V) {
689 valueNumbering.erase(V);
690}
691
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000692//===----------------------------------------------------------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000693// GVN Pass
694//===----------------------------------------------------------------------===//
695
696namespace {
Owen Anderson6fafe842008-06-20 01:15:47 +0000697 struct VISIBILITY_HIDDEN ValueNumberScope {
698 ValueNumberScope* parent;
699 DenseMap<uint32_t, Value*> table;
700
701 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
702 };
703}
704
705namespace {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000706
707 class VISIBILITY_HIDDEN GVN : public FunctionPass {
708 bool runOnFunction(Function &F);
709 public:
710 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000711 GVN() : FunctionPass(&ID) { }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000712
713 private:
Chris Lattner663e4412008-12-01 00:40:32 +0000714 MemoryDependenceAnalysis *MD;
715 DominatorTree *DT;
716
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000717 ValueTable VN;
Owen Anderson6fafe842008-06-20 01:15:47 +0000718 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000719
Owen Andersona37226a2007-08-07 23:12:31 +0000720 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
721 PhiMapType phiMap;
722
723
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000724 // This transformation requires dominator postdominator info
725 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000726 AU.addRequired<DominatorTree>();
727 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000728 AU.addRequired<AliasAnalysis>();
Owen Andersonb70a5712008-06-23 17:49:45 +0000729
730 AU.addPreserved<DominatorTree>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000731 AU.addPreserved<AliasAnalysis>();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000732 }
733
734 // Helper fuctions
735 // FIXME: eliminate or document these better
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000736 bool processLoad(LoadInst* L,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000737 DenseMap<Value*, LoadInst*> &lastLoad,
738 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000739 bool processInstruction(Instruction* I,
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000740 DenseMap<Value*, LoadInst*>& lastSeenLoad,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000741 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson830db6a2007-08-02 18:16:06 +0000742 bool processNonLocalLoad(LoadInst* L,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000743 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonaf4240a2008-06-12 19:25:32 +0000744 bool processBlock(DomTreeNode* DTN);
Owen Anderson45537912007-07-26 18:26:51 +0000745 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Anderson1c2763d2007-08-02 17:56:05 +0000746 DenseMap<BasicBlock*, Value*> &Phis,
747 bool top_level = false);
Owen Andersonb2303722008-06-18 21:41:49 +0000748 void dump(DenseMap<uint32_t, Value*>& d);
Owen Anderson3e75a422007-08-14 18:04:11 +0000749 bool iterateOnFunction(Function &F);
Owen Anderson1defe2d2007-08-16 22:51:56 +0000750 Value* CollapsePhi(PHINode* p);
Owen Anderson24866862007-09-16 08:04:16 +0000751 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Andersonb2303722008-06-18 21:41:49 +0000752 bool performPRE(Function& F);
Owen Anderson6fafe842008-06-20 01:15:47 +0000753 Value* lookupNumber(BasicBlock* BB, uint32_t num);
Owen Anderson961edc82008-07-15 16:28:06 +0000754 bool mergeBlockIntoPredecessor(BasicBlock* BB);
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +0000755 void cleanupGlobalSets();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000756 };
757
758 char GVN::ID = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000759}
760
761// createGVNPass - The public interface to this file...
762FunctionPass *llvm::createGVNPass() { return new GVN(); }
763
764static RegisterPass<GVN> X("gvn",
765 "Global Value Numbering");
766
Owen Andersonb2303722008-06-18 21:41:49 +0000767void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson0cd32032007-07-25 19:57:03 +0000768 printf("{\n");
Owen Andersonb2303722008-06-18 21:41:49 +0000769 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson0cd32032007-07-25 19:57:03 +0000770 E = d.end(); I != E; ++I) {
Owen Andersonb2303722008-06-18 21:41:49 +0000771 printf("%d\n", I->first);
Owen Anderson0cd32032007-07-25 19:57:03 +0000772 I->second->dump();
773 }
774 printf("}\n");
775}
776
Owen Anderson1defe2d2007-08-16 22:51:56 +0000777Value* GVN::CollapsePhi(PHINode* p) {
Owen Anderson1defe2d2007-08-16 22:51:56 +0000778 Value* constVal = p->hasConstantValue();
Chris Lattner88365bb2008-03-21 21:14:38 +0000779 if (!constVal) return 0;
Owen Anderson1defe2d2007-08-16 22:51:56 +0000780
Chris Lattner88365bb2008-03-21 21:14:38 +0000781 Instruction* inst = dyn_cast<Instruction>(constVal);
782 if (!inst)
783 return constVal;
784
Chris Lattner663e4412008-12-01 00:40:32 +0000785 if (DT->dominates(inst, p))
Chris Lattner88365bb2008-03-21 21:14:38 +0000786 if (isSafeReplacement(p, inst))
787 return inst;
Owen Anderson1defe2d2007-08-16 22:51:56 +0000788 return 0;
789}
Owen Anderson0cd32032007-07-25 19:57:03 +0000790
Owen Anderson24866862007-09-16 08:04:16 +0000791bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
792 if (!isa<PHINode>(inst))
793 return true;
794
795 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
796 UI != E; ++UI)
797 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
798 if (use_phi->getParent() == inst->getParent())
799 return false;
800
801 return true;
802}
803
Owen Anderson45537912007-07-26 18:26:51 +0000804/// GetValueForBlock - Get the value to use within the specified basic block.
805/// available values are in Phis.
806Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Chris Lattner88365bb2008-03-21 21:14:38 +0000807 DenseMap<BasicBlock*, Value*> &Phis,
808 bool top_level) {
Owen Anderson45537912007-07-26 18:26:51 +0000809
810 // If we have already computed this value, return the previously computed val.
Owen Andersonab870272007-08-03 19:59:35 +0000811 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
812 if (V != Phis.end() && !top_level) return V->second;
Owen Anderson45537912007-07-26 18:26:51 +0000813
Owen Andersoncb29a4f2008-07-02 18:15:31 +0000814 // If the block is unreachable, just return undef, since this path
815 // can't actually occur at runtime.
Chris Lattner663e4412008-12-01 00:40:32 +0000816 if (!DT->isReachableFromEntry(BB))
Owen Andersoncb29a4f2008-07-02 18:15:31 +0000817 return Phis[BB] = UndefValue::get(orig->getType());
Owen Andersonf2aa1602008-07-02 17:20:16 +0000818
Owen Anderson90660202007-08-01 22:01:54 +0000819 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson4b55c3b2007-08-03 11:03:26 +0000820 if (singlePred) {
Owen Andersonab870272007-08-03 19:59:35 +0000821 Value *ret = GetValueForBlock(singlePred, orig, Phis);
822 Phis[BB] = ret;
823 return ret;
Owen Anderson4b55c3b2007-08-03 11:03:26 +0000824 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000825
Owen Anderson45537912007-07-26 18:26:51 +0000826 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
827 // now, then get values to fill in the incoming values for the PHI.
Gabor Greif051a9502008-04-06 20:25:17 +0000828 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
829 BB->begin());
Owen Anderson45537912007-07-26 18:26:51 +0000830 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersonab870272007-08-03 19:59:35 +0000831
832 if (Phis.count(BB) == 0)
833 Phis.insert(std::make_pair(BB, PN));
Owen Anderson4f9ba7c2007-07-30 16:57:08 +0000834
Owen Anderson45537912007-07-26 18:26:51 +0000835 // Fill in the incoming values for the block.
Owen Anderson054ab942007-07-31 17:43:14 +0000836 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
837 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson054ab942007-07-31 17:43:14 +0000838 PN->addIncoming(val, *PI);
839 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000840
Chris Lattner663e4412008-12-01 00:40:32 +0000841 VN.getAliasAnalysis()->copyValue(orig, PN);
Owen Anderson054ab942007-07-31 17:43:14 +0000842
Owen Anderson62bc33c2007-08-16 22:02:55 +0000843 // Attempt to collapse PHI nodes that are trivially redundant
Owen Anderson1defe2d2007-08-16 22:51:56 +0000844 Value* v = CollapsePhi(PN);
Chris Lattner88365bb2008-03-21 21:14:38 +0000845 if (!v) {
846 // Cache our phi construction results
847 phiMap[orig->getPointerOperand()].insert(PN);
848 return PN;
Owen Anderson054ab942007-07-31 17:43:14 +0000849 }
Owen Andersona472c4a2008-05-12 20:15:55 +0000850
Chris Lattner88365bb2008-03-21 21:14:38 +0000851 PN->replaceAllUsesWith(v);
852
853 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
854 E = Phis.end(); I != E; ++I)
855 if (I->second == PN)
856 I->second = v;
857
Chris Lattner663e4412008-12-01 00:40:32 +0000858 DEBUG(cerr << "GVN removed: " << *PN);
859 MD->removeInstruction(PN);
Chris Lattner88365bb2008-03-21 21:14:38 +0000860 PN->eraseFromParent();
861
862 Phis[BB] = v;
863 return v;
Owen Anderson0cd32032007-07-25 19:57:03 +0000864}
865
Owen Anderson62bc33c2007-08-16 22:02:55 +0000866/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
867/// non-local by performing PHI construction.
Owen Anderson830db6a2007-08-02 18:16:06 +0000868bool GVN::processNonLocalLoad(LoadInst* L,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000869 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson62bc33c2007-08-16 22:02:55 +0000870 // Find the non-local dependencies of the load
Chris Lattner396a4a52008-11-29 21:33:22 +0000871 SmallVector<std::pair<BasicBlock*, MemDepResult>, 32> deps;
Chris Lattner663e4412008-12-01 00:40:32 +0000872 MD->getNonLocalDependency(L, deps);
873
874 DEBUG(cerr << "INVESTIGATING NONLOCAL LOAD: " << deps.size() << *L);
875
Owen Anderson0cd32032007-07-25 19:57:03 +0000876
Owen Anderson516eb1c2008-08-26 22:07:42 +0000877 // If we had to process more than one hundred blocks to find the
878 // dependencies, this load isn't worth worrying about. Optimizing
879 // it will be too expensive.
880 if (deps.size() > 100)
881 return false;
882
Chris Lattner86b29ef2008-11-29 21:22:42 +0000883 BasicBlock *EntryBlock = &L->getParent()->getParent()->getEntryBlock();
884
Owen Anderson0cd32032007-07-25 19:57:03 +0000885 DenseMap<BasicBlock*, Value*> repl;
Owen Andersona37226a2007-08-07 23:12:31 +0000886
Owen Anderson62bc33c2007-08-16 22:02:55 +0000887 // Filter out useless results (non-locals, etc)
Chris Lattner396a4a52008-11-29 21:33:22 +0000888 for (SmallVector<std::pair<BasicBlock*, MemDepResult>, 32>::iterator
889 I = deps.begin(), E = deps.end(); I != E; ++I) {
Chris Lattner86b29ef2008-11-29 21:22:42 +0000890 if (I->second.isNone()) {
891 repl[I->first] = UndefValue::get(L->getType());
Owen Anderson45c83882007-07-30 17:29:24 +0000892 continue;
Chris Lattner86b29ef2008-11-29 21:22:42 +0000893 }
894
895 if (I->second.isNonLocal()) {
896 // If this is a non-local dependency in the entry block, then we depend on
897 // the value live-in at the start of the function. We could insert a load
898 // in the entry block to get this, but for now we'll just bail out.
899 // FIXME: Consider emitting a load in the entry block to catch this case!
900 if (I->first == EntryBlock)
901 return false;
902 continue;
903 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000904
Chris Lattner4c724002008-11-29 02:29:27 +0000905 if (StoreInst* S = dyn_cast<StoreInst>(I->second.getInst())) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000906 if (S->getPointerOperand() != L->getPointerOperand())
Owen Anderson0cd32032007-07-25 19:57:03 +0000907 return false;
Chris Lattner88365bb2008-03-21 21:14:38 +0000908 repl[I->first] = S->getOperand(0);
Chris Lattner4c724002008-11-29 02:29:27 +0000909 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second.getInst())) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000910 if (LD->getPointerOperand() != L->getPointerOperand())
Owen Anderson0cd32032007-07-25 19:57:03 +0000911 return false;
Chris Lattner88365bb2008-03-21 21:14:38 +0000912 repl[I->first] = LD;
Owen Anderson0cd32032007-07-25 19:57:03 +0000913 } else {
914 return false;
915 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000916 }
Owen Anderson0cd32032007-07-25 19:57:03 +0000917
Owen Anderson62bc33c2007-08-16 22:02:55 +0000918 // Use cached PHI construction information from previous runs
Owen Andersona37226a2007-08-07 23:12:31 +0000919 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
920 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
921 I != E; ++I) {
922 if ((*I)->getParent() == L->getParent()) {
Owen Andersona37226a2007-08-07 23:12:31 +0000923 L->replaceAllUsesWith(*I);
924 toErase.push_back(L);
925 NumGVNLoad++;
Owen Andersona37226a2007-08-07 23:12:31 +0000926 return true;
Owen Andersona37226a2007-08-07 23:12:31 +0000927 }
Chris Lattner88365bb2008-03-21 21:14:38 +0000928
929 repl.insert(std::make_pair((*I)->getParent(), *I));
Owen Andersona37226a2007-08-07 23:12:31 +0000930 }
Chris Lattner663e4412008-12-01 00:40:32 +0000931
932 DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD: " << *L);
933
Owen Anderson62bc33c2007-08-16 22:02:55 +0000934 // Perform PHI construction
Owen Anderson0d169882007-07-25 22:03:06 +0000935 SmallPtrSet<BasicBlock*, 4> visited;
Owen Anderson1c2763d2007-08-02 17:56:05 +0000936 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson0cd32032007-07-25 19:57:03 +0000937 L->replaceAllUsesWith(v);
938 toErase.push_back(L);
Owen Andersona37226a2007-08-07 23:12:31 +0000939 NumGVNLoad++;
Owen Anderson0cd32032007-07-25 19:57:03 +0000940 return true;
941}
942
Owen Anderson62bc33c2007-08-16 22:02:55 +0000943/// processLoad - Attempt to eliminate a load, first by eliminating it
944/// locally, and then attempting non-local elimination if that fails.
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000945bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
946 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000947 if (L->isVolatile()) {
948 lastLoad[L->getPointerOperand()] = L;
949 return false;
950 }
951
952 Value* pointer = L->getPointerOperand();
953 LoadInst*& last = lastLoad[pointer];
954
955 // ... to a pointer that has been loaded from before...
Owen Anderson8e8278e2007-08-14 17:59:48 +0000956 bool removedNonLocal = false;
Chris Lattner663e4412008-12-01 00:40:32 +0000957 MemDepResult dep = MD->getDependency(L);
Chris Lattner4c724002008-11-29 02:29:27 +0000958 if (dep.isNonLocal() &&
Owen Anderson8e8278e2007-08-14 17:59:48 +0000959 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
960 removedNonLocal = processNonLocalLoad(L, toErase);
961
962 if (!removedNonLocal)
963 last = L;
964
965 return removedNonLocal;
966 }
967
968
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000969 bool deletedLoad = false;
970
Owen Anderson62bc33c2007-08-16 22:02:55 +0000971 // Walk up the dependency chain until we either find
972 // a dependency we can use, or we can't walk any further
Chris Lattner4c724002008-11-29 02:29:27 +0000973 while (Instruction *DepInst = dep.getInst()) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000974 // ... that depends on a store ...
Chris Lattner4c724002008-11-29 02:29:27 +0000975 if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000976 if (S->getPointerOperand() == pointer) {
977 // Remove it!
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000978 L->replaceAllUsesWith(S->getOperand(0));
979 toErase.push_back(L);
980 deletedLoad = true;
981 NumGVNLoad++;
982 }
983
984 // Whether we removed it or not, we can't
985 // go any further
986 break;
Chris Lattner4c724002008-11-29 02:29:27 +0000987 } else if (!isa<LoadInst>(DepInst)) {
988 // Only want to handle loads below.
989 break;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000990 } else if (!last) {
991 // If we don't depend on a store, and we haven't
992 // been loaded before, bail.
993 break;
Chris Lattner4c724002008-11-29 02:29:27 +0000994 } else if (DepInst == last) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000995 // Remove it!
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000996 L->replaceAllUsesWith(last);
997 toErase.push_back(L);
998 deletedLoad = true;
999 NumGVNLoad++;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001000 break;
1001 } else {
Chris Lattner663e4412008-12-01 00:40:32 +00001002 dep = MD->getDependencyFrom(L, DepInst, DepInst->getParent());
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001003 }
1004 }
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001005
Chris Lattner237a8282008-11-30 01:39:32 +00001006 // If this load really doesn't depend on anything, then we must be loading an
1007 // undef value. This can happen when loading for a fresh allocation with no
1008 // intervening stores, for example.
1009 if (dep.isNone()) {
1010 // If this load depends directly on an allocation, there isn't
1011 // anything stored there; therefore, we can optimize this load
1012 // to undef.
Chris Lattner237a8282008-11-30 01:39:32 +00001013 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1014 toErase.push_back(L);
1015 deletedLoad = true;
1016 NumGVNLoad++;
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001017 }
1018
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001019 if (!deletedLoad)
1020 last = L;
1021
1022 return deletedLoad;
1023}
1024
Owen Anderson6fafe842008-06-20 01:15:47 +00001025Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
Owen Andersonb70a5712008-06-23 17:49:45 +00001026 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1027 if (I == localAvail.end())
1028 return 0;
1029
1030 ValueNumberScope* locals = I->second;
Owen Anderson6fafe842008-06-20 01:15:47 +00001031
1032 while (locals) {
1033 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1034 if (I != locals->table.end())
1035 return I->second;
1036 else
1037 locals = locals->parent;
1038 }
1039
1040 return 0;
1041}
1042
Owen Anderson36057c72007-08-14 18:16:29 +00001043/// processInstruction - When calculating availability, handle an instruction
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001044/// by inserting it into the appropriate sets
Owen Andersonaf4240a2008-06-12 19:25:32 +00001045bool GVN::processInstruction(Instruction *I,
Chris Lattner8e1e95c2008-03-21 22:01:16 +00001046 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1047 SmallVectorImpl<Instruction*> &toErase) {
Owen Andersonb2303722008-06-18 21:41:49 +00001048 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1049 bool changed = processLoad(L, lastSeenLoad, toErase);
1050
1051 if (!changed) {
1052 unsigned num = VN.lookup_or_add(L);
Owen Anderson6fafe842008-06-20 01:15:47 +00001053 localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
Owen Andersonb2303722008-06-18 21:41:49 +00001054 }
1055
1056 return changed;
1057 }
1058
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001059 uint32_t nextNum = VN.getNextUnusedValueNumber();
Owen Andersonb2303722008-06-18 21:41:49 +00001060 unsigned num = VN.lookup_or_add(I);
Chris Lattner8e1e95c2008-03-21 22:01:16 +00001061
Owen Andersone5ffa902008-04-07 09:59:07 +00001062 // Allocations are always uniquely numbered, so we can save time and memory
1063 // by fast failing them.
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001064 if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
Owen Anderson6fafe842008-06-20 01:15:47 +00001065 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
Owen Andersone5ffa902008-04-07 09:59:07 +00001066 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00001067 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001068
Owen Anderson62bc33c2007-08-16 22:02:55 +00001069 // Collapse PHI nodes
Owen Anderson31f49672007-08-14 18:33:27 +00001070 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Anderson1defe2d2007-08-16 22:51:56 +00001071 Value* constVal = CollapsePhi(p);
Owen Anderson31f49672007-08-14 18:33:27 +00001072
1073 if (constVal) {
Owen Anderson1defe2d2007-08-16 22:51:56 +00001074 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1075 PI != PE; ++PI)
1076 if (PI->second.count(p))
1077 PI->second.erase(p);
Owen Anderson31f49672007-08-14 18:33:27 +00001078
Owen Anderson1defe2d2007-08-16 22:51:56 +00001079 p->replaceAllUsesWith(constVal);
1080 toErase.push_back(p);
Owen Andersonb2303722008-06-18 21:41:49 +00001081 } else {
Owen Anderson6fafe842008-06-20 01:15:47 +00001082 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
Owen Anderson31f49672007-08-14 18:33:27 +00001083 }
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001084
1085 // If the number we were assigned was a brand new VN, then we don't
1086 // need to do a lookup to see if the number already exists
1087 // somewhere in the domtree: it can't!
1088 } else if (num == nextNum) {
1089 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1090
Owen Anderson62bc33c2007-08-16 22:02:55 +00001091 // Perform value-number based elimination
Owen Anderson6fafe842008-06-20 01:15:47 +00001092 } else if (Value* repl = lookupNumber(I->getParent(), num)) {
Owen Anderson5fc4aba2007-12-08 01:37:09 +00001093 // Remove it!
Owen Andersonbf7d0bc2007-07-31 23:27:13 +00001094 VN.erase(I);
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001095 I->replaceAllUsesWith(repl);
1096 toErase.push_back(I);
1097 return true;
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001098 } else {
Owen Anderson6fafe842008-06-20 01:15:47 +00001099 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001100 }
1101
1102 return false;
1103}
1104
1105// GVN::runOnFunction - This is the main transformation entry point for a
1106// function.
1107//
Owen Anderson3e75a422007-08-14 18:04:11 +00001108bool GVN::runOnFunction(Function& F) {
Chris Lattner663e4412008-12-01 00:40:32 +00001109 MD = &getAnalysis<MemoryDependenceAnalysis>();
1110 DT = &getAnalysis<DominatorTree>();
Owen Andersona472c4a2008-05-12 20:15:55 +00001111 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner663e4412008-12-01 00:40:32 +00001112 VN.setMemDep(MD);
1113 VN.setDomTree(DT);
Owen Andersonb388ca92007-10-18 19:39:33 +00001114
Owen Anderson3e75a422007-08-14 18:04:11 +00001115 bool changed = false;
1116 bool shouldContinue = true;
1117
Owen Anderson5d0af032008-07-16 17:52:31 +00001118 // Merge unconditional branches, allowing PRE to catch more
1119 // optimization opportunities.
1120 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1121 BasicBlock* BB = FI;
1122 ++FI;
Owen Andersonb31b06d2008-07-17 00:01:40 +00001123 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1124 if (removedBlock) NumGVNBlocks++;
1125
1126 changed |= removedBlock;
Owen Anderson5d0af032008-07-16 17:52:31 +00001127 }
1128
Owen Anderson3e75a422007-08-14 18:04:11 +00001129 while (shouldContinue) {
1130 shouldContinue = iterateOnFunction(F);
1131 changed |= shouldContinue;
1132 }
1133
Owen Andersone98c54c2008-07-18 18:03:38 +00001134 if (EnablePRE) {
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001135 bool PREChanged = true;
1136 while (PREChanged) {
1137 PREChanged = performPRE(F);
Owen Andersone98c54c2008-07-18 18:03:38 +00001138 changed |= PREChanged;
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001139 }
Owen Andersone98c54c2008-07-18 18:03:38 +00001140 }
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00001141
1142 cleanupGlobalSets();
1143
Owen Anderson3e75a422007-08-14 18:04:11 +00001144 return changed;
1145}
1146
1147
Owen Andersonaf4240a2008-06-12 19:25:32 +00001148bool GVN::processBlock(DomTreeNode* DTN) {
1149 BasicBlock* BB = DTN->getBlock();
Owen Andersonaf4240a2008-06-12 19:25:32 +00001150 SmallVector<Instruction*, 8> toErase;
1151 DenseMap<Value*, LoadInst*> lastSeenLoad;
1152 bool changed_function = false;
Owen Andersonb2303722008-06-18 21:41:49 +00001153
1154 if (DTN->getIDom())
Owen Anderson6fafe842008-06-20 01:15:47 +00001155 localAvail[BB] =
1156 new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1157 else
1158 localAvail[BB] = new ValueNumberScope(0);
Owen Andersonb2303722008-06-18 21:41:49 +00001159
Owen Andersonaf4240a2008-06-12 19:25:32 +00001160 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1161 BI != BE;) {
1162 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1163 if (toErase.empty()) {
1164 ++BI;
1165 continue;
1166 }
1167
1168 // If we need some instructions deleted, do it now.
1169 NumGVNInstr += toErase.size();
1170
1171 // Avoid iterator invalidation.
1172 bool AtStart = BI == BB->begin();
1173 if (!AtStart)
1174 --BI;
1175
1176 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner663e4412008-12-01 00:40:32 +00001177 E = toErase.end(); I != E; ++I) {
1178 DEBUG(cerr << "GVN removed: " << **I);
1179 MD->removeInstruction(*I);
Owen Andersonaf4240a2008-06-12 19:25:32 +00001180 (*I)->eraseFromParent();
Chris Lattner663e4412008-12-01 00:40:32 +00001181 }
Owen Andersonaf4240a2008-06-12 19:25:32 +00001182
1183 if (AtStart)
1184 BI = BB->begin();
1185 else
1186 ++BI;
1187
1188 toErase.clear();
1189 }
1190
Owen Andersonaf4240a2008-06-12 19:25:32 +00001191 return changed_function;
1192}
1193
Owen Andersonb2303722008-06-18 21:41:49 +00001194/// performPRE - Perform a purely local form of PRE that looks for diamond
1195/// control flow patterns and attempts to perform simple PRE at the join point.
1196bool GVN::performPRE(Function& F) {
1197 bool changed = false;
Owen Anderson5c274ee2008-06-19 19:54:19 +00001198 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Owen Andersonb2303722008-06-18 21:41:49 +00001199 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1200 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1201 BasicBlock* CurrentBlock = *DI;
1202
1203 // Nothing to PRE in the entry block.
1204 if (CurrentBlock == &F.getEntryBlock()) continue;
1205
1206 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1207 BE = CurrentBlock->end(); BI != BE; ) {
Owen Andersonb70a5712008-06-23 17:49:45 +00001208 if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1209 isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1210 BI->mayWriteToMemory()) {
Owen Andersonb2303722008-06-18 21:41:49 +00001211 BI++;
1212 continue;
1213 }
1214
1215 uint32_t valno = VN.lookup(BI);
1216
1217 // Look for the predecessors for PRE opportunities. We're
1218 // only trying to solve the basic diamond case, where
1219 // a value is computed in the successor and one predecessor,
1220 // but not the other. We also explicitly disallow cases
1221 // where the successor is its own predecessor, because they're
1222 // more complicated to get right.
1223 unsigned numWith = 0;
1224 unsigned numWithout = 0;
1225 BasicBlock* PREPred = 0;
Owen Anderson6fafe842008-06-20 01:15:47 +00001226 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersonb2303722008-06-18 21:41:49 +00001227 for (pred_iterator PI = pred_begin(CurrentBlock),
1228 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1229 // We're not interested in PRE where the block is its
Owen Anderson6fafe842008-06-20 01:15:47 +00001230 // own predecessor, on in blocks with predecessors
1231 // that are not reachable.
1232 if (*PI == CurrentBlock) {
Owen Andersonb2303722008-06-18 21:41:49 +00001233 numWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00001234 break;
1235 } else if (!localAvail.count(*PI)) {
1236 numWithout = 2;
1237 break;
1238 }
1239
1240 DenseMap<uint32_t, Value*>::iterator predV =
1241 localAvail[*PI]->table.find(valno);
1242 if (predV == localAvail[*PI]->table.end()) {
Owen Andersonb2303722008-06-18 21:41:49 +00001243 PREPred = *PI;
1244 numWithout++;
Owen Anderson6fafe842008-06-20 01:15:47 +00001245 } else if (predV->second == BI) {
Owen Andersonb2303722008-06-18 21:41:49 +00001246 numWithout = 2;
1247 } else {
Owen Anderson6fafe842008-06-20 01:15:47 +00001248 predMap[*PI] = predV->second;
Owen Andersonb2303722008-06-18 21:41:49 +00001249 numWith++;
1250 }
1251 }
1252
1253 // Don't do PRE when it might increase code size, i.e. when
1254 // we would need to insert instructions in more than one pred.
1255 if (numWithout != 1 || numWith == 0) {
1256 BI++;
1257 continue;
1258 }
1259
Owen Anderson5c274ee2008-06-19 19:54:19 +00001260 // We can't do PRE safely on a critical edge, so instead we schedule
1261 // the edge to be split and perform the PRE the next time we iterate
1262 // on the function.
1263 unsigned succNum = 0;
1264 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1265 i != e; ++i)
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001266 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Owen Anderson5c274ee2008-06-19 19:54:19 +00001267 succNum = i;
1268 break;
1269 }
1270
1271 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1272 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1273 changed = true;
1274 BI++;
1275 continue;
1276 }
1277
Owen Andersonb2303722008-06-18 21:41:49 +00001278 // Instantiate the expression the in predecessor that lacked it.
1279 // Because we are going top-down through the block, all value numbers
1280 // will be available in the predecessor by the time we need them. Any
1281 // that weren't original present will have been instantiated earlier
1282 // in this loop.
1283 Instruction* PREInstr = BI->clone();
1284 bool success = true;
1285 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1286 Value* op = BI->getOperand(i);
1287 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1288 PREInstr->setOperand(i, op);
Owen Andersonc45996b2008-07-11 20:05:13 +00001289 else {
1290 Value* V = lookupNumber(PREPred, VN.lookup(op));
1291 if (!V) {
1292 success = false;
1293 break;
1294 } else
1295 PREInstr->setOperand(i, V);
1296 }
Owen Andersonb2303722008-06-18 21:41:49 +00001297 }
1298
1299 // Fail out if we encounter an operand that is not available in
1300 // the PRE predecessor. This is typically because of loads which
1301 // are not value numbered precisely.
1302 if (!success) {
1303 delete PREInstr;
1304 BI++;
1305 continue;
1306 }
1307
1308 PREInstr->insertBefore(PREPred->getTerminator());
1309 PREInstr->setName(BI->getName() + ".pre");
Owen Anderson6fafe842008-06-20 01:15:47 +00001310 predMap[PREPred] = PREInstr;
Owen Andersonb2303722008-06-18 21:41:49 +00001311 VN.add(PREInstr, valno);
1312 NumGVNPRE++;
1313
1314 // Update the availability map to include the new instruction.
Owen Anderson6fafe842008-06-20 01:15:47 +00001315 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
Owen Andersonb2303722008-06-18 21:41:49 +00001316
1317 // Create a PHI to make the value available in this block.
1318 PHINode* Phi = PHINode::Create(BI->getType(),
1319 BI->getName() + ".pre-phi",
1320 CurrentBlock->begin());
1321 for (pred_iterator PI = pred_begin(CurrentBlock),
1322 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson6fafe842008-06-20 01:15:47 +00001323 Phi->addIncoming(predMap[*PI], *PI);
Owen Andersonb2303722008-06-18 21:41:49 +00001324
1325 VN.add(Phi, valno);
Owen Anderson6fafe842008-06-20 01:15:47 +00001326 localAvail[CurrentBlock]->table[valno] = Phi;
Owen Andersonb2303722008-06-18 21:41:49 +00001327
1328 BI->replaceAllUsesWith(Phi);
Owen Anderson9da52dc2008-06-19 17:53:26 +00001329 VN.erase(BI);
Owen Andersonb2303722008-06-18 21:41:49 +00001330
1331 Instruction* erase = BI;
1332 BI++;
Chris Lattner663e4412008-12-01 00:40:32 +00001333 DEBUG(cerr << "GVN removed: " << *erase);
1334 MD->removeInstruction(erase);
Owen Andersonb2303722008-06-18 21:41:49 +00001335 erase->eraseFromParent();
Owen Andersonb2303722008-06-18 21:41:49 +00001336 changed = true;
1337 }
1338 }
1339
Owen Anderson5c274ee2008-06-19 19:54:19 +00001340 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1341 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1342 SplitCriticalEdge(I->first, I->second, this);
1343
Owen Andersone98c54c2008-07-18 18:03:38 +00001344 return changed || toSplit.size();
Owen Andersonb2303722008-06-18 21:41:49 +00001345}
1346
Owen Anderson961edc82008-07-15 16:28:06 +00001347// iterateOnFunction - Executes one iteration of GVN
Owen Anderson3e75a422007-08-14 18:04:11 +00001348bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00001349 cleanupGlobalSets();
Chris Lattner2e607012008-03-21 21:33:23 +00001350
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001351 // Top-down walk of the dominator tree
Owen Andersonb2303722008-06-18 21:41:49 +00001352 bool changed = false;
Chris Lattner663e4412008-12-01 00:40:32 +00001353 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1354 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Owen Andersonb2303722008-06-18 21:41:49 +00001355 changed |= processBlock(*DI);
Owen Andersonaa0b6342008-06-19 19:57:25 +00001356
Owen Anderson5d0af032008-07-16 17:52:31 +00001357 return changed;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001358}
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00001359
1360void GVN::cleanupGlobalSets() {
1361 VN.clear();
1362 phiMap.clear();
1363
1364 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1365 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1366 delete I->second;
1367 localAvail.clear();
1368}