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