LCSSA.cpp revision 3d2aa47bd3a9e2ea5fdcf1690fa280a5199f4d81
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 Function...
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    /// inLoop - returns true if the given block is within the current loop
80    const bool inLoop(BasicBlock* B) {
81      return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
82    }
83  };
84
85  RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
86}
87
88FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
89const PassInfo *llvm::LCSSAID = X.getPassInfo();
90
91/// runOnFunction - Process all loops in the function, inner-most out.
92bool LCSSA::runOnFunction(Function &F) {
93  bool changed = false;
94  LI = &getAnalysis<LoopInfo>();
95  DF = &getAnalysis<DominanceFrontier>();
96  DT = &getAnalysis<DominatorTree>();
97
98  for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
99    changed |= visitSubloop(*I);
100  }
101
102  return changed;
103}
104
105/// visitSubloop - Recursively process all subloops, and then process the given
106/// loop if it has live-out values.
107bool LCSSA::visitSubloop(Loop* L) {
108  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
109    visitSubloop(*I);
110
111  // Speed up queries by creating a sorted list of blocks
112  LoopBlocks.clear();
113  LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
114  std::sort(LoopBlocks.begin(), LoopBlocks.end());
115
116  SetVector<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L);
117
118  // If no values are affected, we can save a lot of work, since we know that
119  // nothing will be changed.
120  if (AffectedValues.empty())
121    return false;
122
123  std::vector<BasicBlock*> exitBlocks;
124  L->getExitBlocks(exitBlocks);
125
126
127  // Iterate over all affected values for this loop and insert Phi nodes
128  // for them in the appropriate exit blocks
129
130  for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
131       E = AffectedValues.end(); I != E; ++I) {
132    processInstruction(*I, exitBlocks);
133  }
134
135  assert(L->isLCSSAForm());
136
137  return true;
138}
139
140/// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
141/// eliminate all out-of-loop uses.
142void LCSSA::processInstruction(Instruction* Instr,
143                               const std::vector<BasicBlock*>& exitBlocks)
144{
145  ++NumLCSSA; // We are applying the transformation
146
147  std::map<BasicBlock*, Instruction*> Phis;
148
149  // Add the base instruction to the Phis list.  This makes tracking down
150  // the dominating values easier when we're filling in Phi nodes.  This will
151  // be removed later, before we perform use replacement.
152  Phis[Instr->getParent()] = Instr;
153
154  // Phi nodes that need to be IDF-processed
155  std::vector<PHINode*> workList;
156
157  for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
158      BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
159    Instruction*& phi = Phis[*BBI];
160    if (phi == 0 &&
161        DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) {
162      phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
163                                 (*BBI)->begin());
164      workList.push_back(cast<PHINode>(phi));
165      Phis[*BBI] = phi;
166    }
167  }
168
169  // Phi nodes that need to have their incoming values filled.
170  std::vector<PHINode*> needIncomingValues;
171
172  // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
173  // necessary.  Keep track of these new Phi's in the "Phis" map.
174  while (!workList.empty()) {
175    PHINode *CurPHI = workList.back();
176    workList.pop_back();
177
178    // Even though we've removed this Phi from the work list, we still need
179    // to fill in its incoming values.
180    needIncomingValues.push_back(CurPHI);
181
182    // Get the current Phi's DF, and insert Phi nodes.  Add these new
183    // nodes to our worklist.
184    DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
185    if (it != DF->end()) {
186      const DominanceFrontier::DomSetType &S = it->second;
187      for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
188           PE = S.end(); P != PE; ++P) {
189        if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*P))) {
190          Instruction *&Phi = Phis[*P];
191          if (Phi == 0) {
192            // Still doesn't have operands...
193            Phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
194                              (*P)->begin());
195
196            workList.push_back(cast<PHINode>(Phi));
197          }
198        }
199      }
200    }
201  }
202
203  // Fill in all Phis we've inserted that need their incoming values filled in.
204  for (std::vector<PHINode*>::iterator IVI = needIncomingValues.begin(),
205       IVE = needIncomingValues.end(); IVI != IVE; ++IVI) {
206    for (pred_iterator PI = pred_begin((*IVI)->getParent()),
207         E = pred_end((*IVI)->getParent()); PI != E; ++PI)
208      (*IVI)->addIncoming(getValueDominatingBlock(*PI, Phis),
209                          *PI);
210  }
211
212  // Find all uses of the affected value, and replace them with the
213  // appropriate Phi.
214  std::vector<Instruction*> Uses;
215  for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
216       UI != UE; ++UI) {
217    Instruction* use = cast<Instruction>(*UI);
218    // Don't need to update uses within the loop body.
219    if (!inLoop(use->getParent()))
220      Uses.push_back(use);
221  }
222
223  for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
224       II != IE; ++II) {
225    if (PHINode* phi = dyn_cast<PHINode>(*II)) {
226      for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) {
227        if (phi->getIncomingValue(i) == Instr) {
228          Instruction* dominator =
229                        getValueDominatingBlock(phi->getIncomingBlock(i), Phis);
230          phi->setIncomingValue(i, dominator);
231        }
232      }
233    } else {
234       Value *NewVal = getValueDominatingBlock((*II)->getParent(), Phis);
235       (*II)->replaceUsesOfWith(Instr, NewVal);
236    }
237  }
238}
239
240/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
241/// are used by instructions outside of it.
242SetVector<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L) {
243
244  // FIXME: For large loops, we may be able to avoid a lot of use-scanning
245  // by using dominance information.  In particular, if a block does not
246  // dominate any of the loop exits, then none of the values defined in the
247  // block could be used outside the loop.
248
249  SetVector<Instruction*> AffectedValues;
250  for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
251       BB != E; ++BB) {
252    for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
253      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
254           ++UI) {
255        BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
256        if (!inLoop(UserBB)) {
257          AffectedValues.insert(I);
258          break;
259        }
260      }
261  }
262  return AffectedValues;
263}
264
265/// getValueDominatingBlock - Return the value within the potential dominators
266/// map that dominates the given block.
267Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
268                                 std::map<BasicBlock*, Instruction*>& PotDoms) {
269  DominatorTree::Node* bbNode = DT->getNode(BB);
270  while (bbNode != 0) {
271    std::map<BasicBlock*, Instruction*>::iterator I =
272                                               PotDoms.find(bbNode->getBlock());
273    if (I != PotDoms.end()) {
274      return (*I).second;
275    }
276    bbNode = bbNode->getIDom();
277  }
278
279  assert(0 && "No dominating value found.");
280
281  return 0;
282}
283