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/Statistic.h" 35 #include "llvm/Analysis/Dominators.h" 36 #include "llvm/Analysis/LoopInfo.h" 37 #include "llvm/Support/CFG.h" 38 #include <algorithm> 39 #include <iostream> 40 #include <map> 41 #include <vector> 42 43 using namespace llvm; 44 45 namespace { 46 static Statistic<> NumLCSSA("lcssa", 47 "Number of live out of a loop variables"); 48 49 class LCSSA : public FunctionPass { 50 public: 51 52 53 LoopInfo *LI; // Loop information 54 DominatorTree *DT; // Dominator Tree for the current Loop... 55 DominanceFrontier *DF; // Current Dominance Frontier 56 57 virtual bool runOnFunction(Function &F); 58 bool visitSubloop(Loop* L); 59 void processInstruction(Instruction* Instr, 60 const std::vector<BasicBlock*>& LoopBlocks, 61 const std::vector<BasicBlock*>& exitBlocks); 62 63 /// This transformation requires natural loop information & requires that 64 /// loop preheaders be inserted into the CFG. It maintains both of these, 65 /// as well as the CFG. It also requires dominator information. 66 /// 67 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 68 AU.setPreservesCFG(); 69 AU.addRequiredID(LoopSimplifyID); 70 AU.addPreservedID(LoopSimplifyID); 71 AU.addRequired<LoopInfo>(); 72 AU.addPreserved<LoopInfo>(); 73 AU.addRequired<DominatorTree>(); 74 AU.addRequired<DominanceFrontier>(); 75 } 76 private: 77 std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L, 78 const std::vector<BasicBlock*>& LoopBlocks); 79 Instruction *getValueDominatingBlock(BasicBlock *BB, 80 std::map<BasicBlock*, Instruction*> PotDoms); 81 }; 82 83 RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass"); 84 } 85 86 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); } 87 88 bool LCSSA::runOnFunction(Function &F) { 89 bool changed = false; 90 LI = &getAnalysis<LoopInfo>(); 91 DF = &getAnalysis<DominanceFrontier>(); 92 DT = &getAnalysis<DominatorTree>(); 93 94 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) { 95 changed |= visitSubloop(*I); 96 } 97 98 return changed; 99 } 100 101 bool LCSSA::visitSubloop(Loop* L) { 102 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 103 visitSubloop(*I); 104 105 // Speed up queries by creating a sorted list of blocks 106 std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end()); 107 std::sort(LoopBlocks.begin(), LoopBlocks.end()); 108 109 std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L, 110 LoopBlocks); 111 112 // If no values are affected, we can save a lot of work, since we know that 113 // nothing will be changed. 114 if (AffectedValues.empty()) 115 return false; 116 117 std::vector<BasicBlock*> exitBlocks; 118 L->getExitBlocks(exitBlocks); 119 120 121 // Iterate over all affected values for this loop and insert Phi nodes 122 // for them in the appropriate exit blocks 123 124 for (std::set<Instruction*>::iterator I = AffectedValues.begin(), 125 E = AffectedValues.end(); I != E; ++I) { 126 processInstruction(*I, LoopBlocks, exitBlocks); 127 } 128 129 return true; // FIXME: Should be more intelligent in our return value. 130 } 131 132 /// processInstruction - 133 void LCSSA::processInstruction(Instruction* Instr, 134 const std::vector<BasicBlock*>& LoopBlocks, 135 const std::vector<BasicBlock*>& exitBlocks) 136 { 137 ++NumLCSSA; // We are applying the transformation 138 139 std::map<BasicBlock*, Instruction*> Phis; 140 Phis[Instr->getParent()] = Instr; 141 142 // Phi nodes that need to be IDF-processed 143 std::vector<PHINode*> workList; 144 145 for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(), 146 BBE = exitBlocks.end(); BBI != BBE; ++BBI) { 147 PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin()); 148 workList.push_back(phi); 149 Phis[*BBI] = phi; 150 151 // Since LoopSimplify has been run, we know that all of these predecessors 152 // are in the loop, so just hook them up in the obvious manner. 153 //for (pred_iterator PI = pred_begin(*BBI), PE = pred_end(*BBI); PI != PE; 154 // ++PI) 155 // phi->addIncoming(Instr, *PI); 156 } 157 158 // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where 159 // necessary. Keep track of these new Phi's in Phis. 160 while (!workList.empty()) { 161 PHINode *CurPHI = workList.back(); 162 workList.pop_back(); 163 164 // Get the current Phi's DF, and insert Phi nodes. Add these new 165 // nodes to our worklist. 166 DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent()); 167 if (it != DF->end()) { 168 const DominanceFrontier::DomSetType &S = it->second; 169 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(), 170 PE = S.end(); P != PE; ++P) { 171 if (Phis[*P] == 0) { 172 // Still doesn't have operands... 173 PHINode *phi = new PHINode(Instr->getType(), "lcssa"); 174 (*P)->getInstList().insert((*P)->front(), phi); 175 Phis[*P] = phi; 176 177 workList.push_back(phi); 178 } 179 } 180 } 181 182 // Get the predecessor blocks of the current Phi, and use them to hook up 183 // the operands of the current Phi to any members of DFPhis that dominate 184 // it. This is a nop for the Phis inserted directly in the exit blocks, 185 // since they are not dominated by any members of DFPhis. 186 for (pred_iterator PI = pred_begin(CurPHI->getParent()), 187 E = pred_end(CurPHI->getParent()); PI != E; ++PI) 188 CurPHI->addIncoming(getValueDominatingBlock(*PI, Phis), 189 *PI); 190 } 191 192 // Find all uses of the affected value, and replace them with the 193 // appropriate Phi. 194 std::vector<Instruction*> Uses; 195 for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end(); 196 UI != UE; ++UI) { 197 Instruction* use = cast<Instruction>(*UI); 198 // Don't need to update uses within the loop body 199 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), 200 use->getParent()) && 201 !(std::binary_search(exitBlocks.begin(), exitBlocks.end(), 202 use->getParent()) && isa<PHINode>(use))) 203 Uses.push_back(use); 204 } 205 206 // Deliberately remove the initial instruction from Phis set. 207 Phis.erase(Instr->getParent()); 208 209 for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end(); 210 II != IE; ++II) { 211 (*II)->replaceUsesOfWith(Instr, getValueDominatingBlock((*II)->getParent(), 212 Phis)); 213 } 214 } 215 216 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that 217 /// are used by instructions outside of it. 218 std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L, 219 const std::vector<BasicBlock*>& LoopBlocks) { 220 221 // FIXME: For large loops, we may be able to avoid a lot of use-scanning 222 // by using dominance information. In particular, if a block does not 223 // dominate any of the loop exits, then none of the values defined in the 224 // block could be used outside the loop. 225 226 std::set<Instruction*> AffectedValues; 227 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); 228 BB != E; ++BB) { 229 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) 230 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; 231 ++UI) { 232 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); 233 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) { 234 AffectedValues.insert(I); 235 break; 236 } 237 } 238 } 239 return AffectedValues; 240 } 241 242 Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB, 243 std::map<BasicBlock*, Instruction*> PotDoms) { 244 for (std::map<BasicBlock*, Instruction*>::iterator MI = PotDoms.begin(), 245 ME = PotDoms.end(); MI != ME; ++MI) 246 if (DT->getNode((*MI).first)->dominates(DT->getNode(BB))) 247 return (*MI).second; 248 249 // FIXME: Should assert false 250 251 return 0; 252 } 253