1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
16 // live ranges, and should be used with caution on platforms that a very
17 // sensitive to register pressure.
19 //===----------------------------------------------------------------------===//
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"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
40 bool operator()(Value* left, Value* right) {
41 if (!isa<BinaryOperator>(left) || !isa<BinaryOperator>(right))
44 BinaryOperator* BO1 = cast<BinaryOperator>(left);
45 BinaryOperator* BO2 = cast<BinaryOperator>(right);
47 if ((*this)(BO1->getOperand(0), BO2->getOperand(0)))
49 else if ((*this)(BO2->getOperand(0), BO1->getOperand(0)))
52 return (*this)(BO1->getOperand(1), BO2->getOperand(1));
58 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
59 bool runOnFunction(Function &F);
61 static char ID; // Pass identification, replacement for typeid
62 GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; }
65 uint32_t nextValueNumber;
66 typedef std::map<Value*, uint32_t, ExprLT> ValueTable;
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<DominatorTree>();
71 AU.addRequired<PostDominatorTree>();
75 // FIXME: eliminate or document these better
76 void dump(ValueTable& VN, std::set<Value*>& s);
77 void dump_unique(ValueTable& VN, std::set<Value*, ExprLT>& s);
78 void clean(ValueTable VN, std::set<Value*, ExprLT>& set);
79 bool add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V);
80 Value* find_leader(ValueTable VN, std::set<Value*, ExprLT>& vals, Value* v);
81 Value* phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
82 std::set<Value*, ExprLT>& set,
83 Value* V, BasicBlock* pred);
84 void phi_translate_set(ValueTable& VN, std::set<Value*, ExprLT>& MS,
85 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
86 std::set<Value*, ExprLT>& out);
88 void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
89 std::vector<Value*>& vec);
91 // For a given block, calculate the generated expressions, temporaries,
92 // and the AVAIL_OUT set
93 void CalculateAvailOut(ValueTable& VN, std::set<Value*, ExprLT>& MS,
95 std::set<Value*, ExprLT>& currExps,
96 std::set<PHINode*>& currPhis,
97 std::set<Value*>& currTemps,
98 std::set<Value*, ExprLT>& currAvail,
99 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
107 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
109 RegisterPass<GVNPRE> X("gvnpre",
110 "Global Value Numbering/Partial Redundancy Elimination");
114 bool GVNPRE::add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V) {
115 std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, nextValueNumber));
118 if (isa<BinaryOperator>(V) || isa<PHINode>(V))
123 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
124 std::set<Value*, ExprLT>& vals,
127 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
129 if (!cmp(v, *I) && !cmp(*I, v))
135 Value* GVNPRE::phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
136 std::set<Value*, ExprLT>& set,
137 Value* V, BasicBlock* pred) {
141 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
142 Value* newOp1 = isa<Instruction>(BO->getOperand(0))
143 ? phi_translate(VN, MS, set,
144 find_leader(VN, set, BO->getOperand(0)),
150 Value* newOp2 = isa<Instruction>(BO->getOperand(1))
151 ? phi_translate(VN, MS, set,
152 find_leader(VN, set, BO->getOperand(1)),
158 if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
159 Value* newVal = BinaryOperator::create(BO->getOpcode(),
161 BO->getName()+".gvnpre");
163 if (!find_leader(VN, set, newVal)) {
171 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
172 if (P->getParent() == pred->getTerminator()->getSuccessor(0))
173 return P->getIncomingValueForBlock(pred);
179 void GVNPRE::phi_translate_set(GVNPRE::ValueTable& VN,
180 std::set<Value*, ExprLT>& MS,
181 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
182 std::set<Value*, ExprLT>& out) {
183 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(),
184 E = anticIn.end(); I != E; ++I) {
185 Value* V = phi_translate(VN, MS, anticIn, *I, B);
191 // Remove all expressions whose operands are not themselves in the set
192 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
193 std::vector<Value*> worklist;
194 topo_sort(VN, set, worklist);
196 while (!worklist.empty()) {
197 Value* v = worklist.back();
200 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
201 bool lhsValid = false;
202 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
204 if (VN[*I] == VN[BO->getOperand(0)]);
207 bool rhsValid = false;
208 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
210 if (VN[*I] == VN[BO->getOperand(1)]);
213 if (!lhsValid || !rhsValid)
219 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
220 std::set<Value*, ExprLT>& set,
221 std::vector<Value*>& vec) {
222 std::set<Value*, ExprLT> toErase;
223 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
225 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
226 for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
227 if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
233 std::vector<Value*> Q;
234 std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
235 std::set_difference(set.begin(), set.end(),
236 toErase.begin(), toErase.end(),
239 std::set<Value*> visited;
243 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
244 Value* l = find_leader(VN, set, BO->getOperand(0));
245 Value* r = find_leader(VN, set, BO->getOperand(1));
247 if (l != 0 && isa<Instruction>(l) &&
248 visited.find(l) == visited.end())
250 else if (r != 0 && isa<Instruction>(r) &&
251 visited.find(r) == visited.end())
267 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*>& s) {
269 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
276 void GVNPRE::dump_unique(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
278 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
285 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
287 std::set<Value*, ExprLT>& currExps,
288 std::set<PHINode*>& currPhis,
289 std::set<Value*>& currTemps,
290 std::set<Value*, ExprLT>& currAvail,
291 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
293 BasicBlock* BB = DI->getBlock();
295 // A block inherits AVAIL_OUT from its dominator
296 if (DI->getIDom() != 0)
297 currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
298 availOut[DI->getIDom()->getBlock()].end());
301 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
304 // Handle PHI nodes...
305 if (PHINode* p = dyn_cast<PHINode>(BI)) {
309 // Handle binary ops...
310 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
311 Value* leftValue = BO->getOperand(0);
312 Value* rightValue = BO->getOperand(1);
316 if (isa<Instruction>(leftValue))
317 currExps.insert(leftValue);
318 if (isa<Instruction>(rightValue))
319 currExps.insert(rightValue);
322 //currTemps.insert(BO);
324 // Handle unsupported ops
325 } else if (!BI->isTerminator()){
327 currTemps.insert(BI);
330 if (!BI->isTerminator())
331 currAvail.insert(BI);
335 bool GVNPRE::runOnFunction(Function &F) {
337 std::set<Value*, ExprLT> maximalSet;
339 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
340 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
341 std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
342 std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
343 std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
345 DominatorTree &DT = getAnalysis<DominatorTree>();
347 // First Phase of BuildSets - calculate AVAIL_OUT
349 // Top-down walk of the dominator tree
350 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
351 E = df_end(DT.getRootNode()); DI != E; ++DI) {
353 // Get the sets to update for this block
354 std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
355 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
356 std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
357 std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];
359 CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
360 currTemps, currAvail, availableOut);
363 DOUT << "Maximal Set: ";
364 dump_unique(VN, maximalSet);
367 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
369 // Second Phase of BuildSets - calculate ANTIC_IN
371 std::set<BasicBlock*> visited;
374 unsigned iterations = 0;
377 std::set<Value*, ExprLT> anticOut;
379 // Top-down walk of the postdominator tree
380 for (df_iterator<DomTreeNode*> PDI =
381 df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
383 BasicBlock* BB = PDI->getBlock();
384 DOUT << "Block: " << BB->getName() << "\n";
386 dump(VN, generatedTemporaries[BB]);
390 dump_unique(VN, generatedExpressions[BB]);
393 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
394 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
396 if (BB->getTerminator()->getNumSuccessors() == 1) {
397 if (visited.find(BB->getTerminator()->getSuccessor(0)) ==
399 phi_translate_set(VN, maximalSet, maximalSet, BB, anticOut);
401 phi_translate_set(VN, maximalSet,
402 anticipatedIn[BB->getTerminator()->getSuccessor(0)], BB, anticOut);
403 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
404 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
405 anticOut.insert(anticipatedIn[first].begin(),
406 anticipatedIn[first].end());
407 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
408 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
409 std::set<Value*, ExprLT>& succAnticIn = anticipatedIn[currSucc];
411 std::set<Value*, ExprLT> temp;
412 std::insert_iterator<std::set<Value*, ExprLT> > temp_ins(temp,
414 std::set_intersection(anticOut.begin(), anticOut.end(),
415 succAnticIn.begin(), succAnticIn.end(),
419 anticOut.insert(temp.begin(), temp.end());
423 DOUT << "ANTIC_OUT: ";
424 dump_unique(VN, anticOut);
427 std::set<Value*, ExprLT> S;
428 std::insert_iterator<std::set<Value*, ExprLT> > s_ins(S, S.begin());
429 std::set_union(anticOut.begin(), anticOut.end(),
430 generatedExpressions[BB].begin(),
431 generatedExpressions[BB].end(),
436 for (std::set<Value*, ExprLT>::iterator I = S.begin(), E = S.end();
438 if (generatedTemporaries[BB].find(*I) == generatedTemporaries[BB].end())
444 DOUT << "ANTIC_IN: ";
445 dump_unique(VN, anticIn);
448 if (old.size() != anticIn.size())
457 DOUT << "Iterations: " << iterations << "\n";
459 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
460 DOUT << "Name: " << I->getName().c_str() << "\n";
463 dump(VN, generatedTemporaries[I]);
467 dump_unique(VN, generatedExpressions[I]);
470 DOUT << "ANTIC_IN: ";
471 dump_unique(VN, anticipatedIn[I]);
474 DOUT << "AVAIL_OUT: ";
475 dump_unique(VN, availableOut[I]);