5ab0ff745d16406ca9e546eeb7bcbf8a1502ebd2
[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     MachineLoop *CurLoop;          // The current loop we are working on.
60     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
61
62     // For each BB and opcode pair, keep a list of hoisted instructions.
63     DenseMap<std::pair<unsigned, unsigned>,
64       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     /// Hoist - When an instruction is found to only use loop invariant operands
115     /// that is safe to hoist, this instruction is called to do the dirty work.
116     ///
117     void Hoist(MachineInstr *MI);
118   };
119 } // end anonymous namespace
120
121 char MachineLICM::ID = 0;
122 static RegisterPass<MachineLICM>
123 X("machinelicm", "Machine Loop Invariant Code Motion");
124
125 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
126
127 /// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
128 /// loop that has a preheader.
129 static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
130   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
131     if (L->getLoopPreheader())
132       return false;
133   return true;
134 }
135
136 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
137 /// is not preserved so it is not a good idea to run LICM multiple times on one
138 /// loop.
139 ///
140 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
141   DEBUG(errs() << "******** Machine LICM ********\n");
142
143   Changed = false;
144   TM = &MF.getTarget();
145   TII = TM->getInstrInfo();
146   TRI = TM->getRegisterInfo();
147   RegInfo = &MF.getRegInfo();
148   AllocatableSet = TRI->getAllocatableSet(MF);
149
150   // Get our Loop information...
151   LI = &getAnalysis<MachineLoopInfo>();
152   DT = &getAnalysis<MachineDominatorTree>();
153   AA = &getAnalysis<AliasAnalysis>();
154
155   for (MachineLoopInfo::iterator
156          I = LI->begin(), E = LI->end(); I != E; ++I) {
157     CurLoop = *I;
158
159     // Only visit outer-most preheader-sporting loops.
160     if (!LoopIsOuterMostWithPreheader(CurLoop))
161       continue;
162
163     // Determine the block to which to hoist instructions. If we can't find a
164     // suitable loop preheader, we can't do any hoisting.
165     //
166     // FIXME: We are only hoisting if the basic block coming into this loop
167     // has only one successor. This isn't the case in general because we haven't
168     // broken critical edges or added preheaders.
169     CurPreheader = CurLoop->getLoopPreheader();
170     if (!CurPreheader)
171       continue;
172
173     HoistRegion(DT->getNode(CurLoop->getHeader()));
174   }
175
176   return Changed;
177 }
178
179 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
180 /// dominated by the specified block, and that are in the current loop) in depth
181 /// first order w.r.t the DominatorTree. This allows us to visit definitions
182 /// before uses, allowing us to hoist a loop body in one pass without iteration.
183 ///
184 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
185   assert(N != 0 && "Null dominator tree node?");
186   MachineBasicBlock *BB = N->getBlock();
187
188   // If this subregion is not in the top level loop at all, exit.
189   if (!CurLoop->contains(BB)) return;
190
191   for (MachineBasicBlock::iterator
192          MII = BB->begin(), E = BB->end(); MII != E; ) {
193     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
194     MachineInstr &MI = *MII;
195
196     Hoist(&MI);
197
198     MII = NextMII;
199   }
200
201   const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
202
203   for (unsigned I = 0, E = Children.size(); I != E; ++I)
204     HoistRegion(Children[I]);
205 }
206
207 /// IsLoopInvariantInst - Returns true if the instruction is loop
208 /// invariant. I.e., all virtual register operands are defined outside of the
209 /// loop, physical registers aren't accessed explicitly, and there are no side
210 /// effects that aren't captured by the operands or other flags.
211 /// 
212 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
213   const TargetInstrDesc &TID = I.getDesc();
214   
215   // Ignore stuff that we obviously can't hoist.
216   if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
217       TID.hasUnmodeledSideEffects())
218     return false;
219
220   if (TID.mayLoad()) {
221     // Okay, this instruction does a load. As a refinement, we allow the target
222     // to decide whether the loaded value is actually a constant. If so, we can
223     // actually use it as a load.
224     if (!I.isInvariantLoad(AA))
225       // FIXME: we should be able to sink loads with no other side effects if
226       // there is nothing that can change memory from here until the end of
227       // block. This is a trivial form of alias analysis.
228       return false;
229   }
230
231   DEBUG({
232       errs() << "--- Checking if we can hoist " << I;
233       if (I.getDesc().getImplicitUses()) {
234         errs() << "  * Instruction has implicit uses:\n";
235
236         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
237         for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
238              *ImpUses; ++ImpUses)
239           errs() << "      -> " << TRI->getName(*ImpUses) << "\n";
240       }
241
242       if (I.getDesc().getImplicitDefs()) {
243         errs() << "  * Instruction has implicit defines:\n";
244
245         const TargetRegisterInfo *TRI = TM->getRegisterInfo();
246         for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
247              *ImpDefs; ++ImpDefs)
248           errs() << "      -> " << TRI->getName(*ImpDefs) << "\n";
249       }
250     });
251
252   if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
253     DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
254     return false;
255   }
256
257   // The instruction is loop invariant if all of its operands are.
258   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
259     const MachineOperand &MO = I.getOperand(i);
260
261     if (!MO.isReg())
262       continue;
263
264     unsigned Reg = MO.getReg();
265     if (Reg == 0) continue;
266
267     // Don't hoist an instruction that uses or defines a physical register.
268     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
269       if (MO.isUse()) {
270         // If the physreg has no defs anywhere, it's just an ambient register
271         // and we can freely move its uses. Alternatively, if it's allocatable,
272         // it could get allocated to something with a def during allocation.
273         if (!RegInfo->def_empty(Reg))
274           return false;
275         if (AllocatableSet.test(Reg))
276           return false;
277         // Check for a def among the register's aliases too.
278         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
279           unsigned AliasReg = *Alias;
280           if (!RegInfo->def_empty(AliasReg))
281             return false;
282           if (AllocatableSet.test(AliasReg))
283             return false;
284         }
285         // Otherwise it's safe to move.
286         continue;
287       } else if (!MO.isDead()) {
288         // A def that isn't dead. We can't move it.
289         return false;
290       }
291     }
292
293     if (!MO.isUse())
294       continue;
295
296     assert(RegInfo->getVRegDef(Reg) &&
297            "Machine instr not mapped for this vreg?!");
298
299     // If the loop contains the definition of an operand, then the instruction
300     // isn't loop invariant.
301     if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
302       return false;
303   }
304
305   // If we got this far, the instruction is loop invariant!
306   return true;
307 }
308
309
310 /// HasPHIUses - Return true if the specified register has any PHI use.
311 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
312   for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
313          UE = RegInfo->use_end(); UI != UE; ++UI) {
314     MachineInstr *UseMI = &*UI;
315     if (UseMI->getOpcode() == TargetInstrInfo::PHI)
316       return true;
317   }
318   return false;
319 }
320
321 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
322 /// the given loop invariant.
323 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
324   if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
325     return false;
326
327   // FIXME: For now, only hoist re-materilizable instructions. LICM will
328   // increase register pressure. We want to make sure it doesn't increase
329   // spilling.
330   if (!TII->isTriviallyReMaterializable(&MI, AA))
331     return false;
332
333   // If result(s) of this instruction is used by PHIs, then don't hoist it.
334   // The presence of joins makes it difficult for current register allocator
335   // implementation to perform remat.
336   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
337     const MachineOperand &MO = MI.getOperand(i);
338     if (!MO.isReg() || !MO.isDef())
339       continue;
340     if (HasPHIUses(MO.getReg(), RegInfo))
341       return false;
342   }
343
344   return true;
345 }
346
347 static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
348                                       std::vector<const MachineInstr*> &PrevMIs,
349                                       MachineRegisterInfo *RegInfo) {
350   unsigned NumOps = MI->getNumOperands();
351   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
352     const MachineInstr *PrevMI = PrevMIs[i];
353     unsigned NumOps2 = PrevMI->getNumOperands();
354     if (NumOps != NumOps2)
355       continue;
356     bool IsSame = true;
357     for (unsigned j = 0; j != NumOps; ++j) {
358       const MachineOperand &MO = MI->getOperand(j);
359       if (MO.isReg() && MO.isDef()) {
360         if (RegInfo->getRegClass(MO.getReg()) !=
361             RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
362           IsSame = false;
363           break;
364         }
365         continue;
366       }
367       if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
368         IsSame = false;
369         break;
370       }
371     }
372     if (IsSame)
373       return PrevMI;
374   }
375   return 0;
376 }
377
378 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
379   // If not, we may be able to unfold a load and hoist that.
380   // First test whether the instruction is loading from an amenable
381   // memory location.
382   if (!MI->getDesc().mayLoad()) return 0;
383   if (!MI->hasOneMemOperand()) return 0;
384   MachineMemOperand *MMO = *MI->memoperands_begin();
385   if (MMO->isVolatile()) return 0;
386   MachineFunction &MF = *MI->getParent()->getParent();
387   if (!MMO->getValue()) return 0;
388   if (const PseudoSourceValue *PSV =
389         dyn_cast<PseudoSourceValue>(MMO->getValue())) {
390     if (!PSV->isConstant(MF.getFrameInfo())) return 0;
391   } else {
392     if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
393   }
394   // Next determine the register class for a temporary register.
395   unsigned NewOpc =
396     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
397                                     /*UnfoldLoad=*/true,
398                                     /*UnfoldStore=*/false);
399   if (NewOpc == 0) return 0;
400   const TargetInstrDesc &TID = TII->get(NewOpc);
401   if (TID.getNumDefs() != 1) return 0;
402   const TargetRegisterClass *RC = TID.OpInfo[0].getRegClass(TRI);
403   // Ok, we're unfolding. Create a temporary register and do the unfold.
404   unsigned Reg = RegInfo->createVirtualRegister(RC);
405   SmallVector<MachineInstr *, 2> NewMIs;
406   bool Success =
407     TII->unfoldMemoryOperand(MF, MI, Reg,
408                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
409                              NewMIs);
410   (void)Success;
411   assert(Success &&
412          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
413          "succeeded!");
414   assert(NewMIs.size() == 2 &&
415          "Unfolded a load into multiple instructions!");
416   MachineBasicBlock *MBB = MI->getParent();
417   MBB->insert(MI, NewMIs[0]);
418   MBB->insert(MI, NewMIs[1]);
419   // If unfolding produced a load that wasn't loop-invariant or profitable to
420   // hoist, discard the new instructions and bail.
421   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
422     NewMIs[0]->eraseFromParent();
423     NewMIs[1]->eraseFromParent();
424     return 0;
425   }
426   // Otherwise we successfully unfolded a load that we can hoist.
427   MI->eraseFromParent();
428   return NewMIs[0];
429 }
430
431 /// Hoist - When an instruction is found to use only loop invariant operands
432 /// that are safe to hoist, this instruction is called to do the dirty work.
433 ///
434 void MachineLICM::Hoist(MachineInstr *MI) {
435   // First check whether we should hoist this instruction.
436   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
437     // If not, try unfolding a hoistable load.
438     MI = ExtractHoistableLoad(MI);
439     if (!MI) return;
440   }
441
442   // Now move the instructions to the predecessor, inserting it before any
443   // terminator instructions.
444   DEBUG({
445       errs() << "Hoisting " << *MI;
446       if (CurPreheader->getBasicBlock())
447         errs() << " to MachineBasicBlock "
448                << CurPreheader->getBasicBlock()->getName();
449       if (MI->getParent()->getBasicBlock())
450         errs() << " from MachineBasicBlock "
451                << MI->getParent()->getBasicBlock()->getName();
452       errs() << "\n";
453     });
454
455   // Look for opportunity to CSE the hoisted instruction.
456   std::pair<unsigned, unsigned> BBOpcPair =
457     std::make_pair(CurPreheader->getNumber(), MI->getOpcode());
458   DenseMap<std::pair<unsigned, unsigned>,
459     std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
460   bool DoneCSE = false;
461   if (CI != CSEMap.end()) {
462     const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
463     if (Dup) {
464       DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
465       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
466         const MachineOperand &MO = MI->getOperand(i);
467         if (MO.isReg() && MO.isDef())
468           RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
469       }
470       MI->eraseFromParent();
471       DoneCSE = true;
472       ++NumCSEed;
473     }
474   }
475
476   // Otherwise, splice the instruction to the preheader.
477   if (!DoneCSE) {
478     CurPreheader->splice(CurPreheader->getFirstTerminator(),
479                          MI->getParent(), MI);
480     // Add to the CSE map.
481     if (CI != CSEMap.end())
482       CI->second.push_back(MI);
483     else {
484       std::vector<const MachineInstr*> CSEMIs;
485       CSEMIs.push_back(MI);
486       CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));
487     }
488   }
489
490   ++NumHoisted;
491   Changed = true;
492 }