LLVM API Documentation

MachineLICM.cpp

Go to the documentation of this file.
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 // This pass does not attempt to throttle itself to limit register pressure.
00014 // The register allocation phases are expected to perform rematerialization
00015 // to recover when register pressure is high.
00016 //
00017 // This pass is not intended to be a replacement or a complete alternative
00018 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
00019 // constructs that are not exposed before lowering and instruction selection.
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #define DEBUG_TYPE "machine-licm"
00024 #include "llvm/CodeGen/Passes.h"
00025 #include "llvm/CodeGen/MachineDominators.h"
00026 #include "llvm/CodeGen/MachineLoopInfo.h"
00027 #include "llvm/CodeGen/MachineRegisterInfo.h"
00028 #include "llvm/Target/TargetRegisterInfo.h"
00029 #include "llvm/Target/TargetInstrInfo.h"
00030 #include "llvm/Target/TargetMachine.h"
00031 #include "llvm/ADT/Statistic.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Compiler.h"
00034 #include "llvm/Support/Debug.h"
00035 
00036 using namespace llvm;
00037 
00038 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
00039 
00040 namespace {
00041   class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
00042     const TargetMachine   *TM;
00043     const TargetInstrInfo *TII;
00044 
00045     // Various analyses that we use...
00046     MachineLoopInfo      *LI;      // Current MachineLoopInfo
00047     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
00048     MachineRegisterInfo  *RegInfo; // Machine register information
00049 
00050     // State that is updated as we process loops
00051     bool         Changed;          // True if a loop is changed.
00052     MachineLoop *CurLoop;          // The current loop we are working on.
00053     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
00054   public:
00055     static char ID; // Pass identification, replacement for typeid
00056     MachineLICM() : MachineFunctionPass(&ID) {}
00057 
00058     virtual bool runOnMachineFunction(MachineFunction &MF);
00059 
00060     const char *getPassName() const { return "Machine Instruction LICM"; }
00061 
00062     // FIXME: Loop preheaders?
00063     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00064       AU.setPreservesCFG();
00065       AU.addRequired<MachineLoopInfo>();
00066       AU.addRequired<MachineDominatorTree>();
00067       AU.addPreserved<MachineLoopInfo>();
00068       AU.addPreserved<MachineDominatorTree>();
00069       MachineFunctionPass::getAnalysisUsage(AU);
00070     }
00071   private:
00072     /// IsLoopInvariantInst - Returns true if the instruction is loop
00073     /// invariant. I.e., all virtual register operands are defined outside of
00074     /// the loop, physical registers aren't accessed (explicitly or implicitly),
00075     /// and the instruction is hoistable.
00076     /// 
00077     bool IsLoopInvariantInst(MachineInstr &I);
00078 
00079     /// HoistRegion - Walk the specified region of the CFG (defined by all
00080     /// blocks dominated by the specified block, and that are in the current
00081     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
00082     /// visit definitions before uses, allowing us to hoist a loop body in one
00083     /// pass without iteration.
00084     ///
00085     void HoistRegion(MachineDomTreeNode *N);
00086 
00087     /// Hoist - When an instruction is found to only use loop invariant operands
00088     /// that is safe to hoist, this instruction is called to do the dirty work.
00089     ///
00090     void Hoist(MachineInstr &MI);
00091   };
00092 } // end anonymous namespace
00093 
00094 char MachineLICM::ID = 0;
00095 static RegisterPass<MachineLICM>
00096 X("machinelicm", "Machine Loop Invariant Code Motion");
00097 
00098 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
00099 
00100 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
00101 /// loop that has a preheader.
00102 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
00103   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
00104     if (L->getLoopPreheader())
00105       return false;
00106   return true;
00107 }
00108 
00109 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
00110 /// is not preserved so it is not a good idea to run LICM multiple times on one
00111 /// loop.
00112 ///
00113 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
00114   DOUT << "******** Machine LICM ********\n";
00115 
00116   Changed = false;
00117   TM = &MF.getTarget();
00118   TII = TM->getInstrInfo();
00119   RegInfo = &MF.getRegInfo();
00120 
00121   // Get our Loop information...
00122   LI = &getAnalysis<MachineLoopInfo>();
00123   DT = &getAnalysis<MachineDominatorTree>();
00124 
00125   for (MachineLoopInfo::iterator
00126          I = LI->begin(), E = LI->end(); I != E; ++I) {
00127     CurLoop = *I;
00128 
00129     // Only visit outer-most preheader-sporting loops.
00130     if (!LoopIsOuterMostWithPreheader(CurLoop))
00131       continue;
00132 
00133     // Determine the block to which to hoist instructions. If we can't find a
00134     // suitable loop preheader, we can't do any hoisting.
00135     //
00136     // FIXME: We are only hoisting if the basic block coming into this loop
00137     // has only one successor. This isn't the case in general because we haven't
00138     // broken critical edges or added preheaders.
00139     CurPreheader = CurLoop->getLoopPreheader();
00140     if (!CurPreheader)
00141       continue;
00142 
00143     HoistRegion(DT->getNode(CurLoop->getHeader()));
00144   }
00145 
00146   return Changed;
00147 }
00148 
00149 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
00150 /// dominated by the specified block, and that are in the current loop) in depth
00151 /// first order w.r.t the DominatorTree. This allows us to visit definitions
00152 /// before uses, allowing us to hoist a loop body in one pass without iteration.
00153 ///
00154 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
00155   assert(N != 0 && "Null dominator tree node?");
00156   MachineBasicBlock *BB = N->getBlock();
00157 
00158   // If this subregion is not in the top level loop at all, exit.
00159   if (!CurLoop->contains(BB)) return;
00160 
00161   for (MachineBasicBlock::iterator
00162          I = BB->begin(), E = BB->end(); I != E; ) {
00163     MachineInstr &MI = *I++;
00164 
00165     // Try hoisting the instruction out of the loop. We can only do this if
00166     // all of the operands of the instruction are loop invariant and if it is
00167     // safe to hoist the instruction.
00168     Hoist(MI);
00169   }
00170 
00171   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
00172 
00173   for (unsigned I = 0, E = Children.size(); I != E; ++I)
00174     HoistRegion(Children[I]);
00175 }
00176 
00177 /// IsLoopInvariantInst - Returns true if the instruction is loop
00178 /// invariant. I.e., all virtual register operands are defined outside of the
00179 /// loop, physical registers aren't accessed explicitly, and there are no side
00180 /// effects that aren't captured by the operands or other flags.
00181 /// 
00182 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
00183   const TargetInstrDesc &TID = I.getDesc();
00184   
00185   // Ignore stuff that we obviously can't hoist.
00186   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
00187       TID.hasUnmodeledSideEffects())
00188     return false;
00189   
00190   if (TID.mayLoad()) {
00191     // Okay, this instruction does a load. As a refinement, we allow the target
00192     // to decide whether the loaded value is actually a constant. If so, we can
00193     // actually use it as a load.
00194     if (!TII->isInvariantLoad(&I))
00195       // FIXME: we should be able to sink loads with no other side effects if
00196       // there is nothing that can change memory from here until the end of
00197       // block. This is a trivial form of alias analysis.
00198       return false;
00199   }
00200 
00201   DEBUG({
00202       DOUT << "--- Checking if we can hoist " << I;
00203       if (I.getDesc().getImplicitUses()) {
00204         DOUT << "  * Instruction has implicit uses:\n";
00205 
00206         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
00207         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
00208              *ImpUses; ++ImpUses)
00209           DOUT << "      -> " << TRI->getName(*ImpUses) << "\n";
00210       }
00211 
00212       if (I.getDesc().getImplicitDefs()) {
00213         DOUT << "  * Instruction has implicit defines:\n";
00214 
00215         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
00216         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
00217              *ImpDefs; ++ImpDefs)
00218           DOUT << "      -> " << TRI->getName(*ImpDefs) << "\n";
00219       }
00220     });
00221 
00222   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
00223     DOUT << "Cannot hoist with implicit defines or uses\n";
00224     return false;
00225   }
00226 
00227   // The instruction is loop invariant if all of its operands are.
00228   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
00229     const MachineOperand &MO = I.getOperand(i);
00230 
00231     if (!MO.isReg())
00232       continue;
00233 
00234     unsigned Reg = MO.getReg();
00235     if (Reg == 0) continue;
00236 
00237     // Don't hoist an instruction that uses or defines a physical register.
00238     if (TargetRegisterInfo::isPhysicalRegister(Reg))
00239       return false;
00240 
00241     if (!MO.isUse())
00242       continue;
00243 
00244     assert(RegInfo->getVRegDef(Reg) &&
00245            "Machine instr not mapped for this vreg?!");
00246 
00247     // If the loop contains the definition of an operand, then the instruction
00248     // isn't loop invariant.
00249     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
00250       return false;
00251   }
00252 
00253   // If we got this far, the instruction is loop invariant!
00254   return true;
00255 }
00256 
00257 /// Hoist - When an instruction is found to use only loop invariant operands
00258 /// that are safe to hoist, this instruction is called to do the dirty work.
00259 ///
00260 void MachineLICM::Hoist(MachineInstr &MI) {
00261   if (!IsLoopInvariantInst(MI)) return;
00262 
00263   // Now move the instructions to the predecessor, inserting it before any
00264   // terminator instructions.
00265   DEBUG({
00266       DOUT << "Hoisting " << MI;
00267       if (CurPreheader->getBasicBlock())
00268         DOUT << " to MachineBasicBlock "
00269              << CurPreheader->getBasicBlock()->getName();
00270       if (MI.getParent()->getBasicBlock())
00271         DOUT << " from MachineBasicBlock "
00272              << MI.getParent()->getBasicBlock()->getName();
00273       DOUT << "\n";
00274     });
00275 
00276   CurPreheader->splice(CurPreheader->getFirstTerminator(), MI.getParent(), &MI);
00277 
00278   ++NumHoisted;
00279   Changed = true;
00280 }