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