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