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, uint32_t 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,
126 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
134 Value* GVNPRE::phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
135 std::set<Value*, ExprLT>& set,
136 Value* V, BasicBlock* pred) {
140 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
141 Value* newOp1 = isa<Instruction>(BO->getOperand(0))
142 ? phi_translate(VN, MS, set,
143 find_leader(VN, set, VN[BO->getOperand(0)]),
149 Value* newOp2 = isa<Instruction>(BO->getOperand(1))
150 ? phi_translate(VN, MS, set,
151 find_leader(VN, set, VN[BO->getOperand(0)]),
157 if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
158 Value* newVal = BinaryOperator::create(BO->getOpcode(),
160 BO->getName()+".gvnpre");
162 if (!find_leader(VN, set, VN[newVal]))
167 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
168 if (P->getParent() == pred->getTerminator()->getSuccessor(0))
169 return P->getIncomingValueForBlock(pred);
175 void GVNPRE::phi_translate_set(GVNPRE::ValueTable& VN,
176 std::set<Value*, ExprLT>& MS,
177 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
178 std::set<Value*, ExprLT>& out) {
179 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(),
180 E = anticIn.end(); I != E; ++I) {
181 Value* V = phi_translate(VN, MS, anticIn, *I, B);
187 // Remove all expressions whose operands are not themselves in the set
188 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
189 std::vector<Value*> worklist;
190 topo_sort(VN, set, worklist);
192 while (!worklist.empty()) {
193 Value* v = worklist.back();
196 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
197 bool lhsValid = false;
198 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
200 if (VN[*I] == VN[BO->getOperand(0)]);
203 bool rhsValid = false;
204 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
206 if (VN[*I] == VN[BO->getOperand(1)]);
209 if (!lhsValid || !rhsValid)
215 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
216 std::set<Value*, ExprLT>& set,
217 std::vector<Value*>& vec) {
218 std::set<Value*, ExprLT> toErase;
219 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
221 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
222 for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
223 if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
229 std::vector<Value*> Q;
230 std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
231 std::set_difference(set.begin(), set.end(),
232 toErase.begin(), toErase.end(),
235 std::set<Value*, ExprLT> visited;
239 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
240 Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
241 Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
243 if (l != 0 && visited.find(l) == visited.end())
245 else if (r != 0 && visited.find(r) == visited.end())
261 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*>& s) {
263 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
270 void GVNPRE::dump_unique(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
272 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
279 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
281 std::set<Value*, ExprLT>& currExps,
282 std::set<PHINode*>& currPhis,
283 std::set<Value*>& currTemps,
284 std::set<Value*, ExprLT>& currAvail,
285 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
287 BasicBlock* BB = DI->getBlock();
289 // A block inherits AVAIL_OUT from its dominator
290 if (DI->getIDom() != 0)
291 currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
292 availOut[DI->getIDom()->getBlock()].end());
295 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
298 // Handle PHI nodes...
299 if (PHINode* p = dyn_cast<PHINode>(BI)) {
303 // Handle binary ops...
304 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
305 Value* leftValue = BO->getOperand(0);
306 Value* rightValue = BO->getOperand(1);
310 if (isa<Instruction>(leftValue))
311 currExps.insert(leftValue);
312 if (isa<Instruction>(rightValue))
313 currExps.insert(rightValue);
316 currTemps.insert(BO);
318 // Handle unsupported ops
319 } else if (!BI->isTerminator()){
321 currTemps.insert(BI);
324 if (!BI->isTerminator())
325 currAvail.insert(BI);
329 bool GVNPRE::runOnFunction(Function &F) {
331 std::set<Value*, ExprLT> maximalSet;
333 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
334 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
335 std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
336 std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
337 std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
339 DominatorTree &DT = getAnalysis<DominatorTree>();
341 // First Phase of BuildSets - calculate AVAIL_OUT
343 // Top-down walk of the dominator tree
344 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
345 E = df_end(DT.getRootNode()); DI != E; ++DI) {
347 // Get the sets to update for this block
348 std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
349 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
350 std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
351 std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];
353 CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
354 currTemps, currAvail, availableOut);
357 DOUT << "Maximal Set: ";
358 dump_unique(VN, maximalSet);
361 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
363 // Second Phase of BuildSets - calculate ANTIC_IN
365 std::set<BasicBlock*> visited;
368 unsigned iterations = 0;
371 std::set<Value*, ExprLT> anticOut;
373 // Top-down walk of the postdominator tree
374 for (df_iterator<DomTreeNode*> PDI =
375 df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
377 BasicBlock* BB = PDI->getBlock();
378 DOUT << "Block: " << BB->getName() << "\n";
380 dump(VN, generatedTemporaries[BB]);
384 dump_unique(VN, generatedExpressions[BB]);
387 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
388 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
390 if (BB->getTerminator()->getNumSuccessors() == 1) {
391 if (visited.find(BB->getTerminator()->getSuccessor(0)) ==
393 phi_translate_set(VN, maximalSet, maximalSet, BB, anticOut);
395 phi_translate_set(VN, maximalSet,
396 anticipatedIn[BB->getTerminator()->getSuccessor(0)], BB, anticOut);
397 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
398 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
399 anticOut.insert(anticipatedIn[first].begin(),
400 anticipatedIn[first].end());
401 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
402 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
403 std::set<Value*, ExprLT>& succAnticIn = anticipatedIn[currSucc];
405 std::set<Value*, ExprLT> temp;
406 std::insert_iterator<std::set<Value*, ExprLT> > temp_ins(temp,
408 std::set_intersection(anticOut.begin(), anticOut.end(),
409 succAnticIn.begin(), succAnticIn.end(),
413 anticOut.insert(temp.begin(), temp.end());
417 DOUT << "ANTIC_OUT: ";
418 dump_unique(VN, anticOut);
421 std::set<Value*, ExprLT> S;
422 std::insert_iterator<std::set<Value*, ExprLT> > s_ins(S, S.begin());
423 std::set_union(anticOut.begin(), anticOut.end(),
424 generatedExpressions[BB].begin(),
425 generatedExpressions[BB].end(),
430 for (std::set<Value*, ExprLT>::iterator I = S.begin(), E = S.end();
432 if (generatedTemporaries[BB].find(*I) == generatedTemporaries[BB].end())
438 DOUT << "ANTIC_IN: ";
439 dump_unique(VN, anticIn);
451 DOUT << "Iterations: " << iterations << "\n";
453 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
454 DOUT << "Name: " << I->getName().c_str() << "\n";
457 dump(VN, generatedTemporaries[I]);
461 dump_unique(VN, generatedExpressions[I]);
464 DOUT << "ANTIC_IN: ";
465 dump_unique(VN, anticipatedIn[I]);
468 DOUT << "AVAIL_OUT: ";
469 dump_unique(VN, availableOut[I]);