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     LLVM_DEBUG(dbgs() << "LICM: Analysing sink candidate: " << *I);
804     if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I)) {
805       LLVM_DEBUG(dbgs() << "LICM: Added as sink candidate.\n");
806       Candidates.push_back(&*I);
807       continue;
808     }
809     LLVM_DEBUG(dbgs() << "LICM: Not added as sink candidate.\n");
810   }
811 
812   for (MachineInstr *I : Candidates) {
813     const MachineOperand &MO = I->getOperand(0);
814     if (!MO.isDef() || !MO.isReg() || !MO.getReg())
815       continue;
816     if (!MRI->hasOneDef(MO.getReg()))
817       continue;
818     bool CanSink = true;
819     MachineBasicBlock *SinkBlock = nullptr;
820     LLVM_DEBUG(dbgs() << "LICM: Try sinking: " << *I);
821 
822     for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
823       LLVM_DEBUG(dbgs() << "LICM:    Analysing use: "; MI.dump());
824       // FIXME: Come up with a proper cost model that estimates whether sinking
825       // the instruction (and thus possibly executing it on every loop
826       // iteration) is more expensive than a register.
827       // For now assumes that copies are cheap and thus almost always worth it.
828       if (!MI.isCopy()) {
829         CanSink = false;
830         break;
831       }
832       if (!SinkBlock) {
833         SinkBlock = MI.getParent();
834         LLVM_DEBUG(dbgs() << "LICM:   Setting sink block to: "
835                           << printMBBReference(*SinkBlock) << "\n");
836         continue;
837       }
838       SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
839       if (!SinkBlock) {
840         LLVM_DEBUG(dbgs() << "LICM:   Can't find nearest dominator\n");
841         CanSink = false;
842         break;
843       }
844       LLVM_DEBUG(dbgs() << "LICM:   Setting nearest common dom block: " <<
845                  printMBBReference(*SinkBlock) << "\n");
846     }
847     if (!CanSink) {
848       LLVM_DEBUG(dbgs() << "LICM: Can't sink instruction.\n");
849       continue;
850     }
851     if (!SinkBlock) {
852       LLVM_DEBUG(dbgs() << "LICM: Not sinking, can't find sink block.\n");
853       continue;
854     }
855     if (SinkBlock == Preheader) {
856       LLVM_DEBUG(dbgs() << "LICM: Not sinking, sink block is the preheader\n");
857       continue;
858     }
859 
860     LLVM_DEBUG(dbgs() << "LICM: Sinking to " << printMBBReference(*SinkBlock)
861                       << " from " << printMBBReference(*I->getParent())
862                       << ": " << *I);
863     SinkBlock->splice(SinkBlock->getFirstNonPHI(), Preheader, I);
864 
865     // The instruction is moved from its basic block, so do not retain the
866     // debug information.
867     assert(!I->isDebugInstr() && "Should not sink debug inst");
868     I->setDebugLoc(DebugLoc());
869   }
870 }
871 
872 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
873   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
874 }
875 
876 /// Find all virtual register references that are liveout of the preheader to
877 /// initialize the starting "register pressure". Note this does not count live
878 /// through (livein but not used) registers.
879 void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
880   std::fill(RegPressure.begin(), RegPressure.end(), 0);
881 
882   // If the preheader has only a single predecessor and it ends with a
883   // fallthrough or an unconditional branch, then scan its predecessor for live
884   // defs as well. This happens whenever the preheader is created by splitting
885   // the critical edge from the loop predecessor to the loop header.
886   if (BB->pred_size() == 1) {
887     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
888     SmallVector<MachineOperand, 4> Cond;
889     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
890       InitRegPressure(*BB->pred_begin());
891   }
892 
893   for (const MachineInstr &MI : *BB)
894     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
895 }
896 
897 /// Update estimate of register pressure after the specified instruction.
898 void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
899                                         bool ConsiderUnseenAsDef) {
900   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
901   for (const auto &RPIdAndCost : Cost) {
902     unsigned Class = RPIdAndCost.first;
903     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
904       RegPressure[Class] = 0;
905     else
906       RegPressure[Class] += RPIdAndCost.second;
907   }
908 }
909 
910 /// Calculate the additional register pressure that the registers used in MI
911 /// cause.
912 ///
913 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
914 /// figure out which usages are live-ins.
915 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
916 DenseMap<unsigned, int>
917 MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
918                                   bool ConsiderUnseenAsDef) {
919   DenseMap<unsigned, int> Cost;
920   if (MI->isImplicitDef())
921     return Cost;
922   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
923     const MachineOperand &MO = MI->getOperand(i);
924     if (!MO.isReg() || MO.isImplicit())
925       continue;
926     Register Reg = MO.getReg();
927     if (!Register::isVirtualRegister(Reg))
928       continue;
929 
930     // FIXME: It seems bad to use RegSeen only for some of these calculations.
931     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
932     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
933 
934     RegClassWeight W = TRI->getRegClassWeight(RC);
935     int RCCost = 0;
936     if (MO.isDef())
937       RCCost = W.RegWeight;
938     else {
939       bool isKill = isOperandKill(MO, MRI);
940       if (isNew && !isKill && ConsiderUnseenAsDef)
941         // Haven't seen this, it must be a livein.
942         RCCost = W.RegWeight;
943       else if (!isNew && isKill)
944         RCCost = -W.RegWeight;
945     }
946     if (RCCost == 0)
947       continue;
948     const int *PS = TRI->getRegClassPressureSets(RC);
949     for (; *PS != -1; ++PS) {
950       if (Cost.find(*PS) == Cost.end())
951         Cost[*PS] = RCCost;
952       else
953         Cost[*PS] += RCCost;
954     }
955   }
956   return Cost;
957 }
958 
959 /// Return true if this machine instruction loads from global offset table or
960 /// constant pool.
961 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
962   assert(MI.mayLoad() && "Expected MI that loads!");
963 
964   // If we lost memory operands, conservatively assume that the instruction
965   // reads from everything..
966   if (MI.memoperands_empty())
967     return true;
968 
969   for (MachineMemOperand *MemOp : MI.memoperands())
970     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
971       if (PSV->isGOT() || PSV->isConstantPool())
972         return true;
973 
974   return false;
975 }
976 
977 // This function iterates through all the operands of the input store MI and
978 // checks that each register operand statisfies isCallerPreservedPhysReg.
979 // This means, the value being stored and the address where it is being stored
980 // is constant throughout the body of the function (not including prologue and
981 // epilogue). When called with an MI that isn't a store, it returns false.
982 // A future improvement can be to check if the store registers are constant
983 // throughout the loop rather than throughout the funtion.
984 static bool isInvariantStore(const MachineInstr &MI,
985                              const TargetRegisterInfo *TRI,
986                              const MachineRegisterInfo *MRI) {
987 
988   bool FoundCallerPresReg = false;
989   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
990       (MI.getNumOperands() == 0))
991     return false;
992 
993   // Check that all register operands are caller-preserved physical registers.
994   for (const MachineOperand &MO : MI.operands()) {
995     if (MO.isReg()) {
996       Register Reg = MO.getReg();
997       // If operand is a virtual register, check if it comes from a copy of a
998       // physical register.
999       if (Register::isVirtualRegister(Reg))
1000         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
1001       if (Register::isVirtualRegister(Reg))
1002         return false;
1003       if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
1004         return false;
1005       else
1006         FoundCallerPresReg = true;
1007     } else if (!MO.isImm()) {
1008         return false;
1009     }
1010   }
1011   return FoundCallerPresReg;
1012 }
1013 
1014 // Return true if the input MI is a copy instruction that feeds an invariant
1015 // store instruction. This means that the src of the copy has to satisfy
1016 // isCallerPreservedPhysReg and atleast one of it's users should satisfy
1017 // isInvariantStore.
1018 static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
1019                                         const MachineRegisterInfo *MRI,
1020                                         const TargetRegisterInfo *TRI) {
1021 
1022   // FIXME: If targets would like to look through instructions that aren't
1023   // pure copies, this can be updated to a query.
1024   if (!MI.isCopy())
1025     return false;
1026 
1027   const MachineFunction *MF = MI.getMF();
1028   // Check that we are copying a constant physical register.
1029   Register CopySrcReg = MI.getOperand(1).getReg();
1030   if (Register::isVirtualRegister(CopySrcReg))
1031     return false;
1032 
1033   if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
1034     return false;
1035 
1036   Register CopyDstReg = MI.getOperand(0).getReg();
1037   // Check if any of the uses of the copy are invariant stores.
1038   assert(Register::isVirtualRegister(CopyDstReg) &&
1039          "copy dst is not a virtual reg");
1040 
1041   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
1042     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
1043       return true;
1044   }
1045   return false;
1046 }
1047 
1048 /// Returns true if the instruction may be a suitable candidate for LICM.
1049 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
1050 bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
1051   // Check if it's safe to move the instruction.
1052   bool DontMoveAcrossStore = true;
1053   if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
1054       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
1055     LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
1056     return false;
1057   }
1058 
1059   // If it is load then check if it is guaranteed to execute by making sure that
1060   // it dominates all exiting blocks. If it doesn't, then there is a path out of
1061   // the loop which does not execute this load, so we can't hoist it. Loads
1062   // from constant memory are not safe to speculate all the time, for example
1063   // indexed load from a jump table.
1064   // Stores and side effects are already checked by isSafeToMove.
1065   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
1066       !IsGuaranteedToExecute(I.getParent())) {
1067     LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
1068     return false;
1069   }
1070 
1071   // Convergent attribute has been used on operations that involve inter-thread
1072   // communication which results are implicitly affected by the enclosing
1073   // control flows. It is not safe to hoist or sink such operations across
1074   // control flow.
1075   if (I.isConvergent())
1076     return false;
1077 
1078   return true;
1079 }
1080 
1081 /// Returns true if the instruction is loop invariant.
1082 bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
1083   if (!IsLICMCandidate(I)) {
1084     LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
1085     return false;
1086   }
1087   return CurLoop->isLoopInvariant(I);
1088 }
1089 
1090 /// Return true if the specified instruction is used by a phi node and hoisting
1091 /// it could cause a copy to be inserted.
1092 bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
1093   SmallVector<const MachineInstr*, 8> Work(1, MI);
1094   do {
1095     MI = Work.pop_back_val();
1096     for (const MachineOperand &MO : MI->operands()) {
1097       if (!MO.isReg() || !MO.isDef())
1098         continue;
1099       Register Reg = MO.getReg();
1100       if (!Register::isVirtualRegister(Reg))
1101         continue;
1102       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1103         // A PHI may cause a copy to be inserted.
1104         if (UseMI.isPHI()) {
1105           // A PHI inside the loop causes a copy because the live range of Reg is
1106           // extended across the PHI.
1107           if (CurLoop->contains(&UseMI))
1108             return true;
1109           // A PHI in an exit block can cause a copy to be inserted if the PHI
1110           // has multiple predecessors in the loop with different values.
1111           // For now, approximate by rejecting all exit blocks.
1112           if (isExitBlock(UseMI.getParent()))
1113             return true;
1114           continue;
1115         }
1116         // Look past copies as well.
1117         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1118           Work.push_back(&UseMI);
1119       }
1120     }
1121   } while (!Work.empty());
1122   return false;
1123 }
1124 
1125 /// Compute operand latency between a def of 'Reg' and an use in the current
1126 /// loop, return true if the target considered it high.
1127 bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
1128                                             Register Reg) const {
1129   if (MRI->use_nodbg_empty(Reg))
1130     return false;
1131 
1132   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1133     if (UseMI.isCopyLike())
1134       continue;
1135     if (!CurLoop->contains(UseMI.getParent()))
1136       continue;
1137     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1138       const MachineOperand &MO = UseMI.getOperand(i);
1139       if (!MO.isReg() || !MO.isUse())
1140         continue;
1141       Register MOReg = MO.getReg();
1142       if (MOReg != Reg)
1143         continue;
1144 
1145       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1146         return true;
1147     }
1148 
1149     // Only look at the first in loop use.
1150     break;
1151   }
1152 
1153   return false;
1154 }
1155 
1156 /// Return true if the instruction is marked "cheap" or the operand latency
1157 /// between its def and a use is one or less.
1158 bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
1159   if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
1160     return true;
1161 
1162   bool isCheap = false;
1163   unsigned NumDefs = MI.getDesc().getNumDefs();
1164   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1165     MachineOperand &DefMO = MI.getOperand(i);
1166     if (!DefMO.isReg() || !DefMO.isDef())
1167       continue;
1168     --NumDefs;
1169     Register Reg = DefMO.getReg();
1170     if (Register::isPhysicalRegister(Reg))
1171       continue;
1172 
1173     if (!TII->hasLowDefLatency(SchedModel, MI, i))
1174       return false;
1175     isCheap = true;
1176   }
1177 
1178   return isCheap;
1179 }
1180 
1181 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1182 /// given cost matrix can cause high register pressure.
1183 bool
1184 MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1185                                          bool CheapInstr) {
1186   for (const auto &RPIdAndCost : Cost) {
1187     if (RPIdAndCost.second <= 0)
1188       continue;
1189 
1190     unsigned Class = RPIdAndCost.first;
1191     int Limit = RegLimit[Class];
1192 
1193     // Don't hoist cheap instructions if they would increase register pressure,
1194     // even if we're under the limit.
1195     if (CheapInstr && !HoistCheapInsts)
1196       return true;
1197 
1198     for (const auto &RP : BackTrace)
1199       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1200         return true;
1201   }
1202 
1203   return false;
1204 }
1205 
1206 /// Traverse the back trace from header to the current block and update their
1207 /// register pressures to reflect the effect of hoisting MI from the current
1208 /// block to the preheader.
1209 void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1210   // First compute the 'cost' of the instruction, i.e. its contribution
1211   // to register pressure.
1212   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1213                                /*ConsiderUnseenAsDef=*/false);
1214 
1215   // Update register pressure of blocks from loop header to current block.
1216   for (auto &RP : BackTrace)
1217     for (const auto &RPIdAndCost : Cost)
1218       RP[RPIdAndCost.first] += RPIdAndCost.second;
1219 }
1220 
1221 /// Return true if it is potentially profitable to hoist the given loop
1222 /// invariant.
1223 bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
1224   if (MI.isImplicitDef())
1225     return true;
1226 
1227   // Besides removing computation from the loop, hoisting an instruction has
1228   // these effects:
1229   //
1230   // - The value defined by the instruction becomes live across the entire
1231   //   loop. This increases register pressure in the loop.
1232   //
1233   // - If the value is used by a PHI in the loop, a copy will be required for
1234   //   lowering the PHI after extending the live range.
1235   //
1236   // - When hoisting the last use of a value in the loop, that value no longer
1237   //   needs to be live in the loop. This lowers register pressure in the loop.
1238 
1239   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
1240     return true;
1241 
1242   bool CheapInstr = IsCheapInstruction(MI);
1243   bool CreatesCopy = HasLoopPHIUse(&MI);
1244 
1245   // Don't hoist a cheap instruction if it would create a copy in the loop.
1246   if (CheapInstr && CreatesCopy) {
1247     LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1248     return false;
1249   }
1250 
1251   // Rematerializable instructions should always be hoisted since the register
1252   // allocator can just pull them down again when needed.
1253   if (TII->isTriviallyReMaterializable(MI, AA))
1254     return true;
1255 
1256   // FIXME: If there are long latency loop-invariant instructions inside the
1257   // loop at this point, why didn't the optimizer's LICM hoist them?
1258   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1259     const MachineOperand &MO = MI.getOperand(i);
1260     if (!MO.isReg() || MO.isImplicit())
1261       continue;
1262     Register Reg = MO.getReg();
1263     if (!Register::isVirtualRegister(Reg))
1264       continue;
1265     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1266       LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
1267       ++NumHighLatency;
1268       return true;
1269     }
1270   }
1271 
1272   // Estimate register pressure to determine whether to LICM the instruction.
1273   // In low register pressure situation, we can be more aggressive about
1274   // hoisting. Also, favors hoisting long latency instructions even in
1275   // moderately high pressure situation.
1276   // Cheap instructions will only be hoisted if they don't increase register
1277   // pressure at all.
1278   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1279                                /*ConsiderUnseenAsDef=*/false);
1280 
1281   // Visit BBs from header to current BB, if hoisting this doesn't cause
1282   // high register pressure, then it's safe to proceed.
1283   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1284     LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1285     ++NumLowRP;
1286     return true;
1287   }
1288 
1289   // Don't risk increasing register pressure if it would create copies.
1290   if (CreatesCopy) {
1291     LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1292     return false;
1293   }
1294 
1295   // Do not "speculate" in high register pressure situation. If an
1296   // instruction is not guaranteed to be executed in the loop, it's best to be
1297   // conservative.
1298   if (AvoidSpeculation &&
1299       (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1300     LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
1301     return false;
1302   }
1303 
1304   // High register pressure situation, only hoist if the instruction is going
1305   // to be remat'ed.
1306   if (!TII->isTriviallyReMaterializable(MI, AA) &&
1307       !MI.isDereferenceableInvariantLoad(AA)) {
1308     LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1309     return false;
1310   }
1311 
1312   return true;
1313 }
1314 
1315 /// Unfold a load from the given machineinstr if the load itself could be
1316 /// hoisted. Return the unfolded and hoistable load, or null if the load
1317 /// couldn't be unfolded or if it wouldn't be hoistable.
1318 MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
1319   // Don't unfold simple loads.
1320   if (MI->canFoldAsLoad())
1321     return nullptr;
1322 
1323   // If not, we may be able to unfold a load and hoist that.
1324   // First test whether the instruction is loading from an amenable
1325   // memory location.
1326   if (!MI->isDereferenceableInvariantLoad(AA))
1327     return nullptr;
1328 
1329   // Next determine the register class for a temporary register.
1330   unsigned LoadRegIndex;
1331   unsigned NewOpc =
1332     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1333                                     /*UnfoldLoad=*/true,
1334                                     /*UnfoldStore=*/false,
1335                                     &LoadRegIndex);
1336   if (NewOpc == 0) return nullptr;
1337   const MCInstrDesc &MID = TII->get(NewOpc);
1338   MachineFunction &MF = *MI->getMF();
1339   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1340   // Ok, we're unfolding. Create a temporary register and do the unfold.
1341   Register Reg = MRI->createVirtualRegister(RC);
1342 
1343   SmallVector<MachineInstr *, 2> NewMIs;
1344   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1345                                           /*UnfoldLoad=*/true,
1346                                           /*UnfoldStore=*/false, NewMIs);
1347   (void)Success;
1348   assert(Success &&
1349          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1350          "succeeded!");
1351   assert(NewMIs.size() == 2 &&
1352          "Unfolded a load into multiple instructions!");
1353   MachineBasicBlock *MBB = MI->getParent();
1354   MachineBasicBlock::iterator Pos = MI;
1355   MBB->insert(Pos, NewMIs[0]);
1356   MBB->insert(Pos, NewMIs[1]);
1357   // If unfolding produced a load that wasn't loop-invariant or profitable to
1358   // hoist, discard the new instructions and bail.
1359   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
1360     NewMIs[0]->eraseFromParent();
1361     NewMIs[1]->eraseFromParent();
1362     return nullptr;
1363   }
1364 
1365   // Update register pressure for the unfolded instruction.
1366   UpdateRegPressure(NewMIs[1]);
1367 
1368   // Otherwise we successfully unfolded a load that we can hoist.
1369 
1370   // Update the call site info.
1371   if (MI->shouldUpdateCallSiteInfo())
1372     MF.eraseCallSiteInfo(MI);
1373 
1374   MI->eraseFromParent();
1375   return NewMIs[0];
1376 }
1377 
1378 /// Initialize the CSE map with instructions that are in the current loop
1379 /// preheader that may become duplicates of instructions that are hoisted
1380 /// out of the loop.
1381 void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
1382   for (MachineInstr &MI : *BB)
1383     CSEMap[MI.getOpcode()].push_back(&MI);
1384 }
1385 
1386 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1387 /// Return this instruction if it's found.
1388 MachineInstr *
1389 MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1390                                   std::vector<MachineInstr *> &PrevMIs) {
1391   for (MachineInstr *PrevMI : PrevMIs)
1392     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1393       return PrevMI;
1394 
1395   return nullptr;
1396 }
1397 
1398 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1399 /// computes the same value. If it's found, do a RAU on with the definition of
1400 /// the existing instruction rather than hoisting the instruction to the
1401 /// preheader.
1402 bool MachineLICMBase::EliminateCSE(
1403     MachineInstr *MI,
1404     DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
1405   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1406   // the undef property onto uses.
1407   if (CI == CSEMap.end() || MI->isImplicitDef())
1408     return false;
1409 
1410   if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1411     LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1412 
1413     // Replace virtual registers defined by MI by their counterparts defined
1414     // by Dup.
1415     SmallVector<unsigned, 2> Defs;
1416     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1417       const MachineOperand &MO = MI->getOperand(i);
1418 
1419       // Physical registers may not differ here.
1420       assert((!MO.isReg() || MO.getReg() == 0 ||
1421               !Register::isPhysicalRegister(MO.getReg()) ||
1422               MO.getReg() == Dup->getOperand(i).getReg()) &&
1423              "Instructions with different phys regs are not identical!");
1424 
1425       if (MO.isReg() && MO.isDef() &&
1426           !Register::isPhysicalRegister(MO.getReg()))
1427         Defs.push_back(i);
1428     }
1429 
1430     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1431     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1432       unsigned Idx = Defs[i];
1433       Register Reg = MI->getOperand(Idx).getReg();
1434       Register DupReg = Dup->getOperand(Idx).getReg();
1435       OrigRCs.push_back(MRI->getRegClass(DupReg));
1436 
1437       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1438         // Restore old RCs if more than one defs.
1439         for (unsigned j = 0; j != i; ++j)
1440           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1441         return false;
1442       }
1443     }
1444 
1445     for (unsigned Idx : Defs) {
1446       Register Reg = MI->getOperand(Idx).getReg();
1447       Register DupReg = Dup->getOperand(Idx).getReg();
1448       MRI->replaceRegWith(Reg, DupReg);
1449       MRI->clearKillFlags(DupReg);
1450       // Clear Dup dead flag if any, we reuse it for Reg.
1451       if (!MRI->use_nodbg_empty(DupReg))
1452         Dup->getOperand(Idx).setIsDead(false);
1453     }
1454 
1455     MI->eraseFromParent();
1456     ++NumCSEed;
1457     return true;
1458   }
1459   return false;
1460 }
1461 
1462 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1463 /// the loop.
1464 bool MachineLICMBase::MayCSE(MachineInstr *MI) {
1465   unsigned Opcode = MI->getOpcode();
1466   DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1467       CSEMap.find(Opcode);
1468   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1469   // the undef property onto uses.
1470   if (CI == CSEMap.end() || MI->isImplicitDef())
1471     return false;
1472 
1473   return LookForDuplicate(MI, CI->second) != nullptr;
1474 }
1475 
1476 /// When an instruction is found to use only loop invariant operands
1477 /// that are safe to hoist, this instruction is called to do the dirty work.
1478 /// It returns true if the instruction is hoisted.
1479 bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
1480   MachineBasicBlock *SrcBlock = MI->getParent();
1481 
1482   // Disable the instruction hoisting due to block hotness
1483   if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1484       (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1485       isTgtHotterThanSrc(SrcBlock, Preheader)) {
1486     ++NumNotHoistedDueToHotness;
1487     return false;
1488   }
1489   // First check whether we should hoist this instruction.
1490   if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
1491     // If not, try unfolding a hoistable load.
1492     MI = ExtractHoistableLoad(MI);
1493     if (!MI) return false;
1494   }
1495 
1496   // If we have hoisted an instruction that may store, it can only be a constant
1497   // store.
1498   if (MI->mayStore())
1499     NumStoreConst++;
1500 
1501   // Now move the instructions to the predecessor, inserting it before any
1502   // terminator instructions.
1503   LLVM_DEBUG({
1504     dbgs() << "Hoisting " << *MI;
1505     if (MI->getParent()->getBasicBlock())
1506       dbgs() << " from " << printMBBReference(*MI->getParent());
1507     if (Preheader->getBasicBlock())
1508       dbgs() << " to " << printMBBReference(*Preheader);
1509     dbgs() << "\n";
1510   });
1511 
1512   // If this is the first instruction being hoisted to the preheader,
1513   // initialize the CSE map with potential common expressions.
1514   if (FirstInLoop) {
1515     InitCSEMap(Preheader);
1516     FirstInLoop = false;
1517   }
1518 
1519   // Look for opportunity to CSE the hoisted instruction.
1520   unsigned Opcode = MI->getOpcode();
1521   DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1522       CSEMap.find(Opcode);
1523   if (!EliminateCSE(MI, CI)) {
1524     // Otherwise, splice the instruction to the preheader.
1525     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1526 
1527     // Since we are moving the instruction out of its basic block, we do not
1528     // retain its debug location. Doing so would degrade the debugging
1529     // experience and adversely affect the accuracy of profiling information.
1530     assert(!MI->isDebugInstr() && "Should not hoist debug inst");
1531     MI->setDebugLoc(DebugLoc());
1532 
1533     // Update register pressure for BBs from header to this block.
1534     UpdateBackTraceRegPressure(MI);
1535 
1536     // Clear the kill flags of any register this instruction defines,
1537     // since they may need to be live throughout the entire loop
1538     // rather than just live for part of it.
1539     for (MachineOperand &MO : MI->operands())
1540       if (MO.isReg() && MO.isDef() && !MO.isDead())
1541         MRI->clearKillFlags(MO.getReg());
1542 
1543     // Add to the CSE map.
1544     if (CI != CSEMap.end())
1545       CI->second.push_back(MI);
1546     else
1547       CSEMap[Opcode].push_back(MI);
1548   }
1549 
1550   ++NumHoisted;
1551   Changed = true;
1552 
1553   return true;
1554 }
1555 
1556 /// Get the preheader for the current loop, splitting a critical edge if needed.
1557 MachineBasicBlock *MachineLICMBase::getCurPreheader() {
1558   // Determine the block to which to hoist instructions. If we can't find a
1559   // suitable loop predecessor, we can't do any hoisting.
1560 
1561   // If we've tried to get a preheader and failed, don't try again.
1562   if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1563     return nullptr;
1564 
1565   if (!CurPreheader) {
1566     CurPreheader = CurLoop->getLoopPreheader();
1567     if (!CurPreheader) {
1568       MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1569       if (!Pred) {
1570         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1571         return nullptr;
1572       }
1573 
1574       CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
1575       if (!CurPreheader) {
1576         CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1577         return nullptr;
1578       }
1579     }
1580   }
1581   return CurPreheader;
1582 }
1583 
1584 /// Is the target basic block at least "BlockFrequencyRatioThreshold"
1585 /// times hotter than the source basic block.
1586 bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1587                                          MachineBasicBlock *TgtBlock) {
1588   // Parse source and target basic block frequency from MBFI
1589   uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1590   uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1591 
1592   // Disable the hoisting if source block frequency is zero
1593   if (!SrcBF)
1594     return true;
1595 
1596   double Ratio = (double)DstBF / SrcBF;
1597 
1598   // Compare the block frequency ratio with the threshold
1599   return Ratio > BlockFrequencyRatioThreshold;
1600 }
1601