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