MachineInstr: Remove unused parameter.
[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 is not intended to be a replacement or a complete alternative
14 // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15 // constructs that are not exposed before lowering and instruction selection.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 using namespace llvm;
40
41 #define DEBUG_TYPE "machine-licm"
42
43 static cl::opt<bool>
44 AvoidSpeculation("avoid-speculation",
45                  cl::desc("MachineLICM should avoid speculation"),
46                  cl::init(true), cl::Hidden);
47
48 static cl::opt<bool>
49 HoistCheapInsts("hoist-cheap-insts",
50                 cl::desc("MachineLICM should hoist even cheap instructions"),
51                 cl::init(false), cl::Hidden);
52
53 static cl::opt<bool>
54 SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55                        cl::desc("MachineLICM should sink instructions into "
56                                 "loops to avoid register spills"),
57                        cl::init(false), cl::Hidden);
58
59 STATISTIC(NumHoisted,
60           "Number of machine instructions hoisted out of loops");
61 STATISTIC(NumLowRP,
62           "Number of instructions hoisted in low reg pressure situation");
63 STATISTIC(NumHighLatency,
64           "Number of high latency instructions hoisted");
65 STATISTIC(NumCSEed,
66           "Number of hoisted machine instructions CSEed");
67 STATISTIC(NumPostRAHoisted,
68           "Number of machine instructions hoisted out of loops post regalloc");
69
70 namespace {
71   class MachineLICM : public MachineFunctionPass {
72     const TargetInstrInfo *TII;
73     const TargetLoweringBase *TLI;
74     const TargetRegisterInfo *TRI;
75     const MachineFrameInfo *MFI;
76     MachineRegisterInfo *MRI;
77     const InstrItineraryData *InstrItins;
78     bool PreRegAlloc;
79
80     // Various analyses that we use...
81     AliasAnalysis        *AA;      // Alias analysis info.
82     MachineLoopInfo      *MLI;     // Current MachineLoopInfo
83     MachineDominatorTree *DT;      // Machine dominator tree for the cur loop
84
85     // State that is updated as we process loops
86     bool         Changed;          // True if a loop is changed.
87     bool         FirstInLoop;      // True if it's the first LICM in the loop.
88     MachineLoop *CurLoop;          // The current loop we are working on.
89     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
90
91     // Exit blocks for CurLoop.
92     SmallVector<MachineBasicBlock*, 8> ExitBlocks;
93
94     bool isExitBlock(const MachineBasicBlock *MBB) const {
95       return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
96         ExitBlocks.end();
97     }
98
99     // Track 'estimated' register pressure.
100     SmallSet<unsigned, 32> RegSeen;
101     SmallVector<unsigned, 8> RegPressure;
102
103     // Register pressure "limit" per register pressure set. If the pressure
104     // is higher than the limit, then it's considered high.
105     SmallVector<unsigned, 8> RegLimit;
106
107     // Register pressure on path leading from loop preheader to current BB.
108     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
109
110     // For each opcode, keep a list of potential CSE instructions.
111     DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
112
113     enum {
114       SpeculateFalse   = 0,
115       SpeculateTrue    = 1,
116       SpeculateUnknown = 2
117     };
118
119     // If a MBB does not dominate loop exiting blocks then it may not safe
120     // to hoist loads from this block.
121     // Tri-state: 0 - false, 1 - true, 2 - unknown
122     unsigned SpeculationState;
123
124   public:
125     static char ID; // Pass identification, replacement for typeid
126     MachineLICM() :
127       MachineFunctionPass(ID), PreRegAlloc(true) {
128         initializeMachineLICMPass(*PassRegistry::getPassRegistry());
129       }
130
131     explicit MachineLICM(bool PreRA) :
132       MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133         initializeMachineLICMPass(*PassRegistry::getPassRegistry());
134       }
135
136     bool runOnMachineFunction(MachineFunction &MF) override;
137
138     void getAnalysisUsage(AnalysisUsage &AU) const override {
139       AU.addRequired<MachineLoopInfo>();
140       AU.addRequired<MachineDominatorTree>();
141       AU.addRequired<AliasAnalysis>();
142       AU.addPreserved<MachineLoopInfo>();
143       AU.addPreserved<MachineDominatorTree>();
144       MachineFunctionPass::getAnalysisUsage(AU);
145     }
146
147     void releaseMemory() override {
148       RegSeen.clear();
149       RegPressure.clear();
150       RegLimit.clear();
151       BackTrace.clear();
152       CSEMap.clear();
153     }
154
155   private:
156     /// CandidateInfo - Keep track of information about hoisting candidates.
157     struct CandidateInfo {
158       MachineInstr *MI;
159       unsigned      Def;
160       int           FI;
161       CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162         : MI(mi), Def(def), FI(fi) {}
163     };
164
165     /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
166     /// invariants out to the preheader.
167     void HoistRegionPostRA();
168
169     /// HoistPostRA - When an instruction is found to only use loop invariant
170     /// operands that is safe to hoist, this instruction is called to do the
171     /// dirty work.
172     void HoistPostRA(MachineInstr *MI, unsigned Def);
173
174     /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
175     /// gather register def and frame object update information.
176     void ProcessMI(MachineInstr *MI,
177                    BitVector &PhysRegDefs,
178                    BitVector &PhysRegClobbers,
179                    SmallSet<int, 32> &StoredFIs,
180                    SmallVectorImpl<CandidateInfo> &Candidates);
181
182     /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
183     /// current loop.
184     void AddToLiveIns(unsigned Reg);
185
186     /// IsLICMCandidate - Returns true if the instruction may be a suitable
187     /// candidate for LICM. e.g. If the instruction is a call, then it's
188     /// obviously not safe to hoist it.
189     bool IsLICMCandidate(MachineInstr &I);
190
191     /// IsLoopInvariantInst - Returns true if the instruction is loop
192     /// invariant. I.e., all virtual register operands are defined outside of
193     /// the loop, physical registers aren't accessed (explicitly or implicitly),
194     /// and the instruction is hoistable.
195     ///
196     bool IsLoopInvariantInst(MachineInstr &I);
197
198     /// HasLoopPHIUse - Return true if the specified instruction is used by any
199     /// phi node in the current loop.
200     bool HasLoopPHIUse(const MachineInstr *MI) const;
201
202     /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
203     /// and an use in the current loop, return true if the target considered
204     /// it 'high'.
205     bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
206                                unsigned Reg) const;
207
208     bool IsCheapInstruction(MachineInstr &MI) const;
209
210     /// CanCauseHighRegPressure - Visit BBs from header to current BB,
211     /// check if hoisting an instruction of the given cost matrix can cause high
212     /// register pressure.
213     bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
214                                  bool Cheap);
215
216     /// UpdateBackTraceRegPressure - Traverse the back trace from header to
217     /// the current block and update their register pressures to reflect the
218     /// effect of hoisting MI from the current block to the preheader.
219     void UpdateBackTraceRegPressure(const MachineInstr *MI);
220
221     /// IsProfitableToHoist - Return true if it is potentially profitable to
222     /// hoist the given loop invariant.
223     bool IsProfitableToHoist(MachineInstr &MI);
224
225     /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
226     /// If not then a load from this mbb may not be safe to hoist.
227     bool IsGuaranteedToExecute(MachineBasicBlock *BB);
228
229     void EnterScope(MachineBasicBlock *MBB);
230
231     void ExitScope(MachineBasicBlock *MBB);
232
233     /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
234     /// dominator tree node if its a leaf or all of its children are done. Walk
235     /// up the dominator tree to destroy ancestors which are now done.
236     void ExitScopeIfDone(MachineDomTreeNode *Node,
237                 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
238                 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
239
240     /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
241     /// blocks dominated by the specified header block, and that are in the
242     /// current loop) in depth first order w.r.t the DominatorTree. This allows
243     /// us to visit definitions before uses, allowing us to hoist a loop body in
244     /// one pass without iteration.
245     ///
246     void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
247     void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
248
249     /// SinkIntoLoop - Sink instructions into loops if profitable. This
250     /// especially tries to prevent register spills caused by register pressure
251     /// if there is little to no overhead moving instructions into loops.
252     void SinkIntoLoop();
253
254     /// InitRegPressure - Find all virtual register references that are liveout
255     /// of the preheader to initialize the starting "register pressure". Note
256     /// this does not count live through (livein but not used) registers.
257     void InitRegPressure(MachineBasicBlock *BB);
258
259     /// calcRegisterCost - Calculate the additional register pressure that the
260     /// registers used in MI cause.
261     ///
262     /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
263     /// figure out which usages are live-ins.
264     /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
265     DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
266                                              bool ConsiderSeen,
267                                              bool ConsiderUnseenAsDef);
268
269     /// UpdateRegPressure - Update estimate of register pressure after the
270     /// specified instruction.
271     void UpdateRegPressure(const MachineInstr *MI,
272                            bool ConsiderUnseenAsDef = false);
273
274     /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
275     /// the load itself could be hoisted. Return the unfolded and hoistable
276     /// load, or null if the load couldn't be unfolded or if it wouldn't
277     /// be hoistable.
278     MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
279
280     /// LookForDuplicate - Find an instruction amount PrevMIs that is a
281     /// duplicate of MI. Return this instruction if it's found.
282     const MachineInstr *LookForDuplicate(const MachineInstr *MI,
283                                      std::vector<const MachineInstr*> &PrevMIs);
284
285     /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
286     /// the preheader that compute the same value. If it's found, do a RAU on
287     /// with the definition of the existing instruction rather than hoisting
288     /// the instruction to the preheader.
289     bool EliminateCSE(MachineInstr *MI,
290            DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
291
292     /// MayCSE - Return true if the given instruction will be CSE'd if it's
293     /// hoisted out of the loop.
294     bool MayCSE(MachineInstr *MI);
295
296     /// Hoist - When an instruction is found to only use loop invariant operands
297     /// that is safe to hoist, this instruction is called to do the dirty work.
298     /// It returns true if the instruction is hoisted.
299     bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
300
301     /// InitCSEMap - Initialize the CSE map with instructions that are in the
302     /// current loop preheader that may become duplicates of instructions that
303     /// are hoisted out of the loop.
304     void InitCSEMap(MachineBasicBlock *BB);
305
306     /// getCurPreheader - Get the preheader for the current loop, splitting
307     /// a critical edge if needed.
308     MachineBasicBlock *getCurPreheader();
309   };
310 } // end anonymous namespace
311
312 char MachineLICM::ID = 0;
313 char &llvm::MachineLICMID = MachineLICM::ID;
314 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
315                 "Machine Loop Invariant Code Motion", false, false)
316 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
317 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
318 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
319 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
320                 "Machine Loop Invariant Code Motion", false, false)
321
322 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
323 /// loop that has a unique predecessor.
324 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
325   // Check whether this loop even has a unique predecessor.
326   if (!CurLoop->getLoopPredecessor())
327     return false;
328   // Ok, now check to see if any of its outer loops do.
329   for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
330     if (L->getLoopPredecessor())
331       return false;
332   // None of them did, so this is the outermost with a unique predecessor.
333   return true;
334 }
335
336 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
337   if (skipOptnoneFunction(*MF.getFunction()))
338     return false;
339
340   Changed = FirstInLoop = false;
341   TII = MF.getSubtarget().getInstrInfo();
342   TLI = MF.getSubtarget().getTargetLowering();
343   TRI = MF.getSubtarget().getRegisterInfo();
344   MFI = MF.getFrameInfo();
345   MRI = &MF.getRegInfo();
346   InstrItins = MF.getSubtarget().getInstrItineraryData();
347
348   PreRegAlloc = MRI->isSSA();
349
350   if (PreRegAlloc)
351     DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
352   else
353     DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
354   DEBUG(dbgs() << MF.getName() << " ********\n");
355
356   if (PreRegAlloc) {
357     // Estimate register pressure during pre-regalloc pass.
358     unsigned NumRPS = TRI->getNumRegPressureSets();
359     RegPressure.resize(NumRPS);
360     std::fill(RegPressure.begin(), RegPressure.end(), 0);
361     RegLimit.resize(NumRPS);
362     for (unsigned i = 0, e = NumRPS; i != e; ++i)
363       RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
364   }
365
366   // Get our Loop information...
367   MLI = &getAnalysis<MachineLoopInfo>();
368   DT  = &getAnalysis<MachineDominatorTree>();
369   AA  = &getAnalysis<AliasAnalysis>();
370
371   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
372   while (!Worklist.empty()) {
373     CurLoop = Worklist.pop_back_val();
374     CurPreheader = nullptr;
375     ExitBlocks.clear();
376
377     // If this is done before regalloc, only visit outer-most preheader-sporting
378     // loops.
379     if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
380       Worklist.append(CurLoop->begin(), CurLoop->end());
381       continue;
382     }
383
384     CurLoop->getExitBlocks(ExitBlocks);
385
386     if (!PreRegAlloc)
387       HoistRegionPostRA();
388     else {
389       // CSEMap is initialized for loop header when the first instruction is
390       // being hoisted.
391       MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
392       FirstInLoop = true;
393       HoistOutOfLoop(N);
394       CSEMap.clear();
395
396       if (SinkInstsToAvoidSpills)
397         SinkIntoLoop();
398     }
399   }
400
401   return Changed;
402 }
403
404 /// InstructionStoresToFI - Return true if instruction stores to the
405 /// specified frame.
406 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
407   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
408          oe = MI->memoperands_end(); o != oe; ++o) {
409     if (!(*o)->isStore() || !(*o)->getPseudoValue())
410       continue;
411     if (const FixedStackPseudoSourceValue *Value =
412         dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
413       if (Value->getFrameIndex() == FI)
414         return true;
415     }
416   }
417   return false;
418 }
419
420 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
421 /// gather register def and frame object update information.
422 void MachineLICM::ProcessMI(MachineInstr *MI,
423                             BitVector &PhysRegDefs,
424                             BitVector &PhysRegClobbers,
425                             SmallSet<int, 32> &StoredFIs,
426                             SmallVectorImpl<CandidateInfo> &Candidates) {
427   bool RuledOut = false;
428   bool HasNonInvariantUse = false;
429   unsigned Def = 0;
430   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
431     const MachineOperand &MO = MI->getOperand(i);
432     if (MO.isFI()) {
433       // Remember if the instruction stores to the frame index.
434       int FI = MO.getIndex();
435       if (!StoredFIs.count(FI) &&
436           MFI->isSpillSlotObjectIndex(FI) &&
437           InstructionStoresToFI(MI, FI))
438         StoredFIs.insert(FI);
439       HasNonInvariantUse = true;
440       continue;
441     }
442
443     // We can't hoist an instruction defining a physreg that is clobbered in
444     // the loop.
445     if (MO.isRegMask()) {
446       PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
447       continue;
448     }
449
450     if (!MO.isReg())
451       continue;
452     unsigned Reg = MO.getReg();
453     if (!Reg)
454       continue;
455     assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
456            "Not expecting virtual register!");
457
458     if (!MO.isDef()) {
459       if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
460         // If it's using a non-loop-invariant register, then it's obviously not
461         // safe to hoist.
462         HasNonInvariantUse = true;
463       continue;
464     }
465
466     if (MO.isImplicit()) {
467       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
468         PhysRegClobbers.set(*AI);
469       if (!MO.isDead())
470         // Non-dead implicit def? This cannot be hoisted.
471         RuledOut = true;
472       // No need to check if a dead implicit def is also defined by
473       // another instruction.
474       continue;
475     }
476
477     // FIXME: For now, avoid instructions with multiple defs, unless
478     // it's a dead implicit def.
479     if (Def)
480       RuledOut = true;
481     else
482       Def = Reg;
483
484     // If we have already seen another instruction that defines the same
485     // register, then this is not safe.  Two defs is indicated by setting a
486     // PhysRegClobbers bit.
487     for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
488       if (PhysRegDefs.test(*AS))
489         PhysRegClobbers.set(*AS);
490       PhysRegDefs.set(*AS);
491     }
492     if (PhysRegClobbers.test(Reg))
493       // MI defined register is seen defined by another instruction in
494       // the loop, it cannot be a LICM candidate.
495       RuledOut = true;
496   }
497
498   // Only consider reloads for now and remats which do not have register
499   // operands. FIXME: Consider unfold load folding instructions.
500   if (Def && !RuledOut) {
501     int FI = INT_MIN;
502     if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
503         (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
504       Candidates.push_back(CandidateInfo(MI, Def, FI));
505   }
506 }
507
508 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
509 /// invariants out to the preheader.
510 void MachineLICM::HoistRegionPostRA() {
511   MachineBasicBlock *Preheader = getCurPreheader();
512   if (!Preheader)
513     return;
514
515   unsigned NumRegs = TRI->getNumRegs();
516   BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
517   BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
518
519   SmallVector<CandidateInfo, 32> Candidates;
520   SmallSet<int, 32> StoredFIs;
521
522   // Walk the entire region, count number of defs for each register, and
523   // collect potential LICM candidates.
524   const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
525   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
526     MachineBasicBlock *BB = Blocks[i];
527
528     // If the header of the loop containing this basic block is a landing pad,
529     // then don't try to hoist instructions out of this loop.
530     const MachineLoop *ML = MLI->getLoopFor(BB);
531     if (ML && ML->getHeader()->isLandingPad()) continue;
532
533     // Conservatively treat live-in's as an external def.
534     // FIXME: That means a reload that're reused in successor block(s) will not
535     // be LICM'ed.
536     for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
537            E = BB->livein_end(); I != E; ++I) {
538       unsigned Reg = *I;
539       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
540         PhysRegDefs.set(*AI);
541     }
542
543     SpeculationState = SpeculateUnknown;
544     for (MachineBasicBlock::iterator
545            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
546       MachineInstr *MI = &*MII;
547       ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
548     }
549   }
550
551   // Gather the registers read / clobbered by the terminator.
552   BitVector TermRegs(NumRegs);
553   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
554   if (TI != Preheader->end()) {
555     for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
556       const MachineOperand &MO = TI->getOperand(i);
557       if (!MO.isReg())
558         continue;
559       unsigned Reg = MO.getReg();
560       if (!Reg)
561         continue;
562       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
563         TermRegs.set(*AI);
564     }
565   }
566
567   // Now evaluate whether the potential candidates qualify.
568   // 1. Check if the candidate defined register is defined by another
569   //    instruction in the loop.
570   // 2. If the candidate is a load from stack slot (always true for now),
571   //    check if the slot is stored anywhere in the loop.
572   // 3. Make sure candidate def should not clobber
573   //    registers read by the terminator. Similarly its def should not be
574   //    clobbered by the terminator.
575   for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
576     if (Candidates[i].FI != INT_MIN &&
577         StoredFIs.count(Candidates[i].FI))
578       continue;
579
580     unsigned Def = Candidates[i].Def;
581     if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
582       bool Safe = true;
583       MachineInstr *MI = Candidates[i].MI;
584       for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
585         const MachineOperand &MO = MI->getOperand(j);
586         if (!MO.isReg() || MO.isDef() || !MO.getReg())
587           continue;
588         unsigned Reg = MO.getReg();
589         if (PhysRegDefs.test(Reg) ||
590             PhysRegClobbers.test(Reg)) {
591           // If it's using a non-loop-invariant register, then it's obviously
592           // not safe to hoist.
593           Safe = false;
594           break;
595         }
596       }
597       if (Safe)
598         HoistPostRA(MI, Candidates[i].Def);
599     }
600   }
601 }
602
603 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
604 /// loop, and make sure it is not killed by any instructions in the loop.
605 void MachineLICM::AddToLiveIns(unsigned Reg) {
606   const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
607   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
608     MachineBasicBlock *BB = Blocks[i];
609     if (!BB->isLiveIn(Reg))
610       BB->addLiveIn(Reg);
611     for (MachineBasicBlock::iterator
612            MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
613       MachineInstr *MI = &*MII;
614       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
615         MachineOperand &MO = MI->getOperand(i);
616         if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
617         if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
618           MO.setIsKill(false);
619       }
620     }
621   }
622 }
623
624 /// HoistPostRA - When an instruction is found to only use loop invariant
625 /// operands that is safe to hoist, this instruction is called to do the
626 /// dirty work.
627 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
628   MachineBasicBlock *Preheader = getCurPreheader();
629
630   // Now move the instructions to the predecessor, inserting it before any
631   // terminator instructions.
632   DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
633                << MI->getParent()->getNumber() << ": " << *MI);
634
635   // Splice the instruction to the preheader.
636   MachineBasicBlock *MBB = MI->getParent();
637   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
638
639   // Add register to livein list to all the BBs in the current loop since a
640   // loop invariant must be kept live throughout the whole loop. This is
641   // important to ensure later passes do not scavenge the def register.
642   AddToLiveIns(Def);
643
644   ++NumPostRAHoisted;
645   Changed = true;
646 }
647
648 // IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
649 // If not then a load from this mbb may not be safe to hoist.
650 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
651   if (SpeculationState != SpeculateUnknown)
652     return SpeculationState == SpeculateFalse;
653
654   if (BB != CurLoop->getHeader()) {
655     // Check loop exiting blocks.
656     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
657     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
658     for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
659       if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
660         SpeculationState = SpeculateTrue;
661         return false;
662       }
663   }
664
665   SpeculationState = SpeculateFalse;
666   return true;
667 }
668
669 void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
670   DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
671
672   // Remember livein register pressure.
673   BackTrace.push_back(RegPressure);
674 }
675
676 void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
677   DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
678   BackTrace.pop_back();
679 }
680
681 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
682 /// dominator tree node if its a leaf or all of its children are done. Walk
683 /// up the dominator tree to destroy ancestors which are now done.
684 void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
685                 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
686                 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
687   if (OpenChildren[Node])
688     return;
689
690   // Pop scope.
691   ExitScope(Node->getBlock());
692
693   // Now traverse upwards to pop ancestors whose offsprings are all done.
694   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
695     unsigned Left = --OpenChildren[Parent];
696     if (Left != 0)
697       break;
698     ExitScope(Parent->getBlock());
699     Node = Parent;
700   }
701 }
702
703 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
704 /// blocks dominated by the specified header block, and that are in the
705 /// current loop) in depth first order w.r.t the DominatorTree. This allows
706 /// us to visit definitions before uses, allowing us to hoist a loop body in
707 /// one pass without iteration.
708 ///
709 void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
710   MachineBasicBlock *Preheader = getCurPreheader();
711   if (!Preheader)
712     return;
713
714   SmallVector<MachineDomTreeNode*, 32> Scopes;
715   SmallVector<MachineDomTreeNode*, 8> WorkList;
716   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
717   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
718
719   // Perform a DFS walk to determine the order of visit.
720   WorkList.push_back(HeaderN);
721   while (!WorkList.empty()) {
722     MachineDomTreeNode *Node = WorkList.pop_back_val();
723     assert(Node && "Null dominator tree node?");
724     MachineBasicBlock *BB = Node->getBlock();
725
726     // If the header of the loop containing this basic block is a landing pad,
727     // then don't try to hoist instructions out of this loop.
728     const MachineLoop *ML = MLI->getLoopFor(BB);
729     if (ML && ML->getHeader()->isLandingPad())
730       continue;
731
732     // If this subregion is not in the top level loop at all, exit.
733     if (!CurLoop->contains(BB))
734       continue;
735
736     Scopes.push_back(Node);
737     const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
738     unsigned NumChildren = Children.size();
739
740     // Don't hoist things out of a large switch statement.  This often causes
741     // code to be hoisted that wasn't going to be executed, and increases
742     // register pressure in a situation where it's likely to matter.
743     if (BB->succ_size() >= 25)
744       NumChildren = 0;
745
746     OpenChildren[Node] = NumChildren;
747     // Add children in reverse order as then the next popped worklist node is
748     // the first child of this node.  This means we ultimately traverse the
749     // DOM tree in exactly the same order as if we'd recursed.
750     for (int i = (int)NumChildren-1; i >= 0; --i) {
751       MachineDomTreeNode *Child = Children[i];
752       ParentMap[Child] = Node;
753       WorkList.push_back(Child);
754     }
755   }
756
757   if (Scopes.size() == 0)
758     return;
759
760   // Compute registers which are livein into the loop headers.
761   RegSeen.clear();
762   BackTrace.clear();
763   InitRegPressure(Preheader);
764
765   // Now perform LICM.
766   for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
767     MachineDomTreeNode *Node = Scopes[i];
768     MachineBasicBlock *MBB = Node->getBlock();
769
770     EnterScope(MBB);
771
772     // Process the block
773     SpeculationState = SpeculateUnknown;
774     for (MachineBasicBlock::iterator
775          MII = MBB->begin(), E = MBB->end(); MII != E; ) {
776       MachineBasicBlock::iterator NextMII = MII; ++NextMII;
777       MachineInstr *MI = &*MII;
778       if (!Hoist(MI, Preheader))
779         UpdateRegPressure(MI);
780       MII = NextMII;
781     }
782
783     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
784     ExitScopeIfDone(Node, OpenChildren, ParentMap);
785   }
786 }
787
788 void MachineLICM::SinkIntoLoop() {
789   MachineBasicBlock *Preheader = getCurPreheader();
790   if (!Preheader)
791     return;
792
793   SmallVector<MachineInstr *, 8> Candidates;
794   for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
795        I != Preheader->instr_end(); ++I) {
796     // We need to ensure that we can safely move this instruction into the loop.
797     // As such, it must not have side-effects, e.g. such as a call has.  
798     if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(I))
799       Candidates.push_back(I);
800   }
801
802   for (MachineInstr *I : Candidates) {
803     const MachineOperand &MO = I->getOperand(0);
804     if (!MO.isDef() || !MO.isReg() || !MO.getReg())
805       continue;
806     if (!MRI->hasOneDef(MO.getReg()))
807       continue;
808     bool CanSink = true;
809     MachineBasicBlock *B = nullptr;
810     for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
811       // FIXME: Come up with a proper cost model that estimates whether sinking
812       // the instruction (and thus possibly executing it on every loop
813       // iteration) is more expensive than a register.
814       // For now assumes that copies are cheap and thus almost always worth it.
815       if (!MI.isCopy()) {
816         CanSink = false;
817         break;
818       }
819       if (!B) {
820         B = MI.getParent();
821         continue;
822       }
823       B = DT->findNearestCommonDominator(B, MI.getParent());
824       if (!B) {
825         CanSink = false;
826         break;
827       }
828     }
829     if (!CanSink || !B || B == Preheader)
830       continue;
831     B->splice(B->getFirstNonPHI(), Preheader, I);
832   }
833 }
834
835 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
836   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
837 }
838
839 /// InitRegPressure - Find all virtual register references that are liveout of
840 /// the preheader to initialize the starting "register pressure". Note this
841 /// does not count live through (livein but not used) registers.
842 void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
843   std::fill(RegPressure.begin(), RegPressure.end(), 0);
844
845   // If the preheader has only a single predecessor and it ends with a
846   // fallthrough or an unconditional branch, then scan its predecessor for live
847   // defs as well. This happens whenever the preheader is created by splitting
848   // the critical edge from the loop predecessor to the loop header.
849   if (BB->pred_size() == 1) {
850     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
851     SmallVector<MachineOperand, 4> Cond;
852     if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
853       InitRegPressure(*BB->pred_begin());
854   }
855
856   for (const MachineInstr &MI : *BB)
857     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
858 }
859
860 /// UpdateRegPressure - Update estimate of register pressure after the
861 /// specified instruction.
862 void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
863                                     bool ConsiderUnseenAsDef) {
864   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
865   for (const auto &RPIdAndCost : Cost) {
866     unsigned Class = RPIdAndCost.first;
867     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
868       RegPressure[Class] = 0;
869     else
870       RegPressure[Class] += RPIdAndCost.second;
871   }
872 }
873
874 DenseMap<unsigned, int>
875 MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
876                               bool ConsiderUnseenAsDef) {
877   DenseMap<unsigned, int> Cost;
878   if (MI->isImplicitDef())
879     return Cost;
880   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
881     const MachineOperand &MO = MI->getOperand(i);
882     if (!MO.isReg() || MO.isImplicit())
883       continue;
884     unsigned Reg = MO.getReg();
885     if (!TargetRegisterInfo::isVirtualRegister(Reg))
886       continue;
887
888     // FIXME: It seems bad to use RegSeen only for some of these calculations.
889     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
890     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
891
892     RegClassWeight W = TRI->getRegClassWeight(RC);
893     int RCCost = 0;
894     if (MO.isDef())
895       RCCost = W.RegWeight;
896     else {
897       bool isKill = isOperandKill(MO, MRI);
898       if (isNew && !isKill && ConsiderUnseenAsDef)
899         // Haven't seen this, it must be a livein.
900         RCCost = W.RegWeight;
901       else if (!isNew && isKill)
902         RCCost = -W.RegWeight;
903     }
904     if (RCCost == 0)
905       continue;
906     const int *PS = TRI->getRegClassPressureSets(RC);
907     for (; *PS != -1; ++PS) {
908       if (Cost.find(*PS) == Cost.end())
909         Cost[*PS] = RCCost;
910       else
911         Cost[*PS] += RCCost;
912     }
913   }
914   return Cost;
915 }
916
917 /// isLoadFromGOTOrConstantPool - Return true if this machine instruction
918 /// loads from global offset table or constant pool.
919 static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
920   assert (MI.mayLoad() && "Expected MI that loads!");
921   for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
922          E = MI.memoperands_end(); I != E; ++I) {
923     if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
924       if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
925         return true;
926     }
927   }
928   return false;
929 }
930
931 /// IsLICMCandidate - Returns true if the instruction may be a suitable
932 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
933 /// not safe to hoist it.
934 bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
935   // Check if it's safe to move the instruction.
936   bool DontMoveAcrossStore = true;
937   if (!I.isSafeToMove(AA, DontMoveAcrossStore))
938     return false;
939
940   // If it is load then check if it is guaranteed to execute by making sure that
941   // it dominates all exiting blocks. If it doesn't, then there is a path out of
942   // the loop which does not execute this load, so we can't hoist it. Loads
943   // from constant memory are not safe to speculate all the time, for example
944   // indexed load from a jump table.
945   // Stores and side effects are already checked by isSafeToMove.
946   if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
947       !IsGuaranteedToExecute(I.getParent()))
948     return false;
949
950   return true;
951 }
952
953 /// IsLoopInvariantInst - Returns true if the instruction is loop
954 /// invariant. I.e., all virtual register operands are defined outside of the
955 /// loop, physical registers aren't accessed explicitly, and there are no side
956 /// effects that aren't captured by the operands or other flags.
957 ///
958 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
959   if (!IsLICMCandidate(I))
960     return false;
961
962   // The instruction is loop invariant if all of its operands are.
963   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
964     const MachineOperand &MO = I.getOperand(i);
965
966     if (!MO.isReg())
967       continue;
968
969     unsigned Reg = MO.getReg();
970     if (Reg == 0) continue;
971
972     // Don't hoist an instruction that uses or defines a physical register.
973     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
974       if (MO.isUse()) {
975         // If the physreg has no defs anywhere, it's just an ambient register
976         // and we can freely move its uses. Alternatively, if it's allocatable,
977         // it could get allocated to something with a def during allocation.
978         if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
979           return false;
980         // Otherwise it's safe to move.
981         continue;
982       } else if (!MO.isDead()) {
983         // A def that isn't dead. We can't move it.
984         return false;
985       } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
986         // If the reg is live into the loop, we can't hoist an instruction
987         // which would clobber it.
988         return false;
989       }
990     }
991
992     if (!MO.isUse())
993       continue;
994
995     assert(MRI->getVRegDef(Reg) &&
996            "Machine instr not mapped for this vreg?!");
997
998     // If the loop contains the definition of an operand, then the instruction
999     // isn't loop invariant.
1000     if (CurLoop->contains(MRI->getVRegDef(Reg)))
1001       return false;
1002   }
1003
1004   // If we got this far, the instruction is loop invariant!
1005   return true;
1006 }
1007
1008
1009 /// HasLoopPHIUse - Return true if the specified instruction is used by a
1010 /// phi node and hoisting it could cause a copy to be inserted.
1011 bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
1012   SmallVector<const MachineInstr*, 8> Work(1, MI);
1013   do {
1014     MI = Work.pop_back_val();
1015     for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1016       if (!MO->isReg() || !MO->isDef())
1017         continue;
1018       unsigned Reg = MO->getReg();
1019       if (!TargetRegisterInfo::isVirtualRegister(Reg))
1020         continue;
1021       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1022         // A PHI may cause a copy to be inserted.
1023         if (UseMI.isPHI()) {
1024           // A PHI inside the loop causes a copy because the live range of Reg is
1025           // extended across the PHI.
1026           if (CurLoop->contains(&UseMI))
1027             return true;
1028           // A PHI in an exit block can cause a copy to be inserted if the PHI
1029           // has multiple predecessors in the loop with different values.
1030           // For now, approximate by rejecting all exit blocks.
1031           if (isExitBlock(UseMI.getParent()))
1032             return true;
1033           continue;
1034         }
1035         // Look past copies as well.
1036         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1037           Work.push_back(&UseMI);
1038       }
1039     }
1040   } while (!Work.empty());
1041   return false;
1042 }
1043
1044 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1045 /// and an use in the current loop, return true if the target considered
1046 /// it 'high'.
1047 bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
1048                                         unsigned DefIdx, unsigned Reg) const {
1049   if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
1050     return false;
1051
1052   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1053     if (UseMI.isCopyLike())
1054       continue;
1055     if (!CurLoop->contains(UseMI.getParent()))
1056       continue;
1057     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1058       const MachineOperand &MO = UseMI.getOperand(i);
1059       if (!MO.isReg() || !MO.isUse())
1060         continue;
1061       unsigned MOReg = MO.getReg();
1062       if (MOReg != Reg)
1063         continue;
1064
1065       if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
1066         return true;
1067     }
1068
1069     // Only look at the first in loop use.
1070     break;
1071   }
1072
1073   return false;
1074 }
1075
1076 /// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1077 /// the operand latency between its def and a use is one or less.
1078 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
1079   if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
1080     return true;
1081   if (!InstrItins || InstrItins->isEmpty())
1082     return false;
1083
1084   bool isCheap = false;
1085   unsigned NumDefs = MI.getDesc().getNumDefs();
1086   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1087     MachineOperand &DefMO = MI.getOperand(i);
1088     if (!DefMO.isReg() || !DefMO.isDef())
1089       continue;
1090     --NumDefs;
1091     unsigned Reg = DefMO.getReg();
1092     if (TargetRegisterInfo::isPhysicalRegister(Reg))
1093       continue;
1094
1095     if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1096       return false;
1097     isCheap = true;
1098   }
1099
1100   return isCheap;
1101 }
1102
1103 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
1104 /// if hoisting an instruction of the given cost matrix can cause high
1105 /// register pressure.
1106 bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1107                                           bool CheapInstr) {
1108   for (const auto &RPIdAndCost : Cost) {
1109     if (RPIdAndCost.second <= 0)
1110       continue;
1111
1112     unsigned Class = RPIdAndCost.first;
1113     int Limit = RegLimit[Class];
1114
1115     // Don't hoist cheap instructions if they would increase register pressure,
1116     // even if we're under the limit.
1117     if (CheapInstr && !HoistCheapInsts)
1118       return true;
1119
1120     for (const auto &RP : BackTrace)
1121       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1122         return true;
1123   }
1124
1125   return false;
1126 }
1127
1128 /// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1129 /// current block and update their register pressures to reflect the effect
1130 /// of hoisting MI from the current block to the preheader.
1131 void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1132   // First compute the 'cost' of the instruction, i.e. its contribution
1133   // to register pressure.
1134   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1135                                /*ConsiderUnseenAsDef=*/false);
1136
1137   // Update register pressure of blocks from loop header to current block.
1138   for (auto &RP : BackTrace)
1139     for (const auto &RPIdAndCost : Cost)
1140       RP[RPIdAndCost.first] += RPIdAndCost.second;
1141 }
1142
1143 /// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1144 /// the given loop invariant.
1145 bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
1146   if (MI.isImplicitDef())
1147     return true;
1148
1149   // Besides removing computation from the loop, hoisting an instruction has
1150   // these effects:
1151   //
1152   // - The value defined by the instruction becomes live across the entire
1153   //   loop. This increases register pressure in the loop.
1154   //
1155   // - If the value is used by a PHI in the loop, a copy will be required for
1156   //   lowering the PHI after extending the live range.
1157   //
1158   // - When hoisting the last use of a value in the loop, that value no longer
1159   //   needs to be live in the loop. This lowers register pressure in the loop.
1160
1161   bool CheapInstr = IsCheapInstruction(MI);
1162   bool CreatesCopy = HasLoopPHIUse(&MI);
1163
1164   // Don't hoist a cheap instruction if it would create a copy in the loop.
1165   if (CheapInstr && CreatesCopy) {
1166     DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1167     return false;
1168   }
1169
1170   // Rematerializable instructions should always be hoisted since the register
1171   // allocator can just pull them down again when needed.
1172   if (TII->isTriviallyReMaterializable(&MI, AA))
1173     return true;
1174
1175   // FIXME: If there are long latency loop-invariant instructions inside the
1176   // loop at this point, why didn't the optimizer's LICM hoist them?
1177   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1178     const MachineOperand &MO = MI.getOperand(i);
1179     if (!MO.isReg() || MO.isImplicit())
1180       continue;
1181     unsigned Reg = MO.getReg();
1182     if (!TargetRegisterInfo::isVirtualRegister(Reg))
1183       continue;
1184     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1185       DEBUG(dbgs() << "Hoist High Latency: " << MI);
1186       ++NumHighLatency;
1187       return true;
1188     }
1189   }
1190
1191   // Estimate register pressure to determine whether to LICM the instruction.
1192   // In low register pressure situation, we can be more aggressive about
1193   // hoisting. Also, favors hoisting long latency instructions even in
1194   // moderately high pressure situation.
1195   // Cheap instructions will only be hoisted if they don't increase register
1196   // pressure at all.
1197   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1198                                /*ConsiderUnseenAsDef=*/false);
1199
1200   // Visit BBs from header to current BB, if hoisting this doesn't cause
1201   // high register pressure, then it's safe to proceed.
1202   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1203     DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1204     ++NumLowRP;
1205     return true;
1206   }
1207
1208   // Don't risk increasing register pressure if it would create copies.
1209   if (CreatesCopy) {
1210     DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1211     return false;
1212   }
1213
1214   // Do not "speculate" in high register pressure situation. If an
1215   // instruction is not guaranteed to be executed in the loop, it's best to be
1216   // conservative.
1217   if (AvoidSpeculation &&
1218       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1219     DEBUG(dbgs() << "Won't speculate: " << MI);
1220     return false;
1221   }
1222
1223   // High register pressure situation, only hoist if the instruction is going
1224   // to be remat'ed.
1225   if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1226       !MI.isInvariantLoad(AA)) {
1227     DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1228     return false;
1229   }
1230
1231   return true;
1232 }
1233
1234 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
1235   // Don't unfold simple loads.
1236   if (MI->canFoldAsLoad())
1237     return nullptr;
1238
1239   // If not, we may be able to unfold a load and hoist that.
1240   // First test whether the instruction is loading from an amenable
1241   // memory location.
1242   if (!MI->isInvariantLoad(AA))
1243     return nullptr;
1244
1245   // Next determine the register class for a temporary register.
1246   unsigned LoadRegIndex;
1247   unsigned NewOpc =
1248     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1249                                     /*UnfoldLoad=*/true,
1250                                     /*UnfoldStore=*/false,
1251                                     &LoadRegIndex);
1252   if (NewOpc == 0) return nullptr;
1253   const MCInstrDesc &MID = TII->get(NewOpc);
1254   if (MID.getNumDefs() != 1) return nullptr;
1255   MachineFunction &MF = *MI->getParent()->getParent();
1256   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1257   // Ok, we're unfolding. Create a temporary register and do the unfold.
1258   unsigned Reg = MRI->createVirtualRegister(RC);
1259
1260   SmallVector<MachineInstr *, 2> NewMIs;
1261   bool Success =
1262     TII->unfoldMemoryOperand(MF, MI, Reg,
1263                              /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1264                              NewMIs);
1265   (void)Success;
1266   assert(Success &&
1267          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1268          "succeeded!");
1269   assert(NewMIs.size() == 2 &&
1270          "Unfolded a load into multiple instructions!");
1271   MachineBasicBlock *MBB = MI->getParent();
1272   MachineBasicBlock::iterator Pos = MI;
1273   MBB->insert(Pos, NewMIs[0]);
1274   MBB->insert(Pos, NewMIs[1]);
1275   // If unfolding produced a load that wasn't loop-invariant or profitable to
1276   // hoist, discard the new instructions and bail.
1277   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1278     NewMIs[0]->eraseFromParent();
1279     NewMIs[1]->eraseFromParent();
1280     return nullptr;
1281   }
1282
1283   // Update register pressure for the unfolded instruction.
1284   UpdateRegPressure(NewMIs[1]);
1285
1286   // Otherwise we successfully unfolded a load that we can hoist.
1287   MI->eraseFromParent();
1288   return NewMIs[0];
1289 }
1290
1291 void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1292   for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1293     const MachineInstr *MI = &*I;
1294     unsigned Opcode = MI->getOpcode();
1295     CSEMap[Opcode].push_back(MI);
1296   }
1297 }
1298
1299 const MachineInstr*
1300 MachineLICM::LookForDuplicate(const MachineInstr *MI,
1301                               std::vector<const MachineInstr*> &PrevMIs) {
1302   for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1303     const MachineInstr *PrevMI = PrevMIs[i];
1304     if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
1305       return PrevMI;
1306   }
1307   return nullptr;
1308 }
1309
1310 bool MachineLICM::EliminateCSE(MachineInstr *MI,
1311           DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
1312   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1313   // the undef property onto uses.
1314   if (CI == CSEMap.end() || MI->isImplicitDef())
1315     return false;
1316
1317   if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1318     DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1319
1320     // Replace virtual registers defined by MI by their counterparts defined
1321     // by Dup.
1322     SmallVector<unsigned, 2> Defs;
1323     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1324       const MachineOperand &MO = MI->getOperand(i);
1325
1326       // Physical registers may not differ here.
1327       assert((!MO.isReg() || MO.getReg() == 0 ||
1328               !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1329               MO.getReg() == Dup->getOperand(i).getReg()) &&
1330              "Instructions with different phys regs are not identical!");
1331
1332       if (MO.isReg() && MO.isDef() &&
1333           !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1334         Defs.push_back(i);
1335     }
1336
1337     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1338     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1339       unsigned Idx = Defs[i];
1340       unsigned Reg = MI->getOperand(Idx).getReg();
1341       unsigned DupReg = Dup->getOperand(Idx).getReg();
1342       OrigRCs.push_back(MRI->getRegClass(DupReg));
1343
1344       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1345         // Restore old RCs if more than one defs.
1346         for (unsigned j = 0; j != i; ++j)
1347           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1348         return false;
1349       }
1350     }
1351
1352     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1353       unsigned Idx = Defs[i];
1354       unsigned Reg = MI->getOperand(Idx).getReg();
1355       unsigned DupReg = Dup->getOperand(Idx).getReg();
1356       MRI->replaceRegWith(Reg, DupReg);
1357       MRI->clearKillFlags(DupReg);
1358     }
1359
1360     MI->eraseFromParent();
1361     ++NumCSEed;
1362     return true;
1363   }
1364   return false;
1365 }
1366
1367 /// MayCSE - Return true if the given instruction will be CSE'd if it's
1368 /// hoisted out of the loop.
1369 bool MachineLICM::MayCSE(MachineInstr *MI) {
1370   unsigned Opcode = MI->getOpcode();
1371   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1372     CI = CSEMap.find(Opcode);
1373   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1374   // the undef property onto uses.
1375   if (CI == CSEMap.end() || MI->isImplicitDef())
1376     return false;
1377
1378   return LookForDuplicate(MI, CI->second) != nullptr;
1379 }
1380
1381 /// Hoist - When an instruction is found to use only loop invariant operands
1382 /// that are safe to hoist, this instruction is called to do the dirty work.
1383 ///
1384 bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1385   // First check whether we should hoist this instruction.
1386   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1387     // If not, try unfolding a hoistable load.
1388     MI = ExtractHoistableLoad(MI);
1389     if (!MI) return false;
1390   }
1391
1392   // Now move the instructions to the predecessor, inserting it before any
1393   // terminator instructions.
1394   DEBUG({
1395       dbgs() << "Hoisting " << *MI;
1396       if (Preheader->getBasicBlock())
1397         dbgs() << " to MachineBasicBlock "
1398                << Preheader->getName();
1399       if (MI->getParent()->getBasicBlock())
1400         dbgs() << " from MachineBasicBlock "
1401                << MI->getParent()->getName();
1402       dbgs() << "\n";
1403     });
1404
1405   // If this is the first instruction being hoisted to the preheader,
1406   // initialize the CSE map with potential common expressions.
1407   if (FirstInLoop) {
1408     InitCSEMap(Preheader);
1409     FirstInLoop = false;
1410   }
1411
1412   // Look for opportunity to CSE the hoisted instruction.
1413   unsigned Opcode = MI->getOpcode();
1414   DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1415     CI = CSEMap.find(Opcode);
1416   if (!EliminateCSE(MI, CI)) {
1417     // Otherwise, splice the instruction to the preheader.
1418     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1419
1420     // Update register pressure for BBs from header to this block.
1421     UpdateBackTraceRegPressure(MI);
1422
1423     // Clear the kill flags of any register this instruction defines,
1424     // since they may need to be live throughout the entire loop
1425     // rather than just live for part of it.
1426     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1427       MachineOperand &MO = MI->getOperand(i);
1428       if (MO.isReg() && MO.isDef() && !MO.isDead())
1429         MRI->clearKillFlags(MO.getReg());
1430     }
1431
1432     // Add to the CSE map.
1433     if (CI != CSEMap.end())
1434       CI->second.push_back(MI);
1435     else
1436       CSEMap[Opcode].push_back(MI);
1437   }
1438
1439   ++NumHoisted;
1440   Changed = true;
1441
1442   return true;
1443 }
1444
1445 MachineBasicBlock *MachineLICM::getCurPreheader() {
1446   // Determine the block to which to hoist instructions. If we can't find a
1447   // suitable loop predecessor, we can't do any hoisting.
1448
1449   // If we've tried to get a preheader and failed, don't try again.
1450   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1451     return nullptr;
1452
1453   if (!CurPreheader) {
1454     CurPreheader = CurLoop->getLoopPreheader();
1455     if (!CurPreheader) {
1456       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1457       if (!Pred) {
1458         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1459         return nullptr;
1460       }
1461
1462       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1463       if (!CurPreheader) {
1464         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1465         return nullptr;
1466       }
1467     }
1468   }
1469   return CurPreheader;
1470 }