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