1 //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
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
7 //===----------------------------------------------------------------------===//
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.
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSchedule.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/InitializePasses.h"
44 #include "llvm/MC/MCInstrDesc.h"
45 #include "llvm/MC/MCRegister.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
59 #define DEBUG_TYPE "machinelicm"
62 AvoidSpeculation("avoid-speculation",
63 cl::desc("MachineLICM should avoid speculation"),
64 cl::init(true), cl::Hidden
);
67 HoistCheapInsts("hoist-cheap-insts",
68 cl::desc("MachineLICM should hoist even cheap instructions"),
69 cl::init(false), cl::Hidden
);
72 HoistConstStores("hoist-const-stores",
73 cl::desc("Hoist invariant stores"),
74 cl::init(true), cl::Hidden
);
75 // The default threshold of 100 (i.e. if target block is 100 times hotter)
76 // is based on empirical data on a single target and is subject to tuning.
77 static cl::opt
<unsigned>
78 BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
79 cl::desc("Do not hoist instructions if target"
80 "block is N times hotter than the source."),
81 cl::init(100), cl::Hidden
);
83 enum class UseBFI
{ None
, PGO
, All
};
85 static cl::opt
<UseBFI
>
86 DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
87 cl::desc("Disable hoisting instructions to"
89 cl::init(UseBFI::PGO
), cl::Hidden
,
90 cl::values(clEnumValN(UseBFI::None
, "none",
91 "disable the feature"),
92 clEnumValN(UseBFI::PGO
, "pgo",
93 "enable the feature when using profile data"),
94 clEnumValN(UseBFI::All
, "all",
95 "enable the feature with/wo profile data")));
98 "Number of machine instructions hoisted out of loops");
100 "Number of instructions hoisted in low reg pressure situation");
101 STATISTIC(NumHighLatency
,
102 "Number of high latency instructions hoisted");
104 "Number of hoisted machine instructions CSEed");
105 STATISTIC(NumPostRAHoisted
,
106 "Number of machine instructions hoisted out of loops post regalloc");
107 STATISTIC(NumStoreConst
,
108 "Number of stores of const phys reg hoisted out of loops");
109 STATISTIC(NumNotHoistedDueToHotness
,
110 "Number of instructions not hoisted due to block frequency");
114 class MachineLICMBase
: public MachineFunctionPass
{
115 const TargetInstrInfo
*TII
= nullptr;
116 const TargetLoweringBase
*TLI
= nullptr;
117 const TargetRegisterInfo
*TRI
= nullptr;
118 const MachineFrameInfo
*MFI
= nullptr;
119 MachineRegisterInfo
*MRI
= nullptr;
120 TargetSchedModel SchedModel
;
121 bool PreRegAlloc
= false;
122 bool HasProfileData
= false;
124 // Various analyses that we use...
125 AliasAnalysis
*AA
= nullptr; // Alias analysis info.
126 MachineBlockFrequencyInfo
*MBFI
= nullptr; // Machine block frequncy info
127 MachineLoopInfo
*MLI
= nullptr; // Current MachineLoopInfo
128 MachineDominatorTree
*DT
= nullptr; // Machine dominator tree for the cur loop
130 // State that is updated as we process loops
131 bool Changed
= false; // True if a loop is changed.
132 bool FirstInLoop
= false; // True if it's the first LICM in the loop.
133 MachineLoop
*CurLoop
= nullptr; // The current loop we are working on.
134 MachineBasicBlock
*CurPreheader
= nullptr; // The preheader for CurLoop.
136 // Exit blocks for CurLoop.
137 SmallVector
<MachineBasicBlock
*, 8> ExitBlocks
;
139 bool isExitBlock(const MachineBasicBlock
*MBB
) const {
140 return is_contained(ExitBlocks
, MBB
);
143 // Track 'estimated' register pressure.
144 SmallSet
<Register
, 32> RegSeen
;
145 SmallVector
<unsigned, 8> RegPressure
;
147 // Register pressure "limit" per register pressure set. If the pressure
148 // is higher than the limit, then it's considered high.
149 SmallVector
<unsigned, 8> RegLimit
;
151 // Register pressure on path leading from loop preheader to current BB.
152 SmallVector
<SmallVector
<unsigned, 8>, 16> BackTrace
;
154 // For each opcode, keep a list of potential CSE instructions.
155 DenseMap
<unsigned, std::vector
<MachineInstr
*>> CSEMap
;
163 // If a MBB does not dominate loop exiting blocks then it may not safe
164 // to hoist loads from this block.
165 // Tri-state: 0 - false, 1 - true, 2 - unknown
166 unsigned SpeculationState
= SpeculateUnknown
;
169 MachineLICMBase(char &PassID
, bool PreRegAlloc
)
170 : MachineFunctionPass(PassID
), PreRegAlloc(PreRegAlloc
) {}
172 bool runOnMachineFunction(MachineFunction
&MF
) override
;
174 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
175 AU
.addRequired
<MachineLoopInfo
>();
176 if (DisableHoistingToHotterBlocks
!= UseBFI::None
)
177 AU
.addRequired
<MachineBlockFrequencyInfo
>();
178 AU
.addRequired
<MachineDominatorTree
>();
179 AU
.addRequired
<AAResultsWrapperPass
>();
180 AU
.addPreserved
<MachineLoopInfo
>();
181 MachineFunctionPass::getAnalysisUsage(AU
);
184 void releaseMemory() override
{
193 /// Keep track of information about hoisting candidates.
194 struct CandidateInfo
{
199 CandidateInfo(MachineInstr
*mi
, unsigned def
, int fi
)
200 : MI(mi
), Def(def
), FI(fi
) {}
203 void HoistRegionPostRA();
205 void HoistPostRA(MachineInstr
*MI
, unsigned Def
);
207 void ProcessMI(MachineInstr
*MI
, BitVector
&PhysRegDefs
,
208 BitVector
&PhysRegClobbers
, SmallSet
<int, 32> &StoredFIs
,
209 SmallVectorImpl
<CandidateInfo
> &Candidates
);
211 void AddToLiveIns(MCRegister Reg
);
213 bool IsLICMCandidate(MachineInstr
&I
);
215 bool IsLoopInvariantInst(MachineInstr
&I
);
217 bool HasLoopPHIUse(const MachineInstr
*MI
) const;
219 bool HasHighOperandLatency(MachineInstr
&MI
, unsigned DefIdx
,
222 bool IsCheapInstruction(MachineInstr
&MI
) const;
224 bool CanCauseHighRegPressure(const DenseMap
<unsigned, int> &Cost
,
227 void UpdateBackTraceRegPressure(const MachineInstr
*MI
);
229 bool IsProfitableToHoist(MachineInstr
&MI
);
231 bool IsGuaranteedToExecute(MachineBasicBlock
*BB
);
233 bool isTriviallyReMaterializable(const MachineInstr
&MI
) const;
235 void EnterScope(MachineBasicBlock
*MBB
);
237 void ExitScope(MachineBasicBlock
*MBB
);
239 void ExitScopeIfDone(
240 MachineDomTreeNode
*Node
,
241 DenseMap
<MachineDomTreeNode
*, unsigned> &OpenChildren
,
242 const DenseMap
<MachineDomTreeNode
*, MachineDomTreeNode
*> &ParentMap
);
244 void HoistOutOfLoop(MachineDomTreeNode
*HeaderN
);
246 void InitRegPressure(MachineBasicBlock
*BB
);
248 DenseMap
<unsigned, int> calcRegisterCost(const MachineInstr
*MI
,
250 bool ConsiderUnseenAsDef
);
252 void UpdateRegPressure(const MachineInstr
*MI
,
253 bool ConsiderUnseenAsDef
= false);
255 MachineInstr
*ExtractHoistableLoad(MachineInstr
*MI
);
257 MachineInstr
*LookForDuplicate(const MachineInstr
*MI
,
258 std::vector
<MachineInstr
*> &PrevMIs
);
261 EliminateCSE(MachineInstr
*MI
,
262 DenseMap
<unsigned, std::vector
<MachineInstr
*>>::iterator
&CI
);
264 bool MayCSE(MachineInstr
*MI
);
266 bool Hoist(MachineInstr
*MI
, MachineBasicBlock
*Preheader
);
268 void InitCSEMap(MachineBasicBlock
*BB
);
270 bool isTgtHotterThanSrc(MachineBasicBlock
*SrcBlock
,
271 MachineBasicBlock
*TgtBlock
);
272 MachineBasicBlock
*getCurPreheader();
275 class MachineLICM
: public MachineLICMBase
{
278 MachineLICM() : MachineLICMBase(ID
, false) {
279 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
283 class EarlyMachineLICM
: public MachineLICMBase
{
286 EarlyMachineLICM() : MachineLICMBase(ID
, true) {
287 initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
291 } // end anonymous namespace
293 char MachineLICM::ID
;
294 char EarlyMachineLICM::ID
;
296 char &llvm::MachineLICMID
= MachineLICM::ID
;
297 char &llvm::EarlyMachineLICMID
= EarlyMachineLICM::ID
;
299 INITIALIZE_PASS_BEGIN(MachineLICM
, DEBUG_TYPE
,
300 "Machine Loop Invariant Code Motion", false, false)
301 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
302 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo
)
303 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
304 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
305 INITIALIZE_PASS_END(MachineLICM
, DEBUG_TYPE
,
306 "Machine Loop Invariant Code Motion", false, false)
308 INITIALIZE_PASS_BEGIN(EarlyMachineLICM
, "early-machinelicm",
309 "Early Machine Loop Invariant Code Motion", false, false)
310 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
311 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo
)
312 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
313 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
314 INITIALIZE_PASS_END(EarlyMachineLICM
, "early-machinelicm",
315 "Early Machine Loop Invariant Code Motion", false, false)
317 static void addSubLoopsToWorkList(MachineLoop
*Loop
,
318 SmallVectorImpl
<MachineLoop
*> &Worklist
,
320 // Add loop to worklist
321 Worklist
.push_back(Loop
);
323 // If it is pre-ra LICM, add sub loops to worklist.
324 if (PreRA
&& !Loop
->isInnermost()) {
325 MachineLoop::iterator MLI
= Loop
->begin();
326 MachineLoop::iterator MLE
= Loop
->end();
327 for (; MLI
!= MLE
; ++MLI
)
328 addSubLoopsToWorkList(*MLI
, Worklist
, PreRA
);
332 bool MachineLICMBase::runOnMachineFunction(MachineFunction
&MF
) {
333 if (skipFunction(MF
.getFunction()))
336 Changed
= FirstInLoop
= false;
337 const TargetSubtargetInfo
&ST
= MF
.getSubtarget();
338 TII
= ST
.getInstrInfo();
339 TLI
= ST
.getTargetLowering();
340 TRI
= ST
.getRegisterInfo();
341 MFI
= &MF
.getFrameInfo();
342 MRI
= &MF
.getRegInfo();
343 SchedModel
.init(&ST
);
345 PreRegAlloc
= MRI
->isSSA();
346 HasProfileData
= MF
.getFunction().hasProfileData();
349 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
351 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
352 LLVM_DEBUG(dbgs() << MF
.getName() << " ********\n");
355 // Estimate register pressure during pre-regalloc pass.
356 unsigned NumRPS
= TRI
->getNumRegPressureSets();
357 RegPressure
.resize(NumRPS
);
358 std::fill(RegPressure
.begin(), RegPressure
.end(), 0);
359 RegLimit
.resize(NumRPS
);
360 for (unsigned i
= 0, e
= NumRPS
; i
!= e
; ++i
)
361 RegLimit
[i
] = TRI
->getRegPressureSetLimit(MF
, i
);
364 // Get our Loop information...
365 if (DisableHoistingToHotterBlocks
!= UseBFI::None
)
366 MBFI
= &getAnalysis
<MachineBlockFrequencyInfo
>();
367 MLI
= &getAnalysis
<MachineLoopInfo
>();
368 DT
= &getAnalysis
<MachineDominatorTree
>();
369 AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
371 SmallVector
<MachineLoop
*, 8> Worklist
;
373 MachineLoopInfo::iterator MLII
= MLI
->begin();
374 MachineLoopInfo::iterator MLIE
= MLI
->end();
375 for (; MLII
!= MLIE
; ++MLII
)
376 addSubLoopsToWorkList(*MLII
, Worklist
, PreRegAlloc
);
378 while (!Worklist
.empty()) {
379 CurLoop
= Worklist
.pop_back_val();
380 CurPreheader
= nullptr;
383 CurLoop
->getExitBlocks(ExitBlocks
);
388 // CSEMap is initialized for loop header when the first instruction is
390 MachineDomTreeNode
*N
= DT
->getNode(CurLoop
->getHeader());
400 /// Return true if instruction stores to the specified frame.
401 static bool InstructionStoresToFI(const MachineInstr
*MI
, int FI
) {
402 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
403 // true since they have no memory operands.
406 // If we lost memory operands, conservatively assume that the instruction
407 // writes to all slots.
408 if (MI
->memoperands_empty())
410 for (const MachineMemOperand
*MemOp
: MI
->memoperands()) {
411 if (!MemOp
->isStore() || !MemOp
->getPseudoValue())
413 if (const FixedStackPseudoSourceValue
*Value
=
414 dyn_cast
<FixedStackPseudoSourceValue
>(MemOp
->getPseudoValue())) {
415 if (Value
->getFrameIndex() == FI
)
422 /// Examine the instruction for potentai LICM candidate. Also
423 /// gather register def and frame object update information.
424 void MachineLICMBase::ProcessMI(MachineInstr
*MI
,
425 BitVector
&PhysRegDefs
,
426 BitVector
&PhysRegClobbers
,
427 SmallSet
<int, 32> &StoredFIs
,
428 SmallVectorImpl
<CandidateInfo
> &Candidates
) {
429 bool RuledOut
= false;
430 bool HasNonInvariantUse
= false;
432 for (const MachineOperand
&MO
: MI
->operands()) {
434 // Remember if the instruction stores to the frame index.
435 int FI
= MO
.getIndex();
436 if (!StoredFIs
.count(FI
) &&
437 MFI
->isSpillSlotObjectIndex(FI
) &&
438 InstructionStoresToFI(MI
, FI
))
439 StoredFIs
.insert(FI
);
440 HasNonInvariantUse
= true;
444 // We can't hoist an instruction defining a physreg that is clobbered in
446 if (MO
.isRegMask()) {
447 PhysRegClobbers
.setBitsNotInMask(MO
.getRegMask());
453 Register Reg
= MO
.getReg();
456 assert(Reg
.isPhysical() && "Not expecting virtual register!");
459 if (Reg
&& (PhysRegDefs
.test(Reg
) || PhysRegClobbers
.test(Reg
)))
460 // If it's using a non-loop-invariant register, then it's obviously not
462 HasNonInvariantUse
= true;
466 if (MO
.isImplicit()) {
467 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
468 PhysRegClobbers
.set(*AI
);
470 // Non-dead implicit def? This cannot be hoisted.
472 // No need to check if a dead implicit def is also defined by
473 // another instruction.
477 // FIXME: For now, avoid instructions with multiple defs, unless
478 // it's a dead implicit def.
484 // If we have already seen another instruction that defines the same
485 // register, then this is not safe. Two defs is indicated by setting a
486 // PhysRegClobbers bit.
487 for (MCRegAliasIterator
AS(Reg
, TRI
, true); AS
.isValid(); ++AS
) {
488 if (PhysRegDefs
.test(*AS
))
489 PhysRegClobbers
.set(*AS
);
491 // Need a second loop because MCRegAliasIterator can visit the same
493 for (MCRegAliasIterator
AS(Reg
, TRI
, true); AS
.isValid(); ++AS
)
494 PhysRegDefs
.set(*AS
);
496 if (PhysRegClobbers
.test(Reg
))
497 // MI defined register is seen defined by another instruction in
498 // the loop, it cannot be a LICM candidate.
502 // Only consider reloads for now and remats which do not have register
503 // operands. FIXME: Consider unfold load folding instructions.
504 if (Def
&& !RuledOut
) {
505 int FI
= std::numeric_limits
<int>::min();
506 if ((!HasNonInvariantUse
&& IsLICMCandidate(*MI
)) ||
507 (TII
->isLoadFromStackSlot(*MI
, FI
) && MFI
->isSpillSlotObjectIndex(FI
)))
508 Candidates
.push_back(CandidateInfo(MI
, Def
, FI
));
512 /// Walk the specified region of the CFG and hoist loop invariants out to the
514 void MachineLICMBase::HoistRegionPostRA() {
515 MachineBasicBlock
*Preheader
= getCurPreheader();
519 unsigned NumRegs
= TRI
->getNumRegs();
520 BitVector
PhysRegDefs(NumRegs
); // Regs defined once in the loop.
521 BitVector
PhysRegClobbers(NumRegs
); // Regs defined more than once.
523 SmallVector
<CandidateInfo
, 32> Candidates
;
524 SmallSet
<int, 32> StoredFIs
;
526 // Walk the entire region, count number of defs for each register, and
527 // collect potential LICM candidates.
528 for (MachineBasicBlock
*BB
: CurLoop
->getBlocks()) {
529 // If the header of the loop containing this basic block is a landing pad,
530 // then don't try to hoist instructions out of this loop.
531 const MachineLoop
*ML
= MLI
->getLoopFor(BB
);
532 if (ML
&& ML
->getHeader()->isEHPad()) continue;
534 // Conservatively treat live-in's as an external def.
535 // FIXME: That means a reload that're reused in successor block(s) will not
537 for (const auto &LI
: BB
->liveins()) {
538 for (MCRegAliasIterator
AI(LI
.PhysReg
, TRI
, true); AI
.isValid(); ++AI
)
539 PhysRegDefs
.set(*AI
);
542 SpeculationState
= SpeculateUnknown
;
543 for (MachineInstr
&MI
: *BB
)
544 ProcessMI(&MI
, PhysRegDefs
, PhysRegClobbers
, StoredFIs
, Candidates
);
547 // Gather the registers read / clobbered by the terminator.
548 BitVector
TermRegs(NumRegs
);
549 MachineBasicBlock::iterator TI
= Preheader
->getFirstTerminator();
550 if (TI
!= Preheader
->end()) {
551 for (const MachineOperand
&MO
: TI
->operands()) {
554 Register Reg
= MO
.getReg();
557 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
562 // Now evaluate whether the potential candidates qualify.
563 // 1. Check if the candidate defined register is defined by another
564 // instruction in the loop.
565 // 2. If the candidate is a load from stack slot (always true for now),
566 // check if the slot is stored anywhere in the loop.
567 // 3. Make sure candidate def should not clobber
568 // registers read by the terminator. Similarly its def should not be
569 // clobbered by the terminator.
570 for (CandidateInfo
&Candidate
: Candidates
) {
571 if (Candidate
.FI
!= std::numeric_limits
<int>::min() &&
572 StoredFIs
.count(Candidate
.FI
))
575 unsigned Def
= Candidate
.Def
;
576 if (!PhysRegClobbers
.test(Def
) && !TermRegs
.test(Def
)) {
578 MachineInstr
*MI
= Candidate
.MI
;
579 for (const MachineOperand
&MO
: MI
->all_uses()) {
582 Register Reg
= MO
.getReg();
583 if (PhysRegDefs
.test(Reg
) ||
584 PhysRegClobbers
.test(Reg
)) {
585 // If it's using a non-loop-invariant register, then it's obviously
586 // not safe to hoist.
592 HoistPostRA(MI
, Candidate
.Def
);
597 /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
598 /// sure it is not killed by any instructions in the loop.
599 void MachineLICMBase::AddToLiveIns(MCRegister Reg
) {
600 for (MachineBasicBlock
*BB
: CurLoop
->getBlocks()) {
601 if (!BB
->isLiveIn(Reg
))
603 for (MachineInstr
&MI
: *BB
) {
604 for (MachineOperand
&MO
: MI
.all_uses()) {
607 if (MO
.getReg() == Reg
|| TRI
->isSuperRegister(Reg
, MO
.getReg()))
614 /// When an instruction is found to only use loop invariant operands that is
615 /// safe to hoist, this instruction is called to do the dirty work.
616 void MachineLICMBase::HoistPostRA(MachineInstr
*MI
, unsigned Def
) {
617 MachineBasicBlock
*Preheader
= getCurPreheader();
619 // Now move the instructions to the predecessor, inserting it before any
620 // terminator instructions.
621 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader
)
622 << " from " << printMBBReference(*MI
->getParent()) << ": "
625 // Splice the instruction to the preheader.
626 MachineBasicBlock
*MBB
= MI
->getParent();
627 Preheader
->splice(Preheader
->getFirstTerminator(), MBB
, MI
);
629 // Since we are moving the instruction out of its basic block, we do not
630 // retain its debug location. Doing so would degrade the debugging
631 // experience and adversely affect the accuracy of profiling information.
632 assert(!MI
->isDebugInstr() && "Should not hoist debug inst");
633 MI
->setDebugLoc(DebugLoc());
635 // Add register to livein list to all the BBs in the current loop since a
636 // loop invariant must be kept live throughout the whole loop. This is
637 // important to ensure later passes do not scavenge the def register.
644 /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
645 /// may not be safe to hoist.
646 bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock
*BB
) {
647 if (SpeculationState
!= SpeculateUnknown
)
648 return SpeculationState
== SpeculateFalse
;
650 if (BB
!= CurLoop
->getHeader()) {
651 // Check loop exiting blocks.
652 SmallVector
<MachineBasicBlock
*, 8> CurrentLoopExitingBlocks
;
653 CurLoop
->getExitingBlocks(CurrentLoopExitingBlocks
);
654 for (MachineBasicBlock
*CurrentLoopExitingBlock
: CurrentLoopExitingBlocks
)
655 if (!DT
->dominates(BB
, CurrentLoopExitingBlock
)) {
656 SpeculationState
= SpeculateTrue
;
661 SpeculationState
= SpeculateFalse
;
665 /// Check if \p MI is trivially remateralizable and if it does not have any
666 /// virtual register uses. Even though rematerializable RA might not actually
667 /// rematerialize it in this scenario. In that case we do not want to hoist such
668 /// instruction out of the loop in a belief RA will sink it back if needed.
669 bool MachineLICMBase::isTriviallyReMaterializable(
670 const MachineInstr
&MI
) const {
671 if (!TII
->isTriviallyReMaterializable(MI
))
674 for (const MachineOperand
&MO
: MI
.all_uses()) {
675 if (MO
.getReg().isVirtual())
682 void MachineLICMBase::EnterScope(MachineBasicBlock
*MBB
) {
683 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB
) << '\n');
685 // Remember livein register pressure.
686 BackTrace
.push_back(RegPressure
);
689 void MachineLICMBase::ExitScope(MachineBasicBlock
*MBB
) {
690 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB
) << '\n');
691 BackTrace
.pop_back();
694 /// Destroy scope for the MBB that corresponds to the given dominator tree node
695 /// if its a leaf or all of its children are done. Walk up the dominator tree to
696 /// destroy ancestors which are now done.
697 void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode
*Node
,
698 DenseMap
<MachineDomTreeNode
*, unsigned> &OpenChildren
,
699 const DenseMap
<MachineDomTreeNode
*, MachineDomTreeNode
*> &ParentMap
) {
700 if (OpenChildren
[Node
])
704 ExitScope(Node
->getBlock());
705 // Now traverse upwards to pop ancestors whose offsprings are all done.
706 MachineDomTreeNode
*Parent
= ParentMap
.lookup(Node
);
707 if (!Parent
|| --OpenChildren
[Parent
] != 0)
713 /// Walk the specified loop in the CFG (defined by all blocks dominated by the
714 /// specified header block, and that are in the current loop) in depth first
715 /// order w.r.t the DominatorTree. This allows us to visit definitions before
716 /// uses, allowing us to hoist a loop body in one pass without iteration.
717 void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode
*HeaderN
) {
718 MachineBasicBlock
*Preheader
= getCurPreheader();
722 SmallVector
<MachineDomTreeNode
*, 32> Scopes
;
723 SmallVector
<MachineDomTreeNode
*, 8> WorkList
;
724 DenseMap
<MachineDomTreeNode
*, MachineDomTreeNode
*> ParentMap
;
725 DenseMap
<MachineDomTreeNode
*, unsigned> OpenChildren
;
727 // Perform a DFS walk to determine the order of visit.
728 WorkList
.push_back(HeaderN
);
729 while (!WorkList
.empty()) {
730 MachineDomTreeNode
*Node
= WorkList
.pop_back_val();
731 assert(Node
&& "Null dominator tree node?");
732 MachineBasicBlock
*BB
= Node
->getBlock();
734 // If the header of the loop containing this basic block is a landing pad,
735 // then don't try to hoist instructions out of this loop.
736 const MachineLoop
*ML
= MLI
->getLoopFor(BB
);
737 if (ML
&& ML
->getHeader()->isEHPad())
740 // If this subregion is not in the top level loop at all, exit.
741 if (!CurLoop
->contains(BB
))
744 Scopes
.push_back(Node
);
745 unsigned NumChildren
= Node
->getNumChildren();
747 // Don't hoist things out of a large switch statement. This often causes
748 // code to be hoisted that wasn't going to be executed, and increases
749 // register pressure in a situation where it's likely to matter.
750 if (BB
->succ_size() >= 25)
753 OpenChildren
[Node
] = NumChildren
;
755 // Add children in reverse order as then the next popped worklist node is
756 // the first child of this node. This means we ultimately traverse the
757 // DOM tree in exactly the same order as if we'd recursed.
758 for (MachineDomTreeNode
*Child
: reverse(Node
->children())) {
759 ParentMap
[Child
] = Node
;
760 WorkList
.push_back(Child
);
765 if (Scopes
.size() == 0)
768 // Compute registers which are livein into the loop headers.
771 InitRegPressure(Preheader
);
774 for (MachineDomTreeNode
*Node
: Scopes
) {
775 MachineBasicBlock
*MBB
= Node
->getBlock();
780 SpeculationState
= SpeculateUnknown
;
781 for (MachineInstr
&MI
: llvm::make_early_inc_range(*MBB
)) {
782 if (!Hoist(&MI
, Preheader
))
783 UpdateRegPressure(&MI
);
784 // If we have hoisted an instruction that may store, it can only be a
788 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
789 ExitScopeIfDone(Node
, OpenChildren
, ParentMap
);
793 static bool isOperandKill(const MachineOperand
&MO
, MachineRegisterInfo
*MRI
) {
794 return MO
.isKill() || MRI
->hasOneNonDBGUse(MO
.getReg());
797 /// Find all virtual register references that are liveout of the preheader to
798 /// initialize the starting "register pressure". Note this does not count live
799 /// through (livein but not used) registers.
800 void MachineLICMBase::InitRegPressure(MachineBasicBlock
*BB
) {
801 std::fill(RegPressure
.begin(), RegPressure
.end(), 0);
803 // If the preheader has only a single predecessor and it ends with a
804 // fallthrough or an unconditional branch, then scan its predecessor for live
805 // defs as well. This happens whenever the preheader is created by splitting
806 // the critical edge from the loop predecessor to the loop header.
807 if (BB
->pred_size() == 1) {
808 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
809 SmallVector
<MachineOperand
, 4> Cond
;
810 if (!TII
->analyzeBranch(*BB
, TBB
, FBB
, Cond
, false) && Cond
.empty())
811 InitRegPressure(*BB
->pred_begin());
814 for (const MachineInstr
&MI
: *BB
)
815 UpdateRegPressure(&MI
, /*ConsiderUnseenAsDef=*/true);
818 /// Update estimate of register pressure after the specified instruction.
819 void MachineLICMBase::UpdateRegPressure(const MachineInstr
*MI
,
820 bool ConsiderUnseenAsDef
) {
821 auto Cost
= calcRegisterCost(MI
, /*ConsiderSeen=*/true, ConsiderUnseenAsDef
);
822 for (const auto &RPIdAndCost
: Cost
) {
823 unsigned Class
= RPIdAndCost
.first
;
824 if (static_cast<int>(RegPressure
[Class
]) < -RPIdAndCost
.second
)
825 RegPressure
[Class
] = 0;
827 RegPressure
[Class
] += RPIdAndCost
.second
;
831 /// Calculate the additional register pressure that the registers used in MI
834 /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
835 /// figure out which usages are live-ins.
836 /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
837 DenseMap
<unsigned, int>
838 MachineLICMBase::calcRegisterCost(const MachineInstr
*MI
, bool ConsiderSeen
,
839 bool ConsiderUnseenAsDef
) {
840 DenseMap
<unsigned, int> Cost
;
841 if (MI
->isImplicitDef())
843 for (unsigned i
= 0, e
= MI
->getDesc().getNumOperands(); i
!= e
; ++i
) {
844 const MachineOperand
&MO
= MI
->getOperand(i
);
845 if (!MO
.isReg() || MO
.isImplicit())
847 Register Reg
= MO
.getReg();
848 if (!Reg
.isVirtual())
851 // FIXME: It seems bad to use RegSeen only for some of these calculations.
852 bool isNew
= ConsiderSeen
? RegSeen
.insert(Reg
).second
: false;
853 const TargetRegisterClass
*RC
= MRI
->getRegClass(Reg
);
855 RegClassWeight W
= TRI
->getRegClassWeight(RC
);
858 RCCost
= W
.RegWeight
;
860 bool isKill
= isOperandKill(MO
, MRI
);
861 if (isNew
&& !isKill
&& ConsiderUnseenAsDef
)
862 // Haven't seen this, it must be a livein.
863 RCCost
= W
.RegWeight
;
864 else if (!isNew
&& isKill
)
865 RCCost
= -W
.RegWeight
;
869 const int *PS
= TRI
->getRegClassPressureSets(RC
);
870 for (; *PS
!= -1; ++PS
) {
871 if (!Cost
.contains(*PS
))
880 /// Return true if this machine instruction loads from global offset table or
882 static bool mayLoadFromGOTOrConstantPool(MachineInstr
&MI
) {
883 assert(MI
.mayLoad() && "Expected MI that loads!");
885 // If we lost memory operands, conservatively assume that the instruction
886 // reads from everything..
887 if (MI
.memoperands_empty())
890 for (MachineMemOperand
*MemOp
: MI
.memoperands())
891 if (const PseudoSourceValue
*PSV
= MemOp
->getPseudoValue())
892 if (PSV
->isGOT() || PSV
->isConstantPool())
898 // This function iterates through all the operands of the input store MI and
899 // checks that each register operand statisfies isCallerPreservedPhysReg.
900 // This means, the value being stored and the address where it is being stored
901 // is constant throughout the body of the function (not including prologue and
902 // epilogue). When called with an MI that isn't a store, it returns false.
903 // A future improvement can be to check if the store registers are constant
904 // throughout the loop rather than throughout the funtion.
905 static bool isInvariantStore(const MachineInstr
&MI
,
906 const TargetRegisterInfo
*TRI
,
907 const MachineRegisterInfo
*MRI
) {
909 bool FoundCallerPresReg
= false;
910 if (!MI
.mayStore() || MI
.hasUnmodeledSideEffects() ||
911 (MI
.getNumOperands() == 0))
914 // Check that all register operands are caller-preserved physical registers.
915 for (const MachineOperand
&MO
: MI
.operands()) {
917 Register Reg
= MO
.getReg();
918 // If operand is a virtual register, check if it comes from a copy of a
919 // physical register.
921 Reg
= TRI
->lookThruCopyLike(MO
.getReg(), MRI
);
924 if (!TRI
->isCallerPreservedPhysReg(Reg
.asMCReg(), *MI
.getMF()))
927 FoundCallerPresReg
= true;
928 } else if (!MO
.isImm()) {
932 return FoundCallerPresReg
;
935 // Return true if the input MI is a copy instruction that feeds an invariant
936 // store instruction. This means that the src of the copy has to satisfy
937 // isCallerPreservedPhysReg and atleast one of it's users should satisfy
939 static bool isCopyFeedingInvariantStore(const MachineInstr
&MI
,
940 const MachineRegisterInfo
*MRI
,
941 const TargetRegisterInfo
*TRI
) {
943 // FIXME: If targets would like to look through instructions that aren't
944 // pure copies, this can be updated to a query.
948 const MachineFunction
*MF
= MI
.getMF();
949 // Check that we are copying a constant physical register.
950 Register CopySrcReg
= MI
.getOperand(1).getReg();
951 if (CopySrcReg
.isVirtual())
954 if (!TRI
->isCallerPreservedPhysReg(CopySrcReg
.asMCReg(), *MF
))
957 Register CopyDstReg
= MI
.getOperand(0).getReg();
958 // Check if any of the uses of the copy are invariant stores.
959 assert(CopyDstReg
.isVirtual() && "copy dst is not a virtual reg");
961 for (MachineInstr
&UseMI
: MRI
->use_instructions(CopyDstReg
)) {
962 if (UseMI
.mayStore() && isInvariantStore(UseMI
, TRI
, MRI
))
968 /// Returns true if the instruction may be a suitable candidate for LICM.
969 /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
970 bool MachineLICMBase::IsLICMCandidate(MachineInstr
&I
) {
971 // Check if it's safe to move the instruction.
972 bool DontMoveAcrossStore
= true;
973 if ((!I
.isSafeToMove(AA
, DontMoveAcrossStore
)) &&
974 !(HoistConstStores
&& isInvariantStore(I
, TRI
, MRI
))) {
975 LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
979 // If it is a load then check if it is guaranteed to execute by making sure
980 // that it dominates all exiting blocks. If it doesn't, then there is a path
981 // out of the loop which does not execute this load, so we can't hoist it.
982 // Loads from constant memory are safe to speculate, for example indexed load
983 // from a jump table.
984 // Stores and side effects are already checked by isSafeToMove.
985 if (I
.mayLoad() && !mayLoadFromGOTOrConstantPool(I
) &&
986 !IsGuaranteedToExecute(I
.getParent())) {
987 LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
991 // Convergent attribute has been used on operations that involve inter-thread
992 // communication which results are implicitly affected by the enclosing
993 // control flows. It is not safe to hoist or sink such operations across
995 if (I
.isConvergent())
998 if (!TII
->shouldHoist(I
, CurLoop
))
1004 /// Returns true if the instruction is loop invariant.
1005 bool MachineLICMBase::IsLoopInvariantInst(MachineInstr
&I
) {
1006 if (!IsLICMCandidate(I
)) {
1007 LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
1010 return CurLoop
->isLoopInvariant(I
);
1013 /// Return true if the specified instruction is used by a phi node and hoisting
1014 /// it could cause a copy to be inserted.
1015 bool MachineLICMBase::HasLoopPHIUse(const MachineInstr
*MI
) const {
1016 SmallVector
<const MachineInstr
*, 8> Work(1, MI
);
1018 MI
= Work
.pop_back_val();
1019 for (const MachineOperand
&MO
: MI
->all_defs()) {
1020 Register Reg
= MO
.getReg();
1021 if (!Reg
.isVirtual())
1023 for (MachineInstr
&UseMI
: MRI
->use_instructions(Reg
)) {
1024 // A PHI may cause a copy to be inserted.
1025 if (UseMI
.isPHI()) {
1026 // A PHI inside the loop causes a copy because the live range of Reg is
1027 // extended across the PHI.
1028 if (CurLoop
->contains(&UseMI
))
1030 // A PHI in an exit block can cause a copy to be inserted if the PHI
1031 // has multiple predecessors in the loop with different values.
1032 // For now, approximate by rejecting all exit blocks.
1033 if (isExitBlock(UseMI
.getParent()))
1037 // Look past copies as well.
1038 if (UseMI
.isCopy() && CurLoop
->contains(&UseMI
))
1039 Work
.push_back(&UseMI
);
1042 } while (!Work
.empty());
1046 /// Compute operand latency between a def of 'Reg' and an use in the current
1047 /// loop, return true if the target considered it high.
1048 bool MachineLICMBase::HasHighOperandLatency(MachineInstr
&MI
, unsigned DefIdx
,
1049 Register Reg
) const {
1050 if (MRI
->use_nodbg_empty(Reg
))
1053 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(Reg
)) {
1054 if (UseMI
.isCopyLike())
1056 if (!CurLoop
->contains(UseMI
.getParent()))
1058 for (unsigned i
= 0, e
= UseMI
.getNumOperands(); i
!= e
; ++i
) {
1059 const MachineOperand
&MO
= UseMI
.getOperand(i
);
1060 if (!MO
.isReg() || !MO
.isUse())
1062 Register MOReg
= MO
.getReg();
1066 if (TII
->hasHighOperandLatency(SchedModel
, MRI
, MI
, DefIdx
, UseMI
, i
))
1070 // Only look at the first in loop use.
1077 /// Return true if the instruction is marked "cheap" or the operand latency
1078 /// between its def and a use is one or less.
1079 bool MachineLICMBase::IsCheapInstruction(MachineInstr
&MI
) const {
1080 if (TII
->isAsCheapAsAMove(MI
) || MI
.isCopyLike())
1083 bool isCheap
= false;
1084 unsigned NumDefs
= MI
.getDesc().getNumDefs();
1085 for (unsigned i
= 0, e
= MI
.getNumOperands(); NumDefs
&& i
!= e
; ++i
) {
1086 MachineOperand
&DefMO
= MI
.getOperand(i
);
1087 if (!DefMO
.isReg() || !DefMO
.isDef())
1090 Register Reg
= DefMO
.getReg();
1091 if (Reg
.isPhysical())
1094 if (!TII
->hasLowDefLatency(SchedModel
, MI
, i
))
1102 /// Visit BBs from header to current BB, check if hoisting an instruction of the
1103 /// given cost matrix can cause high register pressure.
1105 MachineLICMBase::CanCauseHighRegPressure(const DenseMap
<unsigned, int>& Cost
,
1107 for (const auto &RPIdAndCost
: Cost
) {
1108 if (RPIdAndCost
.second
<= 0)
1111 unsigned Class
= RPIdAndCost
.first
;
1112 int Limit
= RegLimit
[Class
];
1114 // Don't hoist cheap instructions if they would increase register pressure,
1115 // even if we're under the limit.
1116 if (CheapInstr
&& !HoistCheapInsts
)
1119 for (const auto &RP
: BackTrace
)
1120 if (static_cast<int>(RP
[Class
]) + RPIdAndCost
.second
>= Limit
)
1127 /// Traverse the back trace from header to the current block and update their
1128 /// register pressures to reflect the effect of hoisting MI from the current
1129 /// block to the preheader.
1130 void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr
*MI
) {
1131 // First compute the 'cost' of the instruction, i.e. its contribution
1132 // to register pressure.
1133 auto Cost
= calcRegisterCost(MI
, /*ConsiderSeen=*/false,
1134 /*ConsiderUnseenAsDef=*/false);
1136 // Update register pressure of blocks from loop header to current block.
1137 for (auto &RP
: BackTrace
)
1138 for (const auto &RPIdAndCost
: Cost
)
1139 RP
[RPIdAndCost
.first
] += RPIdAndCost
.second
;
1142 /// Return true if it is potentially profitable to hoist the given loop
1144 bool MachineLICMBase::IsProfitableToHoist(MachineInstr
&MI
) {
1145 if (MI
.isImplicitDef())
1148 // Besides removing computation from the loop, hoisting an instruction has
1151 // - The value defined by the instruction becomes live across the entire
1152 // loop. This increases register pressure in the loop.
1154 // - If the value is used by a PHI in the loop, a copy will be required for
1155 // lowering the PHI after extending the live range.
1157 // - When hoisting the last use of a value in the loop, that value no longer
1158 // needs to be live in the loop. This lowers register pressure in the loop.
1160 if (HoistConstStores
&& isCopyFeedingInvariantStore(MI
, MRI
, TRI
))
1163 bool CheapInstr
= IsCheapInstruction(MI
);
1164 bool CreatesCopy
= HasLoopPHIUse(&MI
);
1166 // Don't hoist a cheap instruction if it would create a copy in the loop.
1167 if (CheapInstr
&& CreatesCopy
) {
1168 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI
);
1172 // Rematerializable instructions should always be hoisted providing the
1173 // register allocator can just pull them down again when needed.
1174 if (isTriviallyReMaterializable(MI
))
1177 // FIXME: If there are long latency loop-invariant instructions inside the
1178 // loop at this point, why didn't the optimizer's LICM hoist them?
1179 for (unsigned i
= 0, e
= MI
.getDesc().getNumOperands(); i
!= e
; ++i
) {
1180 const MachineOperand
&MO
= MI
.getOperand(i
);
1181 if (!MO
.isReg() || MO
.isImplicit())
1183 Register Reg
= MO
.getReg();
1184 if (!Reg
.isVirtual())
1186 if (MO
.isDef() && HasHighOperandLatency(MI
, i
, Reg
)) {
1187 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI
);
1193 // Estimate register pressure to determine whether to LICM the instruction.
1194 // In low register pressure situation, we can be more aggressive about
1195 // hoisting. Also, favors hoisting long latency instructions even in
1196 // moderately high pressure situation.
1197 // Cheap instructions will only be hoisted if they don't increase register
1199 auto Cost
= calcRegisterCost(&MI
, /*ConsiderSeen=*/false,
1200 /*ConsiderUnseenAsDef=*/false);
1202 // Visit BBs from header to current BB, if hoisting this doesn't cause
1203 // high register pressure, then it's safe to proceed.
1204 if (!CanCauseHighRegPressure(Cost
, CheapInstr
)) {
1205 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI
);
1210 // Don't risk increasing register pressure if it would create copies.
1212 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI
);
1216 // Do not "speculate" in high register pressure situation. If an
1217 // instruction is not guaranteed to be executed in the loop, it's best to be
1219 if (AvoidSpeculation
&&
1220 (!IsGuaranteedToExecute(MI
.getParent()) && !MayCSE(&MI
))) {
1221 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI
);
1225 // High register pressure situation, only hoist if the instruction is going
1227 if (!isTriviallyReMaterializable(MI
) &&
1228 !MI
.isDereferenceableInvariantLoad()) {
1229 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI
);
1236 /// Unfold a load from the given machineinstr if the load itself could be
1237 /// hoisted. Return the unfolded and hoistable load, or null if the load
1238 /// couldn't be unfolded or if it wouldn't be hoistable.
1239 MachineInstr
*MachineLICMBase::ExtractHoistableLoad(MachineInstr
*MI
) {
1240 // Don't unfold simple loads.
1241 if (MI
->canFoldAsLoad())
1244 // If not, we may be able to unfold a load and hoist that.
1245 // First test whether the instruction is loading from an amenable
1247 if (!MI
->isDereferenceableInvariantLoad())
1250 // Next determine the register class for a temporary register.
1251 unsigned LoadRegIndex
;
1253 TII
->getOpcodeAfterMemoryUnfold(MI
->getOpcode(),
1254 /*UnfoldLoad=*/true,
1255 /*UnfoldStore=*/false,
1257 if (NewOpc
== 0) return nullptr;
1258 const MCInstrDesc
&MID
= TII
->get(NewOpc
);
1259 MachineFunction
&MF
= *MI
->getMF();
1260 const TargetRegisterClass
*RC
= TII
->getRegClass(MID
, LoadRegIndex
, TRI
, MF
);
1261 // Ok, we're unfolding. Create a temporary register and do the unfold.
1262 Register Reg
= MRI
->createVirtualRegister(RC
);
1264 SmallVector
<MachineInstr
*, 2> NewMIs
;
1265 bool Success
= TII
->unfoldMemoryOperand(MF
, *MI
, Reg
,
1266 /*UnfoldLoad=*/true,
1267 /*UnfoldStore=*/false, NewMIs
);
1270 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1272 assert(NewMIs
.size() == 2 &&
1273 "Unfolded a load into multiple instructions!");
1274 MachineBasicBlock
*MBB
= MI
->getParent();
1275 MachineBasicBlock::iterator Pos
= MI
;
1276 MBB
->insert(Pos
, NewMIs
[0]);
1277 MBB
->insert(Pos
, NewMIs
[1]);
1278 // If unfolding produced a load that wasn't loop-invariant or profitable to
1279 // hoist, discard the new instructions and bail.
1280 if (!IsLoopInvariantInst(*NewMIs
[0]) || !IsProfitableToHoist(*NewMIs
[0])) {
1281 NewMIs
[0]->eraseFromParent();
1282 NewMIs
[1]->eraseFromParent();
1286 // Update register pressure for the unfolded instruction.
1287 UpdateRegPressure(NewMIs
[1]);
1289 // Otherwise we successfully unfolded a load that we can hoist.
1291 // Update the call site info.
1292 if (MI
->shouldUpdateCallSiteInfo())
1293 MF
.eraseCallSiteInfo(MI
);
1295 MI
->eraseFromParent();
1299 /// Initialize the CSE map with instructions that are in the current loop
1300 /// preheader that may become duplicates of instructions that are hoisted
1301 /// out of the loop.
1302 void MachineLICMBase::InitCSEMap(MachineBasicBlock
*BB
) {
1303 for (MachineInstr
&MI
: *BB
)
1304 CSEMap
[MI
.getOpcode()].push_back(&MI
);
1307 /// Find an instruction amount PrevMIs that is a duplicate of MI.
1308 /// Return this instruction if it's found.
1310 MachineLICMBase::LookForDuplicate(const MachineInstr
*MI
,
1311 std::vector
<MachineInstr
*> &PrevMIs
) {
1312 for (MachineInstr
*PrevMI
: PrevMIs
)
1313 if (TII
->produceSameValue(*MI
, *PrevMI
, (PreRegAlloc
? MRI
: nullptr)))
1319 /// Given a LICM'ed instruction, look for an instruction on the preheader that
1320 /// computes the same value. If it's found, do a RAU on with the definition of
1321 /// the existing instruction rather than hoisting the instruction to the
1323 bool MachineLICMBase::EliminateCSE(
1325 DenseMap
<unsigned, std::vector
<MachineInstr
*>>::iterator
&CI
) {
1326 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1327 // the undef property onto uses.
1328 if (CI
== CSEMap
.end() || MI
->isImplicitDef())
1331 if (MachineInstr
*Dup
= LookForDuplicate(MI
, CI
->second
)) {
1332 LLVM_DEBUG(dbgs() << "CSEing " << *MI
<< " with " << *Dup
);
1334 // Replace virtual registers defined by MI by their counterparts defined
1336 SmallVector
<unsigned, 2> Defs
;
1337 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1338 const MachineOperand
&MO
= MI
->getOperand(i
);
1340 // Physical registers may not differ here.
1341 assert((!MO
.isReg() || MO
.getReg() == 0 || !MO
.getReg().isPhysical() ||
1342 MO
.getReg() == Dup
->getOperand(i
).getReg()) &&
1343 "Instructions with different phys regs are not identical!");
1345 if (MO
.isReg() && MO
.isDef() && !MO
.getReg().isPhysical())
1349 SmallVector
<const TargetRegisterClass
*, 2> OrigRCs
;
1350 for (unsigned i
= 0, e
= Defs
.size(); i
!= e
; ++i
) {
1351 unsigned Idx
= Defs
[i
];
1352 Register Reg
= MI
->getOperand(Idx
).getReg();
1353 Register DupReg
= Dup
->getOperand(Idx
).getReg();
1354 OrigRCs
.push_back(MRI
->getRegClass(DupReg
));
1356 if (!MRI
->constrainRegClass(DupReg
, MRI
->getRegClass(Reg
))) {
1357 // Restore old RCs if more than one defs.
1358 for (unsigned j
= 0; j
!= i
; ++j
)
1359 MRI
->setRegClass(Dup
->getOperand(Defs
[j
]).getReg(), OrigRCs
[j
]);
1364 for (unsigned Idx
: Defs
) {
1365 Register Reg
= MI
->getOperand(Idx
).getReg();
1366 Register DupReg
= Dup
->getOperand(Idx
).getReg();
1367 MRI
->replaceRegWith(Reg
, DupReg
);
1368 MRI
->clearKillFlags(DupReg
);
1369 // Clear Dup dead flag if any, we reuse it for Reg.
1370 if (!MRI
->use_nodbg_empty(DupReg
))
1371 Dup
->getOperand(Idx
).setIsDead(false);
1374 MI
->eraseFromParent();
1381 /// Return true if the given instruction will be CSE'd if it's hoisted out of
1383 bool MachineLICMBase::MayCSE(MachineInstr
*MI
) {
1384 unsigned Opcode
= MI
->getOpcode();
1385 DenseMap
<unsigned, std::vector
<MachineInstr
*>>::iterator CI
=
1386 CSEMap
.find(Opcode
);
1387 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1388 // the undef property onto uses.
1389 if (CI
== CSEMap
.end() || MI
->isImplicitDef())
1392 return LookForDuplicate(MI
, CI
->second
) != nullptr;
1395 /// When an instruction is found to use only loop invariant operands
1396 /// that are safe to hoist, this instruction is called to do the dirty work.
1397 /// It returns true if the instruction is hoisted.
1398 bool MachineLICMBase::Hoist(MachineInstr
*MI
, MachineBasicBlock
*Preheader
) {
1399 MachineBasicBlock
*SrcBlock
= MI
->getParent();
1401 // Disable the instruction hoisting due to block hotness
1402 if ((DisableHoistingToHotterBlocks
== UseBFI::All
||
1403 (DisableHoistingToHotterBlocks
== UseBFI::PGO
&& HasProfileData
)) &&
1404 isTgtHotterThanSrc(SrcBlock
, Preheader
)) {
1405 ++NumNotHoistedDueToHotness
;
1408 // First check whether we should hoist this instruction.
1409 if (!IsLoopInvariantInst(*MI
) || !IsProfitableToHoist(*MI
)) {
1410 // If not, try unfolding a hoistable load.
1411 MI
= ExtractHoistableLoad(MI
);
1412 if (!MI
) return false;
1415 // If we have hoisted an instruction that may store, it can only be a constant
1420 // Now move the instructions to the predecessor, inserting it before any
1421 // terminator instructions.
1423 dbgs() << "Hoisting " << *MI
;
1424 if (MI
->getParent()->getBasicBlock())
1425 dbgs() << " from " << printMBBReference(*MI
->getParent());
1426 if (Preheader
->getBasicBlock())
1427 dbgs() << " to " << printMBBReference(*Preheader
);
1431 // If this is the first instruction being hoisted to the preheader,
1432 // initialize the CSE map with potential common expressions.
1434 InitCSEMap(Preheader
);
1435 FirstInLoop
= false;
1438 // Look for opportunity to CSE the hoisted instruction.
1439 unsigned Opcode
= MI
->getOpcode();
1440 DenseMap
<unsigned, std::vector
<MachineInstr
*>>::iterator CI
=
1441 CSEMap
.find(Opcode
);
1442 if (!EliminateCSE(MI
, CI
)) {
1443 // Otherwise, splice the instruction to the preheader.
1444 Preheader
->splice(Preheader
->getFirstTerminator(),MI
->getParent(),MI
);
1446 // Since we are moving the instruction out of its basic block, we do not
1447 // retain its debug location. Doing so would degrade the debugging
1448 // experience and adversely affect the accuracy of profiling information.
1449 assert(!MI
->isDebugInstr() && "Should not hoist debug inst");
1450 MI
->setDebugLoc(DebugLoc());
1452 // Update register pressure for BBs from header to this block.
1453 UpdateBackTraceRegPressure(MI
);
1455 // Clear the kill flags of any register this instruction defines,
1456 // since they may need to be live throughout the entire loop
1457 // rather than just live for part of it.
1458 for (MachineOperand
&MO
: MI
->all_defs())
1460 MRI
->clearKillFlags(MO
.getReg());
1462 // Add to the CSE map.
1463 if (CI
!= CSEMap
.end())
1464 CI
->second
.push_back(MI
);
1466 CSEMap
[Opcode
].push_back(MI
);
1475 /// Get the preheader for the current loop, splitting a critical edge if needed.
1476 MachineBasicBlock
*MachineLICMBase::getCurPreheader() {
1477 // Determine the block to which to hoist instructions. If we can't find a
1478 // suitable loop predecessor, we can't do any hoisting.
1480 // If we've tried to get a preheader and failed, don't try again.
1481 if (CurPreheader
== reinterpret_cast<MachineBasicBlock
*>(-1))
1484 if (!CurPreheader
) {
1485 CurPreheader
= CurLoop
->getLoopPreheader();
1486 if (!CurPreheader
) {
1487 MachineBasicBlock
*Pred
= CurLoop
->getLoopPredecessor();
1489 CurPreheader
= reinterpret_cast<MachineBasicBlock
*>(-1);
1493 CurPreheader
= Pred
->SplitCriticalEdge(CurLoop
->getHeader(), *this);
1494 if (!CurPreheader
) {
1495 CurPreheader
= reinterpret_cast<MachineBasicBlock
*>(-1);
1500 return CurPreheader
;
1503 /// Is the target basic block at least "BlockFrequencyRatioThreshold"
1504 /// times hotter than the source basic block.
1505 bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock
*SrcBlock
,
1506 MachineBasicBlock
*TgtBlock
) {
1507 // Parse source and target basic block frequency from MBFI
1508 uint64_t SrcBF
= MBFI
->getBlockFreq(SrcBlock
).getFrequency();
1509 uint64_t DstBF
= MBFI
->getBlockFreq(TgtBlock
).getFrequency();
1511 // Disable the hoisting if source block frequency is zero
1515 double Ratio
= (double)DstBF
/ SrcBF
;
1517 // Compare the block frequency ratio with the threshold
1518 return Ratio
> BlockFrequencyRatioThreshold
;