xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineLICM.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
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/CodeGen/MachineLICM.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.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/MachineDomTreeUpdater.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineOperand.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetLowering.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSchedule.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/MC/MCInstrDesc.h"
46 #include "llvm/MC/MCRegister.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 HoistConstStores("hoist-const-stores",
73                  cl::desc("Hoist invariant stores"),
74                  cl::init(true), cl::Hidden);
75 
76 static cl::opt<bool> HoistConstLoads("hoist-const-loads",
77                                      cl::desc("Hoist invariant loads"),
78                                      cl::init(true), cl::Hidden);
79 
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   enum HoistResult { NotHoisted = 1, Hoisted = 2, ErasedMI = 4 };
119 
120   class MachineLICMImpl {
121     const TargetInstrInfo *TII = nullptr;
122     const TargetLoweringBase *TLI = nullptr;
123     const TargetRegisterInfo *TRI = nullptr;
124     const MachineFrameInfo *MFI = nullptr;
125     MachineRegisterInfo *MRI = nullptr;
126     TargetSchedModel SchedModel;
127     bool PreRegAlloc = false;
128     bool HasProfileData = false;
129     Pass *LegacyPass;
130     MachineFunctionAnalysisManager *MFAM;
131 
132     // Various analyses that we use...
133     AliasAnalysis *AA = nullptr;               // Alias analysis info.
134     MachineBlockFrequencyInfo *MBFI = nullptr; // Machine block frequncy info
135     MachineLoopInfo *MLI = nullptr;            // Current MachineLoopInfo
136     MachineDomTreeUpdater *MDTU = nullptr;     // Wraps current dominator tree
137 
138     // State that is updated as we process loops
139     bool Changed = false;           // True if a loop is changed.
140     bool FirstInLoop = false;       // True if it's the first LICM in the loop.
141 
142     // Holds information about whether it is allowed to move load instructions
143     // out of the loop
144     SmallDenseMap<MachineLoop *, bool> AllowedToHoistLoads;
145 
146     // Exit blocks of each Loop.
147     DenseMap<MachineLoop *, SmallVector<MachineBasicBlock *, 8>> ExitBlockMap;
148 
149     bool isExitBlock(MachineLoop *CurLoop, const MachineBasicBlock *MBB) {
150       auto [It, Inserted] = ExitBlockMap.try_emplace(CurLoop);
151       if (Inserted) {
152         SmallVector<MachineBasicBlock *, 8> ExitBlocks;
153         CurLoop->getExitBlocks(ExitBlocks);
154         It->second = std::move(ExitBlocks);
155       }
156       return is_contained(It->second, MBB);
157     }
158 
159     // Track 'estimated' register pressure.
160     SmallDenseSet<Register> RegSeen;
161     SmallVector<unsigned, 8> RegPressure;
162 
163     // Register pressure "limit" per register pressure set. If the pressure
164     // is higher than the limit, then it's considered high.
165     SmallVector<unsigned, 8> RegLimit;
166 
167     // Register pressure on path leading from loop preheader to current BB.
168     SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
169 
170     // For each opcode per preheader, keep a list of potential CSE instructions.
171     DenseMap<MachineBasicBlock *,
172              DenseMap<unsigned, std::vector<MachineInstr *>>>
173         CSEMap;
174 
175     enum {
176       SpeculateFalse   = 0,
177       SpeculateTrue    = 1,
178       SpeculateUnknown = 2
179     };
180 
181     // If a MBB does not dominate loop exiting blocks then it may not safe
182     // to hoist loads from this block.
183     // Tri-state: 0 - false, 1 - true, 2 - unknown
184     unsigned SpeculationState = SpeculateUnknown;
185 
186   public:
187     MachineLICMImpl(bool PreRegAlloc, Pass *LegacyPass,
188                     MachineFunctionAnalysisManager *MFAM)
189         : PreRegAlloc(PreRegAlloc), LegacyPass(LegacyPass), MFAM(MFAM) {
190       assert((LegacyPass || MFAM) && "LegacyPass or MFAM must be provided");
191       assert(!(LegacyPass && MFAM) &&
192              "LegacyPass and MFAM cannot be provided at the same time");
193     }
194 
195     bool run(MachineFunction &MF);
196 
197     void releaseMemory() {
198       RegSeen.clear();
199       RegPressure.clear();
200       RegLimit.clear();
201       BackTrace.clear();
202       CSEMap.clear();
203       ExitBlockMap.clear();
204     }
205 
206   private:
207     /// Keep track of information about hoisting candidates.
208     struct CandidateInfo {
209       MachineInstr *MI;
210       Register      Def;
211       int           FI;
212 
213       CandidateInfo(MachineInstr *mi, Register def, int fi)
214         : MI(mi), Def(def), FI(fi) {}
215     };
216 
217     void HoistRegionPostRA(MachineLoop *CurLoop);
218 
219     void HoistPostRA(MachineInstr *MI, Register Def, MachineLoop *CurLoop);
220 
221     void ProcessMI(MachineInstr *MI, BitVector &RUDefs, BitVector &RUClobbers,
222                    SmallDenseSet<int> &StoredFIs,
223                    SmallVectorImpl<CandidateInfo> &Candidates,
224                    MachineLoop *CurLoop);
225 
226     void AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop);
227 
228     bool IsLICMCandidate(MachineInstr &I, MachineLoop *CurLoop);
229 
230     bool IsLoopInvariantInst(MachineInstr &I, MachineLoop *CurLoop);
231 
232     bool HasLoopPHIUse(const MachineInstr *MI, MachineLoop *CurLoop);
233 
234     bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, Register Reg,
235                                MachineLoop *CurLoop) const;
236 
237     bool IsCheapInstruction(MachineInstr &MI) const;
238 
239     bool CanCauseHighRegPressure(const SmallDenseMap<unsigned, int> &Cost,
240                                  bool Cheap);
241 
242     void UpdateBackTraceRegPressure(const MachineInstr *MI);
243 
244     bool IsProfitableToHoist(MachineInstr &MI, MachineLoop *CurLoop);
245 
246     bool IsGuaranteedToExecute(MachineBasicBlock *BB, MachineLoop *CurLoop);
247 
248     bool isTriviallyReMaterializable(const MachineInstr &MI) const;
249 
250     void EnterScope(MachineBasicBlock *MBB);
251 
252     void ExitScope(MachineBasicBlock *MBB);
253 
254     void ExitScopeIfDone(
255         MachineDomTreeNode *Node,
256         DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
257         const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
258 
259     void HoistOutOfLoop(MachineDomTreeNode *HeaderN, MachineLoop *CurLoop);
260 
261     void InitRegPressure(MachineBasicBlock *BB);
262 
263     SmallDenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
264                                                   bool ConsiderSeen,
265                                                   bool ConsiderUnseenAsDef);
266 
267     void UpdateRegPressure(const MachineInstr *MI,
268                            bool ConsiderUnseenAsDef = false);
269 
270     MachineInstr *ExtractHoistableLoad(MachineInstr *MI, MachineLoop *CurLoop);
271 
272     MachineInstr *LookForDuplicate(const MachineInstr *MI,
273                                    std::vector<MachineInstr *> &PrevMIs);
274 
275     bool
276     EliminateCSE(MachineInstr *MI,
277                  DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
278 
279     bool MayCSE(MachineInstr *MI);
280 
281     unsigned Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
282                    MachineLoop *CurLoop);
283 
284     void InitCSEMap(MachineBasicBlock *BB);
285 
286     void InitializeLoadsHoistableLoops();
287 
288     bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
289                             MachineBasicBlock *TgtBlock);
290     MachineBasicBlock *getOrCreatePreheader(MachineLoop *CurLoop);
291   };
292 
293   class MachineLICMBase : public MachineFunctionPass {
294     bool PreRegAlloc;
295 
296   public:
297     MachineLICMBase(char &ID, bool PreRegAlloc)
298         : MachineFunctionPass(ID), PreRegAlloc(PreRegAlloc) {}
299 
300     bool runOnMachineFunction(MachineFunction &MF) override;
301 
302     void getAnalysisUsage(AnalysisUsage &AU) const override {
303       AU.addRequired<MachineLoopInfoWrapperPass>();
304       if (DisableHoistingToHotterBlocks != UseBFI::None)
305         AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
306       AU.addRequired<MachineDominatorTreeWrapperPass>();
307       AU.addRequired<AAResultsWrapperPass>();
308       AU.addPreserved<MachineLoopInfoWrapperPass>();
309       MachineFunctionPass::getAnalysisUsage(AU);
310     }
311   };
312 
313   class MachineLICM : public MachineLICMBase {
314   public:
315     static char ID;
316     MachineLICM() : MachineLICMBase(ID, false) {
317       initializeMachineLICMPass(*PassRegistry::getPassRegistry());
318     }
319   };
320 
321   class EarlyMachineLICM : public MachineLICMBase {
322   public:
323     static char ID;
324     EarlyMachineLICM() : MachineLICMBase(ID, true) {
325       initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
326     }
327   };
328 
329 } // end anonymous namespace
330 
331 char MachineLICM::ID;
332 char EarlyMachineLICM::ID;
333 
334 char &llvm::MachineLICMID = MachineLICM::ID;
335 char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
336 
337 INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
338                       "Machine Loop Invariant Code Motion", false, false)
339 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
340 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
341 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
342 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
343 INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
344                     "Machine Loop Invariant Code Motion", false, false)
345 
346 INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
347                       "Early Machine Loop Invariant Code Motion", false, false)
348 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
349 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
350 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
351 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
352 INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
353                     "Early Machine Loop Invariant Code Motion", false, false)
354 
355 bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
356   if (skipFunction(MF.getFunction()))
357     return false;
358 
359   MachineLICMImpl Impl(PreRegAlloc, this, nullptr);
360   return Impl.run(MF);
361 }
362 
363 #define GET_RESULT(RESULT, GETTER, INFIX)                                      \
364   ((LegacyPass)                                                                \
365        ? &LegacyPass->getAnalysis<RESULT##INFIX##WrapperPass>().GETTER()       \
366        : &MFAM->getResult<RESULT##Analysis>(MF))
367 
368 bool MachineLICMImpl::run(MachineFunction &MF) {
369   AA = MFAM != nullptr
370            ? &MFAM->getResult<FunctionAnalysisManagerMachineFunctionProxy>(MF)
371                   .getManager()
372                   .getResult<AAManager>(MF.getFunction())
373            : &LegacyPass->getAnalysis<AAResultsWrapperPass>().getAAResults();
374   MachineDomTreeUpdater DTU(GET_RESULT(MachineDominatorTree, getDomTree, ),
375                             MachineDomTreeUpdater::UpdateStrategy::Lazy);
376   MDTU = &DTU;
377   MLI = GET_RESULT(MachineLoop, getLI, Info);
378   MBFI = DisableHoistingToHotterBlocks != UseBFI::None
379              ? GET_RESULT(MachineBlockFrequency, getMBFI, Info)
380              : nullptr;
381 
382   Changed = FirstInLoop = false;
383   const TargetSubtargetInfo &ST = MF.getSubtarget();
384   TII = ST.getInstrInfo();
385   TLI = ST.getTargetLowering();
386   TRI = ST.getRegisterInfo();
387   MFI = &MF.getFrameInfo();
388   MRI = &MF.getRegInfo();
389   SchedModel.init(&ST);
390 
391   HasProfileData = MF.getFunction().hasProfileData();
392 
393   if (PreRegAlloc)
394     LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
395   else
396     LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
397   LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
398 
399   if (PreRegAlloc) {
400     // Estimate register pressure during pre-regalloc pass.
401     unsigned NumRPS = TRI->getNumRegPressureSets();
402     RegPressure.resize(NumRPS);
403     llvm::fill(RegPressure, 0);
404     RegLimit.resize(NumRPS);
405     for (unsigned i = 0, e = NumRPS; i != e; ++i)
406       RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
407   }
408 
409   if (HoistConstLoads)
410     InitializeLoadsHoistableLoops();
411 
412   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
413   while (!Worklist.empty()) {
414     MachineLoop *CurLoop = Worklist.pop_back_val();
415 
416     if (!PreRegAlloc) {
417       HoistRegionPostRA(CurLoop);
418     } else {
419       // CSEMap is initialized for loop header when the first instruction is
420       // being hoisted.
421       MachineDomTreeNode *N = MDTU->getDomTree().getNode(CurLoop->getHeader());
422       FirstInLoop = true;
423       HoistOutOfLoop(N, CurLoop);
424       CSEMap.clear();
425     }
426   }
427   releaseMemory();
428   return Changed;
429 }
430 
431 /// Return true if instruction stores to the specified frame.
432 static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
433   // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
434   // true since they have no memory operands.
435   if (!MI->mayStore())
436      return false;
437   // If we lost memory operands, conservatively assume that the instruction
438   // writes to all slots.
439   if (MI->memoperands_empty())
440     return true;
441   for (const MachineMemOperand *MemOp : MI->memoperands()) {
442     if (!MemOp->isStore() || !MemOp->getPseudoValue())
443       continue;
444     if (const FixedStackPseudoSourceValue *Value =
445         dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
446       if (Value->getFrameIndex() == FI)
447         return true;
448     }
449   }
450   return false;
451 }
452 
453 static void applyBitsNotInRegMaskToRegUnitsMask(const TargetRegisterInfo &TRI,
454                                                 BitVector &RUs,
455                                                 const uint32_t *Mask) {
456   // FIXME: This intentionally works in reverse due to some issues with the
457   // Register Units infrastructure.
458   //
459   // This is used to apply callee-saved-register masks to the clobbered regunits
460   // mask.
461   //
462   // The right way to approach this is to start with a BitVector full of ones,
463   // then reset all the bits of the regunits of each register that is set in the
464   // mask (registers preserved), then OR the resulting bits with the Clobbers
465   // mask. This correctly prioritizes the saved registers, so if a RU is shared
466   // between a register that is preserved, and one that is NOT preserved, that
467   // RU will not be set in the output vector (the clobbers).
468   //
469   // What we have to do for now is the opposite: we have to assume that the
470   // regunits of all registers that are NOT preserved are clobbered, even if
471   // those regunits are preserved by another register. So if a RU is shared
472   // like described previously, that RU will be set.
473   //
474   // This is to work around an issue which appears in AArch64, but isn't
475   // exclusive to that target: AArch64's Qn registers (128 bits) have Dn
476   // register (lower 64 bits). A few Dn registers are preserved by some calling
477   // conventions, but Qn and Dn share exactly the same reg units.
478   //
479   // If we do this the right way, Qn will be marked as NOT clobbered even though
480   // its upper 64 bits are NOT preserved. The conservative approach handles this
481   // correctly at the cost of some missed optimizations on other targets.
482   //
483   // This is caused by how RegUnits are handled within TableGen. Ideally, Qn
484   // should have an extra RegUnit to model the "unknown" bits not covered by the
485   // subregs.
486   BitVector RUsFromRegsNotInMask(TRI.getNumRegUnits());
487   const unsigned NumRegs = TRI.getNumRegs();
488   const unsigned MaskWords = (NumRegs + 31) / 32;
489   for (unsigned K = 0; K < MaskWords; ++K) {
490     const uint32_t Word = Mask[K];
491     for (unsigned Bit = 0; Bit < 32; ++Bit) {
492       const unsigned PhysReg = (K * 32) + Bit;
493       if (PhysReg == NumRegs)
494         break;
495 
496       if (PhysReg && !((Word >> Bit) & 1)) {
497         for (MCRegUnit Unit : TRI.regunits(PhysReg))
498           RUsFromRegsNotInMask.set(Unit);
499       }
500     }
501   }
502 
503   RUs |= RUsFromRegsNotInMask;
504 }
505 
506 /// Examine the instruction for potential LICM candidate. Also
507 /// gather register def and frame object update information.
508 void MachineLICMImpl::ProcessMI(MachineInstr *MI, BitVector &RUDefs,
509                                 BitVector &RUClobbers,
510                                 SmallDenseSet<int> &StoredFIs,
511                                 SmallVectorImpl<CandidateInfo> &Candidates,
512                                 MachineLoop *CurLoop) {
513   bool RuledOut = false;
514   bool HasNonInvariantUse = false;
515   Register Def;
516   for (const MachineOperand &MO : MI->operands()) {
517     if (MO.isFI()) {
518       // Remember if the instruction stores to the frame index.
519       int FI = MO.getIndex();
520       if (!StoredFIs.count(FI) &&
521           MFI->isSpillSlotObjectIndex(FI) &&
522           InstructionStoresToFI(MI, FI))
523         StoredFIs.insert(FI);
524       HasNonInvariantUse = true;
525       continue;
526     }
527 
528     // We can't hoist an instruction defining a physreg that is clobbered in
529     // the loop.
530     if (MO.isRegMask()) {
531       applyBitsNotInRegMaskToRegUnitsMask(*TRI, RUClobbers, MO.getRegMask());
532       continue;
533     }
534 
535     if (!MO.isReg())
536       continue;
537     Register Reg = MO.getReg();
538     if (!Reg)
539       continue;
540     assert(Reg.isPhysical() && "Not expecting virtual register!");
541 
542     if (!MO.isDef()) {
543       if (!HasNonInvariantUse) {
544         for (MCRegUnit Unit : TRI->regunits(Reg)) {
545           // If it's using a non-loop-invariant register, then it's obviously
546           // not safe to hoist.
547           if (RUDefs.test(Unit) || RUClobbers.test(Unit)) {
548             HasNonInvariantUse = true;
549             break;
550           }
551         }
552       }
553       continue;
554     }
555 
556     // FIXME: For now, avoid instructions with multiple defs, unless it's dead.
557     if (!MO.isDead()) {
558       if (Def)
559         RuledOut = true;
560       else
561         Def = Reg;
562     }
563 
564     // If we have already seen another instruction that defines the same
565     // register, then this is not safe.  Two defs is indicated by setting a
566     // PhysRegClobbers bit.
567     for (MCRegUnit Unit : TRI->regunits(Reg)) {
568       if (RUDefs.test(Unit)) {
569         RUClobbers.set(Unit);
570         RuledOut = true;
571       } else if (RUClobbers.test(Unit)) {
572         // MI defined register is seen defined by another instruction in
573         // the loop, it cannot be a LICM candidate.
574         RuledOut = true;
575       }
576 
577       RUDefs.set(Unit);
578     }
579   }
580 
581   // Only consider reloads for now and remats which do not have register
582   // operands. FIXME: Consider unfold load folding instructions.
583   if (Def && !RuledOut) {
584     int FI = std::numeric_limits<int>::min();
585     if ((!HasNonInvariantUse && IsLICMCandidate(*MI, CurLoop)) ||
586         (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
587       Candidates.push_back(CandidateInfo(MI, Def, FI));
588   }
589 }
590 
591 /// Walk the specified region of the CFG and hoist loop invariants out to the
592 /// preheader.
593 void MachineLICMImpl::HoistRegionPostRA(MachineLoop *CurLoop) {
594   MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
595   if (!Preheader)
596     return;
597 
598   unsigned NumRegUnits = TRI->getNumRegUnits();
599   BitVector RUDefs(NumRegUnits);     // RUs defined once in the loop.
600   BitVector RUClobbers(NumRegUnits); // RUs defined more than once.
601 
602   SmallVector<CandidateInfo, 32> Candidates;
603   SmallDenseSet<int> StoredFIs;
604 
605   // Walk the entire region, count number of defs for each register, and
606   // collect potential LICM candidates.
607   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
608     // If the header of the loop containing this basic block is a landing pad,
609     // then don't try to hoist instructions out of this loop.
610     const MachineLoop *ML = MLI->getLoopFor(BB);
611     if (ML && ML->getHeader()->isEHPad()) continue;
612 
613     // Conservatively treat live-in's as an external def.
614     // FIXME: That means a reload that're reused in successor block(s) will not
615     // be LICM'ed.
616     for (const auto &LI : BB->liveins()) {
617       for (MCRegUnit Unit : TRI->regunits(LI.PhysReg))
618         RUDefs.set(Unit);
619     }
620 
621     // Funclet entry blocks will clobber all registers
622     if (const uint32_t *Mask = BB->getBeginClobberMask(TRI))
623       applyBitsNotInRegMaskToRegUnitsMask(*TRI, RUClobbers, Mask);
624 
625     // EH landing pads clobber exception pointer/selector registers.
626     if (BB->isEHPad()) {
627       const MachineFunction &MF = *BB->getParent();
628       const Constant *PersonalityFn = MF.getFunction().getPersonalityFn();
629       const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
630       if (MCRegister Reg = TLI.getExceptionPointerRegister(PersonalityFn))
631         for (MCRegUnit Unit : TRI->regunits(Reg))
632           RUClobbers.set(Unit);
633       if (MCRegister Reg = TLI.getExceptionSelectorRegister(PersonalityFn))
634         for (MCRegUnit Unit : TRI->regunits(Reg))
635           RUClobbers.set(Unit);
636     }
637 
638     SpeculationState = SpeculateUnknown;
639     for (MachineInstr &MI : *BB)
640       ProcessMI(&MI, RUDefs, RUClobbers, StoredFIs, Candidates, CurLoop);
641   }
642 
643   // Gather the registers read / clobbered by the terminator.
644   BitVector TermRUs(NumRegUnits);
645   MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
646   if (TI != Preheader->end()) {
647     for (const MachineOperand &MO : TI->operands()) {
648       if (!MO.isReg())
649         continue;
650       Register Reg = MO.getReg();
651       if (!Reg)
652         continue;
653       for (MCRegUnit Unit : TRI->regunits(Reg))
654         TermRUs.set(Unit);
655     }
656   }
657 
658   // Now evaluate whether the potential candidates qualify.
659   // 1. Check if the candidate defined register is defined by another
660   //    instruction in the loop.
661   // 2. If the candidate is a load from stack slot (always true for now),
662   //    check if the slot is stored anywhere in the loop.
663   // 3. Make sure candidate def should not clobber
664   //    registers read by the terminator. Similarly its def should not be
665   //    clobbered by the terminator.
666   for (CandidateInfo &Candidate : Candidates) {
667     if (Candidate.FI != std::numeric_limits<int>::min() &&
668         StoredFIs.count(Candidate.FI))
669       continue;
670 
671     Register Def = Candidate.Def;
672     bool Safe = true;
673     for (MCRegUnit Unit : TRI->regunits(Def)) {
674       if (RUClobbers.test(Unit) || TermRUs.test(Unit)) {
675         Safe = false;
676         break;
677       }
678     }
679 
680     if (!Safe)
681       continue;
682 
683     MachineInstr *MI = Candidate.MI;
684     for (const MachineOperand &MO : MI->all_uses()) {
685       if (!MO.getReg())
686         continue;
687       for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
688         if (RUDefs.test(Unit) || RUClobbers.test(Unit)) {
689           // If it's using a non-loop-invariant register, then it's obviously
690           // not safe to hoist.
691           Safe = false;
692           break;
693         }
694       }
695 
696       if (!Safe)
697         break;
698     }
699 
700     if (Safe)
701       HoistPostRA(MI, Candidate.Def, CurLoop);
702   }
703 }
704 
705 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
706 /// sure it is not killed by any instructions in the loop.
707 void MachineLICMImpl::AddToLiveIns(MCRegister Reg, MachineLoop *CurLoop) {
708   for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
709     if (!BB->isLiveIn(Reg))
710       BB->addLiveIn(Reg);
711     for (MachineInstr &MI : *BB) {
712       for (MachineOperand &MO : MI.all_uses()) {
713         if (!MO.getReg())
714           continue;
715         if (TRI->regsOverlap(Reg, MO.getReg()))
716           MO.setIsKill(false);
717       }
718     }
719   }
720 }
721 
722 /// When an instruction is found to only use loop invariant operands that is
723 /// safe to hoist, this instruction is called to do the dirty work.
724 void MachineLICMImpl::HoistPostRA(MachineInstr *MI, Register Def,
725                                   MachineLoop *CurLoop) {
726   MachineBasicBlock *Preheader = CurLoop->getLoopPreheader();
727 
728   // Now move the instructions to the predecessor, inserting it before any
729   // terminator instructions.
730   LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
731                     << " from " << printMBBReference(*MI->getParent()) << ": "
732                     << *MI);
733 
734   // Splice the instruction to the preheader.
735   MachineBasicBlock *MBB = MI->getParent();
736   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
737 
738   // Since we are moving the instruction out of its basic block, we do not
739   // retain its debug location. Doing so would degrade the debugging
740   // experience and adversely affect the accuracy of profiling information.
741   assert(!MI->isDebugInstr() && "Should not hoist debug inst");
742   MI->setDebugLoc(DebugLoc());
743 
744   // Add register to livein list to all the BBs in the current loop since a
745   // loop invariant must be kept live throughout the whole loop. This is
746   // important to ensure later passes do not scavenge the def register.
747   AddToLiveIns(Def, CurLoop);
748 
749   ++NumPostRAHoisted;
750   Changed = true;
751 }
752 
753 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
754 /// may not be safe to hoist.
755 bool MachineLICMImpl::IsGuaranteedToExecute(MachineBasicBlock *BB,
756                                             MachineLoop *CurLoop) {
757   if (SpeculationState != SpeculateUnknown)
758     return SpeculationState == SpeculateFalse;
759 
760   if (BB != CurLoop->getHeader()) {
761     // Check loop exiting blocks.
762     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
763     CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
764     for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
765       if (!MDTU->getDomTree().dominates(BB, CurrentLoopExitingBlock)) {
766         SpeculationState = SpeculateTrue;
767         return false;
768       }
769   }
770 
771   SpeculationState = SpeculateFalse;
772   return true;
773 }
774 
775 /// Check if \p MI is trivially remateralizable and if it does not have any
776 /// virtual register uses. Even though rematerializable RA might not actually
777 /// rematerialize it in this scenario. In that case we do not want to hoist such
778 /// instruction out of the loop in a belief RA will sink it back if needed.
779 bool MachineLICMImpl::isTriviallyReMaterializable(
780     const MachineInstr &MI) const {
781   if (!TII->isTriviallyReMaterializable(MI))
782     return false;
783 
784   for (const MachineOperand &MO : MI.all_uses()) {
785     if (MO.getReg().isVirtual())
786       return false;
787   }
788 
789   return true;
790 }
791 
792 void MachineLICMImpl::EnterScope(MachineBasicBlock *MBB) {
793   LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
794 
795   // Remember livein register pressure.
796   BackTrace.push_back(RegPressure);
797 }
798 
799 void MachineLICMImpl::ExitScope(MachineBasicBlock *MBB) {
800   LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
801   BackTrace.pop_back();
802 }
803 
804 /// Destroy scope for the MBB that corresponds to the given dominator tree node
805 /// if its a leaf or all of its children are done. Walk up the dominator tree to
806 /// destroy ancestors which are now done.
807 void MachineLICMImpl::ExitScopeIfDone(
808     MachineDomTreeNode *Node,
809     DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
810     const DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap) {
811   if (OpenChildren[Node])
812     return;
813 
814   for(;;) {
815     ExitScope(Node->getBlock());
816     // Now traverse upwards to pop ancestors whose offsprings are all done.
817     MachineDomTreeNode *Parent = ParentMap.lookup(Node);
818     if (!Parent || --OpenChildren[Parent] != 0)
819       break;
820     Node = Parent;
821   }
822 }
823 
824 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
825 /// specified header block, and that are in the current loop) in depth first
826 /// order w.r.t the DominatorTree. This allows us to visit definitions before
827 /// uses, allowing us to hoist a loop body in one pass without iteration.
828 void MachineLICMImpl::HoistOutOfLoop(MachineDomTreeNode *HeaderN,
829                                      MachineLoop *CurLoop) {
830   MachineBasicBlock *Preheader = getOrCreatePreheader(CurLoop);
831   if (!Preheader)
832     return;
833 
834   SmallVector<MachineDomTreeNode*, 32> Scopes;
835   SmallVector<MachineDomTreeNode*, 8> WorkList;
836   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
837   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
838 
839   // Perform a DFS walk to determine the order of visit.
840   WorkList.push_back(HeaderN);
841   while (!WorkList.empty()) {
842     MachineDomTreeNode *Node = WorkList.pop_back_val();
843     assert(Node && "Null dominator tree node?");
844     MachineBasicBlock *BB = Node->getBlock();
845 
846     // If the header of the loop containing this basic block is a landing pad,
847     // then don't try to hoist instructions out of this loop.
848     const MachineLoop *ML = MLI->getLoopFor(BB);
849     if (ML && ML->getHeader()->isEHPad())
850       continue;
851 
852     // If this subregion is not in the top level loop at all, exit.
853     if (!CurLoop->contains(BB))
854       continue;
855 
856     Scopes.push_back(Node);
857     unsigned NumChildren = Node->getNumChildren();
858 
859     // Don't hoist things out of a large switch statement.  This often causes
860     // code to be hoisted that wasn't going to be executed, and increases
861     // register pressure in a situation where it's likely to matter.
862     if (BB->succ_size() >= 25)
863       NumChildren = 0;
864 
865     OpenChildren[Node] = NumChildren;
866     if (NumChildren) {
867       // Add children in reverse order as then the next popped worklist node is
868       // the first child of this node.  This means we ultimately traverse the
869       // DOM tree in exactly the same order as if we'd recursed.
870       for (MachineDomTreeNode *Child : reverse(Node->children())) {
871         ParentMap[Child] = Node;
872         WorkList.push_back(Child);
873       }
874     }
875   }
876 
877   if (Scopes.size() == 0)
878     return;
879 
880   // Compute registers which are livein into the loop headers.
881   RegSeen.clear();
882   BackTrace.clear();
883   InitRegPressure(Preheader);
884 
885   // Now perform LICM.
886   for (MachineDomTreeNode *Node : Scopes) {
887     MachineBasicBlock *MBB = Node->getBlock();
888 
889     EnterScope(MBB);
890 
891     // Process the block
892     SpeculationState = SpeculateUnknown;
893     for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
894       unsigned HoistRes = HoistResult::NotHoisted;
895       HoistRes = Hoist(&MI, Preheader, CurLoop);
896       if (HoistRes & HoistResult::NotHoisted) {
897         // We have failed to hoist MI to outermost loop's preheader. If MI is in
898         // a subloop, try to hoist it to subloop's preheader.
899         SmallVector<MachineLoop *> InnerLoopWorkList;
900         for (MachineLoop *L = MLI->getLoopFor(MI.getParent()); L != CurLoop;
901              L = L->getParentLoop())
902           InnerLoopWorkList.push_back(L);
903 
904         while (!InnerLoopWorkList.empty()) {
905           MachineLoop *InnerLoop = InnerLoopWorkList.pop_back_val();
906           MachineBasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader();
907           if (InnerLoopPreheader) {
908             HoistRes = Hoist(&MI, InnerLoopPreheader, InnerLoop);
909             if (HoistRes & HoistResult::Hoisted)
910               break;
911           }
912         }
913       }
914 
915       if (HoistRes & HoistResult::ErasedMI)
916         continue;
917 
918       UpdateRegPressure(&MI);
919     }
920 
921     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
922     ExitScopeIfDone(Node, OpenChildren, ParentMap);
923   }
924 }
925 
926 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
927   return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
928 }
929 
930 /// Find all virtual register references that are liveout of the preheader to
931 /// initialize the starting "register pressure". Note this does not count live
932 /// through (livein but not used) registers.
933 void MachineLICMImpl::InitRegPressure(MachineBasicBlock *BB) {
934   llvm::fill(RegPressure, 0);
935 
936   // If the preheader has only a single predecessor and it ends with a
937   // fallthrough or an unconditional branch, then scan its predecessor for live
938   // defs as well. This happens whenever the preheader is created by splitting
939   // the critical edge from the loop predecessor to the loop header.
940   if (BB->pred_size() == 1) {
941     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
942     SmallVector<MachineOperand, 4> Cond;
943     if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
944       InitRegPressure(*BB->pred_begin());
945   }
946 
947   for (const MachineInstr &MI : *BB)
948     UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
949 }
950 
951 /// Update estimate of register pressure after the specified instruction.
952 void MachineLICMImpl::UpdateRegPressure(const MachineInstr *MI,
953                                         bool ConsiderUnseenAsDef) {
954   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
955   for (const auto &RPIdAndCost : Cost) {
956     unsigned Class = RPIdAndCost.first;
957     if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
958       RegPressure[Class] = 0;
959     else
960       RegPressure[Class] += RPIdAndCost.second;
961   }
962 }
963 
964 /// Calculate the additional register pressure that the registers used in MI
965 /// cause.
966 ///
967 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
968 /// figure out which usages are live-ins.
969 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
970 SmallDenseMap<unsigned, int>
971 MachineLICMImpl::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
972                                   bool ConsiderUnseenAsDef) {
973   SmallDenseMap<unsigned, int> Cost;
974   if (MI->isImplicitDef())
975     return Cost;
976   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
977     const MachineOperand &MO = MI->getOperand(i);
978     if (!MO.isReg() || MO.isImplicit())
979       continue;
980     Register Reg = MO.getReg();
981     if (!Reg.isVirtual())
982       continue;
983 
984     // FIXME: It seems bad to use RegSeen only for some of these calculations.
985     bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
986     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
987 
988     RegClassWeight W = TRI->getRegClassWeight(RC);
989     int RCCost = 0;
990     if (MO.isDef())
991       RCCost = W.RegWeight;
992     else {
993       bool isKill = isOperandKill(MO, MRI);
994       if (isNew && !isKill && ConsiderUnseenAsDef)
995         // Haven't seen this, it must be a livein.
996         RCCost = W.RegWeight;
997       else if (!isNew && isKill)
998         RCCost = -W.RegWeight;
999     }
1000     if (RCCost == 0)
1001       continue;
1002     const int *PS = TRI->getRegClassPressureSets(RC);
1003     for (; *PS != -1; ++PS)
1004       Cost[*PS] += RCCost;
1005   }
1006   return Cost;
1007 }
1008 
1009 /// Return true if this machine instruction loads from global offset table or
1010 /// constant pool.
1011 static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
1012   assert(MI.mayLoad() && "Expected MI that loads!");
1013 
1014   // If we lost memory operands, conservatively assume that the instruction
1015   // reads from everything..
1016   if (MI.memoperands_empty())
1017     return true;
1018 
1019   for (MachineMemOperand *MemOp : MI.memoperands())
1020     if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
1021       if (PSV->isGOT() || PSV->isConstantPool())
1022         return true;
1023 
1024   return false;
1025 }
1026 
1027 // This function iterates through all the operands of the input store MI and
1028 // checks that each register operand statisfies isCallerPreservedPhysReg.
1029 // This means, the value being stored and the address where it is being stored
1030 // is constant throughout the body of the function (not including prologue and
1031 // epilogue). When called with an MI that isn't a store, it returns false.
1032 // A future improvement can be to check if the store registers are constant
1033 // throughout the loop rather than throughout the funtion.
1034 static bool isInvariantStore(const MachineInstr &MI,
1035                              const TargetRegisterInfo *TRI,
1036                              const MachineRegisterInfo *MRI) {
1037 
1038   bool FoundCallerPresReg = false;
1039   if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
1040       (MI.getNumOperands() == 0))
1041     return false;
1042 
1043   // Check that all register operands are caller-preserved physical registers.
1044   for (const MachineOperand &MO : MI.operands()) {
1045     if (MO.isReg()) {
1046       Register Reg = MO.getReg();
1047       // If operand is a virtual register, check if it comes from a copy of a
1048       // physical register.
1049       if (Reg.isVirtual())
1050         Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
1051       if (Reg.isVirtual())
1052         return false;
1053       if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
1054         return false;
1055       else
1056         FoundCallerPresReg = true;
1057     } else if (!MO.isImm()) {
1058         return false;
1059     }
1060   }
1061   return FoundCallerPresReg;
1062 }
1063 
1064 // Return true if the input MI is a copy instruction that feeds an invariant
1065 // store instruction. This means that the src of the copy has to satisfy
1066 // isCallerPreservedPhysReg and atleast one of it's users should satisfy
1067 // isInvariantStore.
1068 static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
1069                                         const MachineRegisterInfo *MRI,
1070                                         const TargetRegisterInfo *TRI) {
1071 
1072   // FIXME: If targets would like to look through instructions that aren't
1073   // pure copies, this can be updated to a query.
1074   if (!MI.isCopy())
1075     return false;
1076 
1077   const MachineFunction *MF = MI.getMF();
1078   // Check that we are copying a constant physical register.
1079   Register CopySrcReg = MI.getOperand(1).getReg();
1080   if (CopySrcReg.isVirtual())
1081     return false;
1082 
1083   if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
1084     return false;
1085 
1086   Register CopyDstReg = MI.getOperand(0).getReg();
1087   // Check if any of the uses of the copy are invariant stores.
1088   assert(CopyDstReg.isVirtual() && "copy dst is not a virtual reg");
1089 
1090   for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
1091     if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
1092       return true;
1093   }
1094   return false;
1095 }
1096 
1097 /// Returns true if the instruction may be a suitable candidate for LICM.
1098 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
1099 bool MachineLICMImpl::IsLICMCandidate(MachineInstr &I, MachineLoop *CurLoop) {
1100   // Check if it's safe to move the instruction.
1101   bool DontMoveAcrossStore = !HoistConstLoads || !AllowedToHoistLoads[CurLoop];
1102   if ((!I.isSafeToMove(DontMoveAcrossStore)) &&
1103       !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
1104     LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
1105     return false;
1106   }
1107 
1108   // If it is a load then check if it is guaranteed to execute by making sure
1109   // that it dominates all exiting blocks. If it doesn't, then there is a path
1110   // out of the loop which does not execute this load, so we can't hoist it.
1111   // Loads from constant memory are safe to speculate, for example indexed load
1112   // from a jump table.
1113   // Stores and side effects are already checked by isSafeToMove.
1114   if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
1115       !IsGuaranteedToExecute(I.getParent(), CurLoop)) {
1116     LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
1117     return false;
1118   }
1119 
1120   // Convergent attribute has been used on operations that involve inter-thread
1121   // communication which results are implicitly affected by the enclosing
1122   // control flows. It is not safe to hoist or sink such operations across
1123   // control flow.
1124   if (I.isConvergent())
1125     return false;
1126 
1127   if (!TII->shouldHoist(I, CurLoop))
1128     return false;
1129 
1130   return true;
1131 }
1132 
1133 /// Returns true if the instruction is loop invariant.
1134 bool MachineLICMImpl::IsLoopInvariantInst(MachineInstr &I,
1135                                           MachineLoop *CurLoop) {
1136   if (!IsLICMCandidate(I, CurLoop)) {
1137     LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
1138     return false;
1139   }
1140   return CurLoop->isLoopInvariant(I);
1141 }
1142 
1143 /// Return true if the specified instruction is used by a phi node and hoisting
1144 /// it could cause a copy to be inserted.
1145 bool MachineLICMImpl::HasLoopPHIUse(const MachineInstr *MI,
1146                                     MachineLoop *CurLoop) {
1147   SmallVector<const MachineInstr *, 8> Work(1, MI);
1148   do {
1149     MI = Work.pop_back_val();
1150     for (const MachineOperand &MO : MI->all_defs()) {
1151       Register Reg = MO.getReg();
1152       if (!Reg.isVirtual())
1153         continue;
1154       for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
1155         // A PHI may cause a copy to be inserted.
1156         if (UseMI.isPHI()) {
1157           // A PHI inside the loop causes a copy because the live range of Reg is
1158           // extended across the PHI.
1159           if (CurLoop->contains(&UseMI))
1160             return true;
1161           // A PHI in an exit block can cause a copy to be inserted if the PHI
1162           // has multiple predecessors in the loop with different values.
1163           // For now, approximate by rejecting all exit blocks.
1164           if (isExitBlock(CurLoop, UseMI.getParent()))
1165             return true;
1166           continue;
1167         }
1168         // Look past copies as well.
1169         if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1170           Work.push_back(&UseMI);
1171       }
1172     }
1173   } while (!Work.empty());
1174   return false;
1175 }
1176 
1177 /// Compute operand latency between a def of 'Reg' and an use in the current
1178 /// loop, return true if the target considered it high.
1179 bool MachineLICMImpl::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
1180                                             Register Reg,
1181                                             MachineLoop *CurLoop) const {
1182   if (MRI->use_nodbg_empty(Reg))
1183     return false;
1184 
1185   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1186     if (UseMI.isCopyLike())
1187       continue;
1188     if (!CurLoop->contains(UseMI.getParent()))
1189       continue;
1190     for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1191       const MachineOperand &MO = UseMI.getOperand(i);
1192       if (!MO.isReg() || !MO.isUse())
1193         continue;
1194       Register MOReg = MO.getReg();
1195       if (MOReg != Reg)
1196         continue;
1197 
1198       if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
1199         return true;
1200     }
1201 
1202     // Only look at the first in loop use.
1203     break;
1204   }
1205 
1206   return false;
1207 }
1208 
1209 /// Return true if the instruction is marked "cheap" or the operand latency
1210 /// between its def and a use is one or less.
1211 bool MachineLICMImpl::IsCheapInstruction(MachineInstr &MI) const {
1212   if (TII->isAsCheapAsAMove(MI) || MI.isSubregToReg())
1213     return true;
1214 
1215   bool isCheap = false;
1216   unsigned NumDefs = MI.getDesc().getNumDefs();
1217   for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1218     MachineOperand &DefMO = MI.getOperand(i);
1219     if (!DefMO.isReg() || !DefMO.isDef())
1220       continue;
1221     --NumDefs;
1222     Register Reg = DefMO.getReg();
1223     if (Reg.isPhysical())
1224       continue;
1225 
1226     if (!TII->hasLowDefLatency(SchedModel, MI, i))
1227       return false;
1228     isCheap = true;
1229   }
1230 
1231   return isCheap;
1232 }
1233 
1234 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1235 /// given cost matrix can cause high register pressure.
1236 bool MachineLICMImpl::CanCauseHighRegPressure(
1237     const SmallDenseMap<unsigned, int> &Cost, bool CheapInstr) {
1238   for (const auto &RPIdAndCost : Cost) {
1239     if (RPIdAndCost.second <= 0)
1240       continue;
1241 
1242     unsigned Class = RPIdAndCost.first;
1243     int Limit = RegLimit[Class];
1244 
1245     // Don't hoist cheap instructions if they would increase register pressure,
1246     // even if we're under the limit.
1247     if (CheapInstr && !HoistCheapInsts)
1248       return true;
1249 
1250     for (const auto &RP : BackTrace)
1251       if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
1252         return true;
1253   }
1254 
1255   return false;
1256 }
1257 
1258 /// Traverse the back trace from header to the current block and update their
1259 /// register pressures to reflect the effect of hoisting MI from the current
1260 /// block to the preheader.
1261 void MachineLICMImpl::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1262   // First compute the 'cost' of the instruction, i.e. its contribution
1263   // to register pressure.
1264   auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1265                                /*ConsiderUnseenAsDef=*/false);
1266 
1267   // Update register pressure of blocks from loop header to current block.
1268   for (auto &RP : BackTrace)
1269     for (const auto &RPIdAndCost : Cost)
1270       RP[RPIdAndCost.first] += RPIdAndCost.second;
1271 }
1272 
1273 /// Return true if it is potentially profitable to hoist the given loop
1274 /// invariant.
1275 bool MachineLICMImpl::IsProfitableToHoist(MachineInstr &MI,
1276                                           MachineLoop *CurLoop) {
1277   if (MI.isImplicitDef())
1278     return true;
1279 
1280   // Besides removing computation from the loop, hoisting an instruction has
1281   // these effects:
1282   //
1283   // - The value defined by the instruction becomes live across the entire
1284   //   loop. This increases register pressure in the loop.
1285   //
1286   // - If the value is used by a PHI in the loop, a copy will be required for
1287   //   lowering the PHI after extending the live range.
1288   //
1289   // - When hoisting the last use of a value in the loop, that value no longer
1290   //   needs to be live in the loop. This lowers register pressure in the loop.
1291 
1292   if (HoistConstStores &&  isCopyFeedingInvariantStore(MI, MRI, TRI))
1293     return true;
1294 
1295   bool CheapInstr = IsCheapInstruction(MI);
1296   bool CreatesCopy = HasLoopPHIUse(&MI, CurLoop);
1297 
1298   // Don't hoist a cheap instruction if it would create a copy in the loop.
1299   if (CheapInstr && CreatesCopy) {
1300     LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1301     return false;
1302   }
1303 
1304   // Rematerializable instructions should always be hoisted providing the
1305   // register allocator can just pull them down again when needed.
1306   if (isTriviallyReMaterializable(MI))
1307     return true;
1308 
1309   // FIXME: If there are long latency loop-invariant instructions inside the
1310   // loop at this point, why didn't the optimizer's LICM hoist them?
1311   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1312     const MachineOperand &MO = MI.getOperand(i);
1313     if (!MO.isReg() || MO.isImplicit())
1314       continue;
1315     Register Reg = MO.getReg();
1316     if (!Reg.isVirtual())
1317       continue;
1318     if (MO.isDef() && HasHighOperandLatency(MI, i, Reg, CurLoop)) {
1319       LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
1320       ++NumHighLatency;
1321       return true;
1322     }
1323   }
1324 
1325   // Estimate register pressure to determine whether to LICM the instruction.
1326   // In low register pressure situation, we can be more aggressive about
1327   // hoisting. Also, favors hoisting long latency instructions even in
1328   // moderately high pressure situation.
1329   // Cheap instructions will only be hoisted if they don't increase register
1330   // pressure at all.
1331   auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1332                                /*ConsiderUnseenAsDef=*/false);
1333 
1334   // Visit BBs from header to current BB, if hoisting this doesn't cause
1335   // high register pressure, then it's safe to proceed.
1336   if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1337     LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1338     ++NumLowRP;
1339     return true;
1340   }
1341 
1342   // Don't risk increasing register pressure if it would create copies.
1343   if (CreatesCopy) {
1344     LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
1345     return false;
1346   }
1347 
1348   // Do not "speculate" in high register pressure situation. If an
1349   // instruction is not guaranteed to be executed in the loop, it's best to be
1350   // conservative.
1351   if (AvoidSpeculation &&
1352       (!IsGuaranteedToExecute(MI.getParent(), CurLoop) && !MayCSE(&MI))) {
1353     LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
1354     return false;
1355   }
1356 
1357   // If we have a COPY with other uses in the loop, hoist to allow the users to
1358   // also be hoisted.
1359   // TODO: Handle all isCopyLike?
1360   if (MI.isCopy() || MI.isRegSequence()) {
1361     Register DefReg = MI.getOperand(0).getReg();
1362     if (DefReg.isVirtual() &&
1363         all_of(MI.uses(),
1364                [this](const MachineOperand &UseOp) {
1365                  return !UseOp.isReg() || UseOp.getReg().isVirtual() ||
1366                         MRI->isConstantPhysReg(UseOp.getReg());
1367                }) &&
1368         IsLoopInvariantInst(MI, CurLoop) &&
1369         any_of(MRI->use_nodbg_instructions(DefReg),
1370                [&CurLoop, this, DefReg,
1371                 Cost = std::move(Cost)](MachineInstr &UseMI) {
1372                  if (!CurLoop->contains(&UseMI))
1373                    return false;
1374 
1375                  // COPY is a cheap instruction, but if moving it won't cause
1376                  // high RP we're fine to hoist it even if the user can't be
1377                  // hoisted later Otherwise we want to check the user if it's
1378                  // hoistable
1379                  if (CanCauseHighRegPressure(Cost, false) &&
1380                      !CurLoop->isLoopInvariant(UseMI, DefReg))
1381                    return false;
1382 
1383                  return true;
1384                }))
1385       return true;
1386   }
1387 
1388   // High register pressure situation, only hoist if the instruction is going
1389   // to be remat'ed.
1390   if (!isTriviallyReMaterializable(MI) &&
1391       !MI.isDereferenceableInvariantLoad()) {
1392     LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1393     return false;
1394   }
1395 
1396   return true;
1397 }
1398 
1399 /// Unfold a load from the given machineinstr if the load itself could be
1400 /// hoisted. Return the unfolded and hoistable load, or null if the load
1401 /// couldn't be unfolded or if it wouldn't be hoistable.
1402 MachineInstr *MachineLICMImpl::ExtractHoistableLoad(MachineInstr *MI,
1403                                                     MachineLoop *CurLoop) {
1404   // Don't unfold simple loads.
1405   if (MI->canFoldAsLoad())
1406     return nullptr;
1407 
1408   // If not, we may be able to unfold a load and hoist that.
1409   // First test whether the instruction is loading from an amenable
1410   // memory location.
1411   if (!MI->isDereferenceableInvariantLoad())
1412     return nullptr;
1413 
1414   // Next determine the register class for a temporary register.
1415   unsigned LoadRegIndex;
1416   unsigned NewOpc =
1417     TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1418                                     /*UnfoldLoad=*/true,
1419                                     /*UnfoldStore=*/false,
1420                                     &LoadRegIndex);
1421   if (NewOpc == 0) return nullptr;
1422   const MCInstrDesc &MID = TII->get(NewOpc);
1423   MachineFunction &MF = *MI->getMF();
1424   const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
1425   // Ok, we're unfolding. Create a temporary register and do the unfold.
1426   Register Reg = MRI->createVirtualRegister(RC);
1427 
1428   SmallVector<MachineInstr *, 2> NewMIs;
1429   bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1430                                           /*UnfoldLoad=*/true,
1431                                           /*UnfoldStore=*/false, NewMIs);
1432   (void)Success;
1433   assert(Success &&
1434          "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1435          "succeeded!");
1436   assert(NewMIs.size() == 2 &&
1437          "Unfolded a load into multiple instructions!");
1438   MachineBasicBlock *MBB = MI->getParent();
1439   MachineBasicBlock::iterator Pos = MI;
1440   MBB->insert(Pos, NewMIs[0]);
1441   MBB->insert(Pos, NewMIs[1]);
1442   // If unfolding produced a load that wasn't loop-invariant or profitable to
1443   // hoist, discard the new instructions and bail.
1444   if (!IsLoopInvariantInst(*NewMIs[0], CurLoop) ||
1445       !IsProfitableToHoist(*NewMIs[0], CurLoop)) {
1446     NewMIs[0]->eraseFromParent();
1447     NewMIs[1]->eraseFromParent();
1448     return nullptr;
1449   }
1450 
1451   // Update register pressure for the unfolded instruction.
1452   UpdateRegPressure(NewMIs[1]);
1453 
1454   // Otherwise we successfully unfolded a load that we can hoist.
1455 
1456   // Update the call info.
1457   if (MI->shouldUpdateAdditionalCallInfo())
1458     MF.eraseAdditionalCallInfo(MI);
1459 
1460   MI->eraseFromParent();
1461   return NewMIs[0];
1462 }
1463 
1464 /// Initialize the CSE map with instructions that are in the current loop
1465 /// preheader that may become duplicates of instructions that are hoisted
1466 /// out of the loop.
1467 void MachineLICMImpl::InitCSEMap(MachineBasicBlock *BB) {
1468   for (MachineInstr &MI : *BB)
1469     CSEMap[BB][MI.getOpcode()].push_back(&MI);
1470 }
1471 
1472 /// Initialize AllowedToHoistLoads with information about whether invariant
1473 /// loads can be moved outside a given loop
1474 void MachineLICMImpl::InitializeLoadsHoistableLoops() {
1475   SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
1476   SmallVector<MachineLoop *, 8> LoopsInPreOrder;
1477 
1478   // Mark all loops as hoistable initially and prepare a list of loops in
1479   // pre-order DFS.
1480   while (!Worklist.empty()) {
1481     auto *L = Worklist.pop_back_val();
1482     AllowedToHoistLoads[L] = true;
1483     LoopsInPreOrder.push_back(L);
1484     llvm::append_range(Worklist, L->getSubLoops());
1485   }
1486 
1487   // Going from the innermost to outermost loops, check if a loop has
1488   // instructions preventing invariant load hoisting. If such instruction is
1489   // found, mark this loop and its parent as non-hoistable and continue
1490   // investigating the next loop.
1491   // Visiting in a reversed pre-ordered DFS manner
1492   // allows us to not process all the instructions of the outer loop if the
1493   // inner loop is proved to be non-load-hoistable.
1494   for (auto *Loop : reverse(LoopsInPreOrder)) {
1495     for (auto *MBB : Loop->blocks()) {
1496       // If this loop has already been marked as non-hoistable, skip it.
1497       if (!AllowedToHoistLoads[Loop])
1498         continue;
1499       for (auto &MI : *MBB) {
1500         if (!MI.isLoadFoldBarrier() && !MI.mayStore() && !MI.isCall() &&
1501             !(MI.mayLoad() && MI.hasOrderedMemoryRef()))
1502           continue;
1503         for (MachineLoop *L = Loop; L != nullptr; L = L->getParentLoop())
1504           AllowedToHoistLoads[L] = false;
1505         break;
1506       }
1507     }
1508   }
1509 }
1510 
1511 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1512 /// Return this instruction if it's found.
1513 MachineInstr *
1514 MachineLICMImpl::LookForDuplicate(const MachineInstr *MI,
1515                                   std::vector<MachineInstr *> &PrevMIs) {
1516   for (MachineInstr *PrevMI : PrevMIs)
1517     if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
1518       return PrevMI;
1519 
1520   return nullptr;
1521 }
1522 
1523 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1524 /// computes the same value. If it's found, do a RAU on with the definition of
1525 /// the existing instruction rather than hoisting the instruction to the
1526 /// preheader.
1527 bool MachineLICMImpl::EliminateCSE(
1528     MachineInstr *MI,
1529     DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
1530   // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1531   // the undef property onto uses.
1532   if (MI->isImplicitDef())
1533     return false;
1534 
1535   // Do not CSE normal loads because between them could be store instructions
1536   // that change the loaded value
1537   if (MI->mayLoad() && !MI->isDereferenceableInvariantLoad())
1538     return false;
1539 
1540   if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
1541     LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
1542 
1543     // Replace virtual registers defined by MI by their counterparts defined
1544     // by Dup.
1545     SmallVector<unsigned, 2> Defs;
1546     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1547       const MachineOperand &MO = MI->getOperand(i);
1548 
1549       // Physical registers may not differ here.
1550       assert((!MO.isReg() || MO.getReg() == 0 || !MO.getReg().isPhysical() ||
1551               MO.getReg() == Dup->getOperand(i).getReg()) &&
1552              "Instructions with different phys regs are not identical!");
1553 
1554       if (MO.isReg() && MO.isDef() && !MO.getReg().isPhysical())
1555         Defs.push_back(i);
1556     }
1557 
1558     SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1559     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1560       unsigned Idx = Defs[i];
1561       Register Reg = MI->getOperand(Idx).getReg();
1562       Register DupReg = Dup->getOperand(Idx).getReg();
1563       OrigRCs.push_back(MRI->getRegClass(DupReg));
1564 
1565       if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1566         // Restore old RCs if more than one defs.
1567         for (unsigned j = 0; j != i; ++j)
1568           MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1569         return false;
1570       }
1571     }
1572 
1573     for (unsigned Idx : Defs) {
1574       Register Reg = MI->getOperand(Idx).getReg();
1575       Register DupReg = Dup->getOperand(Idx).getReg();
1576       MRI->replaceRegWith(Reg, DupReg);
1577       MRI->clearKillFlags(DupReg);
1578       // Clear Dup dead flag if any, we reuse it for Reg.
1579       if (!MRI->use_nodbg_empty(DupReg))
1580         Dup->getOperand(Idx).setIsDead(false);
1581     }
1582 
1583     MI->eraseFromParent();
1584     ++NumCSEed;
1585     return true;
1586   }
1587   return false;
1588 }
1589 
1590 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1591 /// the loop.
1592 bool MachineLICMImpl::MayCSE(MachineInstr *MI) {
1593   if (MI->mayLoad() && !MI->isDereferenceableInvariantLoad())
1594     return false;
1595 
1596   unsigned Opcode = MI->getOpcode();
1597   for (auto &Map : CSEMap) {
1598     // Check this CSEMap's preheader dominates MI's basic block.
1599     if (MDTU->getDomTree().dominates(Map.first, MI->getParent())) {
1600       DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1601           Map.second.find(Opcode);
1602       // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1603       // the undef property onto uses.
1604       if (CI == Map.second.end() || MI->isImplicitDef())
1605         continue;
1606       if (LookForDuplicate(MI, CI->second) != nullptr)
1607         return true;
1608     }
1609   }
1610 
1611   return false;
1612 }
1613 
1614 /// When an instruction is found to use only loop invariant operands
1615 /// that are safe to hoist, this instruction is called to do the dirty work.
1616 /// It returns true if the instruction is hoisted.
1617 unsigned MachineLICMImpl::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader,
1618                                 MachineLoop *CurLoop) {
1619   MachineBasicBlock *SrcBlock = MI->getParent();
1620 
1621   // Disable the instruction hoisting due to block hotness
1622   if ((DisableHoistingToHotterBlocks == UseBFI::All ||
1623       (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
1624       isTgtHotterThanSrc(SrcBlock, Preheader)) {
1625     ++NumNotHoistedDueToHotness;
1626     return HoistResult::NotHoisted;
1627   }
1628   // First check whether we should hoist this instruction.
1629   bool HasExtractHoistableLoad = false;
1630   if (!IsLoopInvariantInst(*MI, CurLoop) ||
1631       !IsProfitableToHoist(*MI, CurLoop)) {
1632     // If not, try unfolding a hoistable load.
1633     MI = ExtractHoistableLoad(MI, CurLoop);
1634     if (!MI)
1635       return HoistResult::NotHoisted;
1636     HasExtractHoistableLoad = true;
1637   }
1638 
1639   // If we have hoisted an instruction that may store, it can only be a constant
1640   // store.
1641   if (MI->mayStore())
1642     NumStoreConst++;
1643 
1644   // Now move the instructions to the predecessor, inserting it before any
1645   // terminator instructions.
1646   LLVM_DEBUG({
1647     dbgs() << "Hoisting " << *MI;
1648     if (MI->getParent()->getBasicBlock())
1649       dbgs() << " from " << printMBBReference(*MI->getParent());
1650     if (Preheader->getBasicBlock())
1651       dbgs() << " to " << printMBBReference(*Preheader);
1652     dbgs() << "\n";
1653   });
1654 
1655   // If this is the first instruction being hoisted to the preheader,
1656   // initialize the CSE map with potential common expressions.
1657   if (FirstInLoop) {
1658     InitCSEMap(Preheader);
1659     FirstInLoop = false;
1660   }
1661 
1662   // Look for opportunity to CSE the hoisted instruction.
1663   unsigned Opcode = MI->getOpcode();
1664   bool HasCSEDone = false;
1665   for (auto &Map : CSEMap) {
1666     // Check this CSEMap's preheader dominates MI's basic block.
1667     if (MDTU->getDomTree().dominates(Map.first, MI->getParent())) {
1668       DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
1669           Map.second.find(Opcode);
1670       if (CI != Map.second.end()) {
1671         if (EliminateCSE(MI, CI)) {
1672           HasCSEDone = true;
1673           break;
1674         }
1675       }
1676     }
1677   }
1678 
1679   if (!HasCSEDone) {
1680     // Otherwise, splice the instruction to the preheader.
1681     Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
1682 
1683     // Since we are moving the instruction out of its basic block, we do not
1684     // retain its debug location. Doing so would degrade the debugging
1685     // experience and adversely affect the accuracy of profiling information.
1686     assert(!MI->isDebugInstr() && "Should not hoist debug inst");
1687     MI->setDebugLoc(DebugLoc());
1688 
1689     // Update register pressure for BBs from header to this block.
1690     UpdateBackTraceRegPressure(MI);
1691 
1692     // Clear the kill flags of any register this instruction defines,
1693     // since they may need to be live throughout the entire loop
1694     // rather than just live for part of it.
1695     for (MachineOperand &MO : MI->all_defs())
1696       if (!MO.isDead())
1697         MRI->clearKillFlags(MO.getReg());
1698 
1699     CSEMap[Preheader][Opcode].push_back(MI);
1700   }
1701 
1702   ++NumHoisted;
1703   Changed = true;
1704 
1705   if (HasCSEDone || HasExtractHoistableLoad)
1706     return HoistResult::Hoisted | HoistResult::ErasedMI;
1707   return HoistResult::Hoisted;
1708 }
1709 
1710 /// Get the preheader for the current loop, splitting a critical edge if needed.
1711 MachineBasicBlock *MachineLICMImpl::getOrCreatePreheader(MachineLoop *CurLoop) {
1712   // Determine the block to which to hoist instructions. If we can't find a
1713   // suitable loop predecessor, we can't do any hoisting.
1714   if (MachineBasicBlock *Preheader = CurLoop->getLoopPreheader())
1715     return Preheader;
1716 
1717   // Try forming a preheader by splitting the critical edge between the single
1718   // predecessor and the loop header.
1719   if (MachineBasicBlock *Pred = CurLoop->getLoopPredecessor()) {
1720     MachineBasicBlock *NewPreheader = Pred->SplitCriticalEdge(
1721         CurLoop->getHeader(), LegacyPass, MFAM, nullptr, MDTU);
1722     if (NewPreheader)
1723       Changed = true;
1724     return NewPreheader;
1725   }
1726 
1727   return nullptr;
1728 }
1729 
1730 /// Is the target basic block at least "BlockFrequencyRatioThreshold"
1731 /// times hotter than the source basic block.
1732 bool MachineLICMImpl::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
1733                                          MachineBasicBlock *TgtBlock) {
1734   // Parse source and target basic block frequency from MBFI
1735   uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
1736   uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
1737 
1738   // Disable the hoisting if source block frequency is zero
1739   if (!SrcBF)
1740     return true;
1741 
1742   double Ratio = (double)DstBF / SrcBF;
1743 
1744   // Compare the block frequency ratio with the threshold
1745   return Ratio > BlockFrequencyRatioThreshold;
1746 }
1747 
1748 template <typename DerivedT, bool PreRegAlloc>
1749 PreservedAnalyses MachineLICMBasePass<DerivedT, PreRegAlloc>::run(
1750     MachineFunction &MF, MachineFunctionAnalysisManager &MFAM) {
1751   bool Changed = MachineLICMImpl(PreRegAlloc, nullptr, &MFAM).run(MF);
1752   if (!Changed)
1753     return PreservedAnalyses::all();
1754   auto PA = getMachineFunctionPassPreservedAnalyses();
1755   PA.preserve<MachineLoopAnalysis>();
1756   return PA;
1757 }
1758 
1759 template class llvm::MachineLICMBasePass<EarlyMachineLICMPass, true>;
1760 template class llvm::MachineLICMBasePass<MachineLICMPass, false>;
1761