Get rid of static constructors for pass registration. Instead, every pass exposes...
[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/MachineFrameInfo.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/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetInstrItineraries.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43
44 using namespace llvm;
45
46 static cl::opt<bool>
47 TrackRegPressure("rp-aware-machine-licm",
48                  cl::desc("Register pressure aware machine LICM"),
49                  cl::init(false), cl::Hidden);
50
51 STATISTIC(NumHoisted,
52           "Number of machine instructions hoisted out of loops");
53 STATISTIC(NumLowRP,
54           "Number of instructions hoisted in low reg pressure situation");
55 STATISTIC(NumHighLatency,
56           "Number of high latency instructions hoisted");
57 STATISTIC(NumCSEed,
58           "Number of hoisted machine instructions CSEed");
59 STATISTIC(NumPostRAHoisted,
60           "Number of machine instructions hoisted out of loops post regalloc");
61
62 namespace {
63   class MachineLICM : public MachineFunctionPass {
64     bool PreRegAlloc;
65
66     const TargetMachine   *TM;
67     const TargetInstrInfo *TII;
68     const TargetLowering *TLI;
69     const TargetRegisterInfo *TRI;
70     const MachineFrameInfo *MFI;
71     MachineRegisterInfo *MRI;
72     const InstrItineraryData *InstrItins;
73
74     // Various analyses that we use...
75     AliasAnalysis        *AA;      // Alias analysis info.
76     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
77     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
78
79     // State that is updated as we process loops
80     bool         Changed;          // True if a loop is changed.
81     bool         FirstInLoop;      // True if it's the first LICM in the loop.
82     MachineLoop *CurLoop;          // The current loop we are working on.
83     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
84
85     BitVector AllocatableSet;
86
87     // Track 'estimated' register pressure.
88     SmallSet<unsigned, 32> RegSeen;
89     SmallVector<unsigned, 8> RegPressure;
90
91     // Register pressure "limit" per register class. If the pressure
92     // is higher than the limit, then it's considered high.
93     SmallVector<unsigned, 8> RegLimit;
94
95     // Register pressure on path leading from loop preheader to current BB.
96     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
97
98     // For each opcode, keep a list of potential CSE instructions.
99     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
100
101   public:
102     static char ID; // Pass identification, replacement for typeid
103     MachineLICM() :
104       MachineFunctionPass(ID), PreRegAlloc(true) {
105         initializeMachineLICMPass(*PassRegistry::getPassRegistry());
106       }
107
108     explicit MachineLICM(bool PreRA) :
109       MachineFunctionPass(ID), PreRegAlloc(PreRA) {
110         initializeMachineLICMPass(*PassRegistry::getPassRegistry());
111       }
112
113     virtual bool runOnMachineFunction(MachineFunction &MF);
114
115     const char *getPassName() const { return "Machine Instruction LICM"; }
116
117     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118       AU.setPreservesCFG();
119       AU.addRequired<MachineLoopInfo>();
120       AU.addRequired<MachineDominatorTree>();
121       AU.addRequired<AliasAnalysis>();
122       AU.addPreserved<MachineLoopInfo>();
123       AU.addPreserved<MachineDominatorTree>();
124       MachineFunctionPass::getAnalysisUsage(AU);
125     }
126
127     virtual void releaseMemory() {
128       RegSeen.clear();
129       RegPressure.clear();
130       RegLimit.clear();
131       for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
132              CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
133         CI->second.clear();
134       CSEMap.clear();
135     }
136
137   private:
138     /// CandidateInfo - Keep track of information about hoisting candidates.
139     struct CandidateInfo {
140       MachineInstr *MI;
141       unsigned      Def;
142       int           FI;
143       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
144         : MI(mi), Def(def), FI(fi) {}
145     };
146
147     /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
148     /// invariants out to the preheader.
149     void HoistRegionPostRA();
150
151     /// HoistPostRA - When an instruction is found to only use loop invariant
152     /// operands that is safe to hoist, this instruction is called to do the
153     /// dirty work.
154     void HoistPostRA(MachineInstr *MI, unsigned Def);
155
156     /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
157     /// gather register def and frame object update information.
158     void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
159                    SmallSet<int, 32> &StoredFIs,
160                    SmallVector<CandidateInfo, 32> &Candidates);
161
162     /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
163     /// current loop.
164     void AddToLiveIns(unsigned Reg);
165
166     /// IsLICMCandidate - Returns true if the instruction may be a suitable
167     /// candidate for LICM. e.g. If the instruction is a call, then it's
168     /// obviously not safe to hoist it.
169     bool IsLICMCandidate(MachineInstr &I);
170
171     /// IsLoopInvariantInst - Returns true if the instruction is loop
172     /// invariant. I.e., all virtual register operands are defined outside of
173     /// the loop, physical registers aren't accessed (explicitly or implicitly),
174     /// and the instruction is hoistable.
175     /// 
176     bool IsLoopInvariantInst(MachineInstr &I);
177
178     /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
179     /// and an use in the current loop.
180     int ComputeOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
181
182     /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
183     /// if hoisting an instruction of the given cost matrix can cause high
184     /// register pressure.
185     bool IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost);
186
187     /// IsProfitableToHoist - Return true if it is potentially profitable to
188     /// hoist the given loop invariant.
189     bool IsProfitableToHoist(MachineInstr &MI);
190
191     /// HoistRegion - Walk the specified region of the CFG (defined by all
192     /// blocks dominated by the specified block, and that are in the current
193     /// loop) in depth first order w.r.t the DominatorTree. This allows us to
194     /// visit definitions before uses, allowing us to hoist a loop body in one
195     /// pass without iteration.
196     ///
197     void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
198
199     /// InitRegPressure - Find all virtual register references that are liveout
200     /// of the preheader to initialize the starting "register pressure". Note
201     /// this does not count live through (livein but not used) registers.
202     void InitRegPressure(MachineBasicBlock *BB);
203
204     /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
205     /// register pressure before and after executing a specifi instruction.
206     void UpdateRegPressureBefore(const MachineInstr *MI);
207     void UpdateRegPressureAfter(const MachineInstr *MI);
208
209     /// isLoadFromConstantMemory - Return true if the given instruction is a
210     /// load from constant memory.
211     bool isLoadFromConstantMemory(MachineInstr *MI);
212
213     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
214     /// the load itself could be hoisted. Return the unfolded and hoistable
215     /// load, or null if the load couldn't be unfolded or if it wouldn't
216     /// be hoistable.
217     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
218
219     /// LookForDuplicate - Find an instruction amount PrevMIs that is a
220     /// duplicate of MI. Return this instruction if it's found.
221     const MachineInstr *LookForDuplicate(const MachineInstr *MI,
222                                      std::vector<const MachineInstr*> &PrevMIs);
223
224     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
225     /// the preheader that compute the same value. If it's found, do a RAU on
226     /// with the definition of the existing instruction rather than hoisting
227     /// the instruction to the preheader.
228     bool EliminateCSE(MachineInstr *MI,
229            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
230
231     /// Hoist - When an instruction is found to only use loop invariant operands
232     /// that is safe to hoist, this instruction is called to do the dirty work.
233     ///
234     void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
235
236     /// InitCSEMap - Initialize the CSE map with instructions that are in the
237     /// current loop preheader that may become duplicates of instructions that
238     /// are hoisted out of the loop.
239     void InitCSEMap(MachineBasicBlock *BB);
240
241     /// getCurPreheader - Get the preheader for the current loop, splitting
242     /// a critical edge if needed.
243     MachineBasicBlock *getCurPreheader();
244   };
245 } // end anonymous namespace
246
247 char MachineLICM::ID = 0;
248 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
249                 "Machine Loop Invariant Code Motion", false, false)
250 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
251 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
252 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
253 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
254                 "Machine Loop Invariant Code Motion", false, false)
255
256 FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
257   return new MachineLICM(PreRegAlloc);
258 }
259
260 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
261 /// loop that has a unique predecessor.
262 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
263   // Check whether this loop even has a unique predecessor.
264   if (!CurLoop->getLoopPredecessor())
265     return false;
266   // Ok, now check to see if any of its outer loops do.
267   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
268     if (L->getLoopPredecessor())
269       return false;
270   // None of them did, so this is the outermost with a unique predecessor.
271   return true;
272 }
273
274 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
275   if (PreRegAlloc)
276     DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
277   else
278     DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
279   DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
280
281   Changed = FirstInLoop = false;
282   TM = &MF.getTarget();
283   TII = TM->getInstrInfo();
284   TLI = TM->getTargetLowering();
285   TRI = TM->getRegisterInfo();
286   MFI = MF.getFrameInfo();
287   MRI = &MF.getRegInfo();
288   InstrItins = TM->getInstrItineraryData();
289   AllocatableSet = TRI->getAllocatableSet(MF);
290
291   if (PreRegAlloc) {
292     // Estimate register pressure during pre-regalloc pass.
293     unsigned NumRC = TRI->getNumRegClasses();
294     RegPressure.resize(NumRC);
295     std::fill(RegPressure.begin(), RegPressure.end(), 0);
296     RegLimit.resize(NumRC);
297     for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
298            E = TRI->regclass_end(); I != E; ++I)
299       RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
300   }
301
302   // Get our Loop information...
303   MLI = &getAnalysis<MachineLoopInfo>();
304   DT  = &getAnalysis<MachineDominatorTree>();
305   AA  = &getAnalysis<AliasAnalysis>();
306
307   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
308   while (!Worklist.empty()) {
309     CurLoop = Worklist.pop_back_val();
310     CurPreheader = 0;
311
312     // If this is done before regalloc, only visit outer-most preheader-sporting
313     // loops.
314     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
315       Worklist.append(CurLoop->begin(), CurLoop->end());
316       continue;
317     }
318
319     if (!PreRegAlloc)
320       HoistRegionPostRA();
321     else {
322       // CSEMap is initialized for loop header when the first instruction is
323       // being hoisted.
324       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
325       FirstInLoop = true;
326       HoistRegion(N, true);
327       CSEMap.clear();
328     }
329   }
330
331   return Changed;
332 }
333
334 /// InstructionStoresToFI - Return true if instruction stores to the
335 /// specified frame.
336 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
337   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
338          oe = MI->memoperands_end(); o != oe; ++o) {
339     if (!(*o)->isStore() || !(*o)->getValue())
340       continue;
341     if (const FixedStackPseudoSourceValue *Value =
342         dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
343       if (Value->getFrameIndex() == FI)
344         return true;
345     }
346   }
347   return false;
348 }
349
350 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
351 /// gather register def and frame object update information.
352 void MachineLICM::ProcessMI(MachineInstr *MI,
353                             unsigned *PhysRegDefs,
354                             SmallSet<int, 32> &StoredFIs,
355                             SmallVector<CandidateInfo, 32> &Candidates) {
356   bool RuledOut = false;
357   bool HasNonInvariantUse = false;
358   unsigned Def = 0;
359   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
360     const MachineOperand &MO = MI->getOperand(i);
361     if (MO.isFI()) {
362       // Remember if the instruction stores to the frame index.
363       int FI = MO.getIndex();
364       if (!StoredFIs.count(FI) &&
365           MFI->isSpillSlotObjectIndex(FI) &&
366           InstructionStoresToFI(MI, FI))
367         StoredFIs.insert(FI);
368       HasNonInvariantUse = true;
369       continue;
370     }
371
372     if (!MO.isReg())
373       continue;
374     unsigned Reg = MO.getReg();
375     if (!Reg)
376       continue;
377     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
378            "Not expecting virtual register!");
379
380     if (!MO.isDef()) {
381       if (Reg && PhysRegDefs[Reg])
382         // If it's using a non-loop-invariant register, then it's obviously not
383         // safe to hoist.
384         HasNonInvariantUse = true;
385       continue;
386     }
387
388     if (MO.isImplicit()) {
389       ++PhysRegDefs[Reg];
390       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
391         ++PhysRegDefs[*AS];
392       if (!MO.isDead())
393         // Non-dead implicit def? This cannot be hoisted.
394         RuledOut = true;
395       // No need to check if a dead implicit def is also defined by
396       // another instruction.
397       continue;
398     }
399
400     // FIXME: For now, avoid instructions with multiple defs, unless
401     // it's a dead implicit def.
402     if (Def)
403       RuledOut = true;
404     else
405       Def = Reg;
406
407     // If we have already seen another instruction that defines the same
408     // register, then this is not safe.
409     if (++PhysRegDefs[Reg] > 1)
410       // MI defined register is seen defined by another instruction in
411       // the loop, it cannot be a LICM candidate.
412       RuledOut = true;
413     for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
414       if (++PhysRegDefs[*AS] > 1)
415         RuledOut = true;
416   }
417
418   // Only consider reloads for now and remats which do not have register
419   // operands. FIXME: Consider unfold load folding instructions.
420   if (Def && !RuledOut) {
421     int FI = INT_MIN;
422     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
423         (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
424       Candidates.push_back(CandidateInfo(MI, Def, FI));
425   }
426 }
427
428 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
429 /// invariants out to the preheader.
430 void MachineLICM::HoistRegionPostRA() {
431   unsigned NumRegs = TRI->getNumRegs();
432   unsigned *PhysRegDefs = new unsigned[NumRegs];
433   std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
434
435   SmallVector<CandidateInfo, 32> Candidates;
436   SmallSet<int, 32> StoredFIs;
437
438   // Walk the entire region, count number of defs for each register, and
439   // collect potential LICM candidates.
440   const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
441   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
442     MachineBasicBlock *BB = Blocks[i];
443     // Conservatively treat live-in's as an external def.
444     // FIXME: That means a reload that're reused in successor block(s) will not
445     // be LICM'ed.
446     for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
447            E = BB->livein_end(); I != E; ++I) {
448       unsigned Reg = *I;
449       ++PhysRegDefs[Reg];
450       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
451         ++PhysRegDefs[*AS];
452     }
453
454     for (MachineBasicBlock::iterator
455            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
456       MachineInstr *MI = &*MII;
457       ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
458     }
459   }
460
461   // Now evaluate whether the potential candidates qualify.
462   // 1. Check if the candidate defined register is defined by another
463   //    instruction in the loop.
464   // 2. If the candidate is a load from stack slot (always true for now),
465   //    check if the slot is stored anywhere in the loop.
466   for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
467     if (Candidates[i].FI != INT_MIN &&
468         StoredFIs.count(Candidates[i].FI))
469       continue;
470
471     if (PhysRegDefs[Candidates[i].Def] == 1) {
472       bool Safe = true;
473       MachineInstr *MI = Candidates[i].MI;
474       for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
475         const MachineOperand &MO = MI->getOperand(j);
476         if (!MO.isReg() || MO.isDef() || !MO.getReg())
477           continue;
478         if (PhysRegDefs[MO.getReg()]) {
479           // If it's using a non-loop-invariant register, then it's obviously
480           // not safe to hoist.
481           Safe = false;
482           break;
483         }
484       }
485       if (Safe)
486         HoistPostRA(MI, Candidates[i].Def);
487     }
488   }
489
490   delete[] PhysRegDefs;
491 }
492
493 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
494 /// loop, and make sure it is not killed by any instructions in the loop.
495 void MachineLICM::AddToLiveIns(unsigned Reg) {
496   const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
497   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
498     MachineBasicBlock *BB = Blocks[i];
499     if (!BB->isLiveIn(Reg))
500       BB->addLiveIn(Reg);
501     for (MachineBasicBlock::iterator
502            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
503       MachineInstr *MI = &*MII;
504       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
505         MachineOperand &MO = MI->getOperand(i);
506         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
507         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
508           MO.setIsKill(false);
509       }
510     }
511   }
512 }
513
514 /// HoistPostRA - When an instruction is found to only use loop invariant
515 /// operands that is safe to hoist, this instruction is called to do the
516 /// dirty work.
517 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
518   MachineBasicBlock *Preheader = getCurPreheader();
519   if (!Preheader) return;
520
521   // Now move the instructions to the predecessor, inserting it before any
522   // terminator instructions.
523   DEBUG({
524       dbgs() << "Hoisting " << *MI;
525       if (Preheader->getBasicBlock())
526         dbgs() << " to MachineBasicBlock "
527                << Preheader->getName();
528       if (MI->getParent()->getBasicBlock())
529         dbgs() << " from MachineBasicBlock "
530                << MI->getParent()->getName();
531       dbgs() << "\n";
532     });
533
534   // Splice the instruction to the preheader.
535   MachineBasicBlock *MBB = MI->getParent();
536   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
537
538   // Add register to livein list to all the BBs in the current loop since a 
539   // loop invariant must be kept live throughout the whole loop. This is
540   // important to ensure later passes do not scavenge the def register.
541   AddToLiveIns(Def);
542
543   ++NumPostRAHoisted;
544   Changed = true;
545 }
546
547 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
548 /// dominated by the specified block, and that are in the current loop) in depth
549 /// first order w.r.t the DominatorTree. This allows us to visit definitions
550 /// before uses, allowing us to hoist a loop body in one pass without iteration.
551 ///
552 void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
553   assert(N != 0 && "Null dominator tree node?");
554   MachineBasicBlock *BB = N->getBlock();
555
556   // If this subregion is not in the top level loop at all, exit.
557   if (!CurLoop->contains(BB)) return;
558
559   MachineBasicBlock *Preheader = getCurPreheader();
560   if (!Preheader)
561     return;
562
563   if (TrackRegPressure) {
564     if (IsHeader) {
565       // Compute registers which are liveout of preheader.
566       RegSeen.clear();
567       BackTrace.clear();
568       InitRegPressure(Preheader);
569     }
570
571     // Remember livein register pressure.
572     BackTrace.push_back(RegPressure);
573   }
574
575   for (MachineBasicBlock::iterator
576          MII = BB->begin(), E = BB->end(); MII != E; ) {
577     MachineBasicBlock::iterator NextMII = MII; ++NextMII;
578     MachineInstr *MI = &*MII;
579
580     if (TrackRegPressure)
581       UpdateRegPressureBefore(MI);
582     Hoist(MI, Preheader);
583     if (TrackRegPressure)
584       UpdateRegPressureAfter(MI);
585
586     MII = NextMII;
587   }
588
589   // Don't hoist things out of a large switch statement.  This often causes
590   // code to be hoisted that wasn't going to be executed, and increases
591   // register pressure in a situation where it's likely to matter.
592   if (BB->succ_size() < 25) {
593     const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
594     for (unsigned I = 0, E = Children.size(); I != E; ++I)
595       HoistRegion(Children[I]);
596   }
597
598   if (TrackRegPressure)
599     BackTrace.pop_back();
600 }
601
602 /// InitRegPressure - Find all virtual register references that are liveout of
603 /// the preheader to initialize the starting "register pressure". Note this
604 /// does not count live through (livein but not used) registers.
605 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
606   std::fill(RegPressure.begin(), RegPressure.end(), 0);
607
608   for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
609        MII != E; ++MII) {
610     MachineInstr *MI = &*MII;
611     for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
612       const MachineOperand &MO = MI->getOperand(i);
613       if (!MO.isReg() || MO.isImplicit())
614         continue;
615       unsigned Reg = MO.getReg();
616       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
617         continue;
618
619       bool isNew = RegSeen.insert(Reg);
620       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
621       EVT VT = *RC->vt_begin();
622       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
623       if (MO.isDef())
624         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
625       else {
626         if (isNew && !MO.isKill())
627           // Haven't seen this, it must be a livein.
628           RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
629         else if (!isNew && MO.isKill())
630           RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
631       }
632     }
633   }
634 }
635
636 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
637 /// register pressure before and after executing a specifi instruction.
638 void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI) {
639   bool NoImpact = MI->isImplicitDef() || MI->isPHI();
640
641   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
642     const MachineOperand &MO = MI->getOperand(i);
643     if (!MO.isReg() || MO.isImplicit() || !MO.isUse())
644       continue;
645     unsigned Reg = MO.getReg();
646     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
647       continue;
648
649     bool isNew = RegSeen.insert(Reg);
650     if (NoImpact)
651       continue;
652
653     if (!isNew && MO.isKill()) {
654       const TargetRegisterClass *RC = MRI->getRegClass(Reg);
655       EVT VT = *RC->vt_begin();
656       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
657       unsigned RCCost = TLI->getRepRegClassCostFor(VT);
658
659       assert(RCCost <= RegPressure[RCId]);
660       RegPressure[RCId] -= RCCost;
661     }
662   }
663 }
664
665 void MachineLICM::UpdateRegPressureAfter(const MachineInstr *MI) {
666   bool NoImpact = MI->isImplicitDef() || MI->isPHI();
667
668   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
669     const MachineOperand &MO = MI->getOperand(i);
670     if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
671       continue;
672     unsigned Reg = MO.getReg();
673     if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
674       continue;
675
676     RegSeen.insert(Reg);
677     if (NoImpact)
678       continue;
679
680     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
681     EVT VT = *RC->vt_begin();
682     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
683     unsigned RCCost = TLI->getRepRegClassCostFor(VT);
684     RegPressure[RCId] += RCCost;
685   }
686 }
687
688 /// IsLICMCandidate - Returns true if the instruction may be a suitable
689 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
690 /// not safe to hoist it.
691 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
692   // Check if it's safe to move the instruction.
693   bool DontMoveAcrossStore = true;
694   if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
695     return false;
696   
697   return true;
698 }
699
700 /// IsLoopInvariantInst - Returns true if the instruction is loop
701 /// invariant. I.e., all virtual register operands are defined outside of the
702 /// loop, physical registers aren't accessed explicitly, and there are no side
703 /// effects that aren't captured by the operands or other flags.
704 /// 
705 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
706   if (!IsLICMCandidate(I))
707     return false;
708
709   // The instruction is loop invariant if all of its operands are.
710   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
711     const MachineOperand &MO = I.getOperand(i);
712
713     if (!MO.isReg())
714       continue;
715
716     unsigned Reg = MO.getReg();
717     if (Reg == 0) continue;
718
719     // Don't hoist an instruction that uses or defines a physical register.
720     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
721       if (MO.isUse()) {
722         // If the physreg has no defs anywhere, it's just an ambient register
723         // and we can freely move its uses. Alternatively, if it's allocatable,
724         // it could get allocated to something with a def during allocation.
725         if (!MRI->def_empty(Reg))
726           return false;
727         if (AllocatableSet.test(Reg))
728           return false;
729         // Check for a def among the register's aliases too.
730         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
731           unsigned AliasReg = *Alias;
732           if (!MRI->def_empty(AliasReg))
733             return false;
734           if (AllocatableSet.test(AliasReg))
735             return false;
736         }
737         // Otherwise it's safe to move.
738         continue;
739       } else if (!MO.isDead()) {
740         // A def that isn't dead. We can't move it.
741         return false;
742       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
743         // If the reg is live into the loop, we can't hoist an instruction
744         // which would clobber it.
745         return false;
746       }
747     }
748
749     if (!MO.isUse())
750       continue;
751
752     assert(MRI->getVRegDef(Reg) &&
753            "Machine instr not mapped for this vreg?!");
754
755     // If the loop contains the definition of an operand, then the instruction
756     // isn't loop invariant.
757     if (CurLoop->contains(MRI->getVRegDef(Reg)))
758       return false;
759   }
760
761   // If we got this far, the instruction is loop invariant!
762   return true;
763 }
764
765
766 /// HasPHIUses - Return true if the specified register has any PHI use.
767 static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
768   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
769          UE = MRI->use_end(); UI != UE; ++UI) {
770     MachineInstr *UseMI = &*UI;
771     if (UseMI->isPHI())
772       return true;
773   }
774   return false;
775 }
776
777 /// isLoadFromConstantMemory - Return true if the given instruction is a
778 /// load from constant memory. Machine LICM will hoist these even if they are
779 /// not re-materializable.
780 bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
781   if (!MI->getDesc().mayLoad()) return false;
782   if (!MI->hasOneMemOperand()) return false;
783   MachineMemOperand *MMO = *MI->memoperands_begin();
784   if (MMO->isVolatile()) return false;
785   if (!MMO->getValue()) return false;
786   const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
787   if (PSV) {
788     MachineFunction &MF = *MI->getParent()->getParent();
789     return PSV->isConstant(MF.getFrameInfo());
790   } else {
791     return AA->pointsToConstantMemory(MMO->getValue());
792   }
793 }
794
795 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
796 /// and an use in the current loop.
797 int MachineLICM::ComputeOperandLatency(MachineInstr &MI,
798                                        unsigned DefIdx, unsigned Reg) {
799   if (MRI->use_nodbg_empty(Reg))
800     // No use? Return arbitrary large number!
801     return 300;
802
803   int Latency = -1;
804   for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
805          E = MRI->use_nodbg_end(); I != E; ++I) {
806     MachineInstr *UseMI = &*I;
807     if (!CurLoop->contains(UseMI->getParent()))
808       continue;
809     for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
810       const MachineOperand &MO = UseMI->getOperand(i);
811       if (!MO.isReg() || !MO.isUse())
812         continue;
813       unsigned MOReg = MO.getReg();
814       if (MOReg != Reg)
815         continue;
816
817       int UseCycle = TII->getOperandLatency(InstrItins, &MI, DefIdx, UseMI, i);
818       Latency = std::max(Latency, UseCycle);
819     }
820
821     if (Latency != -1)
822       break;
823   }
824
825   if (Latency == -1)
826     Latency = InstrItins->getOperandCycle(MI.getDesc().getSchedClass(), DefIdx);
827
828   return Latency;
829 }
830
831 /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
832 /// if hoisting an instruction of the given cost matrix can cause high
833 /// register pressure.
834 bool MachineLICM::IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost) {
835   for (unsigned i = BackTrace.size(); i != 0; --i) {
836     bool AnyIncrease = false;
837     SmallVector<unsigned, 8> &RP = BackTrace[i-1];
838     for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
839          CI != CE; ++CI) {
840       if (CI->second <= 0) 
841         continue;
842       AnyIncrease = true;
843       unsigned RCId = CI->first;
844       if (RP[RCId] + CI->second >= RegLimit[RCId])
845         return true;
846     }
847
848     if (!AnyIncrease)
849       // Hoisting the instruction doesn't increase register pressure.
850       return false;
851   }
852
853   return false;
854 }
855
856 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
857 /// the given loop invariant.
858 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
859   if (MI.isImplicitDef())
860     return true;
861
862   // FIXME: For now, only hoist re-materilizable instructions. LICM will
863   // increase register pressure. We want to make sure it doesn't increase
864   // spilling.
865   // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
866   // these tend to help performance in low register pressure situation. The
867   // trade off is it may cause spill in high pressure situation. It will end up
868   // adding a store in the loop preheader. But the reload is no more expensive.
869   // The side benefit is these loads are frequently CSE'ed.
870   if (!TrackRegPressure || MI.getDesc().isAsCheapAsAMove()) {
871     if (!TII->isTriviallyReMaterializable(&MI, AA) &&
872         !isLoadFromConstantMemory(&MI))
873       return false;
874   } else {
875     // In low register pressure situation, we can be more aggressive about 
876     // hoisting. Also, favors hoisting long latency instructions even in
877     // moderately high pressure situation.
878     DenseMap<unsigned, int> Cost;
879     for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
880       const MachineOperand &MO = MI.getOperand(i);
881       if (!MO.isReg() || MO.isImplicit())
882         continue;
883       unsigned Reg = MO.getReg();
884       if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
885         continue;
886       if (MO.isDef()) {
887         if (InstrItins && !InstrItins->isEmpty()) {
888           int Cycle = ComputeOperandLatency(MI, i, Reg);
889           if (Cycle > 3) {
890             // FIXME: Target specific high latency limit?
891             ++NumHighLatency;
892             return true;
893           }
894         }
895
896         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
897         EVT VT = *RC->vt_begin();
898         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
899         unsigned RCCost = TLI->getRepRegClassCostFor(VT);
900         DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
901         // If the instruction is not register pressure neutrail (or better),
902         // check if hoisting it will cause high register pressure in BB's
903         // leading up to this point.
904         if (CI != Cost.end())
905           CI->second += RCCost;
906         else
907           Cost.insert(std::make_pair(RCId, RCCost));
908       } else if (MO.isKill()) {
909         // Is a virtual register use is a kill, hoisting it out of the loop
910         // may actually reduce register pressure or be register pressure
911         // neutral
912         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
913         EVT VT = *RC->vt_begin();
914         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
915         unsigned RCCost = TLI->getRepRegClassCostFor(VT);
916         DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
917         if (CI != Cost.end())
918           CI->second -= RCCost;
919         else
920           Cost.insert(std::make_pair(RCId, -RCCost));
921       }
922     }
923
924     // Visit BBs from preheader to current BB, if hoisting this doesn't cause
925     // high register pressure, then it's safe to proceed.
926     if (!IncreaseHighRegPressure(Cost)) {
927       ++NumLowRP;
928       return true;
929     }
930
931     // High register pressure situation, only hoist if the instruction is going to
932     // be remat'ed.
933     if (!TII->isTriviallyReMaterializable(&MI, AA) &&
934         !isLoadFromConstantMemory(&MI))
935       return false;
936   }
937
938   // If result(s) of this instruction is used by PHIs, then don't hoist it.
939   // The presence of joins makes it difficult for current register allocator
940   // implementation to perform remat.
941   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
942     const MachineOperand &MO = MI.getOperand(i);
943     if (!MO.isReg() || !MO.isDef())
944       continue;
945     if (HasPHIUses(MO.getReg(), MRI))
946       return false;
947   }
948
949   return true;
950 }
951
952 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
953   // Don't unfold simple loads.
954   if (MI->getDesc().canFoldAsLoad())
955     return 0;
956
957   // If not, we may be able to unfold a load and hoist that.
958   // First test whether the instruction is loading from an amenable
959   // memory location.
960   if (!isLoadFromConstantMemory(MI))
961     return 0;
962
963   // Next determine the register class for a temporary register.
964   unsigned LoadRegIndex;
965   unsigned NewOpc =
966     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
967                                     /*UnfoldLoad=*/true,
968                                     /*UnfoldStore=*/false,
969                                     &LoadRegIndex);
970   if (NewOpc == 0) return 0;
971   const TargetInstrDesc &TID = TII->get(NewOpc);
972   if (TID.getNumDefs() != 1) return 0;
973   const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
974   // Ok, we're unfolding. Create a temporary register and do the unfold.
975   unsigned Reg = MRI->createVirtualRegister(RC);
976
977   MachineFunction &MF = *MI->getParent()->getParent();
978   SmallVector<MachineInstr *, 2> NewMIs;
979   bool Success =
980     TII->unfoldMemoryOperand(MF, MI, Reg,
981                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
982                              NewMIs);
983   (void)Success;
984   assert(Success &&
985          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
986          "succeeded!");
987   assert(NewMIs.size() == 2 &&
988          "Unfolded a load into multiple instructions!");
989   MachineBasicBlock *MBB = MI->getParent();
990   MBB->insert(MI, NewMIs[0]);
991   MBB->insert(MI, NewMIs[1]);
992   // If unfolding produced a load that wasn't loop-invariant or profitable to
993   // hoist, discard the new instructions and bail.
994   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
995     NewMIs[0]->eraseFromParent();
996     NewMIs[1]->eraseFromParent();
997     return 0;
998   }
999   // Otherwise we successfully unfolded a load that we can hoist.
1000   MI->eraseFromParent();
1001   return NewMIs[0];
1002 }
1003
1004 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1005   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1006     const MachineInstr *MI = &*I;
1007     // FIXME: For now, only hoist re-materilizable instructions. LICM will
1008     // increase register pressure. We want to make sure it doesn't increase
1009     // spilling.
1010     if (TII->isTriviallyReMaterializable(MI, AA)) {
1011       unsigned Opcode = MI->getOpcode();
1012       DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1013         CI = CSEMap.find(Opcode);
1014       if (CI != CSEMap.end())
1015         CI->second.push_back(MI);
1016       else {
1017         std::vector<const MachineInstr*> CSEMIs;
1018         CSEMIs.push_back(MI);
1019         CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1020       }
1021     }
1022   }
1023 }
1024
1025 const MachineInstr*
1026 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1027                               std::vector<const MachineInstr*> &PrevMIs) {
1028   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1029     const MachineInstr *PrevMI = PrevMIs[i];
1030     if (TII->produceSameValue(MI, PrevMI))
1031       return PrevMI;
1032   }
1033   return 0;
1034 }
1035
1036 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1037           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1038   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1039   // the undef property onto uses.
1040   if (CI == CSEMap.end() || MI->isImplicitDef())
1041     return false;
1042
1043   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1044     DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1045
1046     // Replace virtual registers defined by MI by their counterparts defined
1047     // by Dup.
1048     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1049       const MachineOperand &MO = MI->getOperand(i);
1050
1051       // Physical registers may not differ here.
1052       assert((!MO.isReg() || MO.getReg() == 0 ||
1053               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1054               MO.getReg() == Dup->getOperand(i).getReg()) &&
1055              "Instructions with different phys regs are not identical!");
1056
1057       if (MO.isReg() && MO.isDef() &&
1058           !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
1059         MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1060         MRI->clearKillFlags(Dup->getOperand(i).getReg());
1061       }
1062     }
1063     MI->eraseFromParent();
1064     ++NumCSEed;
1065     return true;
1066   }
1067   return false;
1068 }
1069
1070 /// Hoist - When an instruction is found to use only loop invariant operands
1071 /// that are safe to hoist, this instruction is called to do the dirty work.
1072 ///
1073 void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1074   // First check whether we should hoist this instruction.
1075   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1076     // If not, try unfolding a hoistable load.
1077     MI = ExtractHoistableLoad(MI);
1078     if (!MI) return;
1079   }
1080
1081   // Now move the instructions to the predecessor, inserting it before any
1082   // terminator instructions.
1083   DEBUG({
1084       dbgs() << "Hoisting " << *MI;
1085       if (Preheader->getBasicBlock())
1086         dbgs() << " to MachineBasicBlock "
1087                << Preheader->getName();
1088       if (MI->getParent()->getBasicBlock())
1089         dbgs() << " from MachineBasicBlock "
1090                << MI->getParent()->getName();
1091       dbgs() << "\n";
1092     });
1093
1094   // If this is the first instruction being hoisted to the preheader,
1095   // initialize the CSE map with potential common expressions.
1096   if (FirstInLoop) {
1097     InitCSEMap(Preheader);
1098     FirstInLoop = false;
1099   }
1100
1101   // Look for opportunity to CSE the hoisted instruction.
1102   unsigned Opcode = MI->getOpcode();
1103   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1104     CI = CSEMap.find(Opcode);
1105   if (!EliminateCSE(MI, CI)) {
1106     // Otherwise, splice the instruction to the preheader.
1107     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1108
1109     // Clear the kill flags of any register this instruction defines,
1110     // since they may need to be live throughout the entire loop
1111     // rather than just live for part of it.
1112     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1113       MachineOperand &MO = MI->getOperand(i);
1114       if (MO.isReg() && MO.isDef() && !MO.isDead())
1115         MRI->clearKillFlags(MO.getReg());
1116     }
1117
1118     // Add to the CSE map.
1119     if (CI != CSEMap.end())
1120       CI->second.push_back(MI);
1121     else {
1122       std::vector<const MachineInstr*> CSEMIs;
1123       CSEMIs.push_back(MI);
1124       CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1125     }
1126   }
1127
1128   ++NumHoisted;
1129   Changed = true;
1130 }
1131
1132 MachineBasicBlock *MachineLICM::getCurPreheader() {
1133   // Determine the block to which to hoist instructions. If we can't find a
1134   // suitable loop predecessor, we can't do any hoisting.
1135
1136   // If we've tried to get a preheader and failed, don't try again.
1137   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1138     return 0;
1139
1140   if (!CurPreheader) {
1141     CurPreheader = CurLoop->getLoopPreheader();
1142     if (!CurPreheader) {
1143       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1144       if (!Pred) {
1145         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1146         return 0;
1147       }
1148
1149       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1150       if (!CurPreheader) {
1151         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1152         return 0;
1153       }
1154     }
1155   }
1156   return CurPreheader;
1157 }