LLVM 24.0.0git
MachineSink.cpp
Go to the documentation of this file.
1//===- MachineSink.cpp - Sinking for machine instructions -----------------===//
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 moves instructions into successor blocks when possible, so that
10// they aren't executed on paths where their results aren't needed.
11//
12// This pass is not intended to be a replacement or a complete alternative
13// for an LLVM-IR-level sinking pass. It is only designed to sink simple
14// constructs that are not exposed before lowering and instruction selection.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
28#include "llvm/Analysis/CFG.h"
55#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/LLVMContext.h"
59#include "llvm/Pass.h"
62#include "llvm/Support/Debug.h"
64#include <cassert>
65#include <cstdint>
66#include <utility>
67#include <vector>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "machine-sink"
72
73static cl::opt<bool>
74 SplitEdges("machine-sink-split",
75 cl::desc("Split critical edges during machine sinking"),
76 cl::init(true), cl::Hidden);
77
79 "machine-sink-bfi",
80 cl::desc("Use block frequency info to find successors to sink"),
81 cl::init(true), cl::Hidden);
82
84 "machine-sink-split-probability-threshold",
86 "Percentage threshold for splitting single-instruction critical edge. "
87 "If the branch threshold is higher than this threshold, we allow "
88 "speculative execution of up to 1 instruction to avoid branching to "
89 "splitted critical edge"),
90 cl::init(40), cl::Hidden);
91
93 "machine-sink-load-instrs-threshold",
94 cl::desc("Do not try to find alias store for a load if there is a in-path "
95 "block whose instruction number is higher than this threshold."),
96 cl::init(2000), cl::Hidden);
97
99 "machine-sink-load-blocks-threshold",
100 cl::desc("Do not try to find alias store for a load if the block number in "
101 "the straight line is higher than this threshold."),
102 cl::init(20), cl::Hidden);
103
104static cl::opt<bool>
105 SinkInstsIntoCycle("sink-insts-to-avoid-spills",
106 cl::desc("Sink instructions into cycles to avoid "
107 "register spills"),
108 cl::init(false), cl::Hidden);
109
111 "machine-sink-cycle-limit",
112 cl::desc(
113 "The maximum number of instructions considered for cycle sinking."),
114 cl::init(50), cl::Hidden);
115
116STATISTIC(NumSunk, "Number of machine instructions sunk");
117STATISTIC(NumCycleSunk, "Number of machine instructions sunk into a cycle");
118STATISTIC(NumSplit, "Number of critical edges split");
119STATISTIC(NumCoalesces, "Number of copies coalesced");
120STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
121
123
124namespace {
125
126class MachineSinking {
127 const TargetSubtargetInfo *STI = nullptr;
128 const TargetInstrInfo *TII = nullptr;
129 const TargetRegisterInfo *TRI = nullptr;
130 MachineRegisterInfo *MRI = nullptr; // Machine register information
131 MachineDominatorTree *DT = nullptr; // Machine dominator tree
132 MachinePostDominatorTree *PDT = nullptr; // Machine post dominator tree
133 MachineCycleInfo *CI = nullptr;
134 ProfileSummaryInfo *PSI = nullptr;
135 MachineBlockFrequencyInfo *MBFI = nullptr;
136 const MachineBranchProbabilityInfo *MBPI = nullptr;
137 AliasAnalysis *AA = nullptr;
138 RegisterClassInfo *RegClassInfo = nullptr;
139 TargetSchedModel SchedModel;
140 // Required for split critical edge
141 LiveIntervals *LIS;
143 LiveVariables *LV;
144 MachineLoopInfo *MLI;
145
146 // Remember which edges have been considered for breaking.
148 CEBCandidates;
149 // Memorize the register that also wanted to sink into the same block along
150 // a different critical edge.
151 // {register to sink, sink-to block} -> the first sink-from block.
152 // We're recording the first sink-from block because that (critical) edge
153 // was deferred until we see another register that's going to sink into the
154 // same block.
156 CEMergeCandidates;
157 // Remember which edges we are about to split.
158 // This is different from CEBCandidates since those edges
159 // will be split.
161
162 DenseSet<Register> RegsToClearKillFlags;
163
164 using AllSuccsCache =
166
167 /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
168 /// post-dominated by another DBG_VALUE of the same variable location.
169 /// This is necessary to detect sequences such as:
170 /// %0 = someinst
171 /// DBG_VALUE %0, !123, !DIExpression()
172 /// %1 = anotherinst
173 /// DBG_VALUE %1, !123, !DIExpression()
174 /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
175 /// would re-order assignments.
176 using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
177
178 using SinkItem = std::pair<MachineInstr *, MachineBasicBlock *>;
179
180 /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
181 /// debug instructions to sink.
183
184 /// Record of debug variables that have had their locations set in the
185 /// current block.
186 DenseSet<DebugVariable> SeenDbgVars;
187
189 HasStoreCache;
190
193 StoreInstrCache;
194
195 /// Cached BB's register pressure.
197 CachedRegisterPressure;
198
199 bool EnableSinkAndFold;
200
201public:
202 MachineSinking(bool EnableSinkAndFold, MachineDominatorTree *DT,
208 RegisterClassInfo *RegClassInfo)
209 : DT(DT), PDT(PDT), CI(CI), PSI(PSI), MBFI(MBFI), MBPI(MBPI), AA(AA),
210 RegClassInfo(RegClassInfo), LIS(LIS), SI(SI), LV(LV), MLI(MLI),
211 EnableSinkAndFold(EnableSinkAndFold) {}
212
213 bool run(MachineFunction &MF);
214
215 void releaseMemory() {
216 CEBCandidates.clear();
217 CEMergeCandidates.clear();
218 }
219
220private:
222 void ProcessDbgInst(MachineInstr &MI);
223 bool isLegalToBreakCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
224 MachineBasicBlock *To, bool BreakPHIEdge);
225 bool isWorthBreakingCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
227 MachineBasicBlock *&DeferredFromBlock);
228
229 bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
231
232 /// Postpone the splitting of the given critical
233 /// edge (\p From, \p To).
234 ///
235 /// We do not split the edges on the fly. Indeed, this invalidates
236 /// the dominance information and thus triggers a lot of updates
237 /// of that information underneath.
238 /// Instead, we postpone all the splits after each iteration of
239 /// the main loop. That way, the information is at least valid
240 /// for the lifetime of an iteration.
241 ///
242 /// \return True if the edge is marked as toSplit, false otherwise.
243 /// False can be returned if, for instance, this is not profitable.
244 bool PostponeSplitCriticalEdge(MachineInstr &MI, MachineBasicBlock *From,
245 MachineBasicBlock *To, bool BreakPHIEdge);
246 bool SinkInstruction(MachineInstr &MI, bool &SawStore,
247 AllSuccsCache &AllSuccessors);
248
249 /// If we sink a COPY inst, some debug users of it's destination may no
250 /// longer be dominated by the COPY, and will eventually be dropped.
251 /// This is easily rectified by forwarding the non-dominated debug uses
252 /// to the copy source.
253 void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
254 MachineBasicBlock *TargetBlock);
255 bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
256 MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
257 bool &LocalUse) const;
259 bool &BreakPHIEdge,
260 AllSuccsCache &AllSuccessors);
261
262 void FindCycleSinkCandidates(CycleRef Cycle, MachineBasicBlock *BB,
264
265 bool
266 aggressivelySinkIntoCycle(CycleRef Cycle, MachineInstr &I,
268
269 bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
271 MachineBasicBlock *SuccToSinkTo,
272 AllSuccsCache &AllSuccessors);
273
274 bool PerformTrivialForwardCoalescing(MachineInstr &MI,
276
277 bool PerformSinkAndFold(MachineInstr &MI, MachineBasicBlock *MBB);
278
280 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
281 AllSuccsCache &AllSuccessors) const;
282
283 std::vector<unsigned> &getBBRegisterPressure(const MachineBasicBlock &MBB,
284 bool UseCache = true);
285
286 bool registerPressureSetExceedsLimit(unsigned NRegs,
287 const TargetRegisterClass *RC,
288 const MachineBasicBlock &MBB);
289
290 bool registerPressureExceedsLimit(const MachineBasicBlock &MBB);
291};
292
293class MachineSinkingLegacy : public MachineFunctionPass {
294public:
295 static char ID;
296
297 MachineSinkingLegacy() : MachineFunctionPass(ID) {}
298
299 bool runOnMachineFunction(MachineFunction &MF) override;
300
301 void getAnalysisUsage(AnalysisUsage &AU) const override {
313 if (UseBlockFreqInfo) {
316 }
318 }
319};
320
321} // end anonymous namespace
322
323char MachineSinkingLegacy::ID = 0;
324
325char &llvm::MachineSinkingLegacyID = MachineSinkingLegacy::ID;
326
327INITIALIZE_PASS_BEGIN(MachineSinkingLegacy, DEBUG_TYPE, "Machine code sinking",
328 false, false)
335INITIALIZE_PASS_END(MachineSinkingLegacy, DEBUG_TYPE, "Machine code sinking",
337
338/// Return true if a target defined block prologue instruction interferes
339/// with a sink candidate.
346 for (MachineBasicBlock::const_iterator PI = BB->getFirstNonPHI(); PI != End;
347 ++PI) {
348 // Only check target defined prologue instructions
349 if (!TII->isBasicBlockPrologue(*PI))
350 continue;
351 for (auto &MO : MI.operands()) {
352 if (!MO.isReg())
353 continue;
354 Register Reg = MO.getReg();
355 if (!Reg)
356 continue;
357 if (MO.isUse()) {
358 if (Reg.isPhysical() &&
359 (TII->isIgnorableUse(MO) || (MRI && MRI->isConstantPhysReg(Reg))))
360 continue;
361 if (PI->modifiesRegister(Reg, TRI))
362 return true;
363 } else {
364 if (PI->readsRegister(Reg, TRI))
365 return true;
366 // Check for interference with non-dead defs
367 auto *DefOp = PI->findRegisterDefOperand(Reg, TRI, false, true);
368 if (DefOp && !DefOp->isDead())
369 return true;
370 }
371 }
372 }
373
374 return false;
375}
376
377bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
379 if (!MI.isCopy())
380 return false;
381
382 Register SrcReg = MI.getOperand(1).getReg();
383 Register DstReg = MI.getOperand(0).getReg();
384 if (!SrcReg.isVirtual() || !DstReg.isVirtual() ||
385 !MRI->hasOneNonDBGUse(SrcReg))
386 return false;
387
388 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
389 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
390 if (SRC != DRC)
391 return false;
392
393 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
394 if (DefMI->isCopyLike())
395 return false;
396 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
397 LLVM_DEBUG(dbgs() << "*** to: " << MI);
398 MRI->replaceRegWith(DstReg, SrcReg);
399 MI.eraseFromParent();
400
401 // Conservatively, clear any kill flags, since it's possible that they are no
402 // longer correct.
403 MRI->clearKillFlags(SrcReg);
404
405 ++NumCoalesces;
406 return true;
407}
408
409bool MachineSinking::PerformSinkAndFold(MachineInstr &MI,
410 MachineBasicBlock *MBB) {
411 if (MI.isCopy() || MI.mayLoadOrStore() ||
412 MI.getOpcode() == TargetOpcode::REG_SEQUENCE)
413 return false;
414
415 // Don't sink instructions that the target prefers not to sink.
416 if (!TII->shouldSink(MI))
417 return false;
418
419 // Check if it's safe to move the instruction.
420 bool SawStore = true;
421 if (!MI.isSafeToMove(SawStore))
422 return false;
423
424 // Convergent operations may not be made control-dependent on additional
425 // values.
426 if (MI.isConvergent())
427 return false;
428
429 // Don't sink defs/uses of hard registers or if the instruction defines more
430 // than one register.
431 // Don't sink more than two register uses - it'll cover most of the cases and
432 // greatly simplifies the register pressure checks.
433 Register DefReg;
434 Register UsedRegA, UsedRegB;
435 for (const MachineOperand &MO : MI.operands()) {
436 if (MO.isImm() || MO.isRegMask() || MO.isRegLiveOut() || MO.isMetadata() ||
437 MO.isMCSymbol() || MO.isDbgInstrRef() || MO.isCFIIndex() ||
438 MO.isIntrinsicID() || MO.isPredicate() || MO.isShuffleMask())
439 continue;
440 if (!MO.isReg())
441 return false;
442
443 Register Reg = MO.getReg();
444 if (Reg == 0)
445 continue;
446
447 if (Reg.isVirtual()) {
448 if (MO.isDef()) {
449 if (DefReg)
450 return false;
451 DefReg = Reg;
452 continue;
453 }
454
455 if (UsedRegA == 0)
456 UsedRegA = Reg;
457 else if (UsedRegB == 0)
458 UsedRegB = Reg;
459 else
460 return false;
461 continue;
462 }
463
464 if (Reg.isPhysical() && MO.isUse() &&
465 (MRI->isConstantPhysReg(Reg) || TII->isIgnorableUse(MO)))
466 continue;
467
468 return false;
469 }
470
471 // Scan uses of the destination register. Every use, except the last, must be
472 // a copy, with a chain of copies terminating with either a copy into a hard
473 // register, or a load/store instruction where the use is part of the
474 // address (*not* the stored value).
475 using SinkInfo = std::pair<MachineInstr *, ExtAddrMode>;
476 SmallVector<SinkInfo> SinkInto;
477 SmallVector<Register> Worklist;
478
479 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
480 const TargetRegisterClass *RCA =
481 UsedRegA == 0 ? nullptr : MRI->getRegClass(UsedRegA);
482 const TargetRegisterClass *RCB =
483 UsedRegB == 0 ? nullptr : MRI->getRegClass(UsedRegB);
484
485 Worklist.push_back(DefReg);
486 while (!Worklist.empty()) {
487 Register Reg = Worklist.pop_back_val();
488
489 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
490 ExtAddrMode MaybeAM;
491 MachineInstr &UseInst = *MO.getParent();
492 if (UseInst.isCopy()) {
493 Register DstReg;
494 if (const MachineOperand &O = UseInst.getOperand(0); O.isReg())
495 DstReg = O.getReg();
496 if (DstReg == 0)
497 return false;
498 if (DstReg.isVirtual()) {
499 Worklist.push_back(DstReg);
500 continue;
501 }
502 // If we are going to replace a copy, the original instruction must be
503 // as cheap as a copy.
504 if (!TII->isAsCheapAsAMove(MI))
505 return false;
506 // The hard register must be in the register class of the original
507 // instruction's destination register.
508 if (!RC->contains(DstReg))
509 return false;
510 } else if (UseInst.mayLoadOrStore()) {
511 // If the destination instruction contains more than one use of the
512 // register, we won't be able to remove the original instruction, so
513 // don't sink.
514 if (llvm::count_if(UseInst.operands(), [Reg](const MachineOperand &MO) {
515 return MO.isReg() && MO.getReg() == Reg;
516 }) > 1)
517 return false;
518 ExtAddrMode AM;
519 if (!TII->canFoldIntoAddrMode(UseInst, Reg, MI, AM))
520 return false;
521 MaybeAM = AM;
522 } else {
523 return false;
524 }
525
526 if (UseInst.getParent() != MI.getParent()) {
527 // If the register class of the register we are replacing is a superset
528 // of any of the register classes of the operands of the materialized
529 // instruction don't consider that live range extended.
530 const TargetRegisterClass *RCS = MRI->getRegClass(Reg);
531 if (RCA && RCA->hasSuperClassEq(RCS))
532 RCA = nullptr;
533 else if (RCB && RCB->hasSuperClassEq(RCS))
534 RCB = nullptr;
535 if (RCA || RCB) {
536 if (RCA == nullptr) {
537 RCA = RCB;
538 RCB = nullptr;
539 }
540
541 unsigned NRegs = !!RCA + !!RCB;
542 if (RCA == RCB)
543 RCB = nullptr;
544
545 // Check we don't exceed register pressure at the destination.
546 const MachineBasicBlock &MBB = *UseInst.getParent();
547 if (RCB == nullptr) {
548 if (registerPressureSetExceedsLimit(NRegs, RCA, MBB))
549 return false;
550 } else if (registerPressureSetExceedsLimit(1, RCA, MBB) ||
551 registerPressureSetExceedsLimit(1, RCB, MBB)) {
552 return false;
553 }
554 }
555 }
556
557 SinkInto.emplace_back(&UseInst, MaybeAM);
558 }
559 }
560
561 if (SinkInto.empty())
562 return false;
563
564 // Now we know we can fold the instruction in all its users.
565 for (auto &[SinkDst, MaybeAM] : SinkInto) {
566 MachineInstr *New = nullptr;
567 LLVM_DEBUG(dbgs() << "Sinking copy of"; MI.dump(); dbgs() << "into";
568 SinkDst->dump());
569 if (SinkDst->isCopy()) {
570 // TODO: After performing the sink-and-fold, the original instruction is
571 // deleted. Its value is still available (in a hard register), so if there
572 // are debug instructions which refer to the (now deleted) virtual
573 // register they could be updated to refer to the hard register, in
574 // principle. However, it's not clear how to do that, moreover in some
575 // cases the debug instructions may need to be replicated proportionally
576 // to the number of the COPY instructions replaced and in some extreme
577 // cases we can end up with quadratic increase in the number of debug
578 // instructions.
579
580 // Sink a copy of the instruction, replacing a COPY instruction.
581 MachineBasicBlock::iterator InsertPt = SinkDst->getIterator();
582 Register DstReg = SinkDst->getOperand(0).getReg();
583 TII->reMaterialize(*SinkDst->getParent(), InsertPt, DstReg, 0, MI);
584 New = &*std::prev(InsertPt);
585 if (!New->getDebugLoc())
586 New->setDebugLoc(SinkDst->getDebugLoc());
587
588 // The operand registers of the "sunk" instruction have their live range
589 // extended and their kill flags may no longer be correct. Conservatively
590 // clear the kill flags.
591 if (UsedRegA)
592 MRI->clearKillFlags(UsedRegA);
593 if (UsedRegB)
594 MRI->clearKillFlags(UsedRegB);
595 } else {
596 // Fold instruction into the addressing mode of a memory instruction.
597 New = TII->emitLdStWithAddr(*SinkDst, MaybeAM);
598
599 // The registers of the addressing mode may have their live range extended
600 // and their kill flags may no longer be correct. Conservatively clear the
601 // kill flags.
602 if (Register R = MaybeAM.BaseReg; R.isValid() && R.isVirtual())
603 MRI->clearKillFlags(R);
604 if (Register R = MaybeAM.ScaledReg; R.isValid() && R.isVirtual())
605 MRI->clearKillFlags(R);
606 }
607 LLVM_DEBUG(dbgs() << "yielding"; New->dump());
608 // Clear the StoreInstrCache, since we may invalidate it by erasing.
609 if (SinkDst->mayStore() && !SinkDst->hasOrderedMemoryRef())
610 StoreInstrCache.clear();
611 SinkDst->eraseFromParent();
612 }
613
614 // Collect operands that need to be cleaned up because the registers no longer
615 // exist (in COPYs and debug instructions). We cannot delete instructions or
616 // clear operands while traversing register uses.
618 Worklist.push_back(DefReg);
619 while (!Worklist.empty()) {
620 Register Reg = Worklist.pop_back_val();
621 for (MachineOperand &MO : MRI->use_operands(Reg)) {
622 MachineInstr *U = MO.getParent();
623 assert((U->isCopy() || U->isDebugInstr()) &&
624 "Only debug uses and copies must remain");
625 if (U->isCopy())
626 Worklist.push_back(U->getOperand(0).getReg());
627 Cleanup.push_back(&MO);
628 }
629 }
630
631 // Delete the dead COPYs and clear operands in debug instructions
632 for (MachineOperand *MO : Cleanup) {
633 MachineInstr *I = MO->getParent();
634 if (I->isCopy()) {
635 I->eraseFromParent();
636 } else {
637 MO->setReg(0);
638 MO->setSubReg(0);
639 }
640 }
641
642 MI.eraseFromParent();
643 return true;
644}
645
646/// AllUsesDominatedByBlock - Return true if all uses of the specified register
647/// occur in blocks dominated by the specified block. If any use is in the
648/// definition block, then return false since it is never legal to move def
649/// after uses.
650bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
651 MachineBasicBlock *MBB,
652 MachineBasicBlock *DefMBB,
653 bool &BreakPHIEdge,
654 bool &LocalUse) const {
655 assert(Reg.isVirtual() && "Only makes sense for vregs");
656
657 // Ignore debug uses because debug info doesn't affect the code.
658 if (MRI->use_nodbg_empty(Reg))
659 return true;
660
661 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
662 // into and they are all PHI nodes. In this case, machine-sink must break
663 // the critical edge first. e.g.
664 //
665 // %bb.1:
666 // Predecessors according to CFG: %bb.0
667 // ...
668 // %def = DEC64_32r %x, implicit-def dead %eflags
669 // ...
670 // JE_4 <%bb.37>, implicit %eflags
671 // Successors according to CFG: %bb.37 %bb.2
672 //
673 // %bb.2:
674 // %p = PHI %y, %bb.0, %def, %bb.1
675 if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
676 MachineInstr *UseInst = MO.getParent();
677 unsigned OpNo = MO.getOperandNo();
678 MachineBasicBlock *UseBlock = UseInst->getParent();
679 return UseBlock == MBB && UseInst->isPHI() &&
680 UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
681 })) {
682 BreakPHIEdge = true;
683 return true;
684 }
685
686 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
687 // Determine the block of the use.
688 MachineInstr *UseInst = MO.getParent();
689 unsigned OpNo = &MO - &UseInst->getOperand(0);
690 MachineBasicBlock *UseBlock = UseInst->getParent();
691 if (UseInst->isPHI()) {
692 // PHI nodes use the operand in the predecessor block, not the block with
693 // the PHI.
694 UseBlock = UseInst->getOperand(OpNo + 1).getMBB();
695 } else if (UseBlock == DefMBB) {
696 LocalUse = true;
697 return false;
698 }
699
700 // Check that it dominates.
701 if (!DT->dominates(MBB, UseBlock))
702 return false;
703 }
704
705 return true;
706}
707
708/// Return true if this machine instruction loads from global offset table or
709/// constant pool.
711 assert(MI.mayLoad() && "Expected MI that loads!");
712
713 // If we lost memory operands, conservatively assume that the instruction
714 // reads from everything..
715 if (MI.memoperands_empty())
716 return true;
717
718 for (MachineMemOperand *MemOp : MI.memoperands())
719 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
720 if (PSV->isGOT() || PSV->isConstantPool())
721 return true;
722
723 return false;
724}
725
726void MachineSinking::FindCycleSinkCandidates(
727 CycleRef Cycle, MachineBasicBlock *BB,
728 SmallVectorImpl<MachineInstr *> &Candidates) {
729 for (auto &MI : *BB) {
730 LLVM_DEBUG(dbgs() << "CycleSink: Analysing candidate: " << MI);
731 if (MI.isMetaInstruction()) {
732 LLVM_DEBUG(dbgs() << "CycleSink: not sinking meta instruction\n");
733 continue;
734 }
735 if (!TII->shouldSink(MI)) {
736 LLVM_DEBUG(dbgs() << "CycleSink: Instruction not a candidate for this "
737 "target\n");
738 continue;
739 }
740 if (!isCycleInvariant(*CI, Cycle, MI)) {
741 LLVM_DEBUG(dbgs() << "CycleSink: Instruction is not cycle invariant\n");
742 continue;
743 }
744 bool DontMoveAcrossStore = true;
745 if (!MI.isSafeToMove(DontMoveAcrossStore)) {
746 LLVM_DEBUG(dbgs() << "CycleSink: Instruction not safe to move.\n");
747 continue;
748 }
749 if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) {
750 LLVM_DEBUG(dbgs() << "CycleSink: Dont sink GOT or constant pool loads\n");
751 continue;
752 }
753 if (MI.isConvergent())
754 continue;
755
756 const MachineOperand &MO = MI.getOperand(0);
757 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
758 continue;
759 if (!MRI->hasOneDef(MO.getReg()))
760 continue;
761
762 LLVM_DEBUG(dbgs() << "CycleSink: Instruction added as candidate.\n");
763 Candidates.push_back(&MI);
764 }
765}
766
767PreservedAnalyses
770 auto *DT = &MFAM.getResult<MachineDominatorTreeAnalysis>(MF);
771 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
772 auto *CI = &MFAM.getResult<MachineCycleAnalysis>(MF);
774 .getCachedResult<ProfileSummaryAnalysis>(
775 *MF.getFunction().getParent());
776 auto *MBFI = UseBlockFreqInfo
778 : nullptr;
779 auto *MBPI = &MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
781 .getManager()
782 .getResult<AAManager>(MF.getFunction());
783 auto *LIS = MFAM.getCachedResult<LiveIntervalsAnalysis>(MF);
784 auto *SI = MFAM.getCachedResult<SlotIndexesAnalysis>(MF);
785 auto *LV = MFAM.getCachedResult<LiveVariablesAnalysis>(MF);
786 auto *MLI = MFAM.getCachedResult<MachineLoopAnalysis>(MF);
787 auto *RegClassInfo = &MFAM.getResult<MachineRegisterClassAnalysis>(MF);
788 MachineSinking Impl(EnableSinkAndFold, DT, PDT, LV, MLI, SI, LIS, CI, PSI,
789 MBFI, MBPI, AA, RegClassInfo);
790 bool Changed = Impl.run(MF);
791 if (!Changed)
792 return PreservedAnalyses::all();
794 PA.preserve<MachineCycleAnalysis>();
795 PA.preserve<MachineLoopAnalysis>();
797 PA.preserve<MachineBlockFrequencyAnalysis>();
798 return PA;
799}
800
802 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
803 OS << MapClassName2PassName(name()); // ideally machine-sink
804 if (EnableSinkAndFold)
805 OS << "<enable-sink-fold>";
806}
807
808bool MachineSinkingLegacy::runOnMachineFunction(MachineFunction &MF) {
809 if (skipFunction(MF.getFunction()))
810 return false;
811
812 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
813 bool EnableSinkAndFold = PassConfig->getEnableSinkAndFold();
814
815 auto *DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
816 auto *PDT =
817 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
818 auto *CI = &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
819 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
820 auto *MBFI =
822 ? &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI()
823 : nullptr;
824 auto *MBPI =
825 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
826 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
827 // Get analyses for split critical edge.
828 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
829 auto *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
830 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
831 auto *SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
832 auto *LVWrapper = getAnalysisIfAvailable<LiveVariablesWrapperPass>();
833 auto *LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
834 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
835 auto *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
836 auto *RegClassInfo =
837 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
838
839 MachineSinking Impl(EnableSinkAndFold, DT, PDT, LV, MLI, SI, LIS, CI, PSI,
840 MBFI, MBPI, AA, RegClassInfo);
841 return Impl.run(MF);
842}
843
844bool MachineSinking::run(MachineFunction &MF) {
845 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
846
847 STI = &MF.getSubtarget();
848 TII = STI->getInstrInfo();
849 TRI = STI->getRegisterInfo();
850 MRI = &MF.getRegInfo();
851
852 bool EverMadeChange = false;
853
854 while (true) {
855 bool MadeChange = false;
856
857 // Process all basic blocks.
858 CEBCandidates.clear();
859 CEMergeCandidates.clear();
860 ToSplit.clear();
861 for (auto &MBB : MF)
862 MadeChange |= ProcessBlock(MBB);
863
864 // If we have anything we marked as toSplit, split it now.
865 MachineDomTreeUpdater MDTU(DT, PDT,
866 MachineDomTreeUpdater::UpdateStrategy::Lazy);
867 for (const auto &Pair : ToSplit) {
868 auto NewSucc = Pair.first->SplitCriticalEdge(
869 Pair.second, {LIS, SI, LV, MLI}, nullptr, &MDTU);
870 if (NewSucc != nullptr) {
871 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
872 << printMBBReference(*Pair.first) << " -- "
873 << printMBBReference(*NewSucc) << " -- "
874 << printMBBReference(*Pair.second) << '\n');
875 if (MBFI)
876 MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
877
878 MadeChange = true;
879 ++NumSplit;
880 CI->splitCriticalEdge(Pair.first, Pair.second, NewSucc);
881 } else
882 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
883 }
884 // If this iteration over the code changed anything, keep iterating.
885 if (!MadeChange)
886 break;
887 EverMadeChange = true;
888 }
889
890 if (SinkInstsIntoCycle) {
892 SchedModel.init(STI);
893 bool HasHighPressure;
894
895 DenseMap<SinkItem, MachineInstr *> SunkInstrs;
896
897 enum CycleSinkStage { COPY, LOW_LATENCY, AGGRESSIVE, END };
898 for (unsigned Stage = CycleSinkStage::COPY; Stage != CycleSinkStage::END;
899 ++Stage, SunkInstrs.clear()) {
900 HasHighPressure = false;
901
902 for (auto Cycle : Cycles) {
903 MachineBasicBlock *Preheader = CI->getCyclePreheader(Cycle);
904 if (!Preheader) {
905 LLVM_DEBUG(dbgs() << "CycleSink: Can't find preheader\n");
906 continue;
907 }
908 SmallVector<MachineInstr *, 8> Candidates;
909 FindCycleSinkCandidates(Cycle, Preheader, Candidates);
910
911 unsigned i = 0;
912
913 // Walk the candidates in reverse order so that we start with the use
914 // of a def-use chain, if there is any.
915 // TODO: Sort the candidates using a cost-model.
916 for (MachineInstr *I : llvm::reverse(Candidates)) {
917 // CycleSinkStage::COPY: Sink a limited number of copies
918 if (Stage == CycleSinkStage::COPY) {
919 if (i++ == SinkIntoCycleLimit) {
921 << "CycleSink: Limit reached of instructions to "
922 "be analyzed.");
923 break;
924 }
925
926 if (!I->isCopy())
927 continue;
928 }
929
930 // CycleSinkStage::LOW_LATENCY: sink unlimited number of instructions
931 // which the target specifies as low-latency
932 if (Stage == CycleSinkStage::LOW_LATENCY &&
933 !TII->hasLowDefLatency(SchedModel, *I, 0))
934 continue;
935
936 if (!aggressivelySinkIntoCycle(Cycle, *I, SunkInstrs))
937 continue;
938 EverMadeChange = true;
939 ++NumCycleSunk;
940 }
941
942 // Recalculate the pressure after sinking
943 if (!HasHighPressure)
944 HasHighPressure = registerPressureExceedsLimit(*Preheader);
945 }
946 if (!HasHighPressure)
947 break;
948 }
949 }
950
951 HasStoreCache.clear();
952 StoreInstrCache.clear();
953
954 // Now clear any kill flags for recorded registers.
955 for (auto I : RegsToClearKillFlags)
956 MRI->clearKillFlags(I);
957 RegsToClearKillFlags.clear();
958
959 releaseMemory();
960 return EverMadeChange;
961}
962
963bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
964 if ((!EnableSinkAndFold && MBB.succ_size() <= 1) || MBB.empty())
965 return false;
966
967 // Don't bother sinking code out of unreachable blocks. In addition to being
968 // unprofitable, it can also lead to infinite looping, because in an
969 // unreachable cycle there may be nowhere to stop.
970 if (!DT->isReachableFromEntry(&MBB))
971 return false;
972
973 bool MadeChange = false;
974
975 // Cache all successors, sorted by frequency info and cycle depth.
976 AllSuccsCache AllSuccessors;
977
978 // Walk the basic block bottom-up. Remember if we saw a store.
980 --I;
981 bool ProcessedBegin, SawStore = false;
982 do {
983 MachineInstr &MI = *I; // The instruction to sink.
984
985 // Predecrement I (if it's not begin) so that it isn't invalidated by
986 // sinking.
987 ProcessedBegin = I == MBB.begin();
988 if (!ProcessedBegin)
989 --I;
990
991 if (MI.isDebugOrPseudoInstr() || MI.isFakeUse()) {
992 if (MI.isDebugValue())
993 ProcessDbgInst(MI);
994 continue;
995 }
996
997 if (EnableSinkAndFold && PerformSinkAndFold(MI, &MBB)) {
998 MadeChange = true;
999 continue;
1000 }
1001
1002 // Can't sink anything out of a block that has less than two successors.
1003 if (MBB.succ_size() <= 1)
1004 continue;
1005
1006 if (PerformTrivialForwardCoalescing(MI, &MBB)) {
1007 MadeChange = true;
1008 continue;
1009 }
1010
1011 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
1012 ++NumSunk;
1013 MadeChange = true;
1014 }
1015
1016 // If we just processed the first instruction in the block, we're done.
1017 } while (!ProcessedBegin);
1018
1019 SeenDbgUsers.clear();
1020 SeenDbgVars.clear();
1021 // recalculate the bb register pressure after sinking one BB.
1022 CachedRegisterPressure.clear();
1023 return MadeChange;
1024}
1025
1026void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
1027 // When we see DBG_VALUEs for registers, record any vreg it reads, so that
1028 // we know what to sink if the vreg def sinks.
1029 assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
1030
1031 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
1032 MI.getDebugLoc()->getInlinedAt());
1033 bool SeenBefore = SeenDbgVars.contains(Var);
1034
1035 for (MachineOperand &MO : MI.debug_operands()) {
1036 if (MO.isReg() && MO.getReg().isVirtual())
1037 SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
1038 }
1039
1040 // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
1041 SeenDbgVars.insert(Var);
1042}
1043
1044bool MachineSinking::isWorthBreakingCriticalEdge(
1045 MachineInstr &MI, MachineBasicBlock *From, MachineBasicBlock *To,
1046 MachineBasicBlock *&DeferredFromBlock) {
1047 // FIXME: Need much better heuristics.
1048
1049 // If the pass has already considered breaking this edge (during this pass
1050 // through the function), then let's go ahead and break it. This means
1051 // sinking multiple "cheap" instructions into the same block.
1052 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
1053 return true;
1054
1055 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
1056 return true;
1057
1058 // Check and record the register and the destination block we want to sink
1059 // into. Note that we want to do the following before the next check on branch
1060 // probability. Because we want to record the initial candidate even if it's
1061 // on hot edge, so that other candidates that might not on hot edges can be
1062 // sinked as well.
1063 for (const auto &MO : MI.all_defs()) {
1064 Register Reg = MO.getReg();
1065 if (!Reg)
1066 continue;
1067 Register SrcReg = Reg.isVirtual() ? TRI->lookThruCopyLike(Reg, MRI) : Reg;
1068 auto Key = std::make_pair(SrcReg, To);
1069 auto Res = CEMergeCandidates.try_emplace(Key, From);
1070 // We wanted to sink the same register into the same block, consider it to
1071 // be profitable.
1072 if (!Res.second) {
1073 // Return the source block that was previously held off.
1074 DeferredFromBlock = Res.first->second;
1075 return true;
1076 }
1077 }
1078
1079 if (From->isSuccessor(To) &&
1080 MBPI->getEdgeProbability(From, To) <=
1081 BranchProbability(SplitEdgeProbabilityThreshold, 100))
1082 return true;
1083
1084 // MI is cheap, we probably don't want to break the critical edge for it.
1085 // However, if this would allow some definitions of its source operands
1086 // to be sunk then it's probably worth it.
1087 for (const MachineOperand &MO : MI.all_uses()) {
1088 Register Reg = MO.getReg();
1089 if (Reg == 0)
1090 continue;
1091
1092 // We don't move live definitions of physical registers,
1093 // so sinking their uses won't enable any opportunities.
1094 if (Reg.isPhysical())
1095 continue;
1096
1097 // If this instruction is the only user of a virtual register,
1098 // check if breaking the edge will enable sinking
1099 // both this instruction and the defining instruction.
1100 if (MRI->hasOneNonDBGUse(Reg)) {
1101 // If the definition resides in same MBB,
1102 // claim it's likely we can sink these together.
1103 // If definition resides elsewhere, we aren't
1104 // blocking it from being sunk so don't break the edge.
1105 MachineInstr *DefMI = MRI->getVRegDef(Reg);
1106 if (DefMI->getParent() == MI.getParent())
1107 return true;
1108 }
1109 }
1110
1111 // Let the target decide if it's worth breaking this
1112 // critical edge for a "cheap" instruction.
1113 return TII->shouldBreakCriticalEdgeToSink(MI);
1114}
1115
1116bool MachineSinking::isLegalToBreakCriticalEdge(MachineInstr &MI,
1117 MachineBasicBlock *FromBB,
1118 MachineBasicBlock *ToBB,
1119 bool BreakPHIEdge) {
1120 // Avoid breaking back edge. From == To means backedge for single BB cycle.
1121 if (!SplitEdges || FromBB == ToBB || !FromBB->isSuccessor(ToBB))
1122 return false;
1123
1124 CycleRef FromCycle = CI->getCycle(FromBB);
1125 CycleRef ToCycle = CI->getCycle(ToBB);
1126
1127 // Check for backedges of more "complex" cycles.
1128 if (FromCycle == ToCycle && FromCycle &&
1129 (!CI->isReducible(FromCycle) || CI->getHeader(FromCycle) == ToBB))
1130 return false;
1131
1132 // It's not always legal to break critical edges and sink the computation
1133 // to the edge.
1134 //
1135 // %bb.1:
1136 // v1024
1137 // Beq %bb.3
1138 // <fallthrough>
1139 // %bb.2:
1140 // ... no uses of v1024
1141 // <fallthrough>
1142 // %bb.3:
1143 // ...
1144 // = v1024
1145 //
1146 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
1147 //
1148 // %bb.1:
1149 // ...
1150 // Bne %bb.2
1151 // %bb.4:
1152 // v1024 =
1153 // B %bb.3
1154 // %bb.2:
1155 // ... no uses of v1024
1156 // <fallthrough>
1157 // %bb.3:
1158 // ...
1159 // = v1024
1160 //
1161 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
1162 // flow. We need to ensure the new basic block where the computation is
1163 // sunk to dominates all the uses.
1164 // It's only legal to break critical edge and sink the computation to the
1165 // new block if all the predecessors of "To", except for "From", are
1166 // not dominated by "From". Given SSA property, this means these
1167 // predecessors are dominated by "To".
1168 //
1169 // There is no need to do this check if all the uses are PHI nodes. PHI
1170 // sources are only defined on the specific predecessor edges.
1171 if (!BreakPHIEdge) {
1172 for (MachineBasicBlock *Pred : ToBB->predecessors())
1173 if (Pred != FromBB && !DT->dominates(ToBB, Pred))
1174 return false;
1175 }
1176
1177 return true;
1178}
1179
1180bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
1181 MachineBasicBlock *FromBB,
1182 MachineBasicBlock *ToBB,
1183 bool BreakPHIEdge) {
1184 bool Status = false;
1185 MachineBasicBlock *DeferredFromBB = nullptr;
1186 if (isWorthBreakingCriticalEdge(MI, FromBB, ToBB, DeferredFromBB)) {
1187 // If there is a DeferredFromBB, we consider FromBB only if _both_
1188 // of them are legal to split.
1189 if ((!DeferredFromBB ||
1190 ToSplit.count(std::make_pair(DeferredFromBB, ToBB)) ||
1191 isLegalToBreakCriticalEdge(MI, DeferredFromBB, ToBB, BreakPHIEdge)) &&
1192 isLegalToBreakCriticalEdge(MI, FromBB, ToBB, BreakPHIEdge)) {
1193 ToSplit.insert(std::make_pair(FromBB, ToBB));
1194 if (DeferredFromBB)
1195 ToSplit.insert(std::make_pair(DeferredFromBB, ToBB));
1196 Status = true;
1197 }
1198 }
1199
1200 return Status;
1201}
1202
1203std::vector<unsigned> &
1204MachineSinking::getBBRegisterPressure(const MachineBasicBlock &MBB,
1205 bool UseCache) {
1206 // Currently to save compiling time, MBB's register pressure will not change
1207 // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
1208 // register pressure is changed after sinking any instructions into it.
1209 // FIXME: need a accurate and cheap register pressure estiminate model here.
1210
1211 auto RP = CachedRegisterPressure.find(&MBB);
1212 if (UseCache && RP != CachedRegisterPressure.end())
1213 return RP->second;
1214
1215 RegionPressure Pressure;
1216 RegPressureTracker RPTracker(Pressure);
1217
1218 // Initialize the register pressure tracker.
1219 RPTracker.init(MBB.getParent(), RegClassInfo, nullptr, &MBB, MBB.end(),
1220 /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
1221
1223 MIE = MBB.instr_begin();
1224 MII != MIE; --MII) {
1225 const MachineInstr &MI = *std::prev(MII);
1226 if (MI.isDebugOrPseudoInstr())
1227 continue;
1228 RegisterOperands RegOpers;
1229 RegOpers.collect(MI, *TRI, *MRI, false, false);
1230 RPTracker.recedeSkipDebugValues();
1231 assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
1232 RPTracker.recede(RegOpers);
1233 }
1234
1235 RPTracker.closeRegion();
1236
1237 if (RP != CachedRegisterPressure.end()) {
1238 CachedRegisterPressure[&MBB] = RPTracker.getPressure().MaxSetPressure;
1239 return CachedRegisterPressure[&MBB];
1240 }
1241
1242 auto It = CachedRegisterPressure.insert(
1243 std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
1244 return It.first->second;
1245}
1246
1247bool MachineSinking::registerPressureSetExceedsLimit(
1248 unsigned NRegs, const TargetRegisterClass *RC,
1249 const MachineBasicBlock &MBB) {
1250 unsigned Weight = NRegs * TRI->getRegClassWeight(RC).RegWeight;
1251 const int *PS = TRI->getRegClassPressureSets(RC);
1252 std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB);
1253 for (; *PS != -1; PS++)
1254 if (Weight + BBRegisterPressure[*PS] >=
1255 RegClassInfo->getRegPressureSetLimit(*PS))
1256 return true;
1257 return false;
1258}
1259
1260// Recalculate RP and check if any pressure set exceeds the set limit.
1261bool MachineSinking::registerPressureExceedsLimit(
1262 const MachineBasicBlock &MBB) {
1263 std::vector<unsigned> BBRegisterPressure = getBBRegisterPressure(MBB, false);
1264
1265 for (unsigned PS = 0; PS < BBRegisterPressure.size(); ++PS) {
1266 if (BBRegisterPressure[PS] >= RegClassInfo->getRegPressureSetLimit(PS)) {
1267 return true;
1268 }
1269 }
1270
1271 return false;
1272}
1273
1274/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
1275bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
1276 MachineBasicBlock *MBB,
1277 MachineBasicBlock *SuccToSinkTo,
1278 AllSuccsCache &AllSuccessors) {
1279 assert(SuccToSinkTo && "Invalid SinkTo Candidate BB");
1280
1281 if (MBB == SuccToSinkTo)
1282 return false;
1283
1284 // It is profitable if SuccToSinkTo does not post dominate current block.
1285 if (!PDT->dominates(SuccToSinkTo, MBB))
1286 return true;
1287
1288 // It is profitable to sink an instruction from a deeper cycle to a shallower
1289 // cycle, even if the latter post-dominates the former (PR21115).
1290 if (CI->getCycleDepth(MBB) > CI->getCycleDepth(SuccToSinkTo))
1291 return true;
1292
1293 // Check if only use in post dominated block is PHI instruction.
1294 bool NonPHIUse = false;
1295 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
1296 MachineBasicBlock *UseBlock = UseInst.getParent();
1297 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
1298 NonPHIUse = true;
1299 }
1300 if (!NonPHIUse)
1301 return true;
1302
1303 // If SuccToSinkTo post dominates then also it may be profitable if MI
1304 // can further profitably sinked into another block in next round.
1305 bool BreakPHIEdge = false;
1306 // FIXME - If finding successor is compile time expensive then cache results.
1307 if (MachineBasicBlock *MBB2 =
1308 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
1309 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
1310
1311 CycleRef MCycle = CI->getCycle(MBB);
1312
1313 // If the instruction is not inside a cycle, it is not profitable to sink MI
1314 // to a post dominate block SuccToSinkTo.
1315 if (!MCycle)
1316 return false;
1317
1318 // If this instruction is inside a Cycle and sinking this instruction can make
1319 // more registers live range shorten, it is still prifitable.
1320 for (const MachineOperand &MO : MI.operands()) {
1321 // Ignore non-register operands.
1322 if (!MO.isReg())
1323 continue;
1324 Register Reg = MO.getReg();
1325 if (Reg == 0)
1326 continue;
1327
1328 if (Reg.isPhysical()) {
1329 // Don't handle non-constant and non-ignorable physical register uses.
1330 if (MO.isUse() && !MRI->isConstantPhysReg(Reg) &&
1331 !TII->isIgnorableUse(MO))
1332 return false;
1333 continue;
1334 }
1335
1336 // Users for the defs are all dominated by SuccToSinkTo.
1337 if (MO.isDef()) {
1338 // This def register's live range is shortened after sinking.
1339 bool LocalUse = false;
1340 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1341 LocalUse))
1342 return false;
1343 } else {
1344 MachineInstr *DefMI = MRI->getVRegDef(Reg);
1345 if (!DefMI)
1346 continue;
1347 CycleRef Cycle = CI->getCycle(DefMI->getParent());
1348 // DefMI is defined outside of cycle. There should be no live range
1349 // impact for this operand. Defination outside of cycle means:
1350 // 1: defination is outside of cycle.
1351 // 2: defination is in this cycle, but it is a PHI in the cycle header.
1352 if (Cycle != MCycle ||
1353 (DefMI->isPHI() && Cycle && CI->isReducible(Cycle) &&
1354 CI->getHeader(Cycle) == DefMI->getParent()))
1355 continue;
1356 // The DefMI is defined inside the cycle.
1357 // If sinking this operand makes some register pressure set exceed limit,
1358 // it is not profitable.
1359 if (registerPressureSetExceedsLimit(1, MRI->getRegClass(Reg),
1360 *SuccToSinkTo)) {
1361 LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
1362 return false;
1363 }
1364 }
1365 }
1366
1367 // If MI is in cycle and all its operands are alive across the whole cycle or
1368 // if no operand sinking make register pressure set exceed limit, it is
1369 // profitable to sink MI.
1370 return true;
1371}
1372
1373/// Get the sorted sequence of successors for this MachineBasicBlock, possibly
1374/// computing it if it was not already cached.
1375SmallVector<MachineBasicBlock *, 4> &
1376MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
1377 AllSuccsCache &AllSuccessors) const {
1378 // Do we have the sorted successors in cache ?
1379 auto Succs = AllSuccessors.find(MBB);
1380 if (Succs != AllSuccessors.end())
1381 return Succs->second;
1382
1383 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors());
1384
1385 // Handle cases where sinking can happen but where the sink point isn't a
1386 // successor. For example:
1387 //
1388 // x = computation
1389 // if () {} else {}
1390 // use x
1391 //
1392 for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
1393 // DomTree children of MBB that have MBB as immediate dominator are added.
1394 if (DTChild->getIDom()->getBlock() == MI.getParent() &&
1395 // Skip MBBs already added to the AllSuccs vector above.
1396 !MBB->isSuccessor(DTChild->getBlock()))
1397 AllSuccs.push_back(DTChild->getBlock());
1398 }
1399
1400 // Sort Successors according to their cycle depth or block frequency info.
1402 AllSuccs, [&](const MachineBasicBlock *L, const MachineBasicBlock *R) {
1403 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
1404 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
1405 if (llvm::shouldOptimizeForSize(MBB, PSI, MBFI) ||
1406 (!LHSFreq && !RHSFreq))
1407 return CI->getCycleDepth(L) < CI->getCycleDepth(R);
1408 return LHSFreq < RHSFreq;
1409 });
1410
1411 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
1412
1413 return it.first->second;
1414}
1415
1416/// FindSuccToSinkTo - Find a successor to sink this instruction to.
1417MachineBasicBlock *
1418MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
1419 bool &BreakPHIEdge,
1420 AllSuccsCache &AllSuccessors) {
1421 assert(MBB && "Invalid MachineBasicBlock!");
1422
1423 // loop over all the operands of the specified instruction. If there is
1424 // anything we can't handle, bail out.
1425
1426 // SuccToSinkTo - This is the successor to sink this instruction to, once we
1427 // decide.
1428 MachineBasicBlock *SuccToSinkTo = nullptr;
1429 for (const MachineOperand &MO : MI.operands()) {
1430 if (!MO.isReg())
1431 continue; // Ignore non-register operands.
1432
1433 Register Reg = MO.getReg();
1434 if (Reg == 0)
1435 continue;
1436
1437 if (Reg.isPhysical()) {
1438 if (MO.isUse()) {
1439 // If the physreg has no defs anywhere, it's just an ambient register
1440 // and we can freely move its uses. Alternatively, if it's allocatable,
1441 // it could get allocated to something with a def during allocation.
1442 if (!MRI->isConstantPhysReg(Reg) && !TII->isIgnorableUse(MO))
1443 return nullptr;
1444 } else if (!MO.isDead()) {
1445 // A def that isn't dead. We can't move it.
1446 return nullptr;
1447 }
1448 } else {
1449 // Virtual register uses are always safe to sink.
1450 if (MO.isUse())
1451 continue;
1452
1453 // If it's not safe to move defs of the register class, then abort.
1454 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
1455 return nullptr;
1456
1457 // Virtual register defs can only be sunk if all their uses are in blocks
1458 // dominated by one of the successors.
1459 if (SuccToSinkTo) {
1460 // If a previous operand picked a block to sink to, then this operand
1461 // must be sinkable to the same block.
1462 bool LocalUse = false;
1463 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
1464 LocalUse))
1465 return nullptr;
1466
1467 continue;
1468 }
1469
1470 // Otherwise, we should look at all the successors and decide which one
1471 // we should sink to. If we have reliable block frequency information
1472 // (frequency != 0) available, give successors with smaller frequencies
1473 // higher priority, otherwise prioritize smaller cycle depths.
1474 for (MachineBasicBlock *SuccBlock :
1475 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
1476 bool LocalUse = false;
1477 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, BreakPHIEdge,
1478 LocalUse)) {
1479 SuccToSinkTo = SuccBlock;
1480 break;
1481 }
1482 if (LocalUse)
1483 // Def is used locally, it's never safe to move this def.
1484 return nullptr;
1485 }
1486
1487 // If we couldn't find a block to sink to, ignore this instruction.
1488 if (!SuccToSinkTo)
1489 return nullptr;
1490 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
1491 return nullptr;
1492 }
1493 }
1494
1495 // It is not possible to sink an instruction into its own block. This can
1496 // happen with cycles.
1497 if (MBB == SuccToSinkTo)
1498 return nullptr;
1499
1500 // It's not safe to sink instructions to EH landing pad. Control flow into
1501 // landing pad is implicitly defined.
1502 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
1503 return nullptr;
1504
1505 // It ought to be okay to sink instructions into an INLINEASM_BR target, but
1506 // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
1507 // the source block (which this code does not yet do). So for now, forbid
1508 // doing so.
1509 if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
1510 return nullptr;
1511
1512 if (SuccToSinkTo && !TII->isSafeToSink(MI, SuccToSinkTo, CI))
1513 return nullptr;
1514
1515 return SuccToSinkTo;
1516}
1517
1518/// Return true if MI is likely to be usable as a memory operation by the
1519/// implicit null check optimization.
1520///
1521/// This is a "best effort" heuristic, and should not be relied upon for
1522/// correctness. This returning true does not guarantee that the implicit null
1523/// check optimization is legal over MI, and this returning false does not
1524/// guarantee MI cannot possibly be used to do a null check.
1526 const TargetInstrInfo *TII,
1527 const TargetRegisterInfo *TRI) {
1528 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
1529
1530 auto *MBB = MI.getParent();
1531 if (MBB->pred_size() != 1)
1532 return false;
1533
1534 auto *PredMBB = *MBB->pred_begin();
1535 auto *PredBB = PredMBB->getBasicBlock();
1536
1537 // Frontends that don't use implicit null checks have no reason to emit
1538 // branches with make.implicit metadata, and this function should always
1539 // return false for them.
1540 if (!PredBB ||
1541 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
1542 return false;
1543
1544 const MachineOperand *BaseOp;
1545 int64_t Offset;
1546 bool OffsetIsScalable;
1547 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
1548 return false;
1549
1550 if (!BaseOp->isReg())
1551 return false;
1552
1553 if (!(MI.mayLoad() && !MI.isPredicable()))
1554 return false;
1555
1556 MachineBranchPredicate MBP;
1557 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
1558 return false;
1559
1560 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
1561 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
1562 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
1563 MBP.LHS.getReg() == BaseOp->getReg();
1564}
1565
1566/// If the sunk instruction is a copy, try to forward the copy instead of
1567/// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
1568/// there's any subregister weirdness involved. Returns true if copy
1569/// propagation occurred.
1570static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI,
1571 Register Reg) {
1572 const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
1573 const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
1574
1575 // Copy DBG_VALUE operand and set the original to undef. We then check to
1576 // see whether this is something that can be copy-forwarded. If it isn't,
1577 // continue around the loop.
1578
1579 const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
1580 auto CopyOperands = TII.isCopyInstr(SinkInst);
1581 if (!CopyOperands)
1582 return false;
1583 SrcMO = CopyOperands->Source;
1584 DstMO = CopyOperands->Destination;
1585
1586 // Check validity of forwarding this copy.
1587 bool PostRA = MRI.getNumVirtRegs() == 0;
1588
1589 // Trying to forward between physical and virtual registers is too hard.
1590 if (Reg.isVirtual() != SrcMO->getReg().isVirtual())
1591 return false;
1592
1593 // Only try virtual register copy-forwarding before regalloc, and physical
1594 // register copy-forwarding after regalloc.
1595 bool arePhysRegs = !Reg.isVirtual();
1596 if (arePhysRegs != PostRA)
1597 return false;
1598
1599 // Pre-regalloc, only forward if all subregisters agree (or there are no
1600 // subregs at all). More analysis might recover some forwardable copies.
1601 if (!PostRA)
1602 for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg))
1603 if (DbgMO.getSubReg() != SrcMO->getSubReg() ||
1604 DbgMO.getSubReg() != DstMO->getSubReg())
1605 return false;
1606
1607 // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
1608 // of this copy. Only forward the copy if the DBG_VALUE operand exactly
1609 // matches the copy destination.
1610 if (PostRA && Reg != DstMO->getReg())
1611 return false;
1612
1613 for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) {
1614 DbgMO.setReg(SrcMO->getReg());
1615 DbgMO.setSubReg(SrcMO->getSubReg());
1616 }
1617 return true;
1618}
1619
1620using MIRegs = std::pair<MachineInstr *, SmallVector<Register, 2>>;
1621/// Sink an instruction and its associated debug instructions.
1622static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
1624 ArrayRef<MIRegs> DbgValuesToSink) {
1625 // If we cannot find a location to use (merge with), then we erase the debug
1626 // location to prevent debug-info driven tools from potentially reporting
1627 // wrong location information.
1628 if (SuccToSinkTo.empty())
1629 MI.setDebugLoc(DebugLoc::getDropped());
1630 else
1631 MI.setDebugLoc(DebugLoc::getMergedLocation(
1632 MI.getDebugLoc(), SuccToSinkTo.findDebugLoc(InsertPos)));
1633
1634 // Move the instruction.
1635 MachineBasicBlock *ParentBlock = MI.getParent();
1636 SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
1638
1639 // Sink a copy of debug users to the insert position. Mark the original
1640 // DBG_VALUE location as 'undef', indicating that any earlier variable
1641 // location should be terminated as we've optimised away the value at this
1642 // point.
1643 for (const auto &DbgValueToSink : DbgValuesToSink) {
1644 MachineInstr *DbgMI = DbgValueToSink.first;
1645 MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI);
1646 SuccToSinkTo.insert(InsertPos, NewDbgMI);
1647
1648 bool PropagatedAllSunkOps = true;
1649 for (Register Reg : DbgValueToSink.second) {
1650 if (DbgMI->hasDebugOperandForReg(Reg)) {
1651 if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) {
1652 PropagatedAllSunkOps = false;
1653 break;
1654 }
1655 }
1656 }
1657 if (!PropagatedAllSunkOps)
1658 DbgMI->setDebugValueUndef();
1659 }
1660}
1661
1662/// hasStoreBetween - check if there is store betweeen straight line blocks From
1663/// and To.
1664bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1665 MachineBasicBlock *To, MachineInstr &MI) {
1666 // Make sure From and To are in straight line which means From dominates To
1667 // and To post dominates From.
1668 if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1669 return true;
1670
1671 auto BlockPair = std::make_pair(From, To);
1672
1673 // Does these two blocks pair be queried before and have a definite cached
1674 // result?
1675 if (auto It = HasStoreCache.find(BlockPair); It != HasStoreCache.end())
1676 return It->second;
1677
1678 if (auto It = StoreInstrCache.find(BlockPair); It != StoreInstrCache.end())
1679 return llvm::any_of(It->second, [&](MachineInstr *I) {
1680 return I->mayAlias(AA, MI, false);
1681 });
1682
1683 bool SawStore = false;
1684 bool HasAliasedStore = false;
1685 DenseSet<MachineBasicBlock *> HandledBlocks;
1686 DenseSet<MachineBasicBlock *> HandledDomBlocks;
1687 // Go through all reachable blocks from From.
1688 for (MachineBasicBlock *BB : depth_first(From)) {
1689 // We insert the instruction at the start of block To, so no need to worry
1690 // about stores inside To.
1691 // Store in block From should be already considered when just enter function
1692 // SinkInstruction.
1693 if (BB == To || BB == From)
1694 continue;
1695
1696 // We already handle this BB in previous iteration.
1697 if (HandledBlocks.count(BB))
1698 continue;
1699
1700 HandledBlocks.insert(BB);
1701 // To post dominates BB, it must be a path from block From.
1702 if (PDT->dominates(To, BB)) {
1703 if (!HandledDomBlocks.count(BB))
1704 HandledDomBlocks.insert(BB);
1705
1706 // If this BB is too big or the block number in straight line between From
1707 // and To is too big, stop searching to save compiling time.
1708 if (BB->sizeWithoutDebugLargerThan(SinkLoadInstsPerBlockThreshold) ||
1709 HandledDomBlocks.size() > SinkLoadBlocksThreshold) {
1710 for (auto *DomBB : HandledDomBlocks) {
1711 if (DomBB != BB && DT->dominates(DomBB, BB))
1712 HasStoreCache[std::make_pair(DomBB, To)] = true;
1713 else if (DomBB != BB && DT->dominates(BB, DomBB))
1714 HasStoreCache[std::make_pair(From, DomBB)] = true;
1715 }
1716 HasStoreCache[BlockPair] = true;
1717 return true;
1718 }
1719
1720 for (MachineInstr &I : *BB) {
1721 // Treat as alias conservatively for a call or an ordered memory
1722 // operation.
1723 if (I.isCall() || I.hasOrderedMemoryRef()) {
1724 for (auto *DomBB : HandledDomBlocks) {
1725 if (DomBB != BB && DT->dominates(DomBB, BB))
1726 HasStoreCache[std::make_pair(DomBB, To)] = true;
1727 else if (DomBB != BB && DT->dominates(BB, DomBB))
1728 HasStoreCache[std::make_pair(From, DomBB)] = true;
1729 }
1730 HasStoreCache[BlockPair] = true;
1731 return true;
1732 }
1733
1734 if (I.mayStore()) {
1735 SawStore = true;
1736 // We still have chance to sink MI if all stores between are not
1737 // aliased to MI.
1738 // Cache all store instructions, so that we don't need to go through
1739 // all From reachable blocks for next load instruction.
1740 if (I.mayAlias(AA, MI, false))
1741 HasAliasedStore = true;
1742 StoreInstrCache[BlockPair].push_back(&I);
1743 }
1744 }
1745 }
1746 }
1747 // If there is no store at all, cache the result.
1748 if (!SawStore)
1749 HasStoreCache[BlockPair] = false;
1750 return HasAliasedStore;
1751}
1752
1753/// Aggressively sink instructions into cycles. This will aggressively try to
1754/// sink all instructions in the top-most preheaders in an attempt to reduce RP.
1755/// In particular, it will sink into multiple successor blocks without limits
1756/// based on the amount of sinking, or the type of ops being sunk (so long as
1757/// they are safe to sink).
1758bool MachineSinking::aggressivelySinkIntoCycle(
1759 CycleRef Cycle, MachineInstr &I,
1760 DenseMap<SinkItem, MachineInstr *> &SunkInstrs) {
1761 // TODO: support instructions with multiple defs
1762 if (I.getNumDefs() > 1)
1763 return false;
1764
1765 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Finding sink block for: " << I);
1766 assert(CI->getCyclePreheader(Cycle) && "Cycle sink needs a preheader block");
1768
1769 MachineOperand &DefMO = I.getOperand(0);
1770 for (MachineInstr &MI : MRI->use_instructions(DefMO.getReg())) {
1771 Uses.push_back({{DefMO.getReg(), DefMO.getSubReg()}, &MI});
1772 }
1773
1774 for (std::pair<RegSubRegPair, MachineInstr *> Entry : Uses) {
1775 MachineInstr *MI = Entry.second;
1776 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Analysing use: " << MI);
1777 if (MI->isPHI()) {
1778 LLVM_DEBUG(
1779 dbgs() << "AggressiveCycleSink: Not attempting to sink for PHI.\n");
1780 continue;
1781 }
1782 // We cannot sink before the prologue
1783 if (MI->isPosition() || TII->isBasicBlockPrologue(*MI)) {
1784 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Use is BasicBlock prologue, "
1785 "can't sink.\n");
1786 continue;
1787 }
1788 if (!CI->contains(Cycle, MI->getParent())) {
1789 LLVM_DEBUG(
1790 dbgs() << "AggressiveCycleSink: Use not in cycle, can't sink.\n");
1791 continue;
1792 }
1793
1794 MachineBasicBlock *SinkBlock = MI->getParent();
1795 MachineInstr *NewMI = nullptr;
1796 SinkItem MapEntry(&I, SinkBlock);
1797
1798 auto SI = SunkInstrs.find(MapEntry);
1799
1800 // Check for the case in which we have already sunk a copy of this
1801 // instruction into the user block.
1802 if (SI != SunkInstrs.end()) {
1803 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Already sunk to block: "
1804 << printMBBReference(*SinkBlock) << "\n");
1805 NewMI = SI->second;
1806 }
1807
1808 // Create a copy of the instruction in the use block.
1809 if (!NewMI) {
1810 LLVM_DEBUG(dbgs() << "AggressiveCycleSink: Sinking instruction to block: "
1811 << printMBBReference(*SinkBlock) << "\n");
1812
1813 NewMI = I.getMF()->CloneMachineInstr(&I);
1814 if (DefMO.getReg().isVirtual()) {
1815 const TargetRegisterClass *TRC = MRI->getRegClass(DefMO.getReg());
1816 Register DestReg = MRI->createVirtualRegister(TRC);
1817 NewMI->substituteRegister(DefMO.getReg(), DestReg, DefMO.getSubReg(),
1818 *TRI);
1819 }
1820 SinkBlock->insert(SinkBlock->SkipPHIsAndLabels(SinkBlock->begin()),
1821 NewMI);
1822 SunkInstrs.insert({MapEntry, NewMI});
1823 }
1824
1825 // Conservatively clear any kill flags on uses of sunk instruction
1826 for (MachineOperand &MO : NewMI->all_uses()) {
1827 assert(MO.isReg() && MO.isUse());
1828 RegsToClearKillFlags.insert(MO.getReg());
1829 }
1830
1831 // The instruction is moved from its basic block, so do not retain the
1832 // debug information.
1833 assert(!NewMI->isDebugInstr() && "Should not sink debug inst");
1834 NewMI->setDebugLoc(DebugLoc());
1835
1836 // Replace the use with the newly created virtual register.
1837 RegSubRegPair &UseReg = Entry.first;
1838 MI->substituteRegister(UseReg.Reg, NewMI->getOperand(0).getReg(),
1839 UseReg.SubReg, *TRI);
1840 }
1841 // If we have replaced all uses, then delete the dead instruction
1842 if (I.isDead(*MRI))
1843 I.eraseFromParent();
1844 return true;
1845}
1846
1847/// SinkInstruction - Determine whether it is safe to sink the specified machine
1848/// instruction out of its current block into a successor.
1849bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1850 AllSuccsCache &AllSuccessors) {
1851 // Don't sink instructions that the target prefers not to sink.
1852 if (!TII->shouldSink(MI))
1853 return false;
1854
1855 // Check if it's safe to move the instruction.
1856 if (!MI.isSafeToMove(SawStore))
1857 return false;
1858
1859 // Convergent operations may not be made control-dependent on additional
1860 // values.
1861 if (MI.isConvergent())
1862 return false;
1863
1864 // Don't break implicit null checks. This is a performance heuristic, and not
1865 // required for correctness.
1867 return false;
1868
1869 // FIXME: This should include support for sinking instructions within the
1870 // block they are currently in to shorten the live ranges. We often get
1871 // instructions sunk into the top of a large block, but it would be better to
1872 // also sink them down before their first use in the block. This xform has to
1873 // be careful not to *increase* register pressure though, e.g. sinking
1874 // "x = y + z" down if it kills y and z would increase the live ranges of y
1875 // and z and only shrink the live range of x.
1876
1877 bool BreakPHIEdge = false;
1878 MachineBasicBlock *ParentBlock = MI.getParent();
1879 MachineBasicBlock *SuccToSinkTo =
1880 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1881
1882 // If there are no outputs, it must have side-effects.
1883 if (!SuccToSinkTo)
1884 return false;
1885
1886 // If the instruction to move defines a dead physical register which is live
1887 // when leaving the basic block, don't move it because it could turn into a
1888 // "zombie" define of that preg. E.g., EFLAGS.
1889 for (const MachineOperand &MO : MI.all_defs()) {
1890 Register Reg = MO.getReg();
1891 if (Reg == 0 || !Reg.isPhysical())
1892 continue;
1893 if (SuccToSinkTo->isLiveIn(Reg))
1894 return false;
1895 }
1896
1897 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1898
1899 // If the block has multiple predecessors, this is a critical edge.
1900 // Decide if we can sink along it or need to break the edge.
1901 if (SuccToSinkTo->pred_size() > 1) {
1902 // We cannot sink a load across a critical edge - there may be stores in
1903 // other code paths.
1904 bool TryBreak = false;
1905 bool Store =
1906 MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1907 if (!MI.isSafeToMove(Store)) {
1908 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1909 TryBreak = true;
1910 }
1911
1912 // We don't want to sink across a critical edge if we don't dominate the
1913 // successor. We could be introducing calculations to new code paths.
1914 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1915 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1916 TryBreak = true;
1917 }
1918
1919 // Don't sink instructions into a cycle.
1920 if (!TryBreak && CI->getCycle(SuccToSinkTo) &&
1921 (!CI->isReducible(CI->getCycle(SuccToSinkTo)) ||
1922 CI->getHeader(CI->getCycle(SuccToSinkTo)) == SuccToSinkTo)) {
1923 LLVM_DEBUG(dbgs() << " *** NOTE: cycle header found\n");
1924 TryBreak = true;
1925 }
1926
1927 // Otherwise we are OK with sinking along a critical edge.
1928 if (!TryBreak)
1929 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1930 else {
1931 // Mark this edge as to be split.
1932 // If the edge can actually be split, the next iteration of the main loop
1933 // will sink MI in the newly created block.
1934 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo,
1935 BreakPHIEdge);
1936 if (!Status)
1937 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1938 "break critical edge\n");
1939 // The instruction will not be sunk this time.
1940 return false;
1941 }
1942 }
1943
1944 if (BreakPHIEdge) {
1945 // BreakPHIEdge is true if all the uses are in the successor MBB being
1946 // sunken into and they are all PHI nodes. In this case, machine-sink must
1947 // break the critical edge first.
1948 bool Status =
1949 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1950 if (!Status)
1951 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1952 "break critical edge\n");
1953 // The instruction will not be sunk this time.
1954 return false;
1955 }
1956
1957 // Determine where to insert into. Skip phi nodes.
1958 MachineBasicBlock::iterator InsertPos =
1959 SuccToSinkTo->SkipPHIsAndLabels(SuccToSinkTo->begin());
1960 if (blockPrologueInterferes(SuccToSinkTo, InsertPos, MI, TRI, TII, MRI)) {
1961 LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
1962 return false;
1963 }
1964
1965 // Collect debug users of any vreg that this inst defines.
1966 SmallVector<MIRegs, 4> DbgUsersToSink;
1967 for (auto &MO : MI.all_defs()) {
1968 if (!MO.getReg().isVirtual())
1969 continue;
1970 auto It = SeenDbgUsers.find(MO.getReg());
1971 if (It == SeenDbgUsers.end())
1972 continue;
1973
1974 // Sink any users that don't pass any other DBG_VALUEs for this variable.
1975 auto &Users = It->second;
1976 for (auto &User : Users) {
1977 MachineInstr *DbgMI = User.getPointer();
1978 if (User.getInt()) {
1979 // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1980 // it, it can't be recovered. Set it undef.
1981 if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg()))
1982 DbgMI->setDebugValueUndef();
1983 } else {
1984 DbgUsersToSink.push_back(
1985 {DbgMI, SmallVector<Register, 2>(1, MO.getReg())});
1986 }
1987 }
1988 }
1989
1990 // After sinking, some debug users may not be dominated any more. If possible,
1991 // copy-propagate their operands. As it's expensive, don't do this if there's
1992 // no debuginfo in the program.
1993 if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1994 SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1995
1996 performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1997
1998 // Conservatively, clear any kill flags, since it's possible that they are no
1999 // longer correct.
2000 // Note that we have to clear the kill flags for any register this instruction
2001 // uses as we may sink over another instruction which currently kills the
2002 // used registers.
2003 for (MachineOperand &MO : MI.all_uses())
2004 RegsToClearKillFlags.insert(MO.getReg()); // Remember to clear kill flags.
2005
2006 return true;
2007}
2008
2009void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
2010 MachineInstr &MI, MachineBasicBlock *TargetBlock) {
2011 assert(MI.isCopy());
2012 assert(MI.getOperand(1).isReg());
2013
2014 // Enumerate all users of vreg operands that are def'd. Skip those that will
2015 // be sunk. For the rest, if they are not dominated by the block we will sink
2016 // MI into, propagate the copy source to them.
2017 SmallVector<MachineInstr *, 4> DbgDefUsers;
2018 SmallVector<Register, 4> DbgUseRegs;
2019 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
2020 for (auto &MO : MI.all_defs()) {
2021 if (!MO.getReg().isVirtual())
2022 continue;
2023 DbgUseRegs.push_back(MO.getReg());
2024 for (auto &User : MRI.use_instructions(MO.getReg())) {
2025 if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
2026 continue;
2027
2028 // If is in same block, will either sink or be use-before-def.
2029 if (User.getParent() == MI.getParent())
2030 continue;
2031
2032 assert(User.hasDebugOperandForReg(MO.getReg()) &&
2033 "DBG_VALUE user of vreg, but has no operand for it?");
2034 DbgDefUsers.push_back(&User);
2035 }
2036 }
2037
2038 // Point the users of this copy that are no longer dominated, at the source
2039 // of the copy.
2040 for (auto *User : DbgDefUsers) {
2041 for (auto &Reg : DbgUseRegs) {
2042 for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) {
2043 DbgOp.setReg(MI.getOperand(1).getReg());
2044 DbgOp.setSubReg(MI.getOperand(1).getSubReg());
2045 }
2046 }
2047 }
2048}
2049
2050//===----------------------------------------------------------------------===//
2051// This pass is not intended to be a replacement or a complete alternative
2052// for the pre-ra machine sink pass. It is only designed to sink COPY
2053// instructions which should be handled after RA.
2054//
2055// This pass sinks COPY instructions into a successor block, if the COPY is not
2056// used in the current block and the COPY is live-in to a single successor
2057// (i.e., doesn't require the COPY to be duplicated). This avoids executing the
2058// copy on paths where their results aren't needed. This also exposes
2059// additional opportunites for dead copy elimination and shrink wrapping.
2060//
2061// These copies were either not handled by or are inserted after the MachineSink
2062// pass. As an example of the former case, the MachineSink pass cannot sink
2063// COPY instructions with allocatable source registers; for AArch64 these type
2064// of copy instructions are frequently used to move function parameters (PhyReg)
2065// into virtual registers in the entry block.
2066//
2067// For the machine IR below, this pass will sink %w19 in the entry into its
2068// successor (%bb.1) because %w19 is only live-in in %bb.1.
2069// %bb.0:
2070// %wzr = SUBSWri %w1, 1
2071// %w19 = COPY %w0
2072// Bcc 11, %bb.2
2073// %bb.1:
2074// Live Ins: %w19
2075// BL @fun
2076// %w0 = ADDWrr %w0, %w19
2077// RET %w0
2078// %bb.2:
2079// %w0 = COPY %wzr
2080// RET %w0
2081// As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
2082// able to see %bb.0 as a candidate.
2083//===----------------------------------------------------------------------===//
2084namespace {
2085
2086class PostRAMachineSinkingImpl {
2087 /// Track which register units have been modified and used.
2088 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
2089
2090 /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
2091 /// entry in this map for each unit it touches. The DBG_VALUE's entry
2092 /// consists of a pointer to the instruction itself, and a vector of registers
2093 /// referred to by the instruction that overlap the key register unit.
2094 DenseMap<MCRegUnit, SmallVector<MIRegs, 2>> SeenDbgInstrs;
2095
2096 /// Sink Copy instructions unused in the same block close to their uses in
2097 /// successors.
2098 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
2099 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
2100
2101public:
2102 bool run(MachineFunction &MF);
2103};
2104
2105class PostRAMachineSinkingLegacy : public MachineFunctionPass {
2106public:
2107 bool runOnMachineFunction(MachineFunction &MF) override;
2108
2109 static char ID;
2110 PostRAMachineSinkingLegacy() : MachineFunctionPass(ID) {}
2111 StringRef getPassName() const override { return "PostRA Machine Sink"; }
2112
2113 void getAnalysisUsage(AnalysisUsage &AU) const override {
2114 AU.setPreservesCFG();
2115 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
2117 }
2118
2119 MachineFunctionProperties getRequiredProperties() const override {
2120 return MachineFunctionProperties().setNoVRegs();
2121 }
2122};
2123
2124} // namespace
2125
2126char PostRAMachineSinkingLegacy::ID = 0;
2127char &llvm::PostRAMachineSinkingID = PostRAMachineSinkingLegacy::ID;
2128
2129INITIALIZE_PASS(PostRAMachineSinkingLegacy, "postra-machine-sink",
2130 "PostRA Machine Sink", false, false)
2131
2132static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, Register Reg,
2134 LiveRegUnits LiveInRegUnits(*TRI);
2135 LiveInRegUnits.addLiveIns(MBB);
2136 return !LiveInRegUnits.available(Reg);
2137}
2138
2139static MachineBasicBlock *
2141 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
2143 // Try to find a single sinkable successor in which Reg is live-in.
2144 MachineBasicBlock *BB = nullptr;
2145 for (auto *SI : SinkableBBs) {
2146 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
2147 // If BB is set here, Reg is live-in to at least two sinkable successors,
2148 // so quit.
2149 if (BB)
2150 return nullptr;
2151 BB = SI;
2152 }
2153 }
2154 // Reg is not live-in to any sinkable successors.
2155 if (!BB)
2156 return nullptr;
2157
2158 // Check if any register aliased with Reg is live-in in other successors.
2159 for (auto *SI : CurBB.successors()) {
2160 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
2161 return nullptr;
2162 }
2163 return BB;
2164}
2165
2166static MachineBasicBlock *
2168 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
2169 ArrayRef<Register> DefedRegsInCopy,
2170 const TargetRegisterInfo *TRI) {
2171 MachineBasicBlock *SingleBB = nullptr;
2172 for (auto DefReg : DefedRegsInCopy) {
2173 MachineBasicBlock *BB =
2174 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
2175 if (!BB || (SingleBB && SingleBB != BB))
2176 return nullptr;
2177 SingleBB = BB;
2178 }
2179 return SingleBB;
2180}
2181
2183 const SmallVectorImpl<unsigned> &UsedOpsInCopy,
2184 const LiveRegUnits &UsedRegUnits,
2185 const TargetRegisterInfo *TRI) {
2186 for (auto U : UsedOpsInCopy) {
2187 MachineOperand &MO = MI->getOperand(U);
2188 Register SrcReg = MO.getReg();
2189 if (!UsedRegUnits.available(SrcReg)) {
2190 MachineBasicBlock::iterator NI = std::next(MI->getIterator());
2191 for (MachineInstr &UI : make_range(NI, CurBB.end())) {
2192 if (UI.killsRegister(SrcReg, TRI)) {
2193 UI.clearRegisterKills(SrcReg, TRI);
2194 MO.setIsKill(true);
2195 break;
2196 }
2197 }
2198 }
2199 }
2200}
2201
2203 const SmallVectorImpl<unsigned> &UsedOpsInCopy,
2204 const SmallVectorImpl<Register> &DefedRegsInCopy) {
2205 for (Register DefReg : DefedRegsInCopy)
2206 SuccBB->removeLiveInOverlappedWith(DefReg);
2207
2208 for (auto U : UsedOpsInCopy)
2209 SuccBB->addLiveIn(MI->getOperand(U).getReg());
2210 SuccBB->sortUniqueLiveIns();
2211}
2212
2214 SmallVectorImpl<unsigned> &UsedOpsInCopy,
2215 SmallVectorImpl<Register> &DefedRegsInCopy,
2216 LiveRegUnits &ModifiedRegUnits,
2217 LiveRegUnits &UsedRegUnits) {
2218 bool HasRegDependency = false;
2219 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2220 MachineOperand &MO = MI->getOperand(i);
2221 if (!MO.isReg())
2222 continue;
2223 Register Reg = MO.getReg();
2224 if (!Reg)
2225 continue;
2226 if (MO.isDef()) {
2227 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
2228 HasRegDependency = true;
2229 break;
2230 }
2231 DefedRegsInCopy.push_back(Reg);
2232
2233 // FIXME: instead of isUse(), readsReg() would be a better fix here,
2234 // For example, we can ignore modifications in reg with undef. However,
2235 // it's not perfectly clear if skipping the internal read is safe in all
2236 // other targets.
2237 } else if (MO.isUse()) {
2238 if (!ModifiedRegUnits.available(Reg)) {
2239 HasRegDependency = true;
2240 break;
2241 }
2242 UsedOpsInCopy.push_back(i);
2243 }
2244 }
2245 return HasRegDependency;
2246}
2247
2248bool PostRAMachineSinkingImpl::tryToSinkCopy(MachineBasicBlock &CurBB,
2249 MachineFunction &MF,
2250 const TargetRegisterInfo *TRI,
2251 const TargetInstrInfo *TII) {
2252 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
2253 // FIXME: For now, we sink only to a successor which has a single predecessor
2254 // so that we can directly sink COPY instructions to the successor without
2255 // adding any new block or branch instruction.
2256 for (MachineBasicBlock *SI : CurBB.successors())
2257 if (!SI->livein_empty() && SI->pred_size() == 1)
2258 SinkableBBs.insert(SI);
2259
2260 if (SinkableBBs.empty())
2261 return false;
2262
2263 bool Changed = false;
2264
2265 // Track which registers have been modified and used between the end of the
2266 // block and the current instruction.
2267 ModifiedRegUnits.clear();
2268 UsedRegUnits.clear();
2269 SeenDbgInstrs.clear();
2270
2271 for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(CurBB))) {
2272 // Track the operand index for use in Copy.
2273 SmallVector<unsigned, 2> UsedOpsInCopy;
2274 // Track the register number defed in Copy.
2275 SmallVector<Register, 2> DefedRegsInCopy;
2276
2277 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
2278 // for DBG_VALUEs later, record them when they're encountered.
2279 if (MI.isDebugValue() && !MI.isDebugRef()) {
2280 SmallDenseMap<MCRegUnit, SmallVector<Register, 2>, 4> MIUnits;
2281 bool IsValid = true;
2282 for (MachineOperand &MO : MI.debug_operands()) {
2283 if (MO.isReg() && MO.getReg().isPhysical()) {
2284 // Bail if we can already tell the sink would be rejected, rather
2285 // than needlessly accumulating lots of DBG_VALUEs.
2286 if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2287 ModifiedRegUnits, UsedRegUnits)) {
2288 IsValid = false;
2289 break;
2290 }
2291
2292 // Record debug use of each reg unit.
2293 for (MCRegUnit Unit : TRI->regunits(MO.getReg()))
2294 MIUnits[Unit].push_back(MO.getReg());
2295 }
2296 }
2297 if (IsValid) {
2298 for (auto &RegOps : MIUnits)
2299 SeenDbgInstrs[RegOps.first].emplace_back(&MI,
2300 std::move(RegOps.second));
2301 }
2302 continue;
2303 }
2304
2305 // Don't postRASink instructions that the target prefers not to sink.
2306 if (!TII->shouldPostRASink(MI))
2307 continue;
2308
2309 if (MI.isDebugOrPseudoInstr())
2310 continue;
2311
2312 // Do not move any instruction across function call.
2313 if (MI.isCall())
2314 return false;
2315
2316 if (!MI.isCopy() || !MI.getOperand(0).isRenamable()) {
2317 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2318 TRI);
2319 continue;
2320 }
2321
2322 // Don't sink the COPY if it would violate a register dependency.
2323 if (hasRegisterDependency(&MI, UsedOpsInCopy, DefedRegsInCopy,
2324 ModifiedRegUnits, UsedRegUnits)) {
2325 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2326 TRI);
2327 continue;
2328 }
2329 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
2330 "Unexpect SrcReg or DefReg");
2331 MachineBasicBlock *SuccBB =
2332 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
2333 // Don't sink if we cannot find a single sinkable successor in which Reg
2334 // is live-in.
2335 if (!SuccBB) {
2336 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2337 TRI);
2338 continue;
2339 }
2340 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
2341 "Unexpected predecessor");
2342
2343 // Collect DBG_VALUEs that must sink with this copy. We've previously
2344 // recorded which reg units that DBG_VALUEs read, if this instruction
2345 // writes any of those units then the corresponding DBG_VALUEs must sink.
2346 MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap;
2347 for (auto &MO : MI.all_defs()) {
2348 for (MCRegUnit Unit : TRI->regunits(MO.getReg())) {
2349 for (const auto &MIRegs : SeenDbgInstrs.lookup(Unit)) {
2350 auto &Regs = DbgValsToSinkMap[MIRegs.first];
2351 llvm::append_range(Regs, MIRegs.second);
2352 }
2353 }
2354 }
2355 auto DbgValsToSink = DbgValsToSinkMap.takeVector();
2356
2357 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccBB);
2358
2359 MachineBasicBlock::iterator InsertPos =
2360 SuccBB->SkipPHIsAndLabels(SuccBB->begin());
2361 if (blockPrologueInterferes(SuccBB, InsertPos, MI, TRI, TII, nullptr)) {
2362 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
2363 TRI);
2364 LLVM_DEBUG(dbgs() << " *** Not sinking: prologue interference\n");
2365 continue;
2366 }
2367
2368 // Clear the kill flag if SrcReg is killed between MI and the end of the
2369 // block.
2370 clearKillFlags(&MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
2371 performSink(MI, *SuccBB, InsertPos, DbgValsToSink);
2372 updateLiveIn(&MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
2373
2374 Changed = true;
2375 ++NumPostRACopySink;
2376 }
2377 return Changed;
2378}
2379
2380bool PostRAMachineSinkingImpl::run(MachineFunction &MF) {
2381 bool Changed = false;
2382 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2383 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
2384
2385 ModifiedRegUnits.init(*TRI);
2386 UsedRegUnits.init(*TRI);
2387 for (auto &BB : MF)
2388 Changed |= tryToSinkCopy(BB, MF, TRI, TII);
2389
2390 return Changed;
2391}
2392
2393bool PostRAMachineSinkingLegacy::runOnMachineFunction(MachineFunction &MF) {
2394 if (skipFunction(MF.getFunction()))
2395 return false;
2396
2397 return PostRAMachineSinkingImpl().run(MF);
2398}
2399
2400PreservedAnalyses
2403 MFPropsModifier _(*this, MF);
2404
2405 if (!PostRAMachineSinkingImpl().run(MF))
2406 return PreservedAnalyses::all();
2407
2410 return PA;
2411}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
basic Basic Alias true
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
#define DEBUG_TYPE
ManagedStatic< HTTPClientCleanup > Cleanup
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition IVUsers.cpp:48
#define I(x, y, z)
Definition MD5.cpp:57
static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI)
Return true if this machine instruction loads from global offset table or constant pool.
static cl::opt< unsigned > SinkLoadInstsPerBlockThreshold("machine-sink-load-instrs-threshold", cl::desc("Do not try to find alias store for a load if there is a in-path " "block whose instruction number is higher than this threshold."), cl::init(2000), cl::Hidden)
static cl::opt< unsigned > SinkIntoCycleLimit("machine-sink-cycle-limit", cl::desc("The maximum number of instructions considered for cycle sinking."), cl::init(50), cl::Hidden)
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB, const SmallVectorImpl< unsigned > &UsedOpsInCopy, const LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo, MachineBasicBlock::iterator InsertPos, ArrayRef< MIRegs > DbgValuesToSink)
Sink an instruction and its associated debug instructions.
static cl::opt< bool > SplitEdges("machine-sink-split", cl::desc("Split critical edges during machine sinking"), cl::init(true), cl::Hidden)
static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
Return true if MI is likely to be usable as a memory operation by the implicit null check optimizatio...
static cl::opt< bool > SinkInstsIntoCycle("sink-insts-to-avoid-spills", cl::desc("Sink instructions into cycles to avoid " "register spills"), cl::init(false), cl::Hidden)
static cl::opt< unsigned > SinkLoadBlocksThreshold("machine-sink-load-blocks-threshold", cl::desc("Do not try to find alias store for a load if the block number in " "the straight line is higher than this threshold."), cl::init(20), cl::Hidden)
static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB, const SmallVectorImpl< unsigned > &UsedOpsInCopy, const SmallVectorImpl< Register > &DefedRegsInCopy)
static bool hasRegisterDependency(MachineInstr *MI, SmallVectorImpl< unsigned > &UsedOpsInCopy, SmallVectorImpl< Register > &DefedRegsInCopy, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits)
Register const TargetRegisterInfo * TRI
std::pair< MachineInstr *, SmallVector< Register, 2 > > MIRegs
Machine code static false bool blockPrologueInterferes(const MachineBasicBlock *BB, MachineBasicBlock::const_iterator End, const MachineInstr &MI, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, const MachineRegisterInfo *MRI)
Return true if a target defined block prologue instruction interferes with a sink candidate.
static cl::opt< unsigned > SplitEdgeProbabilityThreshold("machine-sink-split-probability-threshold", cl::desc("Percentage threshold for splitting single-instruction critical edge. " "If the branch threshold is higher than this threshold, we allow " "speculative execution of up to 1 instruction to avoid branching to " "splitted critical edge"), cl::init(40), cl::Hidden)
static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI, Register Reg)
If the sunk instruction is a copy, try to forward the copy instead of leaving an 'undef' DBG_VALUE in...
static cl::opt< bool > UseBlockFreqInfo("machine-sink-bfi", cl::desc("Use block frequency info to find successors to sink"), cl::init(true), cl::Hidden)
static MachineBasicBlock * getSingleLiveInSuccBB(MachineBasicBlock &CurBB, const SmallPtrSetImpl< MachineBasicBlock * > &SinkableBBs, Register Reg, const TargetRegisterInfo *TRI)
This file implements a map that provides insertion order iteration.
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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the PointerIntPair class.
Remove Loads Into Fake Uses
static const char * name
This file implements a set that has insertion order iteration characteristics.
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
Definition Sink.cpp:173
static bool SinkInstruction(Instruction *Inst, SmallPtrSetImpl< Instruction * > &Stores, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
SinkInstruction - Determine whether it is safe to sink the specified machine instruction out of its c...
Definition Sink.cpp:103
This file defines the SmallSet class.
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
Target-Independent Code Generator Pass Configuration Options pass.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:172
static DebugLoc getDropped()
Definition DebugLoc.h:155
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
iterator_range< const_toplevel_iterator > toplevel_cycles() const
bool isReducible(CycleRef C) const
BlockT * getCyclePreheader(CycleRef C) const
Return the preheader block for C.
void splitCriticalEdge(BlockT *Pred, BlockT *Succ, BlockT *New)
bool contains(CycleRef Outer, CycleRef Inner) const
Returns true iff Outer contains Inner. O(1). Non-strict.
unsigned getCycleDepth(const BlockT *Block) const
Return the depth of the innermost cycle containing Block, or 0 if it is not contained in any cycle.
BlockT * getHeader(CycleRef C) const
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
Module * getParent()
Get the module that this global value is contained inside of...
bool isAsCheapAsAMove(const MachineInstr &MI) const override
bool shouldSink(const MachineInstr &MI) const override
A set of register units used to track register liveness.
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
LLVM_ABI void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
void clear()
Clears the set.
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI void removeLiveInOverlappedWith(MCRegister Reg)
Remove the specified register from any overlapped live in.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
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 bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI void onEdgeSplit(const MachineBasicBlock &NewPredecessor, const MachineBasicBlock &NewSuccessor, const MachineBranchProbabilityInfo &MBPI)
incrementally calculate block frequencies when we split edges, to avoid full CFG traversal.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Legacy analysis pass which computes a MachineCycleInfo.
Analysis pass which computes a MachineDominatorTree.
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
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
void setDebugValueUndef()
Sets all register debug operands in this debug value instruction to be undef.
LLVM_ABI iterator_range< filter_iterator< const MachineOperand *, std::function< bool(const MachineOperand &Op)> > > getDebugOperandsForReg(Register Reg) const
Returns a range of all of the operands that correspond to a debug use of Reg.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isDebugInstr() const
mop_range operands()
LLVM_ABI void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
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...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
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
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
iterator_range< use_iterator > use_operands(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
VectorType takeVector()
Clear the MapVector and return the underlying vector.
Definition MapVector.h:50
void dump() const
Definition Pass.cpp:146
PointerIntPair - This class implements a pair of a pointer and small integer.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Special value supplied for machine level alias analysis.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
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
A vector that has set insertion semantics.
Definition SetVector.h:57
SlotIndexes pass.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
Target-Independent Code Generator Pass Configuration Options.
bool getEnableSinkAndFold() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
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 TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type size() const
Definition DenseSet.h:84
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
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
Abstract Attribute helper functions.
Definition Attributor.h:165
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
void stable_sort(R &&Range)
Definition STLExtras.h:2116
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:1739
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
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:633
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool isCycleInvariant(const MachineCycleInfo &CI, CycleRef Cycle, MachineInstr &I)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
LLVM_ABI char & MachineSinkingLegacyID
MachineSinking - This pass performs sinking on machine instructions.
iterator_range< df_iterator< T > > depth_first(const T &G)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Represents a predicate at the MachineFunction level.
A pair composed of a register and a sub-register index.