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