blob: 9f7fc4d8e7c593bb1904549a8899558ab403ea46 [file] [log] [blame]
Owen Anderson5fba6c12007-05-29 21:53:49 +00001//===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the Owen Anderson and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a hybrid of global value numbering and partial redundancy
11// elimination, known as GVN-PRE. It performs partial redundancy elimination on
12// values, rather than lexical expressions, allowing a more comprehensive view
13// the optimization. It replaces redundant values with uses of earlier
14// occurences of the same value. While this is beneficial in that it eliminates
15// unneeded computation, it also increases register pressure by creating large
Owen Andersonb232efa2007-06-08 20:57:08 +000016// live ranges, and should be used with caution on platforms that are very
Owen Anderson5fba6c12007-05-29 21:53:49 +000017// sensitive to register pressure.
18//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "gvnpre"
22#include "llvm/Value.h"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Instructions.h"
25#include "llvm/Function.h"
26#include "llvm/Analysis/Dominators.h"
27#include "llvm/Analysis/PostDominators.h"
Owen Anderson1ad2c102007-06-19 23:23:54 +000028#include "llvm/ADT/DenseMap.h"
Owen Anderson5fba6c12007-05-29 21:53:49 +000029#include "llvm/ADT/DepthFirstIterator.h"
Owen Anderson2ff912b2007-06-21 17:57:53 +000030#include "llvm/ADT/SmallPtrSet.h"
Owen Anderson5fba6c12007-05-29 21:53:49 +000031#include "llvm/ADT/Statistic.h"
Owen Andersonbe802402007-06-08 01:03:01 +000032#include "llvm/Support/CFG.h"
Owen Anderson5fba6c12007-05-29 21:53:49 +000033#include "llvm/Support/Compiler.h"
Owen Anderson4a6ec8f2007-05-29 23:15:21 +000034#include "llvm/Support/Debug.h"
Owen Anderson5fba6c12007-05-29 21:53:49 +000035#include <algorithm>
Owen Anderson331bf6a2007-05-31 22:44:11 +000036#include <deque>
Owen Anderson5fba6c12007-05-29 21:53:49 +000037#include <map>
Owen Anderson331bf6a2007-05-31 22:44:11 +000038#include <vector>
Owen Anderson5fba6c12007-05-29 21:53:49 +000039#include <set>
Owen Anderson5fba6c12007-05-29 21:53:49 +000040using namespace llvm;
41
Owen Andersonb56fba02007-06-19 03:31:41 +000042//===----------------------------------------------------------------------===//
43// ValueTable Class
44//===----------------------------------------------------------------------===//
45
Owen Andersonfd5683a2007-06-21 00:19:05 +000046/// This class holds the mapping between values and value numbers. It is used
47/// as an efficient mechanism to determine the expression-wise equivalence of
48/// two values.
Owen Andersonb56fba02007-06-19 03:31:41 +000049
50namespace {
51 class VISIBILITY_HIDDEN ValueTable {
52 public:
53 struct Expression {
54 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
55 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
56 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
57 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
58 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
59 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
60 FCMPULT, FCMPULE, FCMPUNE };
61
62 ExpressionOpcode opcode;
63 uint32_t leftVN;
64 uint32_t rightVN;
65
66 bool operator< (const Expression& other) const {
67 if (opcode < other.opcode)
68 return true;
69 else if (opcode > other.opcode)
70 return false;
71 else if (leftVN < other.leftVN)
72 return true;
73 else if (leftVN > other.leftVN)
74 return false;
75 else if (rightVN < other.rightVN)
76 return true;
77 else if (rightVN > other.rightVN)
78 return false;
79 else
80 return false;
Owen Andersona75dd4d2007-06-12 00:50:47 +000081 }
Owen Andersonb56fba02007-06-19 03:31:41 +000082 };
83
84 private:
Owen Anderson1ad2c102007-06-19 23:23:54 +000085 DenseMap<Value*, uint32_t> valueNumbering;
Owen Andersonb56fba02007-06-19 03:31:41 +000086 std::map<Expression, uint32_t> expressionNumbering;
87
88 std::set<Expression> maximalExpressions;
Owen Anderson2ff912b2007-06-21 17:57:53 +000089 SmallPtrSet<Value*, 32> maximalValues;
Owen Andersonb56fba02007-06-19 03:31:41 +000090
91 uint32_t nextValueNumber;
92
93 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
94 Expression::ExpressionOpcode getOpcode(CmpInst* C);
Owen Andersonfd5683a2007-06-21 00:19:05 +000095 Expression create_expression(BinaryOperator* BO);
96 Expression create_expression(CmpInst* C);
Owen Andersonb56fba02007-06-19 03:31:41 +000097 public:
98 ValueTable() { nextValueNumber = 1; }
99 uint32_t lookup_or_add(Value* V);
100 uint32_t lookup(Value* V);
101 void add(Value* V, uint32_t num);
102 void clear();
103 std::set<Expression>& getMaximalExpressions() {
104 return maximalExpressions;
105
106 }
Owen Anderson2ff912b2007-06-21 17:57:53 +0000107 SmallPtrSet<Value*, 32>& getMaximalValues() { return maximalValues; }
Owen Anderson91c54952007-06-19 05:37:32 +0000108 void erase(Value* v);
Owen Andersonb56fba02007-06-19 03:31:41 +0000109 };
110}
111
Owen Andersonfd5683a2007-06-21 00:19:05 +0000112//===----------------------------------------------------------------------===//
113// ValueTable Internal Functions
114//===----------------------------------------------------------------------===//
Owen Andersonb56fba02007-06-19 03:31:41 +0000115ValueTable::Expression::ExpressionOpcode
Owen Andersonfd5683a2007-06-21 00:19:05 +0000116 ValueTable::getOpcode(BinaryOperator* BO) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000117 switch(BO->getOpcode()) {
118 case Instruction::Add:
119 return Expression::ADD;
120 case Instruction::Sub:
121 return Expression::SUB;
122 case Instruction::Mul:
123 return Expression::MUL;
124 case Instruction::UDiv:
125 return Expression::UDIV;
126 case Instruction::SDiv:
127 return Expression::SDIV;
128 case Instruction::FDiv:
129 return Expression::FDIV;
130 case Instruction::URem:
131 return Expression::UREM;
132 case Instruction::SRem:
133 return Expression::SREM;
134 case Instruction::FRem:
135 return Expression::FREM;
136 case Instruction::Shl:
137 return Expression::SHL;
138 case Instruction::LShr:
139 return Expression::LSHR;
140 case Instruction::AShr:
141 return Expression::ASHR;
142 case Instruction::And:
143 return Expression::AND;
144 case Instruction::Or:
145 return Expression::OR;
146 case Instruction::Xor:
147 return Expression::XOR;
148
149 // THIS SHOULD NEVER HAPPEN
150 default:
151 assert(0 && "Binary operator with unknown opcode?");
152 return Expression::ADD;
153 }
154}
155
156ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
157 if (C->getOpcode() == Instruction::ICmp) {
158 switch (C->getPredicate()) {
159 case ICmpInst::ICMP_EQ:
160 return Expression::ICMPEQ;
161 case ICmpInst::ICMP_NE:
162 return Expression::ICMPNE;
163 case ICmpInst::ICMP_UGT:
164 return Expression::ICMPUGT;
165 case ICmpInst::ICMP_UGE:
166 return Expression::ICMPUGE;
167 case ICmpInst::ICMP_ULT:
168 return Expression::ICMPULT;
169 case ICmpInst::ICMP_ULE:
170 return Expression::ICMPULE;
171 case ICmpInst::ICMP_SGT:
172 return Expression::ICMPSGT;
173 case ICmpInst::ICMP_SGE:
174 return Expression::ICMPSGE;
175 case ICmpInst::ICMP_SLT:
176 return Expression::ICMPSLT;
177 case ICmpInst::ICMP_SLE:
178 return Expression::ICMPSLE;
179
180 // THIS SHOULD NEVER HAPPEN
181 default:
182 assert(0 && "Comparison with unknown predicate?");
183 return Expression::ICMPEQ;
184 }
185 } else {
186 switch (C->getPredicate()) {
187 case FCmpInst::FCMP_OEQ:
188 return Expression::FCMPOEQ;
189 case FCmpInst::FCMP_OGT:
190 return Expression::FCMPOGT;
191 case FCmpInst::FCMP_OGE:
192 return Expression::FCMPOGE;
193 case FCmpInst::FCMP_OLT:
194 return Expression::FCMPOLT;
195 case FCmpInst::FCMP_OLE:
196 return Expression::FCMPOLE;
197 case FCmpInst::FCMP_ONE:
198 return Expression::FCMPONE;
199 case FCmpInst::FCMP_ORD:
200 return Expression::FCMPORD;
201 case FCmpInst::FCMP_UNO:
202 return Expression::FCMPUNO;
203 case FCmpInst::FCMP_UEQ:
204 return Expression::FCMPUEQ;
205 case FCmpInst::FCMP_UGT:
206 return Expression::FCMPUGT;
207 case FCmpInst::FCMP_UGE:
208 return Expression::FCMPUGE;
209 case FCmpInst::FCMP_ULT:
210 return Expression::FCMPULT;
211 case FCmpInst::FCMP_ULE:
212 return Expression::FCMPULE;
213 case FCmpInst::FCMP_UNE:
214 return Expression::FCMPUNE;
215
216 // THIS SHOULD NEVER HAPPEN
217 default:
218 assert(0 && "Comparison with unknown predicate?");
219 return Expression::FCMPOEQ;
Owen Anderson223718c2007-06-09 18:35:31 +0000220 }
221 }
Owen Andersonb56fba02007-06-19 03:31:41 +0000222}
223
Owen Andersonfd5683a2007-06-21 00:19:05 +0000224ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
225 Expression e;
226
227 e.leftVN = lookup_or_add(BO->getOperand(0));
228 e.rightVN = lookup_or_add(BO->getOperand(1));
229 e.opcode = getOpcode(BO);
230
231 maximalExpressions.insert(e);
232
233 return e;
234}
235
236ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
237 Expression e;
238
239 e.leftVN = lookup_or_add(C->getOperand(0));
240 e.rightVN = lookup_or_add(C->getOperand(1));
241 e.opcode = getOpcode(C);
242
243 maximalExpressions.insert(e);
244
245 return e;
246}
247
248//===----------------------------------------------------------------------===//
249// ValueTable External Functions
250//===----------------------------------------------------------------------===//
251
252/// lookup_or_add - Returns the value number for the specified value, assigning
253/// it a new number if it did not have one before.
Owen Andersonb56fba02007-06-19 03:31:41 +0000254uint32_t ValueTable::lookup_or_add(Value* V) {
255 maximalValues.insert(V);
256
Owen Anderson1ad2c102007-06-19 23:23:54 +0000257 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Owen Andersonb56fba02007-06-19 03:31:41 +0000258 if (VI != valueNumbering.end())
259 return VI->second;
Owen Anderson223718c2007-06-09 18:35:31 +0000260
Owen Anderson223718c2007-06-09 18:35:31 +0000261
Owen Andersonb56fba02007-06-19 03:31:41 +0000262 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
263 Expression e = create_expression(BO);
264
265 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
266 if (EI != expressionNumbering.end()) {
267 valueNumbering.insert(std::make_pair(V, EI->second));
268 return EI->second;
269 } else {
270 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
271 valueNumbering.insert(std::make_pair(V, nextValueNumber));
272
273 return nextValueNumber++;
274 }
275 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
276 Expression e = create_expression(C);
277
278 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
279 if (EI != expressionNumbering.end()) {
280 valueNumbering.insert(std::make_pair(V, EI->second));
281 return EI->second;
282 } else {
283 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
284 valueNumbering.insert(std::make_pair(V, nextValueNumber));
285
286 return nextValueNumber++;
287 }
288 } else {
289 valueNumbering.insert(std::make_pair(V, nextValueNumber));
290 return nextValueNumber++;
Owen Anderson0b68cda2007-06-03 05:55:58 +0000291 }
Owen Andersonb56fba02007-06-19 03:31:41 +0000292}
293
Owen Andersonfd5683a2007-06-21 00:19:05 +0000294/// lookup - Returns the value number of the specified value. Fails if
295/// the value has not yet been numbered.
Owen Andersonb56fba02007-06-19 03:31:41 +0000296uint32_t ValueTable::lookup(Value* V) {
Owen Anderson1ad2c102007-06-19 23:23:54 +0000297 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Owen Andersonb56fba02007-06-19 03:31:41 +0000298 if (VI != valueNumbering.end())
299 return VI->second;
300 else
301 assert(0 && "Value not numbered?");
302
303 return 0;
304}
305
Owen Andersonfd5683a2007-06-21 00:19:05 +0000306/// add - Add the specified value with the given value number, removing
307/// its old number, if any
Owen Andersonb56fba02007-06-19 03:31:41 +0000308void ValueTable::add(Value* V, uint32_t num) {
Owen Anderson1ad2c102007-06-19 23:23:54 +0000309 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Owen Andersonb56fba02007-06-19 03:31:41 +0000310 if (VI != valueNumbering.end())
311 valueNumbering.erase(VI);
312 valueNumbering.insert(std::make_pair(V, num));
313}
314
Owen Andersonfd5683a2007-06-21 00:19:05 +0000315/// clear - Remove all entries from the ValueTable and the maximal sets
Owen Andersonb56fba02007-06-19 03:31:41 +0000316void ValueTable::clear() {
317 valueNumbering.clear();
318 expressionNumbering.clear();
Owen Andersonb9cbaed2007-06-19 04:32:55 +0000319 maximalExpressions.clear();
320 maximalValues.clear();
Owen Andersonb56fba02007-06-19 03:31:41 +0000321 nextValueNumber = 1;
322}
Owen Anderson0b68cda2007-06-03 05:55:58 +0000323
Owen Andersonfd5683a2007-06-21 00:19:05 +0000324/// erase - Remove a value from the value numbering and maximal sets
Owen Anderson91c54952007-06-19 05:37:32 +0000325void ValueTable::erase(Value* V) {
326 maximalValues.erase(V);
327 valueNumbering.erase(V);
328 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V))
329 maximalExpressions.erase(create_expression(BO));
330 else if (CmpInst* C = dyn_cast<CmpInst>(V))
331 maximalExpressions.erase(create_expression(C));
332}
333
Owen Andersonfd5683a2007-06-21 00:19:05 +0000334//===----------------------------------------------------------------------===//
335// GVNPRE Pass
336//===----------------------------------------------------------------------===//
337
Owen Anderson5fba6c12007-05-29 21:53:49 +0000338namespace {
339
340 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
341 bool runOnFunction(Function &F);
342 public:
343 static char ID; // Pass identification, replacement for typeid
Owen Andersonb9cbaed2007-06-19 04:32:55 +0000344 GVNPRE() : FunctionPass((intptr_t)&ID) { }
Owen Anderson5fba6c12007-05-29 21:53:49 +0000345
346 private:
Owen Andersonbe802402007-06-08 01:03:01 +0000347 ValueTable VN;
Owen Andersona75dd4d2007-06-12 00:50:47 +0000348 std::vector<Instruction*> createdExpressions;
Owen Anderson81d156e2007-05-31 00:42:15 +0000349
Owen Anderson2ff912b2007-06-21 17:57:53 +0000350 std::map<BasicBlock*, SmallPtrSet<Value*, 32> > availableOut;
351 std::map<BasicBlock*, SmallPtrSet<Value*, 32> > anticipatedIn;
Owen Anderson4036ad42007-06-12 22:43:57 +0000352
Owen Andersonfd5683a2007-06-21 00:19:05 +0000353 // This transformation requires dominator postdominator info
Owen Anderson5fba6c12007-05-29 21:53:49 +0000354 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
355 AU.setPreservesCFG();
356 AU.addRequired<DominatorTree>();
357 AU.addRequired<PostDominatorTree>();
358 }
359
360 // Helper fuctions
361 // FIXME: eliminate or document these better
Owen Anderson2ff912b2007-06-21 17:57:53 +0000362 void dump(const SmallPtrSet<Value*, 32>& s) const;
363 void clean(SmallPtrSet<Value*, 32>& set);
364 Value* find_leader(SmallPtrSet<Value*, 32>& vals,
Owen Andersonb56fba02007-06-19 03:31:41 +0000365 uint32_t v);
Owen Anderson4036ad42007-06-12 22:43:57 +0000366 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
Owen Anderson2ff912b2007-06-21 17:57:53 +0000367 void phi_translate_set(SmallPtrSet<Value*, 32>& anticIn, BasicBlock* pred,
368 BasicBlock* succ, SmallPtrSet<Value*, 32>& out);
Owen Anderson5fba6c12007-05-29 21:53:49 +0000369
Owen Anderson2ff912b2007-06-21 17:57:53 +0000370 void topo_sort(SmallPtrSet<Value*, 32>& set,
Owen Anderson0b68cda2007-06-03 05:55:58 +0000371 std::vector<Value*>& vec);
Owen Anderson331bf6a2007-05-31 22:44:11 +0000372
Owen Anderson42769842007-06-12 16:57:50 +0000373 void cleanup();
Owen Anderson06c1e582007-06-20 22:10:02 +0000374 bool elimination();
Owen Andersondd998e12007-06-18 04:42:29 +0000375
Owen Anderson2ff912b2007-06-21 17:57:53 +0000376 void val_insert(SmallPtrSet<Value*, 32>& s, Value* v);
377 void val_replace(SmallPtrSet<Value*, 32>& s, Value* v);
Owen Andersondd998e12007-06-18 04:42:29 +0000378 bool dependsOnInvoke(Value* V);
Owen Anderson06c1e582007-06-20 22:10:02 +0000379 void buildsets_availout(BasicBlock::iterator I,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000380 SmallPtrSet<Value*, 32>& currAvail,
381 SmallPtrSet<PHINode*, 32>& currPhis,
382 SmallPtrSet<Value*, 32>& currExps,
383 SmallPtrSet<Value*, 32>& currTemps);
Owen Anderson06c1e582007-06-20 22:10:02 +0000384 void buildsets_anticout(BasicBlock* BB,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000385 SmallPtrSet<Value*, 32>& anticOut,
Owen Anderson06c1e582007-06-20 22:10:02 +0000386 std::set<BasicBlock*>& visited);
387 bool buildsets_anticin(BasicBlock* BB,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000388 SmallPtrSet<Value*, 32>& anticOut,
389 SmallPtrSet<Value*, 32>& currExps,
390 SmallPtrSet<Value*, 32>& currTemps,
Owen Anderson06c1e582007-06-20 22:10:02 +0000391 std::set<BasicBlock*>& visited);
392 unsigned buildsets(Function& F);
393
394 void insertion_pre(Value* e, BasicBlock* BB,
395 std::map<BasicBlock*, Value*>& avail,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000396 SmallPtrSet<Value*, 32>& new_set);
Owen Anderson06c1e582007-06-20 22:10:02 +0000397 unsigned insertion_mergepoint(std::vector<Value*>& workList,
398 df_iterator<DomTreeNode*> D,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000399 SmallPtrSet<Value*, 32>& new_set);
Owen Anderson06c1e582007-06-20 22:10:02 +0000400 bool insertion(Function& F);
Owen Anderson5fba6c12007-05-29 21:53:49 +0000401
402 };
403
404 char GVNPRE::ID = 0;
405
406}
407
Owen Andersonfd5683a2007-06-21 00:19:05 +0000408// createGVNPREPass - The public interface to this file...
Owen Anderson5fba6c12007-05-29 21:53:49 +0000409FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
410
411RegisterPass<GVNPRE> X("gvnpre",
412 "Global Value Numbering/Partial Redundancy Elimination");
413
Owen Anderson5fba6c12007-05-29 21:53:49 +0000414
Owen Anderson7d76b2a2007-06-08 22:02:36 +0000415STATISTIC(NumInsertedVals, "Number of values inserted");
416STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
417STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
418
Owen Andersonfd5683a2007-06-21 00:19:05 +0000419/// find_leader - Given a set and a value number, return the first
420/// element of the set with that value number, or 0 if no such element
421/// is present
Owen Anderson2ff912b2007-06-21 17:57:53 +0000422Value* GVNPRE::find_leader(SmallPtrSet<Value*, 32>& vals, uint32_t v) {
423 for (SmallPtrSet<Value*, 32>::iterator I = vals.begin(), E = vals.end();
Owen Andersonb56fba02007-06-19 03:31:41 +0000424 I != E; ++I)
425 if (v == VN.lookup(*I))
Owen Anderson0b68cda2007-06-03 05:55:58 +0000426 return *I;
Owen Anderson5fba6c12007-05-29 21:53:49 +0000427
Owen Anderson0b68cda2007-06-03 05:55:58 +0000428 return 0;
Owen Anderson5fba6c12007-05-29 21:53:49 +0000429}
430
Owen Andersonfd5683a2007-06-21 00:19:05 +0000431/// val_insert - Insert a value into a set only if there is not a value
432/// with the same value number already in the set
Owen Anderson2ff912b2007-06-21 17:57:53 +0000433void GVNPRE::val_insert(SmallPtrSet<Value*, 32>& s, Value* v) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000434 uint32_t num = VN.lookup(v);
435 Value* leader = find_leader(s, num);
436 if (leader == 0)
437 s.insert(v);
438}
439
Owen Andersonfd5683a2007-06-21 00:19:05 +0000440/// val_replace - Insert a value into a set, replacing any values already in
441/// the set that have the same value number
Owen Anderson2ff912b2007-06-21 17:57:53 +0000442void GVNPRE::val_replace(SmallPtrSet<Value*, 32>& s, Value* v) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000443 uint32_t num = VN.lookup(v);
444 Value* leader = find_leader(s, num);
445 while (leader != 0) {
446 s.erase(leader);
447 leader = find_leader(s, num);
448 }
449 s.insert(v);
450}
451
Owen Andersonfd5683a2007-06-21 00:19:05 +0000452/// phi_translate - Given a value, its parent block, and a predecessor of its
453/// parent, translate the value into legal for the predecessor block. This
454/// means translating its operands (and recursively, their operands) through
455/// any phi nodes in the parent into values available in the predecessor
Owen Anderson4036ad42007-06-12 22:43:57 +0000456Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
Owen Anderson38b6b222007-06-04 18:05:26 +0000457 if (V == 0)
458 return 0;
459
460 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000461 Value* newOp1 = 0;
462 if (isa<Instruction>(BO->getOperand(0)))
463 newOp1 = phi_translate(find_leader(anticipatedIn[succ],
464 VN.lookup(BO->getOperand(0))),
465 pred, succ);
466 else
467 newOp1 = BO->getOperand(0);
468
Owen Anderson38b6b222007-06-04 18:05:26 +0000469 if (newOp1 == 0)
470 return 0;
471
Owen Andersonb56fba02007-06-19 03:31:41 +0000472 Value* newOp2 = 0;
473 if (isa<Instruction>(BO->getOperand(1)))
474 newOp2 = phi_translate(find_leader(anticipatedIn[succ],
475 VN.lookup(BO->getOperand(1))),
476 pred, succ);
477 else
478 newOp2 = BO->getOperand(1);
479
Owen Anderson38b6b222007-06-04 18:05:26 +0000480 if (newOp2 == 0)
481 return 0;
482
483 if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
Owen Andersonbe802402007-06-08 01:03:01 +0000484 Instruction* newVal = BinaryOperator::create(BO->getOpcode(),
Owen Anderson38b6b222007-06-04 18:05:26 +0000485 newOp1, newOp2,
Owen Anderson91c54952007-06-19 05:37:32 +0000486 BO->getName()+".expr");
Owen Anderson55994f22007-06-08 20:44:02 +0000487
Owen Andersonb56fba02007-06-19 03:31:41 +0000488 uint32_t v = VN.lookup_or_add(newVal);
Owen Anderson4036ad42007-06-12 22:43:57 +0000489
Owen Andersonb56fba02007-06-19 03:31:41 +0000490 Value* leader = find_leader(availableOut[pred], v);
Owen Anderson4036ad42007-06-12 22:43:57 +0000491 if (leader == 0) {
Owen Andersona75dd4d2007-06-12 00:50:47 +0000492 createdExpressions.push_back(newVal);
Owen Anderson38b6b222007-06-04 18:05:26 +0000493 return newVal;
Owen Andersonc8472092007-06-05 22:11:49 +0000494 } else {
Owen Anderson91c54952007-06-19 05:37:32 +0000495 VN.erase(newVal);
Owen Andersonc8472092007-06-05 22:11:49 +0000496 delete newVal;
Owen Anderson4036ad42007-06-12 22:43:57 +0000497 return leader;
Owen Andersonc8472092007-06-05 22:11:49 +0000498 }
Owen Anderson38b6b222007-06-04 18:05:26 +0000499 }
500 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
Owen Andersona75dd4d2007-06-12 00:50:47 +0000501 if (P->getParent() == succ)
Owen Anderson38b6b222007-06-04 18:05:26 +0000502 return P->getIncomingValueForBlock(pred);
Owen Anderson223718c2007-06-09 18:35:31 +0000503 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000504 Value* newOp1 = 0;
505 if (isa<Instruction>(C->getOperand(0)))
506 newOp1 = phi_translate(find_leader(anticipatedIn[succ],
507 VN.lookup(C->getOperand(0))),
508 pred, succ);
509 else
510 newOp1 = C->getOperand(0);
511
Owen Anderson223718c2007-06-09 18:35:31 +0000512 if (newOp1 == 0)
513 return 0;
514
Owen Andersonb56fba02007-06-19 03:31:41 +0000515 Value* newOp2 = 0;
516 if (isa<Instruction>(C->getOperand(1)))
517 newOp2 = phi_translate(find_leader(anticipatedIn[succ],
518 VN.lookup(C->getOperand(1))),
519 pred, succ);
520 else
521 newOp2 = C->getOperand(1);
522
Owen Anderson223718c2007-06-09 18:35:31 +0000523 if (newOp2 == 0)
524 return 0;
525
526 if (newOp1 != C->getOperand(0) || newOp2 != C->getOperand(1)) {
527 Instruction* newVal = CmpInst::create(C->getOpcode(),
528 C->getPredicate(),
529 newOp1, newOp2,
Owen Anderson91c54952007-06-19 05:37:32 +0000530 C->getName()+".expr");
Owen Anderson223718c2007-06-09 18:35:31 +0000531
Owen Andersonb56fba02007-06-19 03:31:41 +0000532 uint32_t v = VN.lookup_or_add(newVal);
Owen Anderson4036ad42007-06-12 22:43:57 +0000533
Owen Andersonb56fba02007-06-19 03:31:41 +0000534 Value* leader = find_leader(availableOut[pred], v);
Owen Anderson4036ad42007-06-12 22:43:57 +0000535 if (leader == 0) {
Owen Andersona75dd4d2007-06-12 00:50:47 +0000536 createdExpressions.push_back(newVal);
Owen Anderson223718c2007-06-09 18:35:31 +0000537 return newVal;
538 } else {
Owen Anderson91c54952007-06-19 05:37:32 +0000539 VN.erase(newVal);
Owen Anderson223718c2007-06-09 18:35:31 +0000540 delete newVal;
Owen Anderson4036ad42007-06-12 22:43:57 +0000541 return leader;
Owen Anderson223718c2007-06-09 18:35:31 +0000542 }
543 }
Owen Anderson38b6b222007-06-04 18:05:26 +0000544 }
545
546 return V;
547}
548
Owen Andersonfd5683a2007-06-21 00:19:05 +0000549/// phi_translate_set - Perform phi translation on every element of a set
Owen Anderson2ff912b2007-06-21 17:57:53 +0000550void GVNPRE::phi_translate_set(SmallPtrSet<Value*, 32>& anticIn,
Owen Andersona75dd4d2007-06-12 00:50:47 +0000551 BasicBlock* pred, BasicBlock* succ,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000552 SmallPtrSet<Value*, 32>& out) {
553 for (SmallPtrSet<Value*, 32>::iterator I = anticIn.begin(),
Owen Anderson38b6b222007-06-04 18:05:26 +0000554 E = anticIn.end(); I != E; ++I) {
Owen Anderson4036ad42007-06-12 22:43:57 +0000555 Value* V = phi_translate(*I, pred, succ);
Owen Anderson38b6b222007-06-04 18:05:26 +0000556 if (V != 0)
557 out.insert(V);
Owen Anderson5fba6c12007-05-29 21:53:49 +0000558 }
559}
560
Owen Andersonfd5683a2007-06-21 00:19:05 +0000561/// dependsOnInvoke - Test if a value has an phi node as an operand, any of
562/// whose inputs is an invoke instruction. If this is true, we cannot safely
563/// PRE the instruction or anything that depends on it.
Owen Andersondd998e12007-06-18 04:42:29 +0000564bool GVNPRE::dependsOnInvoke(Value* V) {
Owen Anderson2320d432007-06-19 23:07:16 +0000565 if (PHINode* p = dyn_cast<PHINode>(V)) {
566 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
567 if (isa<InvokeInst>(*I))
Owen Andersondd998e12007-06-18 04:42:29 +0000568 return true;
Owen Anderson2320d432007-06-19 23:07:16 +0000569 return false;
570 } else {
571 return false;
Owen Anderson658f2c42007-06-16 00:26:54 +0000572 }
Owen Anderson658f2c42007-06-16 00:26:54 +0000573}
574
Owen Andersonfd5683a2007-06-21 00:19:05 +0000575/// clean - Remove all non-opaque values from the set whose operands are not
576/// themselves in the set, as well as all values that depend on invokes (see
577/// above)
Owen Anderson2ff912b2007-06-21 17:57:53 +0000578void GVNPRE::clean(SmallPtrSet<Value*, 32>& set) {
Owen Anderson0b68cda2007-06-03 05:55:58 +0000579 std::vector<Value*> worklist;
Owen Andersonbe802402007-06-08 01:03:01 +0000580 topo_sort(set, worklist);
Owen Anderson5fba6c12007-05-29 21:53:49 +0000581
Owen Andersonbe802402007-06-08 01:03:01 +0000582 for (unsigned i = 0; i < worklist.size(); ++i) {
583 Value* v = worklist[i];
Owen Anderson5fba6c12007-05-29 21:53:49 +0000584
Owen Anderson0b68cda2007-06-03 05:55:58 +0000585 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
Owen Andersonbe802402007-06-08 01:03:01 +0000586 bool lhsValid = !isa<Instruction>(BO->getOperand(0));
587 if (!lhsValid)
Owen Anderson2ff912b2007-06-21 17:57:53 +0000588 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Andersonbe802402007-06-08 01:03:01 +0000589 I != E; ++I)
Owen Andersonb56fba02007-06-19 03:31:41 +0000590 if (VN.lookup(*I) == VN.lookup(BO->getOperand(0))) {
Owen Andersonbe802402007-06-08 01:03:01 +0000591 lhsValid = true;
592 break;
593 }
Owen Andersonb364b412007-06-18 04:30:44 +0000594 if (lhsValid)
595 lhsValid = !dependsOnInvoke(BO->getOperand(0));
Owen Anderson0b68cda2007-06-03 05:55:58 +0000596
Owen Andersonbe802402007-06-08 01:03:01 +0000597 bool rhsValid = !isa<Instruction>(BO->getOperand(1));
598 if (!rhsValid)
Owen Anderson2ff912b2007-06-21 17:57:53 +0000599 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Andersonf1c04e12007-06-18 04:31:21 +0000600 I != E; ++I)
Owen Andersonb56fba02007-06-19 03:31:41 +0000601 if (VN.lookup(*I) == VN.lookup(BO->getOperand(1))) {
Owen Andersonf1c04e12007-06-18 04:31:21 +0000602 rhsValid = true;
603 break;
604 }
Owen Andersonb364b412007-06-18 04:30:44 +0000605 if (rhsValid)
606 rhsValid = !dependsOnInvoke(BO->getOperand(1));
Owen Anderson5fba6c12007-05-29 21:53:49 +0000607
Owen Anderson0b68cda2007-06-03 05:55:58 +0000608 if (!lhsValid || !rhsValid)
609 set.erase(BO);
Owen Anderson223718c2007-06-09 18:35:31 +0000610 } else if (CmpInst* C = dyn_cast<CmpInst>(v)) {
611 bool lhsValid = !isa<Instruction>(C->getOperand(0));
612 if (!lhsValid)
Owen Anderson2ff912b2007-06-21 17:57:53 +0000613 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Anderson223718c2007-06-09 18:35:31 +0000614 I != E; ++I)
Owen Andersonb56fba02007-06-19 03:31:41 +0000615 if (VN.lookup(*I) == VN.lookup(C->getOperand(0))) {
Owen Anderson223718c2007-06-09 18:35:31 +0000616 lhsValid = true;
617 break;
618 }
Owen Anderson2320d432007-06-19 23:07:16 +0000619 if (lhsValid)
620 lhsValid = !dependsOnInvoke(C->getOperand(0));
Owen Anderson658f2c42007-06-16 00:26:54 +0000621
Owen Anderson223718c2007-06-09 18:35:31 +0000622 bool rhsValid = !isa<Instruction>(C->getOperand(1));
623 if (!rhsValid)
Owen Anderson2ff912b2007-06-21 17:57:53 +0000624 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Anderson223718c2007-06-09 18:35:31 +0000625 I != E; ++I)
Owen Andersonb56fba02007-06-19 03:31:41 +0000626 if (VN.lookup(*I) == VN.lookup(C->getOperand(1))) {
Owen Anderson223718c2007-06-09 18:35:31 +0000627 rhsValid = true;
628 break;
629 }
Owen Anderson2320d432007-06-19 23:07:16 +0000630 if (rhsValid)
631 rhsValid = !dependsOnInvoke(C->getOperand(1));
Owen Anderson223718c2007-06-09 18:35:31 +0000632
633 if (!lhsValid || !rhsValid)
634 set.erase(C);
Owen Anderson0b68cda2007-06-03 05:55:58 +0000635 }
Owen Anderson5fba6c12007-05-29 21:53:49 +0000636 }
637}
638
Owen Andersonfd5683a2007-06-21 00:19:05 +0000639/// topo_sort - Given a set of values, sort them by topological
640/// order into the provided vector.
Owen Anderson2ff912b2007-06-21 17:57:53 +0000641void GVNPRE::topo_sort(SmallPtrSet<Value*, 32>& set, std::vector<Value*>& vec) {
642 SmallPtrSet<Value*, 32> toErase;
643 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Anderson331bf6a2007-05-31 22:44:11 +0000644 I != E; ++I) {
Owen Anderson0b68cda2007-06-03 05:55:58 +0000645 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
Owen Anderson2ff912b2007-06-21 17:57:53 +0000646 for (SmallPtrSet<Value*, 32>::iterator SI = set.begin(); SI != E; ++SI) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000647 if (VN.lookup(BO->getOperand(0)) == VN.lookup(*SI) ||
648 VN.lookup(BO->getOperand(1)) == VN.lookup(*SI)) {
Owen Andersonbe802402007-06-08 01:03:01 +0000649 toErase.insert(*SI);
Owen Anderson0b68cda2007-06-03 05:55:58 +0000650 }
Owen Anderson223718c2007-06-09 18:35:31 +0000651 }
652 else if (CmpInst* C = dyn_cast<CmpInst>(*I))
Owen Anderson2ff912b2007-06-21 17:57:53 +0000653 for (SmallPtrSet<Value*, 32>::iterator SI = set.begin(); SI != E; ++SI) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000654 if (VN.lookup(C->getOperand(0)) == VN.lookup(*SI) ||
655 VN.lookup(C->getOperand(1)) == VN.lookup(*SI)) {
Owen Anderson223718c2007-06-09 18:35:31 +0000656 toErase.insert(*SI);
657 }
658 }
Owen Anderson331bf6a2007-05-31 22:44:11 +0000659 }
660
Owen Anderson0b68cda2007-06-03 05:55:58 +0000661 std::vector<Value*> Q;
Owen Anderson2ff912b2007-06-21 17:57:53 +0000662 for (SmallPtrSet<Value*, 32>::iterator I = set.begin(), E = set.end();
Owen Andersonbe802402007-06-08 01:03:01 +0000663 I != E; ++I) {
Owen Anderson2ff912b2007-06-21 17:57:53 +0000664 if (toErase.count(*I) == 0)
Owen Andersonbe802402007-06-08 01:03:01 +0000665 Q.push_back(*I);
666 }
Owen Anderson331bf6a2007-05-31 22:44:11 +0000667
Owen Anderson2ff912b2007-06-21 17:57:53 +0000668 SmallPtrSet<Value*, 32> visited;
Owen Anderson331bf6a2007-05-31 22:44:11 +0000669 while (!Q.empty()) {
Owen Anderson0b68cda2007-06-03 05:55:58 +0000670 Value* e = Q.back();
671
672 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000673 Value* l = find_leader(set, VN.lookup(BO->getOperand(0)));
674 Value* r = find_leader(set, VN.lookup(BO->getOperand(1)));
Owen Anderson0b68cda2007-06-03 05:55:58 +0000675
Owen Andersonddbe4302007-06-05 23:46:12 +0000676 if (l != 0 && isa<Instruction>(l) &&
Owen Anderson2ff912b2007-06-21 17:57:53 +0000677 visited.count(l) == 0)
Owen Anderson0b68cda2007-06-03 05:55:58 +0000678 Q.push_back(l);
Owen Andersonddbe4302007-06-05 23:46:12 +0000679 else if (r != 0 && isa<Instruction>(r) &&
Owen Anderson2ff912b2007-06-21 17:57:53 +0000680 visited.count(r) == 0)
Owen Anderson0b68cda2007-06-03 05:55:58 +0000681 Q.push_back(r);
682 else {
683 vec.push_back(e);
684 visited.insert(e);
685 Q.pop_back();
686 }
Owen Anderson223718c2007-06-09 18:35:31 +0000687 } else if (CmpInst* C = dyn_cast<CmpInst>(e)) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000688 Value* l = find_leader(set, VN.lookup(C->getOperand(0)));
689 Value* r = find_leader(set, VN.lookup(C->getOperand(1)));
Owen Anderson223718c2007-06-09 18:35:31 +0000690
691 if (l != 0 && isa<Instruction>(l) &&
Owen Anderson2ff912b2007-06-21 17:57:53 +0000692 visited.count(l) == 0)
Owen Anderson223718c2007-06-09 18:35:31 +0000693 Q.push_back(l);
694 else if (r != 0 && isa<Instruction>(r) &&
Owen Anderson2ff912b2007-06-21 17:57:53 +0000695 visited.count(r) == 0)
Owen Anderson223718c2007-06-09 18:35:31 +0000696 Q.push_back(r);
697 else {
698 vec.push_back(e);
699 visited.insert(e);
700 Q.pop_back();
701 }
Owen Anderson0b68cda2007-06-03 05:55:58 +0000702 } else {
Owen Anderson331bf6a2007-05-31 22:44:11 +0000703 visited.insert(e);
704 vec.push_back(e);
705 Q.pop_back();
Owen Anderson331bf6a2007-05-31 22:44:11 +0000706 }
707 }
708}
709
Owen Andersonfd5683a2007-06-21 00:19:05 +0000710/// dump - Dump a set of values to standard error
Owen Anderson2ff912b2007-06-21 17:57:53 +0000711void GVNPRE::dump(const SmallPtrSet<Value*, 32>& s) const {
Owen Anderson4a6ec8f2007-05-29 23:15:21 +0000712 DOUT << "{ ";
Owen Anderson2ff912b2007-06-21 17:57:53 +0000713 for (SmallPtrSet<Value*, 32>::iterator I = s.begin(), E = s.end();
Owen Anderson0eca9aa2007-06-03 22:02:14 +0000714 I != E; ++I) {
715 DEBUG((*I)->dump());
716 }
717 DOUT << "}\n\n";
718}
719
Owen Andersonfd5683a2007-06-21 00:19:05 +0000720/// elimination - Phase 3 of the main algorithm. Perform full redundancy
721/// elimination by walking the dominator tree and removing any instruction that
722/// is dominated by another instruction with the same value number.
Owen Anderson06c1e582007-06-20 22:10:02 +0000723bool GVNPRE::elimination() {
Owen Anderson42769842007-06-12 16:57:50 +0000724 DOUT << "\n\nPhase 3: Elimination\n\n";
725
Owen Anderson06c1e582007-06-20 22:10:02 +0000726 bool changed_function = false;
727
Owen Anderson42769842007-06-12 16:57:50 +0000728 std::vector<std::pair<Instruction*, Value*> > replace;
729 std::vector<Instruction*> erase;
730
731 DominatorTree& DT = getAnalysis<DominatorTree>();
732
733 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
734 E = df_end(DT.getRootNode()); DI != E; ++DI) {
735 BasicBlock* BB = DI->getBlock();
736
737 DOUT << "Block: " << BB->getName() << "\n";
Owen Anderson7b0fb442007-06-20 00:43:33 +0000738 dump(availableOut[BB]);
Owen Anderson42769842007-06-12 16:57:50 +0000739 DOUT << "\n\n";
740
741 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
742 BI != BE; ++BI) {
743
744 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI)) {
Owen Andersonb56fba02007-06-19 03:31:41 +0000745 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
Owen Anderson42769842007-06-12 16:57:50 +0000746
747 if (leader != 0)
748 if (Instruction* Instr = dyn_cast<Instruction>(leader))
749 if (Instr->getParent() != 0 && Instr != BI) {
750 replace.push_back(std::make_pair(BI, leader));
751 erase.push_back(BI);
752 ++NumEliminated;
753 }
754 }
755 }
756 }
757
758 while (!replace.empty()) {
759 std::pair<Instruction*, Value*> rep = replace.back();
760 replace.pop_back();
761 rep.first->replaceAllUsesWith(rep.second);
Owen Andersonb0714bb2007-06-20 18:30:20 +0000762 changed_function = true;
Owen Anderson42769842007-06-12 16:57:50 +0000763 }
764
765 for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
766 I != E; ++I)
767 (*I)->eraseFromParent();
Owen Anderson06c1e582007-06-20 22:10:02 +0000768
769 return changed_function;
Owen Anderson42769842007-06-12 16:57:50 +0000770}
771
Owen Andersonfd5683a2007-06-21 00:19:05 +0000772/// cleanup - Delete any extraneous values that were created to represent
773/// expressions without leaders.
Owen Anderson42769842007-06-12 16:57:50 +0000774void GVNPRE::cleanup() {
775 while (!createdExpressions.empty()) {
776 Instruction* I = createdExpressions.back();
777 createdExpressions.pop_back();
778
779 delete I;
780 }
781}
782
Owen Andersonfd5683a2007-06-21 00:19:05 +0000783/// buildsets_availout - When calculating availability, handle an instruction
784/// by inserting it into the appropriate sets
Owen Anderson06c1e582007-06-20 22:10:02 +0000785void GVNPRE::buildsets_availout(BasicBlock::iterator I,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000786 SmallPtrSet<Value*, 32>& currAvail,
787 SmallPtrSet<PHINode*, 32>& currPhis,
788 SmallPtrSet<Value*, 32>& currExps,
789 SmallPtrSet<Value*, 32>& currTemps) {
Owen Anderson06c1e582007-06-20 22:10:02 +0000790 // Handle PHI nodes...
791 if (PHINode* p = dyn_cast<PHINode>(I)) {
792 VN.lookup_or_add(p);
793 currPhis.insert(p);
794
795 // Handle binary ops...
796 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(I)) {
797 Value* leftValue = BO->getOperand(0);
798 Value* rightValue = BO->getOperand(1);
799
800 VN.lookup_or_add(BO);
801
802 if (isa<Instruction>(leftValue))
803 val_insert(currExps, leftValue);
804 if (isa<Instruction>(rightValue))
805 val_insert(currExps, rightValue);
806 val_insert(currExps, BO);
807
808 // Handle cmp ops...
809 } else if (CmpInst* C = dyn_cast<CmpInst>(I)) {
810 Value* leftValue = C->getOperand(0);
811 Value* rightValue = C->getOperand(1);
812
813 VN.lookup_or_add(C);
814
815 if (isa<Instruction>(leftValue))
816 val_insert(currExps, leftValue);
817 if (isa<Instruction>(rightValue))
818 val_insert(currExps, rightValue);
819 val_insert(currExps, C);
820
821 // Handle unsupported ops
822 } else if (!I->isTerminator()){
823 VN.lookup_or_add(I);
824 currTemps.insert(I);
825 }
826
827 if (!I->isTerminator())
828 val_insert(currAvail, I);
829}
Owen Anderson5fba6c12007-05-29 21:53:49 +0000830
Owen Andersonfd5683a2007-06-21 00:19:05 +0000831/// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
832/// set as a function of the ANTIC_IN set of the block's predecessors
Owen Anderson06c1e582007-06-20 22:10:02 +0000833void GVNPRE::buildsets_anticout(BasicBlock* BB,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000834 SmallPtrSet<Value*, 32>& anticOut,
Owen Anderson06c1e582007-06-20 22:10:02 +0000835 std::set<BasicBlock*>& visited) {
836 if (BB->getTerminator()->getNumSuccessors() == 1) {
837 if (visited.find(BB->getTerminator()->getSuccessor(0)) == visited.end())
838 phi_translate_set(VN.getMaximalValues(), BB,
839 BB->getTerminator()->getSuccessor(0), anticOut);
840 else
841 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
842 BB, BB->getTerminator()->getSuccessor(0), anticOut);
843 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
844 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
845 anticOut.insert(anticipatedIn[first].begin(), anticipatedIn[first].end());
846
847 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
848 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
Owen Anderson2ff912b2007-06-21 17:57:53 +0000849 SmallPtrSet<Value*, 32>& succAnticIn = anticipatedIn[currSucc];
Owen Anderson06c1e582007-06-20 22:10:02 +0000850
Owen Anderson2ff912b2007-06-21 17:57:53 +0000851 std::vector<Value*> temp;
852
853 for (SmallPtrSet<Value*, 32>::iterator I = anticOut.begin(),
854 E = anticOut.end(); I != E; ++I)
855 if (succAnticIn.count(*I) == 0)
856 temp.push_back(*I);
857
858 for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
859 I != E; ++I)
860 anticOut.erase(*I);
Owen Anderson06c1e582007-06-20 22:10:02 +0000861 }
862 }
863}
864
Owen Andersonfd5683a2007-06-21 00:19:05 +0000865/// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
866/// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
867/// sets populated in buildsets_availout
Owen Anderson06c1e582007-06-20 22:10:02 +0000868bool GVNPRE::buildsets_anticin(BasicBlock* BB,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000869 SmallPtrSet<Value*, 32>& anticOut,
870 SmallPtrSet<Value*, 32>& currExps,
871 SmallPtrSet<Value*, 32>& currTemps,
Owen Anderson06c1e582007-06-20 22:10:02 +0000872 std::set<BasicBlock*>& visited) {
Owen Anderson2ff912b2007-06-21 17:57:53 +0000873 SmallPtrSet<Value*, 32>& anticIn = anticipatedIn[BB];
874 SmallPtrSet<Value*, 32> old (anticIn.begin(), anticIn.end());
Owen Anderson06c1e582007-06-20 22:10:02 +0000875
876 buildsets_anticout(BB, anticOut, visited);
877
Owen Anderson2ff912b2007-06-21 17:57:53 +0000878 SmallPtrSet<Value*, 32> S;
879 for (SmallPtrSet<Value*, 32>::iterator I = anticOut.begin(),
880 E = anticOut.end(); I != E; ++I)
881 if (currTemps.count(*I) == 0)
882 S.insert(*I);
883
Owen Anderson06c1e582007-06-20 22:10:02 +0000884 anticIn.clear();
Owen Anderson2ff912b2007-06-21 17:57:53 +0000885
886 for (SmallPtrSet<Value*, 32>::iterator I = currExps.begin(),
887 E = currExps.end(); I != E; ++I)
888 if (currTemps.count(*I) == 0)
889 anticIn.insert(*I);
Owen Anderson06c1e582007-06-20 22:10:02 +0000890
Owen Anderson2ff912b2007-06-21 17:57:53 +0000891 for (SmallPtrSet<Value*, 32>::iterator I = S.begin(), E = S.end();
Owen Anderson06c1e582007-06-20 22:10:02 +0000892 I != E; ++I) {
893 // For non-opaque values, we should already have a value numbering.
894 // However, for opaques, such as constants within PHI nodes, it is
895 // possible that they have not yet received a number. Make sure they do
896 // so now.
Owen Anderson27876a32007-06-21 01:59:05 +0000897 if (!isa<BinaryOperator>(*I) && !isa<CmpInst>(*I))
898 VN.lookup_or_add(*I);
899 val_insert(anticIn, *I);
Owen Anderson06c1e582007-06-20 22:10:02 +0000900 }
901
902 clean(anticIn);
903 anticOut.clear();
904
905 if (old.size() != anticIn.size())
906 return true;
907 else
908 return false;
909}
910
Owen Andersonfd5683a2007-06-21 00:19:05 +0000911/// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
912/// and the ANTIC_IN sets.
Owen Anderson06c1e582007-06-20 22:10:02 +0000913unsigned GVNPRE::buildsets(Function& F) {
Owen Anderson2ff912b2007-06-21 17:57:53 +0000914 std::map<BasicBlock*, SmallPtrSet<Value*, 32> > generatedExpressions;
915 std::map<BasicBlock*, SmallPtrSet<PHINode*, 32> > generatedPhis;
916 std::map<BasicBlock*, SmallPtrSet<Value*, 32> > generatedTemporaries;
Owen Anderson06c1e582007-06-20 22:10:02 +0000917
Owen Anderson5fba6c12007-05-29 21:53:49 +0000918 DominatorTree &DT = getAnalysis<DominatorTree>();
919
Owen Anderson634a0632007-06-06 01:27:49 +0000920 // Phase 1, Part 1: calculate AVAIL_OUT
Owen Anderson5fba6c12007-05-29 21:53:49 +0000921
922 // Top-down walk of the dominator tree
Devang Patelbdd1aae2007-06-04 00:32:22 +0000923 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
Owen Anderson5fba6c12007-05-29 21:53:49 +0000924 E = df_end(DT.getRootNode()); DI != E; ++DI) {
925
926 // Get the sets to update for this block
Owen Anderson2ff912b2007-06-21 17:57:53 +0000927 SmallPtrSet<Value*, 32>& currExps = generatedExpressions[DI->getBlock()];
928 SmallPtrSet<PHINode*, 32>& currPhis = generatedPhis[DI->getBlock()];
929 SmallPtrSet<Value*, 32>& currTemps = generatedTemporaries[DI->getBlock()];
930 SmallPtrSet<Value*, 32>& currAvail = availableOut[DI->getBlock()];
Owen Anderson5fba6c12007-05-29 21:53:49 +0000931
Owen Andersonb56fba02007-06-19 03:31:41 +0000932 BasicBlock* BB = DI->getBlock();
933
934 // A block inherits AVAIL_OUT from its dominator
935 if (DI->getIDom() != 0)
936 currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
937 availableOut[DI->getIDom()->getBlock()].end());
938
939
940 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Owen Anderson06c1e582007-06-20 22:10:02 +0000941 BI != BE; ++BI)
942 buildsets_availout(BI, currAvail, currPhis, currExps, currTemps);
Owen Andersonb56fba02007-06-19 03:31:41 +0000943
Owen Anderson5fba6c12007-05-29 21:53:49 +0000944 }
945
Owen Anderson42769842007-06-12 16:57:50 +0000946 // If function has no exit blocks, only perform GVN
Owen Anderson5fba6c12007-05-29 21:53:49 +0000947 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
Owen Anderson42769842007-06-12 16:57:50 +0000948 if (PDT[&F.getEntryBlock()] == 0) {
Owen Anderson06c1e582007-06-20 22:10:02 +0000949 bool changed_function = elimination();
Owen Anderson42769842007-06-12 16:57:50 +0000950 cleanup();
951
Owen Anderson06c1e582007-06-20 22:10:02 +0000952 if (changed_function)
953 return 2; // Bailed early, made changes
954 else
955 return 1; // Bailed early, no changes
Owen Anderson42769842007-06-12 16:57:50 +0000956 }
957
Owen Anderson5fba6c12007-05-29 21:53:49 +0000958
Owen Anderson634a0632007-06-06 01:27:49 +0000959 // Phase 1, Part 2: calculate ANTIC_IN
Owen Anderson5fba6c12007-05-29 21:53:49 +0000960
Owen Anderson0c423072007-05-29 23:26:30 +0000961 std::set<BasicBlock*> visited;
962
Owen Anderson5fba6c12007-05-29 21:53:49 +0000963 bool changed = true;
964 unsigned iterations = 0;
965 while (changed) {
966 changed = false;
Owen Anderson2ff912b2007-06-21 17:57:53 +0000967 SmallPtrSet<Value*, 32> anticOut;
Owen Anderson5fba6c12007-05-29 21:53:49 +0000968
969 // Top-down walk of the postdominator tree
Devang Patelbdd1aae2007-06-04 00:32:22 +0000970 for (df_iterator<DomTreeNode*> PDI =
Owen Andersonbe802402007-06-08 01:03:01 +0000971 df_begin(PDT.getRootNode()), E = df_end(PDT.getRootNode());
Owen Anderson5fba6c12007-05-29 21:53:49 +0000972 PDI != E; ++PDI) {
973 BasicBlock* BB = PDI->getBlock();
Owen Andersond184c182007-06-11 16:25:17 +0000974 if (BB == 0)
975 continue;
976
Owen Anderson0c423072007-05-29 23:26:30 +0000977 visited.insert(BB);
978
Owen Anderson06c1e582007-06-20 22:10:02 +0000979 changed |= buildsets_anticin(BB, anticOut, generatedTemporaries[BB],
980 generatedExpressions[BB], visited);
Owen Anderson5fba6c12007-05-29 21:53:49 +0000981 }
Owen Anderson38b6b222007-06-04 18:05:26 +0000982
Owen Anderson5fba6c12007-05-29 21:53:49 +0000983 iterations++;
984 }
985
Owen Anderson06c1e582007-06-20 22:10:02 +0000986 return 0; // No bail, no changes
987}
988
Owen Andersonfd5683a2007-06-21 00:19:05 +0000989/// insertion_pre - When a partial redundancy has been identified, eliminate it
990/// by inserting appropriate values into the predecessors and a phi node in
991/// the main block
Owen Anderson06c1e582007-06-20 22:10:02 +0000992void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
993 std::map<BasicBlock*, Value*>& avail,
Owen Anderson2ff912b2007-06-21 17:57:53 +0000994 SmallPtrSet<Value*, 32>& new_set) {
Owen Anderson06c1e582007-06-20 22:10:02 +0000995 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
996 Value* e2 = avail[*PI];
997 if (!find_leader(availableOut[*PI], VN.lookup(e2))) {
998 User* U = cast<User>(e2);
999
1000 Value* s1 = 0;
1001 if (isa<BinaryOperator>(U->getOperand(0)) ||
1002 isa<CmpInst>(U->getOperand(0)))
1003 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1004 else
1005 s1 = U->getOperand(0);
1006
1007 Value* s2 = 0;
1008 if (isa<BinaryOperator>(U->getOperand(1)) ||
1009 isa<CmpInst>(U->getOperand(1)))
1010 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1011 else
1012 s2 = U->getOperand(1);
1013
1014 Value* newVal = 0;
1015 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1016 newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1017 BO->getName()+".gvnpre",
1018 (*PI)->getTerminator());
1019 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1020 newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1021 C->getName()+".gvnpre",
1022 (*PI)->getTerminator());
1023
1024 VN.add(newVal, VN.lookup(U));
1025
Owen Anderson2ff912b2007-06-21 17:57:53 +00001026 SmallPtrSet<Value*, 32>& predAvail = availableOut[*PI];
Owen Anderson06c1e582007-06-20 22:10:02 +00001027 val_replace(predAvail, newVal);
Owen Andersonfd5683a2007-06-21 00:19:05 +00001028
Owen Anderson06c1e582007-06-20 22:10:02 +00001029 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1030 if (av != avail.end())
1031 avail.erase(av);
1032 avail.insert(std::make_pair(*PI, newVal));
1033
1034 ++NumInsertedVals;
1035 }
1036 }
1037
1038 PHINode* p = 0;
1039
1040 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1041 if (p == 0)
1042 p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1043
1044 p->addIncoming(avail[*PI], *PI);
1045 }
1046
1047 VN.add(p, VN.lookup(e));
Owen Anderson06c1e582007-06-20 22:10:02 +00001048 val_replace(availableOut[BB], p);
Owen Anderson06c1e582007-06-20 22:10:02 +00001049 new_set.insert(p);
1050
1051 ++NumInsertedPhis;
1052}
1053
Owen Andersonfd5683a2007-06-21 00:19:05 +00001054/// insertion_mergepoint - When walking the dom tree, check at each merge
1055/// block for the possibility of a partial redundancy. If present, eliminate it
Owen Anderson06c1e582007-06-20 22:10:02 +00001056unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1057 df_iterator<DomTreeNode*> D,
Owen Anderson2ff912b2007-06-21 17:57:53 +00001058 SmallPtrSet<Value*, 32>& new_set) {
Owen Anderson06c1e582007-06-20 22:10:02 +00001059 bool changed_function = false;
1060 bool new_stuff = false;
1061
1062 BasicBlock* BB = D->getBlock();
1063 for (unsigned i = 0; i < workList.size(); ++i) {
1064 Value* e = workList[i];
1065
1066 if (isa<BinaryOperator>(e) || isa<CmpInst>(e)) {
1067 if (find_leader(availableOut[D->getIDom()->getBlock()],
1068 VN.lookup(e)) != 0)
1069 continue;
1070
1071 std::map<BasicBlock*, Value*> avail;
1072 bool by_some = false;
1073 int num_avail = 0;
1074
1075 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1076 ++PI) {
1077 Value *e2 = phi_translate(e, *PI, BB);
1078 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1079
1080 if (e3 == 0) {
1081 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1082 if (av != avail.end())
1083 avail.erase(av);
1084 avail.insert(std::make_pair(*PI, e2));
1085 } else {
1086 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1087 if (av != avail.end())
1088 avail.erase(av);
1089 avail.insert(std::make_pair(*PI, e3));
1090
1091 by_some = true;
1092 num_avail++;
1093 }
1094 }
1095
1096 if (by_some && num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
1097 insertion_pre(e, BB, avail, new_set);
1098
1099 changed_function = true;
1100 new_stuff = true;
1101 }
1102 }
1103 }
1104
1105 unsigned retval = 0;
1106 if (changed_function)
1107 retval += 1;
1108 if (new_stuff)
1109 retval += 2;
1110
1111 return retval;
1112}
1113
Owen Andersonfd5683a2007-06-21 00:19:05 +00001114/// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1115/// merge points. When one is found, check for a partial redundancy. If one is
1116/// present, eliminate it. Repeat this walk until no changes are made.
Owen Anderson06c1e582007-06-20 22:10:02 +00001117bool GVNPRE::insertion(Function& F) {
1118 bool changed_function = false;
1119
1120 DominatorTree &DT = getAnalysis<DominatorTree>();
Owen Andersonbe802402007-06-08 01:03:01 +00001121
Owen Anderson2ff912b2007-06-21 17:57:53 +00001122 std::map<BasicBlock*, SmallPtrSet<Value*, 32> > new_sets;
Owen Andersonbe802402007-06-08 01:03:01 +00001123 bool new_stuff = true;
1124 while (new_stuff) {
1125 new_stuff = false;
Owen Andersonbe802402007-06-08 01:03:01 +00001126 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1127 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1128 BasicBlock* BB = DI->getBlock();
1129
Owen Andersond184c182007-06-11 16:25:17 +00001130 if (BB == 0)
1131 continue;
1132
Owen Anderson2ff912b2007-06-21 17:57:53 +00001133 SmallPtrSet<Value*, 32>& new_set = new_sets[BB];
1134 SmallPtrSet<Value*, 32>& availOut = availableOut[BB];
1135 SmallPtrSet<Value*, 32>& anticIn = anticipatedIn[BB];
Owen Andersonbe802402007-06-08 01:03:01 +00001136
Owen Anderson55994f22007-06-08 20:44:02 +00001137 new_set.clear();
1138
Owen Andersonbe802402007-06-08 01:03:01 +00001139 // Replace leaders with leaders inherited from dominator
1140 if (DI->getIDom() != 0) {
Owen Anderson2ff912b2007-06-21 17:57:53 +00001141 SmallPtrSet<Value*, 32>& dom_set = new_sets[DI->getIDom()->getBlock()];
1142 for (SmallPtrSet<Value*, 32>::iterator I = dom_set.begin(),
Owen Andersonbe802402007-06-08 01:03:01 +00001143 E = dom_set.end(); I != E; ++I) {
1144 new_set.insert(*I);
Owen Andersonb56fba02007-06-19 03:31:41 +00001145 val_replace(availOut, *I);
Owen Andersonbe802402007-06-08 01:03:01 +00001146 }
1147 }
1148
1149 // If there is more than one predecessor...
1150 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1151 std::vector<Value*> workList;
1152 topo_sort(anticIn, workList);
1153
1154 DOUT << "Merge Block: " << BB->getName() << "\n";
1155 DOUT << "ANTIC_IN: ";
Owen Anderson7b0fb442007-06-20 00:43:33 +00001156 dump(anticIn);
Owen Andersonbe802402007-06-08 01:03:01 +00001157 DOUT << "\n";
1158
Owen Anderson06c1e582007-06-20 22:10:02 +00001159 unsigned result = insertion_mergepoint(workList, DI, new_set);
1160 if (result & 1)
1161 changed_function = true;
1162 if (result & 2)
1163 new_stuff = true;
Owen Andersonbe802402007-06-08 01:03:01 +00001164 }
1165 }
Owen Andersonbe802402007-06-08 01:03:01 +00001166 }
Owen Anderson634a0632007-06-06 01:27:49 +00001167
Owen Anderson06c1e582007-06-20 22:10:02 +00001168 return changed_function;
1169}
1170
Owen Andersonfd5683a2007-06-21 00:19:05 +00001171// GVNPRE::runOnFunction - This is the main transformation entry point for a
1172// function.
1173//
Owen Anderson06c1e582007-06-20 22:10:02 +00001174bool GVNPRE::runOnFunction(Function &F) {
Owen Andersonfd5683a2007-06-21 00:19:05 +00001175 // Clean out global sets from any previous functions
Owen Anderson06c1e582007-06-20 22:10:02 +00001176 VN.clear();
1177 createdExpressions.clear();
1178 availableOut.clear();
1179 anticipatedIn.clear();
1180
1181 bool changed_function = false;
1182
1183 // Phase 1: BuildSets
Owen Andersonfd5683a2007-06-21 00:19:05 +00001184 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1185 // NOTE: If full postdom information is no available, this will bail
1186 // early, performing GVN but not PRE
Owen Anderson06c1e582007-06-20 22:10:02 +00001187 unsigned bail = buildsets(F);
1188 //If a bail occurred, terminate early
1189 if (bail != 0)
1190 return (bail == 2);
1191
1192 // Phase 2: Insert
Owen Andersonfd5683a2007-06-21 00:19:05 +00001193 // This phase inserts values to make partially redundant values
1194 // fully redundant
Owen Anderson06c1e582007-06-20 22:10:02 +00001195 changed_function |= insertion(F);
1196
Owen Anderson634a0632007-06-06 01:27:49 +00001197 // Phase 3: Eliminate
Owen Andersonfd5683a2007-06-21 00:19:05 +00001198 // This phase performs trivial full redundancy elimination
Owen Anderson06c1e582007-06-20 22:10:02 +00001199 changed_function |= elimination();
Owen Anderson55994f22007-06-08 20:44:02 +00001200
Owen Andersonbe802402007-06-08 01:03:01 +00001201 // Phase 4: Cleanup
Owen Andersonfd5683a2007-06-21 00:19:05 +00001202 // This phase cleans up values that were created solely
1203 // as leaders for expressions
Owen Anderson42769842007-06-12 16:57:50 +00001204 cleanup();
Owen Andersonbe802402007-06-08 01:03:01 +00001205
Owen Andersonb0714bb2007-06-20 18:30:20 +00001206 return changed_function;
Owen Anderson5fba6c12007-05-29 21:53:49 +00001207}