1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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:
14 // for (...) for (...)
19 // X3 = phi(X1, X2) X3 = phi(X1, X2)
20 // ... = X3 + 4 X4 = phi(X3)
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.
28 //===----------------------------------------------------------------------===//
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"
45 static Statistic<> NumLCSSA("lcssa",
46 "Number of live out of a loop variables");
48 class LCSSA : public FunctionPass {
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;
57 virtual bool runOnFunction(Function &F);
58 bool visitSubloop(Loop* L);
59 void processInstruction(Instruction* Instr,
60 const std::vector<BasicBlock*>& exitBlocks);
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.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequiredID(LoopSimplifyID);
69 AU.addPreservedID(LoopSimplifyID);
70 AU.addRequired<LoopInfo>();
71 AU.addRequired<DominatorTree>();
72 AU.addRequired<DominanceFrontier>();
75 SetVector<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L);
76 Instruction *getValueDominatingBlock(BasicBlock *BB,
77 std::map<BasicBlock*, Instruction*>& PotDoms);
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);
85 RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
88 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
89 const PassInfo *llvm::LCSSAID = X.getPassInfo();
91 /// runOnFunction - Process all loops in the function, inner-most out.
92 bool LCSSA::runOnFunction(Function &F) {
95 LI = &getAnalysis<LoopInfo>();
96 DF = &getAnalysis<DominanceFrontier>();
97 DT = &getAnalysis<DominatorTree>();
99 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
100 changed |= visitSubloop(*I);
106 /// visitSubloop - Recursively process all subloops, and then process the given
107 /// loop if it has live-out values.
108 bool LCSSA::visitSubloop(Loop* L) {
109 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
112 // Speed up queries by creating a sorted list of blocks
114 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
115 std::sort(LoopBlocks.begin(), LoopBlocks.end());
117 SetVector<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L);
119 // If no values are affected, we can save a lot of work, since we know that
120 // nothing will be changed.
121 if (AffectedValues.empty())
124 std::vector<BasicBlock*> exitBlocks;
125 L->getExitBlocks(exitBlocks);
128 // Iterate over all affected values for this loop and insert Phi nodes
129 // for them in the appropriate exit blocks
131 for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
132 E = AffectedValues.end(); I != E; ++I) {
133 processInstruction(*I, exitBlocks);
136 assert(L->isLCSSAForm());
141 /// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
142 /// eliminate all out-of-loop uses.
143 void LCSSA::processInstruction(Instruction* Instr,
144 const std::vector<BasicBlock*>& exitBlocks)
146 ++NumLCSSA; // We are applying the transformation
148 std::map<BasicBlock*, Instruction*> Phis;
150 // Add the base instruction to the Phis list. This makes tracking down
151 // the dominating values easier when we're filling in Phi nodes. This will
152 // be removed later, before we perform use replacement.
153 Phis[Instr->getParent()] = Instr;
155 // Phi nodes that need to be IDF-processed
156 std::vector<PHINode*> workList;
158 for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
159 BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
160 Instruction*& phi = Phis[*BBI];
162 DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) {
163 phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
165 workList.push_back(cast<PHINode>(phi));
169 // Phi nodes that need to have their incoming values filled.
170 std::vector<PHINode*> needIncomingValues;
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();
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);
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];
192 // Still doesn't have operands...
193 Phi = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
196 workList.push_back(cast<PHINode>(Phi));
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),
212 // Find all uses of the affected value, and replace them with the
214 std::vector<Instruction*> Uses;
215 for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
217 Instruction* use = cast<Instruction>(*UI);
218 BasicBlock* UserBB = use->getParent();
219 if (PHINode* p = dyn_cast<PHINode>(use)) {
220 unsigned OperandNo = UI.getOperandNo();
221 UserBB = p->getIncomingBlock(OperandNo/2);
224 // Don't need to update uses within the loop body.
225 if (!inLoop(use->getParent()))
229 for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
231 if (PHINode* phi = dyn_cast<PHINode>(*II)) {
232 for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) {
233 if (phi->getIncomingValue(i) == Instr) {
234 Instruction* dominator =
235 getValueDominatingBlock(phi->getIncomingBlock(i), Phis);
236 phi->setIncomingValue(i, dominator);
240 Value *NewVal = getValueDominatingBlock((*II)->getParent(), Phis);
241 (*II)->replaceUsesOfWith(Instr, NewVal);
246 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
247 /// are used by instructions outside of it.
248 SetVector<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L) {
250 // FIXME: For large loops, we may be able to avoid a lot of use-scanning
251 // by using dominance information. In particular, if a block does not
252 // dominate any of the loop exits, then none of the values defined in the
253 // block could be used outside the loop.
255 SetVector<Instruction*> AffectedValues;
256 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
258 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
259 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
261 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
262 if (PHINode* p = dyn_cast<PHINode>(*UI)) {
263 unsigned OperandNo = UI.getOperandNo();
264 UserBB = p->getIncomingBlock(OperandNo/2);
267 if (!inLoop(UserBB)) {
268 AffectedValues.insert(I);
273 return AffectedValues;
276 /// getValueDominatingBlock - Return the value within the potential dominators
277 /// map that dominates the given block.
278 Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
279 std::map<BasicBlock*, Instruction*>& PotDoms) {
280 DominatorTree::Node* bbNode = DT->getNode(BB);
281 while (bbNode != 0) {
282 std::map<BasicBlock*, Instruction*>::iterator I =
283 PotDoms.find(bbNode->getBlock());
284 if (I != PotDoms.end()) {
287 bbNode = bbNode->getIDom();
290 assert(0 && "No dominating value found.");