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