LLVM API Documentation
00001 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass performs loop invariant code motion on machine instructions. We 00011 // attempt to remove as much code from the body of a loop as possible. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "machine-licm" 00016 #include "llvm/CodeGen/Passes.h" 00017 #include "llvm/CodeGen/MachineDominators.h" 00018 #include "llvm/CodeGen/MachineLoopInfo.h" 00019 #include "llvm/CodeGen/MachineRegisterInfo.h" 00020 #include "llvm/Target/TargetRegisterInfo.h" 00021 #include "llvm/Target/TargetInstrInfo.h" 00022 #include "llvm/Target/TargetMachine.h" 00023 #include "llvm/ADT/SmallVector.h" 00024 #include "llvm/ADT/Statistic.h" 00025 #include "llvm/Support/CommandLine.h" 00026 #include "llvm/Support/Compiler.h" 00027 #include "llvm/Support/Debug.h" 00028 00029 using namespace llvm; 00030 00031 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops"); 00032 00033 namespace { 00034 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass { 00035 const TargetMachine *TM; 00036 const TargetInstrInfo *TII; 00037 00038 // Various analyses that we use... 00039 MachineLoopInfo *LI; // Current MachineLoopInfo 00040 MachineDominatorTree *DT; // Machine dominator tree for the cur loop 00041 MachineRegisterInfo *RegInfo; // Machine register information 00042 00043 // State that is updated as we process loops 00044 bool Changed; // True if a loop is changed. 00045 MachineLoop *CurLoop; // The current loop we are working on. 00046 public: 00047 static char ID; // Pass identification, replacement for typeid 00048 MachineLICM() : MachineFunctionPass(&ID) {} 00049 00050 virtual bool runOnMachineFunction(MachineFunction &MF); 00051 00052 // FIXME: Loop preheaders? 00053 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00054 AU.setPreservesCFG(); 00055 AU.addRequired<MachineLoopInfo>(); 00056 AU.addRequired<MachineDominatorTree>(); 00057 AU.addPreserved<MachineLoopInfo>(); 00058 AU.addPreserved<MachineDominatorTree>(); 00059 MachineFunctionPass::getAnalysisUsage(AU); 00060 } 00061 private: 00062 /// VisitAllLoops - Visit all of the loops in depth first order and try to 00063 /// hoist invariant instructions from them. 00064 /// 00065 void VisitAllLoops(MachineLoop *L) { 00066 const std::vector<MachineLoop*> &SubLoops = L->getSubLoops(); 00067 00068 for (MachineLoop::iterator 00069 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) { 00070 MachineLoop *ML = *I; 00071 00072 // Traverse the body of the loop in depth first order on the dominator 00073 // tree so that we are guaranteed to see definitions before we see uses. 00074 VisitAllLoops(ML); 00075 HoistRegion(DT->getNode(ML->getHeader())); 00076 } 00077 00078 HoistRegion(DT->getNode(L->getHeader())); 00079 } 00080 00081 /// IsInSubLoop - A little predicate that returns true if the specified 00082 /// basic block is in a subloop of the current one, not the current one 00083 /// itself. 00084 /// 00085 bool IsInSubLoop(MachineBasicBlock *BB) { 00086 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 00087 return LI->getLoopFor(BB) != CurLoop; 00088 } 00089 00090 /// IsLoopInvariantInst - Returns true if the instruction is loop 00091 /// invariant. I.e., all virtual register operands are defined outside of 00092 /// the loop, physical registers aren't accessed (explicitly or implicitly), 00093 /// and the instruction is hoistable. 00094 /// 00095 bool IsLoopInvariantInst(MachineInstr &I); 00096 00097 /// FindPredecessors - Get all of the predecessors of the loop that are not 00098 /// back-edges. 00099 /// 00100 void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) { 00101 const MachineBasicBlock *Header = CurLoop->getHeader(); 00102 00103 for (MachineBasicBlock::const_pred_iterator 00104 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I) 00105 if (!CurLoop->contains(*I)) 00106 Preds.push_back(*I); 00107 } 00108 00109 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of 00110 /// the predecessor basic block (but before the terminator instructions). 00111 /// 00112 void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB, 00113 MachineBasicBlock *FromMBB, 00114 MachineInstr *MI); 00115 00116 /// HoistRegion - Walk the specified region of the CFG (defined by all 00117 /// blocks dominated by the specified block, and that are in the current 00118 /// loop) in depth first order w.r.t the DominatorTree. This allows us to 00119 /// visit definitions before uses, allowing us to hoist a loop body in one 00120 /// pass without iteration. 00121 /// 00122 void HoistRegion(MachineDomTreeNode *N); 00123 00124 /// Hoist - When an instruction is found to only use loop invariant operands 00125 /// that is safe to hoist, this instruction is called to do the dirty work. 00126 /// 00127 void Hoist(MachineInstr &MI); 00128 }; 00129 } // end anonymous namespace 00130 00131 char MachineLICM::ID = 0; 00132 static RegisterPass<MachineLICM> 00133 X("machinelicm", "Machine Loop Invariant Code Motion"); 00134 00135 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); } 00136 00137 /// Hoist expressions out of the specified loop. Note, alias info for inner loop 00138 /// is not preserved so it is not a good idea to run LICM multiple times on one 00139 /// loop. 00140 /// 00141 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) { 00142 DOUT << "******** Machine LICM ********\n"; 00143 00144 Changed = false; 00145 TM = &MF.getTarget(); 00146 TII = TM->getInstrInfo(); 00147 RegInfo = &MF.getRegInfo(); 00148 00149 // Get our Loop information... 00150 LI = &getAnalysis<MachineLoopInfo>(); 00151 DT = &getAnalysis<MachineDominatorTree>(); 00152 00153 for (MachineLoopInfo::iterator 00154 I = LI->begin(), E = LI->end(); I != E; ++I) { 00155 CurLoop = *I; 00156 00157 // Visit all of the instructions of the loop. We want to visit the subloops 00158 // first, though, so that we can hoist their invariants first into their 00159 // containing loop before we process that loop. 00160 VisitAllLoops(CurLoop); 00161 } 00162 00163 return Changed; 00164 } 00165 00166 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks 00167 /// dominated by the specified block, and that are in the current loop) in depth 00168 /// first order w.r.t the DominatorTree. This allows us to visit definitions 00169 /// before uses, allowing us to hoist a loop body in one pass without iteration. 00170 /// 00171 void MachineLICM::HoistRegion(MachineDomTreeNode *N) { 00172 assert(N != 0 && "Null dominator tree node?"); 00173 MachineBasicBlock *BB = N->getBlock(); 00174 00175 // If this subregion is not in the top level loop at all, exit. 00176 if (!CurLoop->contains(BB)) return; 00177 00178 // Only need to process the contents of this block if it is not part of a 00179 // subloop (which would already have been processed). 00180 if (!IsInSubLoop(BB)) 00181 for (MachineBasicBlock::iterator 00182 I = BB->begin(), E = BB->end(); I != E; ) { 00183 MachineInstr &MI = *I++; 00184 00185 // Try hoisting the instruction out of the loop. We can only do this if 00186 // all of the operands of the instruction are loop invariant and if it is 00187 // safe to hoist the instruction. 00188 Hoist(MI); 00189 } 00190 00191 const std::vector<MachineDomTreeNode*> &Children = N->getChildren(); 00192 00193 for (unsigned I = 0, E = Children.size(); I != E; ++I) 00194 HoistRegion(Children[I]); 00195 } 00196 00197 /// IsLoopInvariantInst - Returns true if the instruction is loop 00198 /// invariant. I.e., all virtual register operands are defined outside of the 00199 /// loop, physical registers aren't accessed explicitly, and there are no side 00200 /// effects that aren't captured by the operands or other flags. 00201 /// 00202 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) { 00203 const TargetInstrDesc &TID = I.getDesc(); 00204 00205 // Ignore stuff that we obviously can't hoist. 00206 if (TID.mayStore() || TID.isCall() || TID.isReturn() || TID.isBranch() || 00207 TID.hasUnmodeledSideEffects()) 00208 return false; 00209 00210 if (TID.mayLoad()) { 00211 // Okay, this instruction does a load. As a refinement, we allow the target 00212 // to decide whether the loaded value is actually a constant. If so, we can 00213 // actually use it as a load. 00214 if (!TII->isInvariantLoad(&I)) 00215 // FIXME: we should be able to sink loads with no other side effects if 00216 // there is nothing that can change memory from here until the end of 00217 // block. This is a trivial form of alias analysis. 00218 return false; 00219 } 00220 00221 DEBUG({ 00222 DOUT << "--- Checking if we can hoist " << I; 00223 if (I.getDesc().getImplicitUses()) { 00224 DOUT << " * Instruction has implicit uses:\n"; 00225 00226 const TargetRegisterInfo *TRI = TM->getRegisterInfo(); 00227 for (const unsigned *ImpUses = I.getDesc().getImplicitUses(); 00228 *ImpUses; ++ImpUses) 00229 DOUT << " -> " << TRI->getName(*ImpUses) << "\n"; 00230 } 00231 00232 if (I.getDesc().getImplicitDefs()) { 00233 DOUT << " * Instruction has implicit defines:\n"; 00234 00235 const TargetRegisterInfo *TRI = TM->getRegisterInfo(); 00236 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs(); 00237 *ImpDefs; ++ImpDefs) 00238 DOUT << " -> " << TRI->getName(*ImpDefs) << "\n"; 00239 } 00240 }); 00241 00242 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) { 00243 DOUT << "Cannot hoist with implicit defines or uses\n"; 00244 return false; 00245 } 00246 00247 // The instruction is loop invariant if all of its operands are. 00248 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 00249 const MachineOperand &MO = I.getOperand(i); 00250 00251 if (!MO.isReg()) 00252 continue; 00253 00254 if (MO.isDef() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())) 00255 // Don't hoist an instruction that defines a physical register. 00256 return false; 00257 00258 if (!MO.isUse()) 00259 continue; 00260 00261 unsigned Reg = MO.getReg(); 00262 if (Reg == 0) continue; 00263 00264 // Don't hoist instructions that access physical registers. 00265 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 00266 return false; 00267 00268 assert(RegInfo->getVRegDef(Reg) && 00269 "Machine instr not mapped for this vreg?!"); 00270 00271 // If the loop contains the definition of an operand, then the instruction 00272 // isn't loop invariant. 00273 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent())) 00274 return false; 00275 } 00276 00277 // If we got this far, the instruction is loop invariant! 00278 return true; 00279 } 00280 00281 /// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of the 00282 /// predecessor basic block (but before the terminator instructions). 00283 /// 00284 void MachineLICM::MoveInstToEndOfBlock(MachineBasicBlock *ToMBB, 00285 MachineBasicBlock *FromMBB, 00286 MachineInstr *MI) { 00287 DEBUG({ 00288 DOUT << "Hoisting " << *MI; 00289 if (ToMBB->getBasicBlock()) 00290 DOUT << " to MachineBasicBlock " 00291 << ToMBB->getBasicBlock()->getName(); 00292 if (FromMBB->getBasicBlock()) 00293 DOUT << " from MachineBasicBlock " 00294 << FromMBB->getBasicBlock()->getName(); 00295 DOUT << "\n"; 00296 }); 00297 00298 MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator(); 00299 MachineBasicBlock::iterator To, From = FromMBB->begin(); 00300 00301 while (&*From != MI) 00302 ++From; 00303 00304 assert(From != FromMBB->end() && "Didn't find instr in BB!"); 00305 00306 To = From; 00307 ToMBB->splice(WhereIter, FromMBB, From, ++To); 00308 ++NumHoisted; 00309 } 00310 00311 /// Hoist - When an instruction is found to use only loop invariant operands 00312 /// that are safe to hoist, this instruction is called to do the dirty work. 00313 /// 00314 void MachineLICM::Hoist(MachineInstr &MI) { 00315 if (!IsLoopInvariantInst(MI)) return; 00316 00317 std::vector<MachineBasicBlock*> Preds; 00318 00319 // Non-back-edge predecessors. 00320 FindPredecessors(Preds); 00321 00322 // Either we don't have any predecessors(?!) or we have more than one, which 00323 // is forbidden. 00324 if (Preds.empty() || Preds.size() != 1) return; 00325 00326 // Check that the predecessor is qualified to take the hoisted instruction. 00327 // I.e., there is only one edge from the predecessor, and it's to the loop 00328 // header. 00329 MachineBasicBlock *MBB = Preds.front(); 00330 00331 // FIXME: We are assuming at first that the basic block coming into this loop 00332 // has only one successor. This isn't the case in general because we haven't 00333 // broken critical edges or added preheaders. 00334 if (MBB->succ_size() != 1) return; 00335 assert(*MBB->succ_begin() == CurLoop->getHeader() && 00336 "The predecessor doesn't feed directly into the loop header!"); 00337 00338 // Now move the instructions to the predecessor. 00339 MoveInstToEndOfBlock(MBB, MI.getParent(), &MI); 00340 Changed = true; 00341 }