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