LCSSA.cpp revision 9e1c1ddd4b514731236c0c24184ae194fb4d3706
1//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Owen Anderson and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops by placing phi nodes at the end of the loops for
11// all values that are live across the loop boundary.  For example, it turns
12// the left into the right code:
13//
14// for (...)                for (...)
15//   if (c)                   if(c)
16//     X1 = ...                 X1 = ...
17//   else                     else
18//     X2 = ...                 X2 = ...
19//   X3 = phi(X1, X2)         X3 = phi(X1, X2)
20// ... = X3 + 4              X4 = phi(X3)
21//                           ... = X4 + 4
22//
23// This is still valid LLVM; the extra phi nodes are purely redundant, and will
24// be trivially eliminated by InstCombine.  The major benefit of this
25// transformation is that it makes many other loop optimizations, such as
26// LoopUnswitching, simpler.
27//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Pass.h"
32#include "llvm/Function.h"
33#include "llvm/Instructions.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Analysis/Dominators.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Support/CFG.h"
39#include <algorithm>
40#include <map>
41
42using namespace llvm;
43
44namespace {
45  static Statistic<> NumLCSSA("lcssa",
46                              "Number of live out of a loop variables");
47
48  class LCSSA : public FunctionPass {
49  public:
50
51
52    LoopInfo *LI;  // Loop information
53    DominatorTree *DT;       // Dominator Tree for the current Loop...
54    DominanceFrontier *DF;   // Current Dominance Frontier
55    std::vector<BasicBlock*> *LoopBlocks;
56
57    virtual bool runOnFunction(Function &F);
58    bool visitSubloop(Loop* L);
59    void processInstruction(Instruction* Instr,
60                            const std::vector<BasicBlock*>& exitBlocks);
61
62    /// This transformation requires natural loop information & requires that
63    /// loop preheaders be inserted into the CFG.  It maintains both of these,
64    /// as well as the CFG.  It also requires dominator information.
65    ///
66    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67      AU.setPreservesCFG();
68      AU.addRequiredID(LoopSimplifyID);
69      AU.addPreservedID(LoopSimplifyID);
70      AU.addRequired<LoopInfo>();
71      AU.addRequired<DominatorTree>();
72      AU.addRequired<DominanceFrontier>();
73    }
74  private:
75    SetVector<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L);
76    Instruction *getValueDominatingBlock(BasicBlock *BB,
77                                  std::map<BasicBlock*, Instruction*>& PotDoms);
78
79    bool inLoopBlocks(BasicBlock* B) { return std::binary_search(
80                                   LoopBlocks->begin(), LoopBlocks->end(), B); }
81  };
82
83  RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
84}
85
86FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
87
88bool LCSSA::runOnFunction(Function &F) {
89  bool changed = false;
90  LI = &getAnalysis<LoopInfo>();
91  DF = &getAnalysis<DominanceFrontier>();
92  DT = &getAnalysis<DominatorTree>();
93  LoopBlocks = new std::vector<BasicBlock*>;
94
95  for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
96    changed |= visitSubloop(*I);
97  }
98
99  return changed;
100}
101
102bool LCSSA::visitSubloop(Loop* L) {
103  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
104    visitSubloop(*I);
105
106  // Speed up queries by creating a sorted list of blocks
107  LoopBlocks->clear();
108  LoopBlocks->insert(LoopBlocks->end(), L->block_begin(), L->block_end());
109  std::sort(LoopBlocks->begin(), LoopBlocks->end());
110
111  SetVector<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L);
112
113  // If no values are affected, we can save a lot of work, since we know that
114  // nothing will be changed.
115  if (AffectedValues.empty())
116    return false;
117
118  std::vector<BasicBlock*> exitBlocks;
119  L->getExitBlocks(exitBlocks);
120
121
122  // Iterate over all affected values for this loop and insert Phi nodes
123  // for them in the appropriate exit blocks
124
125  for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
126       E = AffectedValues.end(); I != E; ++I) {
127    processInstruction(*I, exitBlocks);
128  }
129
130  return true; // FIXME: Should be more intelligent in our return value.
131}
132
133/// processInstruction -
134void LCSSA::processInstruction(Instruction* Instr,
135                               const std::vector<BasicBlock*>& exitBlocks)
136{
137  ++NumLCSSA; // We are applying the transformation
138
139  std::map<BasicBlock*, Instruction*> Phis;
140
141  // Add the base instruction to the Phis list.  This makes tracking down
142  // the dominating values easier when we're filling in Phi nodes.  This will
143  // be removed later, before we perform use replacement.
144  Phis[Instr->getParent()] = Instr;
145
146  // Phi nodes that need to be IDF-processed
147  std::vector<PHINode*> workList;
148
149  for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
150      BBE = exitBlocks.end(); BBI != BBE; ++BBI)
151    if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) {
152      PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin());
153      workList.push_back(phi);
154      Phis[*BBI] = phi;
155    }
156
157  // Phi nodes that need to have their incoming values filled.
158  std::vector<PHINode*> needIncomingValues;
159
160  // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
161  // necessary.  Keep track of these new Phi's in the "Phis" map.
162  while (!workList.empty()) {
163    PHINode *CurPHI = workList.back();
164    workList.pop_back();
165
166    // Even though we've removed this Phi from the work list, we still need
167    // to fill in its incoming values.
168    needIncomingValues.push_back(CurPHI);
169
170    // Get the current Phi's DF, and insert Phi nodes.  Add these new
171    // nodes to our worklist.
172    DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
173    if (it != DF->end()) {
174      const DominanceFrontier::DomSetType &S = it->second;
175      for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
176           PE = S.end(); P != PE; ++P) {
177        Instruction *&Phi = Phis[*P];
178        if (Phi == 0) {
179          // Still doesn't have operands...
180          Phi = new PHINode(Instr->getType(), "lcssa", (*P)->begin());
181
182          workList.push_back(cast<PHINode>(Phi));
183        }
184      }
185    }
186  }
187
188  // Fill in all Phis we've inserted that need their incoming values filled in.
189  for (std::vector<PHINode*>::iterator IVI = needIncomingValues.begin(),
190       IVE = needIncomingValues.end(); IVI != IVE; ++IVI) {
191    for (pred_iterator PI = pred_begin((*IVI)->getParent()),
192         E = pred_end((*IVI)->getParent()); PI != E; ++PI)
193      (*IVI)->addIncoming(getValueDominatingBlock(*PI, Phis),
194                          *PI);
195  }
196
197  // Find all uses of the affected value, and replace them with the
198  // appropriate Phi.
199  std::vector<Instruction*> Uses;
200  for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
201       UI != UE; ++UI) {
202    Instruction* use = cast<Instruction>(*UI);
203    // Don't need to update uses within the loop body, and we don't want to
204    // overwrite the Phi nodes that we inserted into the exit blocks either.
205    if (!inLoopBlocks(use->getParent()) &&
206        !(std::binary_search(exitBlocks.begin(), exitBlocks.end(),
207        use->getParent()) && isa<PHINode>(use)))
208      Uses.push_back(use);
209  }
210
211  // Deliberately remove the initial instruction from Phis set.  It would mess
212  // up use-replacement.
213  Phis.erase(Instr->getParent());
214
215  for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
216       II != IE; ++II) {
217    if (PHINode* phi = dyn_cast<PHINode>(*II)) {
218      for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) {
219        if (phi->getIncomingValue(i) == Instr) {
220          Instruction* dominator =
221                        getValueDominatingBlock(phi->getIncomingBlock(i), Phis);
222          phi->setIncomingValue(i, dominator);
223        }
224      }
225    } else {
226       Value *NewVal = getValueDominatingBlock((*II)->getParent(), Phis);
227       (*II)->replaceUsesOfWith(Instr, NewVal);
228    }
229  }
230}
231
232/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
233/// are used by instructions outside of it.
234SetVector<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L) {
235
236  // FIXME: For large loops, we may be able to avoid a lot of use-scanning
237  // by using dominance information.  In particular, if a block does not
238  // dominate any of the loop exits, then none of the values defined in the
239  // block could be used outside the loop.
240
241  SetVector<Instruction*> AffectedValues;
242  for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
243       BB != E; ++BB) {
244    for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
245      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
246           ++UI) {
247        BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
248        if (!std::binary_search(LoopBlocks->begin(), LoopBlocks->end(), UserBB))
249        {
250          AffectedValues.insert(I);
251          break;
252        }
253      }
254  }
255  return AffectedValues;
256}
257
258Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
259                                 std::map<BasicBlock*, Instruction*>& PotDoms) {
260  DominatorTree::Node* bbNode = DT->getNode(BB);
261  while (bbNode != 0) {
262    std::map<BasicBlock*, Instruction*>::iterator I =
263                                               PotDoms.find(bbNode->getBlock());
264    if (I != PotDoms.end()) {
265      return (*I).second;
266    }
267    bbNode = bbNode->getIDom();
268  }
269
270  assert(0 && "No dominating value found.");
271
272  return 0;
273}
274