Code refactoring.
[oota-llvm.git] / lib / CodeGen / MachineLICM.cpp
1 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion on machine instructions. We
11 // attempt to remove as much code from the body of a loop as possible.
12 //
13 // This pass does not attempt to throttle itself to limit register pressure.
14 // The register allocation phases are expected to perform rematerialization
15 // to recover when register pressure is high.
16 //
17 // This pass is not intended to be a replacement or a complete alternative
18 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19 // constructs that are not exposed before lowering and instruction selection.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #define DEBUG_TYPE "machine-licm"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
42 STATISTIC(NumCSEed,   "Number of hoisted machine instructions CSEed");
43
44 namespace {
45   class MachineLICM : public MachineFunctionPass {
46     const TargetMachine   *TM;
47     const TargetInstrInfo *TII;
48     const TargetRegisterInfo *TRI;
49     BitVector AllocatableSet;
50
51     // Various analyses that we use...
52     AliasAnalysis        *AA;      // Alias analysis info.
53     MachineLoopInfo      *LI;      // Current MachineLoopInfo
54     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
55     MachineRegisterInfo  *RegInfo; // Machine register information
56
57     // State that is updated as we process loops
58     bool         Changed;          // True if a loop is changed.
59     bool         FirstInLoop;      // True if it's the first LICM in the loop.
60     MachineLoop *CurLoop;          // The current loop we are working on.
61     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
62
63     // For each opcode, keep a list of potentail CSE instructions.
64     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
65   public:
66     static char ID; // Pass identification, replacement for typeid
67     MachineLICM() : MachineFunctionPass(&ID) {}
68
69     virtual bool runOnMachineFunction(MachineFunction &MF);
70
71     const char *getPassName() const { return "Machine Instruction LICM"; }
72
73     // FIXME: Loop preheaders?
74     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75       AU.setPreservesCFG();
76       AU.addRequired<MachineLoopInfo>();
77       AU.addRequired<MachineDominatorTree>();
78       AU.addRequired<AliasAnalysis>();
79       AU.addPreserved<MachineLoopInfo>();
80       AU.addPreserved<MachineDominatorTree>();
81       MachineFunctionPass::getAnalysisUsage(AU);
82     }
83
84     virtual void releaseMemory() {
85       CSEMap.clear();
86     }
87
88   private:
89     /// IsLoopInvariantInst - Returns true if the instruction is loop
90     /// invariant. I.e., all virtual register operands are defined outside of
91     /// the loop, physical registers aren't accessed (explicitly or implicitly),
92     /// and the instruction is hoistable.
93     /// 
94     bool IsLoopInvariantInst(MachineInstr &I);
95
96     /// IsProfitableToHoist - Return true if it is potentially profitable to
97     /// hoist the given loop invariant.
98     bool IsProfitableToHoist(MachineInstr &MI);
99
100     /// HoistRegion - Walk the specified region of the CFG (defined by all
101     /// blocks dominated by the specified block, and that are in the current
102     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103     /// visit definitions before uses, allowing us to hoist a loop body in one
104     /// pass without iteration.
105     ///
106     void HoistRegion(MachineDomTreeNode *N);
107
108     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109     /// the load itself could be hoisted. Return the unfolded and hoistable
110     /// load, or null if the load couldn't be unfolded or if it wouldn't
111     /// be hoistable.
112     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
113
114     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
115     /// the preheader that compute the same value. If it's found, do a RAU on
116     /// with the definition of the existing instruction rather than hoisting
117     /// the instruction to the preheader.
118     bool EliminateCSE(MachineInstr *MI,
119            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
120
121     /// Hoist - When an instruction is found to only use loop invariant operands
122     /// that is safe to hoist, this instruction is called to do the dirty work.
123     ///
124     void Hoist(MachineInstr *MI);
125
126     /// InitCSEMap - Initialize the CSE map with instructions that are in the
127     /// current loop preheader that may become duplicates of instructions that
128     /// are hoisted out of the loop.
129     void InitCSEMap(MachineBasicBlock *BB);
130   };
131 } // end anonymous namespace
132
133 char MachineLICM::ID = 0;
134 static RegisterPass<MachineLICM>
135 X("machinelicm", "Machine Loop Invariant Code Motion");
136
137 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
138
139 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
140 /// loop that has a preheader.
141 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
142   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
143     if (L->getLoopPreheader())
144       return false;
145   return true;
146 }
147
148 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
149 /// is not preserved so it is not a good idea to run LICM multiple times on one
150 /// loop.
151 ///
152 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
153   DEBUG(errs() << "******** Machine LICM ********\n");
154
155   Changed = FirstInLoop = false;
156   TM = &MF.getTarget();
157   TII = TM->getInstrInfo();
158   TRI = TM->getRegisterInfo();
159   RegInfo = &MF.getRegInfo();
160   AllocatableSet = TRI->getAllocatableSet(MF);
161
162   // Get our Loop information...
163   LI = &getAnalysis<MachineLoopInfo>();
164   DT = &getAnalysis<MachineDominatorTree>();
165   AA = &getAnalysis<AliasAnalysis>();
166
167   for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
168     CurLoop = *I;
169
170     // Only visit outer-most preheader-sporting loops.
171     if (!LoopIsOuterMostWithPreheader(CurLoop))
172       continue;
173
174     // Determine the block to which to hoist instructions. If we can't find a
175     // suitable loop preheader, we can't do any hoisting.
176     //
177     // FIXME: We are only hoisting if the basic block coming into this loop
178     // has only one successor. This isn't the case in general because we haven't
179     // broken critical edges or added preheaders.
180     CurPreheader = CurLoop->getLoopPreheader();
181     if (!CurPreheader)
182       continue;
183
184     // CSEMap is initialized for loop header when the first instruction is
185     // being hoisted.
186     FirstInLoop = true;
187     HoistRegion(DT->getNode(CurLoop->getHeader()));
188     CSEMap.clear();
189   }
190
191   return Changed;
192 }
193
194 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
195 /// dominated by the specified block, and that are in the current loop) in depth
196 /// first order w.r.t the DominatorTree. This allows us to visit definitions
197 /// before uses, allowing us to hoist a loop body in one pass without iteration.
198 ///
199 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
200   assert(N != 0 && "Null dominator tree node?");
201   MachineBasicBlock *BB = N->getBlock();
202
203   // If this subregion is not in the top level loop at all, exit.
204   if (!CurLoop->contains(BB)) return;
205
206   for (MachineBasicBlock::iterator
207          MII = BB->begin(), E = BB->end(); MII != E; ) {
208     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
209     Hoist(&*MII);
210     MII = NextMII;
211   }
212
213   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
214
215   for (unsigned I = 0, E = Children.size(); I != E; ++I)
216     HoistRegion(Children[I]);
217 }
218
219 /// IsLoopInvariantInst - Returns true if the instruction is loop
220 /// invariant. I.e., all virtual register operands are defined outside of the
221 /// loop, physical registers aren't accessed explicitly, and there are no side
222 /// effects that aren't captured by the operands or other flags.
223 /// 
224 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
225   const TargetInstrDesc &TID = I.getDesc();
226   
227   // Ignore stuff that we obviously can't hoist.
228   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
229       TID.hasUnmodeledSideEffects())
230     return false;
231
232   if (TID.mayLoad()) {
233     // Okay, this instruction does a load. As a refinement, we allow the target
234     // to decide whether the loaded value is actually a constant. If so, we can
235     // actually use it as a load.
236     if (!I.isInvariantLoad(AA))
237       // FIXME: we should be able to sink loads with no other side effects if
238       // there is nothing that can change memory from here until the end of
239       // block. This is a trivial form of alias analysis.
240       return false;
241   }
242
243   DEBUG({
244       errs() << "--- Checking if we can hoist " << I;
245       if (I.getDesc().getImplicitUses()) {
246         errs() << "  * Instruction has implicit uses:\n";
247
248         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
249         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
250              *ImpUses; ++ImpUses)
251           errs() << "      -> " << TRI->getName(*ImpUses) << "\n";
252       }
253
254       if (I.getDesc().getImplicitDefs()) {
255         errs() << "  * Instruction has implicit defines:\n";
256
257         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
258         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
259              *ImpDefs; ++ImpDefs)
260           errs() << "      -> " << TRI->getName(*ImpDefs) << "\n";
261       }
262     });
263
264   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
265     DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
266     return false;
267   }
268
269   // The instruction is loop invariant if all of its operands are.
270   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
271     const MachineOperand &MO = I.getOperand(i);
272
273     if (!MO.isReg())
274       continue;
275
276     unsigned Reg = MO.getReg();
277     if (Reg == 0) continue;
278
279     // Don't hoist an instruction that uses or defines a physical register.
280     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
281       if (MO.isUse()) {
282         // If the physreg has no defs anywhere, it's just an ambient register
283         // and we can freely move its uses. Alternatively, if it's allocatable,
284         // it could get allocated to something with a def during allocation.
285         if (!RegInfo->def_empty(Reg))
286           return false;
287         if (AllocatableSet.test(Reg))
288           return false;
289         // Check for a def among the register's aliases too.
290         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
291           unsigned AliasReg = *Alias;
292           if (!RegInfo->def_empty(AliasReg))
293             return false;
294           if (AllocatableSet.test(AliasReg))
295             return false;
296         }
297         // Otherwise it's safe to move.
298         continue;
299       } else if (!MO.isDead()) {
300         // A def that isn't dead. We can't move it.
301         return false;
302       }
303     }
304
305     if (!MO.isUse())
306       continue;
307
308     assert(RegInfo->getVRegDef(Reg) &&
309            "Machine instr not mapped for this vreg?!");
310
311     // If the loop contains the definition of an operand, then the instruction
312     // isn't loop invariant.
313     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
314       return false;
315   }
316
317   // If we got this far, the instruction is loop invariant!
318   return true;
319 }
320
321
322 /// HasPHIUses - Return true if the specified register has any PHI use.
323 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
324   for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
325          UE = RegInfo->use_end(); UI != UE; ++UI) {
326     MachineInstr *UseMI = &*UI;
327     if (UseMI->getOpcode() == TargetInstrInfo::PHI)
328       return true;
329   }
330   return false;
331 }
332
333 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
334 /// the given loop invariant.
335 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
336   if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
337     return false;
338
339   // FIXME: For now, only hoist re-materilizable instructions. LICM will
340   // increase register pressure. We want to make sure it doesn't increase
341   // spilling.
342   if (!TII->isTriviallyReMaterializable(&MI, AA))
343     return false;
344
345   // If result(s) of this instruction is used by PHIs, then don't hoist it.
346   // The presence of joins makes it difficult for current register allocator
347   // implementation to perform remat.
348   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
349     const MachineOperand &MO = MI.getOperand(i);
350     if (!MO.isReg() || !MO.isDef())
351       continue;
352     if (HasPHIUses(MO.getReg(), RegInfo))
353       return false;
354   }
355
356   return true;
357 }
358
359 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
360   // If not, we may be able to unfold a load and hoist that.
361   // First test whether the instruction is loading from an amenable
362   // memory location.
363   if (!MI->getDesc().mayLoad()) return 0;
364   if (!MI->hasOneMemOperand()) return 0;
365   MachineMemOperand *MMO = *MI->memoperands_begin();
366   if (MMO->isVolatile()) return 0;
367   MachineFunction &MF = *MI->getParent()->getParent();
368   if (!MMO->getValue()) return 0;
369   if (const PseudoSourceValue *PSV =
370         dyn_cast<PseudoSourceValue>(MMO->getValue())) {
371     if (!PSV->isConstant(MF.getFrameInfo())) return 0;
372   } else {
373     if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
374   }
375   // Next determine the register class for a temporary register.
376   unsigned LoadRegIndex;
377   unsigned NewOpc =
378     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
379                                     /*UnfoldLoad=*/true,
380                                     /*UnfoldStore=*/false,
381                                     &LoadRegIndex);
382   if (NewOpc == 0) return 0;
383   const TargetInstrDesc &TID = TII->get(NewOpc);
384   if (TID.getNumDefs() != 1) return 0;
385   const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
386   // Ok, we're unfolding. Create a temporary register and do the unfold.
387   unsigned Reg = RegInfo->createVirtualRegister(RC);
388   SmallVector<MachineInstr *, 2> NewMIs;
389   bool Success =
390     TII->unfoldMemoryOperand(MF, MI, Reg,
391                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
392                              NewMIs);
393   (void)Success;
394   assert(Success &&
395          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
396          "succeeded!");
397   assert(NewMIs.size() == 2 &&
398          "Unfolded a load into multiple instructions!");
399   MachineBasicBlock *MBB = MI->getParent();
400   MBB->insert(MI, NewMIs[0]);
401   MBB->insert(MI, NewMIs[1]);
402   // If unfolding produced a load that wasn't loop-invariant or profitable to
403   // hoist, discard the new instructions and bail.
404   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
405     NewMIs[0]->eraseFromParent();
406     NewMIs[1]->eraseFromParent();
407     return 0;
408   }
409   // Otherwise we successfully unfolded a load that we can hoist.
410   MI->eraseFromParent();
411   return NewMIs[0];
412 }
413
414 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
415   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
416     const MachineInstr *MI = &*I;
417     // FIXME: For now, only hoist re-materilizable instructions. LICM will
418     // increase register pressure. We want to make sure it doesn't increase
419     // spilling.
420     if (TII->isTriviallyReMaterializable(MI, AA)) {
421       unsigned Opcode = MI->getOpcode();
422       DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
423         CI = CSEMap.find(Opcode);
424       if (CI != CSEMap.end())
425         CI->second.push_back(MI);
426       else {
427         std::vector<const MachineInstr*> CSEMIs;
428         CSEMIs.push_back(MI);
429         CSEMap.insert(std::make_pair(Opcode, CSEMIs));
430       }
431     }
432   }
433 }
434
435 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
436                                       std::vector<const MachineInstr*> &PrevMIs,
437                                       MachineRegisterInfo *RegInfo) {
438   unsigned NumOps = MI->getNumOperands();
439   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
440     const MachineInstr *PrevMI = PrevMIs[i];
441     unsigned NumOps2 = PrevMI->getNumOperands();
442     if (NumOps != NumOps2)
443       continue;
444     bool IsSame = true;
445     for (unsigned j = 0; j != NumOps; ++j) {
446       const MachineOperand &MO = MI->getOperand(j);
447       if (MO.isReg() && MO.isDef()) {
448         if (RegInfo->getRegClass(MO.getReg()) !=
449             RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
450           IsSame = false;
451           break;
452         }
453         continue;
454       }
455       if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
456         IsSame = false;
457         break;
458       }
459     }
460     if (IsSame)
461       return PrevMI;
462   }
463   return 0;
464 }
465
466 bool MachineLICM::EliminateCSE(MachineInstr *MI,
467           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
468   if (CI != CSEMap.end()) {
469     if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo)) {
470       DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
471       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
472         const MachineOperand &MO = MI->getOperand(i);
473         if (MO.isReg() && MO.isDef())
474           RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
475       }
476       MI->eraseFromParent();
477       ++NumCSEed;
478       return true;
479     }
480   }
481   return false;
482 }
483
484 /// Hoist - When an instruction is found to use only loop invariant operands
485 /// that are safe to hoist, this instruction is called to do the dirty work.
486 ///
487 void MachineLICM::Hoist(MachineInstr *MI) {
488   // First check whether we should hoist this instruction.
489   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
490     // If not, try unfolding a hoistable load.
491     MI = ExtractHoistableLoad(MI);
492     if (!MI) return;
493   }
494
495   // Now move the instructions to the predecessor, inserting it before any
496   // terminator instructions.
497   DEBUG({
498       errs() << "Hoisting " << *MI;
499       if (CurPreheader->getBasicBlock())
500         errs() << " to MachineBasicBlock "
501                << CurPreheader->getBasicBlock()->getName();
502       if (MI->getParent()->getBasicBlock())
503         errs() << " from MachineBasicBlock "
504                << MI->getParent()->getBasicBlock()->getName();
505       errs() << "\n";
506     });
507
508   // If this is the first instruction being hoisted to the preheader,
509   // initialize the CSE map with potential common expressions.
510   InitCSEMap(CurPreheader);
511
512   // Look for opportunity to CSE the hoisted instruction.
513   unsigned Opcode = MI->getOpcode();
514   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
515     CI = CSEMap.find(Opcode);
516   if (!EliminateCSE(MI, CI)) {
517     // Otherwise, splice the instruction to the preheader.
518     CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
519
520     // Add to the CSE map.
521     if (CI != CSEMap.end())
522       CI->second.push_back(MI);
523     else {
524       std::vector<const MachineInstr*> CSEMIs;
525       CSEMIs.push_back(MI);
526       CSEMap.insert(std::make_pair(Opcode, CSEMIs));
527     }
528   }
529
530   ++NumHoisted;
531   Changed = true;
532 }