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