LLVM 24.0.0git
MachinePipeliner.cpp
Go to the documentation of this file.
1//===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10//
11// This SMS implementation is a target-independent back-end pass. When enabled,
12// the pass runs just prior to the register allocation pass, while the machine
13// IR is in SSA form. If software pipelining is successful, then the original
14// loop is replaced by the optimized loop. The optimized loop contains one or
15// more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16// the instructions cannot be scheduled in a given MII, we increase the MII by
17// one and try again.
18//
19// The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20// represent loop carried dependences in the DAG as order edges to the Phi
21// nodes. We also perform several passes over the DAG to eliminate unnecessary
22// edges that inhibit the ability to pipeline. The implementation uses the
23// DFAPacketizer class to compute the minimum initiation interval and the check
24// where an instruction may be inserted in the pipelined schedule.
25//
26// In order for the SMS pass to work, several target specific hooks need to be
27// implemented to get information about the loop structure and to rewrite
28// instructions.
29//
30//===----------------------------------------------------------------------===//
31
33#include "CodeGenOptions.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallSet.h"
44#include "llvm/ADT/Statistic.h"
73#include "llvm/Config/llvm-config.h"
74#include "llvm/IR/Attributes.h"
75#include "llvm/IR/Function.h"
77#include "llvm/MC/LaneBitmask.h"
78#include "llvm/MC/MCInstrDesc.h"
80#include "llvm/Pass.h"
82#include "llvm/Support/Debug.h"
84#include <algorithm>
85#include <cassert>
86#include <climits>
87#include <cstdint>
88#include <deque>
89#include <functional>
90#include <iomanip>
91#include <iterator>
92#include <map>
93#include <memory>
94#include <sstream>
95#include <tuple>
96#include <utility>
97#include <vector>
98
99using namespace llvm;
100
101#define DEBUG_TYPE "pipeliner"
102
103STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
104STATISTIC(NumPipelined, "Number of loops software pipelined");
105STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
106STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
107STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
108STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
109STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
110STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
111STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
112STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
113STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
114STATISTIC(NumFailTooManyStores, "Pipeliner abort due to too many stores");
115
116unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
119
121 "Modulo Software Pipelining", false, false)
127 "Modulo Software Pipelining", false, false)
128
129namespace {
130
131/// This class holds an SUnit corresponding to a memory operation and other
132/// information related to the instruction.
136
137 /// The value of a memory operand.
138 const Value *MemOpValue = nullptr;
139
140 /// The offset of a memory operand.
141 int64_t MemOpOffset = 0;
142
144
145 /// True if all the underlying objects are identified.
146 bool IsAllIdentified = false;
147
149
150 bool isTriviallyDisjoint(const SUnitWithMemInfo &Other) const;
151
152 bool isUnknown() const { return MemOpValue == nullptr; }
153
154private:
156};
157
158/// Add loop-carried chain dependencies. This class handles the same type of
159/// dependencies added by `ScheduleDAGInstrs::buildSchedGraph`, but takes into
160/// account dependencies across iterations.
162 // Type of instruction that is relevant to order-dependencies
163 enum class InstrTag {
164 Barrier = 0, ///< A barrier event instruction.
165 LoadOrStore = 1, ///< An instruction that may load or store memory, but is
166 ///< not a barrier event.
167 FPExceptions = 2, ///< An instruction that does not match above, but may
168 ///< raise floatin-point exceptions.
169 };
170
171 struct TaggedSUnit : PointerIntPair<SUnit *, 2> {
172 TaggedSUnit(SUnit *SU, InstrTag Tag)
173 : PointerIntPair<SUnit *, 2>(SU, unsigned(Tag)) {}
174
175 InstrTag getTag() const { return InstrTag(getInt()); }
176 };
177
178 /// Holds instructions that may form loop-carried order-dependencies, but not
179 /// global barriers.
180 struct NoBarrierInstsChunk {
184
185 void append(SUnit *SU);
186 };
187
189 BatchAAResults *BAA;
190 std::vector<SUnit> &SUnits;
191
192 /// The size of SUnits, for convenience.
193 const unsigned N;
194
195 /// Loop-carried Edges.
196 std::vector<BitVector> LoopCarried;
197
198 /// Instructions related to chain dependencies. They are one of the
199 /// following:
200 ///
201 /// 1. Barrier event.
202 /// 2. Load, but neither a barrier event, invariant load, nor may load trap
203 /// value.
204 /// 3. Store, but not a barrier event.
205 /// 4. None of them, but may raise floating-point exceptions.
206 ///
207 /// This is used when analyzing loop-carried dependencies that access global
208 /// barrier instructions.
209 std::vector<TaggedSUnit> TaggedSUnits;
210
211 const TargetInstrInfo *TII = nullptr;
212
213public:
215 const TargetInstrInfo *TII);
216
217 /// The main function to compute loop-carried order-dependencies.
218 void computeDependencies();
219
220 const BitVector &getLoopCarried(unsigned Idx) const {
221 return LoopCarried[Idx];
222 }
223
224private:
225 /// Tags to \p SU if the instruction may affect the order-dependencies.
226 std::optional<InstrTag> getInstrTag(SUnit *SU) const;
227
228 void addLoopCarriedDepenenciesForChunks(const NoBarrierInstsChunk &From,
229 const NoBarrierInstsChunk &To);
230
231 /// Add a loop-carried order dependency between \p Src and \p Dst if we
232 /// cannot prove they are independent.
233 void addDependenciesBetweenSUs(const SUnitWithMemInfo &Src,
234 const SUnitWithMemInfo &Dst);
235
236 void computeDependenciesAux();
237
238 void setLoopCarriedDep(const SUnit *Src, const SUnit *Dst) {
239 LoopCarried[Src->NodeNum].set(Dst->NodeNum);
240 }
241};
242
243/// The main class in the implementation of the target independent
244/// software pipeliner pass.
246public:
247 const CodeGenOptions &Opts;
248 MachineFunction *MF = nullptr;
250 const MachineLoopInfo *MLI = nullptr;
252 const TargetInstrInfo *TII = nullptr;
254 LiveIntervals *LIS = nullptr;
255 AAResults *AA = nullptr;
257 const TargetMachine *TM = nullptr;
258 bool disabledByPragma = false;
259 unsigned II_setByPragma = 0;
260
261#ifndef NDEBUG
262 static int NumTries;
263#endif
264
265 /// Cache the target analysis information about the loop.
266 struct LoopInfo {
272 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo> LoopPipelinerInfo =
273 nullptr;
274 };
276
282
283 /// Run the software pipeliner over all loops in the function.
284 bool run();
285
286private:
287 void preprocessPhiNodes(MachineBasicBlock &B);
288 bool canPipelineLoop(MachineLoop &L);
289 bool scheduleLoop(MachineLoop &L);
290 bool swingModuloScheduler(MachineLoop &L);
291 void setPragmaPipelineOptions(MachineLoop &L);
292 bool runWindowScheduler(MachineLoop &L);
293 bool useSwingModuloScheduler();
294 bool useWindowScheduler(bool Changed);
295};
296
297} // end anonymous namespace
298
299#ifndef NDEBUG
300int MachinePipelinerImpl::NumTries = 0;
301#endif
302
310
311/// The "main" function for implementing Swing Modulo Scheduling.
313 bool Changed = false;
314 for (const auto &L : *MLI)
315 Changed |= scheduleLoop(*L);
316
317 return Changed;
318}
319
321 MachineFunction &MF, function_ref<const MachineLoopInfo &()> GetMLI,
322 function_ref<LiveIntervals &()> GetLIS, function_ref<AAResults &()> GetAA,
326 if (MF.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
327 !getCodeGenOptions(MF).pipeliner_opt_size)
328 return false;
329
331 return false;
332
333 // Cannot pipeline loops without instruction itineraries if we are using
334 // DFA for the pipeliner.
335 if (MF.getSubtarget().useDFAforSMS() &&
338 return false;
339
340 LiveIntervals &LIS = GetLIS();
341 MachinePipelinerImpl MP(MF, GetMLI(), LIS, GetAA(), GetORE(), GetRCI(),
342 GetMDT());
343 return MP.run();
344}
345
347 if (skipFunction(MF.getFunction()))
348 return false;
349
350 return runMachinePipeliner(
351 MF,
352 [&]() -> const MachineLoopInfo & {
354 },
355 [&]() -> LiveIntervals & {
357 },
358 [&]() -> AAResults & {
359 return getAnalysis<AAResultsWrapperPass>().getAAResults();
360 },
363 },
364 [&]() -> RegisterClassInfo & {
366 },
367 [&]() -> MachineDominatorTree * {
368 auto *MDTWrapper =
370 return MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
371 });
372}
373
378 MF,
379 [&]() -> const MachineLoopInfo & {
380 return MFAM.getResult<MachineLoopAnalysis>(MF);
381 },
382 [&]() -> LiveIntervals & {
383 return MFAM.getResult<LiveIntervalsAnalysis>(MF);
384 },
385 [&]() -> AAResults & {
386 return MFAM
388 .getManager()
389 .getResult<AAManager>(MF.getFunction());
390 },
393 },
394 [&]() -> RegisterClassInfo & {
396 },
397 [&]() -> MachineDominatorTree * {
399 }))
400 return PreservedAnalyses::all();
401
405 return PA;
406}
407
408/// Attempt to perform the SMS algorithm on the specified loop. This function is
409/// the main entry point for the algorithm. The function identifies candidate
410/// loops, calculates the minimum initiation interval, and attempts to schedule
411/// the loop.
412bool MachinePipelinerImpl::scheduleLoop(MachineLoop &L) {
413 bool Changed = false;
414 for (const auto &InnerLoop : L)
415 Changed |= scheduleLoop(*InnerLoop);
416
417#ifndef NDEBUG
418 // Stop trying after reaching the limit (if any).
419 int Limit = Opts.pipeliner_max;
420 if (Limit >= 0) {
421 if (NumTries >= Limit)
422 return Changed;
423 NumTries++;
424 }
425#endif
426
427 setPragmaPipelineOptions(L);
428 if (!canPipelineLoop(L)) {
429 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
430 ORE->emit([&]() {
431 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
432 L.getStartLoc(), L.getHeader())
433 << "Failed to pipeline loop";
434 });
435
436 LI.LoopPipelinerInfo.reset();
437 return Changed;
438 }
439
440 ++NumTrytoPipeline;
441 if (useSwingModuloScheduler())
442 Changed = swingModuloScheduler(L);
443
444 if (useWindowScheduler(Changed))
445 Changed = runWindowScheduler(L);
446
447#ifdef EXPENSIVE_CHECKS
448 assert((!Changed || !MDT || MDT->verify()) &&
449 "Dominator tree not updated for the pipelined loop");
450#endif
451
452 LI.LoopPipelinerInfo.reset();
453 return Changed;
454}
455
456void MachinePipelinerImpl::setPragmaPipelineOptions(MachineLoop &L) {
457 // Reset the pragma for the next loop in iteration.
458 disabledByPragma = false;
459 II_setByPragma = 0;
460
461 MachineBasicBlock *LBLK = L.getTopBlock();
462
463 if (LBLK == nullptr)
464 return;
465
466 const BasicBlock *BBLK = LBLK->getBasicBlock();
467 if (BBLK == nullptr)
468 return;
469
470 const Instruction *TI = BBLK->getTerminator();
471 MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
472 if (LoopID == nullptr)
473 return;
474
475 assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
476 assert(LoopID->getOperand(0) == LoopID && "invalid loop");
477
478 for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
479 MDNode *MD = dyn_cast<MDNode>(MDO);
480
481 if (MD == nullptr)
482 continue;
483
484 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
485
486 if (S == nullptr)
487 continue;
488
489 if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
490 assert(MD->getNumOperands() == 2 &&
491 "Pipeline initiation interval hint metadata should have two operands.");
493 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
494 assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
495 } else if (S->getString() == "llvm.loop.pipeline.disable") {
496 disabledByPragma = true;
497 }
498 }
499}
500
501/// Depth-first search to detect cycles among PHI dependencies.
502/// Returns true if a cycle is detected within the PHI-only subgraph.
503static bool hasPHICycleDFS(
504 unsigned Reg, const DenseMap<unsigned, SmallVector<unsigned, 2>> &PhiDeps,
505 SmallSet<unsigned, 8> &Visited, SmallSet<unsigned, 8> &RecStack) {
506
507 // If Reg is not a PHI-def it cannot contribute to a PHI cycle.
508 auto It = PhiDeps.find(Reg);
509 if (It == PhiDeps.end())
510 return false;
511
512 if (RecStack.count(Reg))
513 return true; // backedge.
514 if (Visited.count(Reg))
515 return false;
516
517 Visited.insert(Reg);
518 RecStack.insert(Reg);
519
520 for (unsigned Dep : It->second) {
521 if (hasPHICycleDFS(Dep, PhiDeps, Visited, RecStack))
522 return true;
523 }
524
525 RecStack.erase(Reg);
526 return false;
527}
528
529static bool hasPHICycle(const MachineBasicBlock *LoopHeader,
530 const MachineRegisterInfo &MRI) {
532
533 // Collect PHI nodes and their dependencies.
534 for (const MachineInstr &MI : LoopHeader->phis()) {
535 unsigned DefReg = MI.getOperand(0).getReg();
536 auto Ins = PhiDeps.try_emplace(DefReg).first;
537
538 // PHI operands are (Reg, MBB) pairs starting at index 1.
539 for (unsigned I = 1; I < MI.getNumOperands(); I += 2)
540 Ins->second.push_back(MI.getOperand(I).getReg());
541 }
542
543 // DFS to detect cycles among PHI nodes.
544 SmallSet<unsigned, 8> Visited, RecStack;
545
546 // Start DFS from each PHI-def.
547 for (const auto &KV : PhiDeps) {
548 unsigned Reg = KV.first;
549 if (hasPHICycleDFS(Reg, PhiDeps, Visited, RecStack))
550 return true;
551 }
552
553 return false;
554}
555
556/// Return true if the loop can be software pipelined. The algorithm is
557/// restricted to loops with a single basic block. Make sure that the
558/// branch in the loop can be analyzed.
559bool MachinePipelinerImpl::canPipelineLoop(MachineLoop &L) {
560 if (L.getNumBlocks() != 1) {
561 ORE->emit([&]() {
562 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
563 L.getStartLoc(), L.getHeader())
564 << "Not a single basic block: "
565 << ore::NV("NumBlocks", L.getNumBlocks());
566 });
567 return false;
568 }
569
570 if (hasPHICycle(L.getHeader(), MF->getRegInfo())) {
571 LLVM_DEBUG(dbgs() << "Cannot pipeline loop due to PHI cycle\n");
572 return false;
573 }
574
575 if (disabledByPragma) {
576 ORE->emit([&]() {
577 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
578 L.getStartLoc(), L.getHeader())
579 << "Disabled by Pragma.";
580 });
581 return false;
582 }
583
584 // Check if the branch can't be understood because we can't do pipelining
585 // if that's the case.
586 LI.TBB = nullptr;
587 LI.FBB = nullptr;
588 LI.BrCond.clear();
589 if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
590 LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
591 NumFailBranch++;
592 ORE->emit([&]() {
593 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
594 L.getStartLoc(), L.getHeader())
595 << "The branch can't be understood";
596 });
597 return false;
598 }
599
600 LI.LoopInductionVar = nullptr;
601 LI.LoopCompare = nullptr;
602 LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
603 if (!LI.LoopPipelinerInfo) {
604 LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
605 NumFailLoop++;
606 ORE->emit([&]() {
607 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
608 L.getStartLoc(), L.getHeader())
609 << "The loop structure is not supported";
610 });
611 return false;
612 }
613
614 if (!L.getLoopPreheader()) {
615 LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
616 NumFailPreheader++;
617 ORE->emit([&]() {
618 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
619 L.getStartLoc(), L.getHeader())
620 << "No loop preheader found";
621 });
622 return false;
623 }
624
625 unsigned NumStores = 0;
626 for (MachineInstr &MI : *L.getHeader())
627 if (MI.mayStore())
628 ++NumStores;
629 if (NumStores > Opts.pipeliner_max_num_stores) {
630 LLVM_DEBUG(dbgs() << "Too many stores\n");
631 NumFailTooManyStores++;
632 ORE->emit([&]() {
633 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
634 L.getStartLoc(), L.getHeader())
635 << "Too many store instructions in the loop: "
636 << ore::NV("NumStores", NumStores) << " > "
637 << ore::NV("SwpMaxNumStores", Opts.pipeliner_max_num_stores)
638 << ".";
639 });
640 return false;
641 }
642
643 // Remove any subregisters from inputs to phi nodes.
644 preprocessPhiNodes(*L.getHeader());
645 return true;
646}
647
648void MachinePipelinerImpl::preprocessPhiNodes(MachineBasicBlock &B) {
649 MachineRegisterInfo &MRI = MF->getRegInfo();
650 SlotIndexes &Slots = *LIS->getSlotIndexes();
651
652 for (MachineInstr &PI : B.phis()) {
653 MachineOperand &DefOp = PI.getOperand(0);
654 assert(DefOp.getSubReg() == 0);
655 auto *RC = MRI.getRegClass(DefOp.getReg());
656
657 for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
658 MachineOperand &RegOp = PI.getOperand(i);
659 if (RegOp.getSubReg() == 0)
660 continue;
661
662 // If the operand uses a subregister, replace it with a new register
663 // without subregisters, and generate a copy to the new register.
665 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
667 const DebugLoc &DL = PredB.findDebugLoc(At);
668 auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
669 .addReg(RegOp.getReg(), getRegState(RegOp),
670 RegOp.getSubReg());
671 Slots.insertMachineInstrInMaps(*Copy);
672 RegOp.setReg(NewReg);
673 RegOp.setSubReg(0);
674 }
675 }
676}
677
678/// The SMS algorithm consists of the following main steps:
679/// 1. Computation and analysis of the dependence graph.
680/// 2. Ordering of the nodes (instructions).
681/// 3. Attempt to Schedule the loop.
682bool MachinePipelinerImpl::swingModuloScheduler(MachineLoop &L) {
683 assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
684
685 SwingSchedulerDAG SMS(*MF, MLI, ORE, L, *LIS, *RegClassInfo, II_setByPragma,
686 LI.LoopPipelinerInfo.get(), AA, MDT);
687
688 MachineBasicBlock *MBB = L.getHeader();
689 // The kernel should not include any terminator instructions. These
690 // will be added back later.
691 SMS.startBlock(MBB);
692
693 // Compute the number of 'real' instructions in the basic block by
694 // ignoring terminators.
695 unsigned size = MBB->size();
697 E = MBB->instr_end();
698 I != E; ++I, --size)
699 ;
700
701 SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
702 SMS.schedule();
703 SMS.exitRegion();
704
705 SMS.finishBlock();
706 return SMS.hasNewSchedule();
707}
708
721
722bool MachinePipelinerImpl::runWindowScheduler(MachineLoop &L) {
724 Context.MF = MF;
725 Context.MLI = MLI;
726 Context.TM = TM;
727 Context.AA = AA;
728 Context.LIS = LIS;
729 Context.RegClassInfo = RegClassInfo;
730 WindowScheduler WS(&Context, L, MDT);
731 return WS.run();
732}
733
734bool MachinePipelinerImpl::useSwingModuloScheduler() {
735 // SwingModuloScheduler does not work when WindowScheduler is forced.
736 return Opts.window_sched != WindowSchedulingFlag::Force;
737}
738
739bool MachinePipelinerImpl::useWindowScheduler(bool Changed) {
740 // WindowScheduler does not work for following cases:
741 // 1. when it is off.
742 // 2. when SwingModuloScheduler is successfully scheduled.
743 // 3. when pragma II is enabled.
744 if (II_setByPragma) {
745 LLVM_DEBUG(dbgs() << "Window scheduling is disabled when "
746 "llvm.loop.pipeline.initiationinterval is set.\n");
747 return false;
748 }
749
750 return Opts.window_sched == WindowSchedulingFlag::Force ||
751 (Opts.window_sched == WindowSchedulingFlag::On && !Changed);
752}
753
754void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
755 if (Opts.pipeliner_force_ii > 0)
756 MII = Opts.pipeliner_force_ii;
757 else if (II_setByPragma > 0)
758 MII = II_setByPragma;
759 else
760 MII = std::max(ResMII, RecMII);
761}
762
763void SwingSchedulerDAG::setMAX_II() {
764 if (Opts.pipeliner_force_ii > 0)
765 MAX_II = Opts.pipeliner_force_ii;
766 else if (II_setByPragma > 0)
767 MAX_II = II_setByPragma;
768 else
769 MAX_II = MII + Opts.pipeliner_ii_search_range;
770}
771
773 const MachineLoopInfo *MLI,
775 MachineLoop &L, LiveIntervals &lis,
776 const RegisterClassInfo &rci, unsigned II,
778 AliasAnalysis *AA,
780 : ScheduleDAGInstrs(MF, MLI, false), ORE(ORE), Loop(L), LIS(lis),
781 RegClassInfo(rci), II_setByPragma(II), LoopPipelinerInfo(PLI),
782 Topo(SUnits, &ExitSU), AA(AA), BAA(*AA), MDT(MDT) {
783 initPolicy();
784 MF.getSubtarget().getSMSMutations(Mutations);
785 if (Opts.pipeliner_enable_copytophi)
786 Mutations.push_back(std::make_unique<CopyToPhiMutation>());
787 BAA.enableCrossIterationMode();
788}
789
790/// We override the schedule function in ScheduleDAGInstrs to implement the
791/// scheduling part of the Swing Modulo Scheduling algorithm.
793 buildSchedGraph(AA);
794 const LoopCarriedEdges LCE = addLoopCarriedDependences();
795 updatePhiDependences();
796 Topo.InitDAGTopologicalSorting();
797 changeDependences();
798 postProcessDAG();
799 DDG = std::make_unique<SwingSchedulerDDG>(SUnits, &EntrySU, &ExitSU, LCE);
800 LLVM_DEBUG({
801 dump();
802 dbgs() << "===== Loop Carried Edges Begin =====\n";
803 for (SUnit &SU : SUnits)
804 LCE.dump(&SU, TRI, &MRI);
805 dbgs() << "===== Loop Carried Edges End =====\n";
806 });
807
808 NodeSetType NodeSets;
809 findCircuits(NodeSets);
810 NodeSetType Circuits = NodeSets;
811
812 // Calculate the MII.
813 unsigned ResMII = calculateResMII();
814 unsigned RecMII = calculateRecMII(NodeSets);
815
816 fuseRecs(NodeSets);
817
818 // This flag is used for testing and can cause correctness problems.
819 if (Opts.pipeliner_ignore_recmii)
820 RecMII = 0;
821
822 setMII(ResMII, RecMII);
823 setMAX_II();
824
825 LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
826 << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
827
828 // Can't schedule a loop without a valid MII.
829 if (MII == 0) {
830 LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
831 NumFailZeroMII++;
832 ORE->emit([&]() {
834 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
835 << "Invalid Minimal Initiation Interval: 0";
836 });
837 return;
838 }
839
840 // Don't pipeline large loops.
841 if (Opts.pipeliner_max_mii != -1 && (int)MII > Opts.pipeliner_max_mii) {
842 LLVM_DEBUG(dbgs() << "MII > " << Opts.pipeliner_max_mii
843 << ", we don't pipeline large loops\n");
844 NumFailLargeMaxMII++;
845 ORE->emit([&]() {
847 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
848 << "Minimal Initiation Interval too large: "
849 << ore::NV("MII", (int)MII) << " > "
850 << ore::NV("SwpMaxMii", Opts.pipeliner_max_mii) << "."
851 << "Refer to -pipeliner-max-mii.";
852 });
853 return;
854 }
855
856 computeNodeFunctions(NodeSets);
857
858 registerPressureFilter(NodeSets);
859
860 colocateNodeSets(NodeSets);
861
862 checkNodeSets(NodeSets);
863
864 LLVM_DEBUG({
865 for (auto &I : NodeSets) {
866 dbgs() << " Rec NodeSet ";
867 I.dump();
868 }
869 });
870
871 llvm::stable_sort(NodeSets, std::greater<NodeSet>());
872
873 groupRemainingNodes(NodeSets);
874
875 removeDuplicateNodes(NodeSets);
876
877 LLVM_DEBUG({
878 for (auto &I : NodeSets) {
879 dbgs() << " NodeSet ";
880 I.dump();
881 }
882 });
883
884 computeNodeOrder(NodeSets);
885
886 // check for node order issues
887 checkValidNodeOrder(Circuits);
888
889 SMSchedule Schedule(&MF, this);
890 Scheduled = schedulePipeline(Schedule);
891
892 if (!Scheduled){
893 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
894 NumFailNoSchedule++;
895 ORE->emit([&]() {
897 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
898 << "Unable to find schedule";
899 });
900 return;
901 }
902
903 unsigned numStages = Schedule.getMaxStageCount();
904 // No need to generate pipeline if there are no overlapped iterations.
905 if (numStages == 0) {
906 LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
907 NumFailZeroStage++;
908 ORE->emit([&]() {
910 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
911 << "No need to pipeline - no overlapped iterations in schedule.";
912 });
913 return;
914 }
915 // Check that the maximum stage count is less than user-defined limit.
916 if (Opts.pipeliner_max_stages > -1 &&
917 (int)numStages > Opts.pipeliner_max_stages) {
918 LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">"
919 << Opts.pipeliner_max_stages
920 << " : too many stages, abort\n");
921 NumFailLargeMaxStage++;
922 ORE->emit([&]() {
924 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
925 << "Too many stages in schedule: "
926 << ore::NV("numStages", (int)numStages) << " > "
927 << ore::NV("SwpMaxStages", Opts.pipeliner_max_stages)
928 << ". Refer to -pipeliner-max-stages.";
929 });
930 return;
931 }
932
933 ORE->emit([&]() {
934 return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
935 Loop.getHeader())
936 << "Pipelined succesfully!";
937 });
938
939 // Generate the schedule as a ModuloSchedule.
940 DenseMap<MachineInstr *, int> Cycles, Stages;
941 std::vector<MachineInstr *> OrderedInsts;
942 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
943 ++Cycle) {
944 for (SUnit *SU : Schedule.getInstructions(Cycle)) {
945 OrderedInsts.push_back(SU->getInstr());
946 Cycles[SU->getInstr()] = Cycle;
947 Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
948 }
949 }
951 for (auto &KV : NewMIs) {
952 Cycles[KV.first] = Cycles[KV.second];
953 Stages[KV.first] = Stages[KV.second];
954 NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
955 }
956
957 ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
958 std::move(Stages));
959 if (Opts.pipeliner_annotate_for_testing) {
960 assert(NewInstrChanges.empty() &&
961 "Cannot serialize a schedule with InstrChanges!");
963 MSTI.annotate();
964 return;
965 }
966 // The experimental code generator can't work if there are InstChanges.
967 if (Opts.pipeliner_experimental_cg && NewInstrChanges.empty()) {
968 PeelingModuloScheduleExpander MSE(MF, MS, &LIS, MDT);
969 MSE.expand();
970 } else if (Opts.pipeliner_mve_cg && NewInstrChanges.empty() &&
971 LoopPipelinerInfo->isMVEExpanderSupported() &&
973 ModuloScheduleExpanderMVE MSE(MF, MS, LIS, MDT);
974 MSE.expand();
975 } else {
976 ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges), MDT);
977 MSE.expand();
978 MSE.cleanup();
979 }
980 ++NumPipelined;
981}
982
983/// Clean up after the software pipeliner runs.
985 for (auto &KV : NewMIs)
986 MF.deleteMachineInstr(KV.second);
987 NewMIs.clear();
988
989 // Call the superclass.
991}
992
993/// Return the register values for the operands of a Phi instruction.
994/// This function assume the instruction is a Phi.
995static void getPhiRegs(const MachineInstr &Phi, const MachineBasicBlock *Loop,
996 Register &InitVal, Register &LoopVal) {
997 assert(Phi.isPHI() && "Expecting a Phi.");
998
999 InitVal = Register();
1000 LoopVal = Register();
1001 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1002 if (Phi.getOperand(i + 1).getMBB() != Loop)
1003 InitVal = Phi.getOperand(i).getReg();
1004 else
1005 LoopVal = Phi.getOperand(i).getReg();
1006
1007 assert(InitVal && LoopVal && "Unexpected Phi structure.");
1008}
1009
1010/// Return the Phi register value that comes the loop block.
1012 const MachineBasicBlock *LoopBB) {
1013 for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1014 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
1015 return Phi.getOperand(i).getReg();
1016 return Register();
1017}
1018
1019/// Return true if SUb can be reached from SUa following the chain edges.
1020static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
1022 SmallVector<SUnit *, 8> Worklist;
1023 Worklist.push_back(SUa);
1024 while (!Worklist.empty()) {
1025 const SUnit *SU = Worklist.pop_back_val();
1026 for (const auto &SI : SU->Succs) {
1027 SUnit *SuccSU = SI.getSUnit();
1028 if (SI.getKind() == SDep::Order) {
1029 if (Visited.count(SuccSU))
1030 continue;
1031 if (SuccSU == SUb)
1032 return true;
1033 Worklist.push_back(SuccSU);
1034 Visited.insert(SuccSU);
1035 }
1036 }
1037 }
1038 return false;
1039}
1040
1042 if (!getUnderlyingObjects())
1043 return;
1044 for (const Value *Obj : UnderlyingObjs)
1045 if (!isIdentifiedObject(Obj)) {
1046 IsAllIdentified = false;
1047 break;
1048 }
1049}
1050
1052 const SUnitWithMemInfo &Other) const {
1053 // If all underlying objects are identified objects and there is no overlap
1054 // between them, then these two instructions are disjoint.
1055 if (!IsAllIdentified || !Other.IsAllIdentified)
1056 return false;
1057 for (const Value *Obj : UnderlyingObjs)
1058 if (llvm::is_contained(Other.UnderlyingObjs, Obj))
1059 return false;
1060 return true;
1061}
1062
1063/// Collect the underlying objects for the memory references of an instruction.
1064/// This function calls the code in ValueTracking, but first checks that the
1065/// instruction has a memory operand.
1066/// Returns false if we cannot find the underlying objects.
1067bool SUnitWithMemInfo::getUnderlyingObjects() {
1068 const MachineInstr *MI = SU->getInstr();
1069 if (!MI->hasOneMemOperand())
1070 return false;
1071 MachineMemOperand *MM = *MI->memoperands_begin();
1072 if (!MM->getValue())
1073 return false;
1074 MemOpValue = MM->getValue();
1075 MemOpOffset = MM->getOffset();
1077
1078 // TODO: A no alias scope may be valid only in a single iteration. In this
1079 // case we need to peel off it like LoopAccessAnalysis does.
1080 AATags = MM->getAAInfo();
1081 return true;
1082}
1083
1084/// Returns true if there is a loop-carried order dependency from \p Src to \p
1085/// Dst.
1086static bool hasLoopCarriedMemDep(const SUnitWithMemInfo &Src,
1087 const SUnitWithMemInfo &Dst,
1088 BatchAAResults &BAA,
1089 const TargetInstrInfo *TII) {
1090 if (Src.isTriviallyDisjoint(Dst))
1091 return false;
1092 if (isSuccOrder(Src.SU, Dst.SU))
1093 return false;
1094
1095 MachineInstr &SrcMI = *Src.SU->getInstr();
1096 MachineInstr &DstMI = *Dst.SU->getInstr();
1097
1098 const MachineBasicBlock *LoopBB = SrcMI.getParent();
1099 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
1100 if (!mayOverlapInLaterIter(&SrcMI, &DstMI, LoopBB, MRI, *TII))
1101 return false;
1102
1103 // Second, the more expensive check that uses alias analysis on the
1104 // base registers. If they alias, and the load offset is less than
1105 // the store offset, the mark the dependence as loop carried.
1106 if (Src.isUnknown() || Dst.isUnknown())
1107 return true;
1108 if (Src.MemOpValue == Dst.MemOpValue && Src.MemOpOffset <= Dst.MemOpOffset)
1109 return true;
1110
1111 if (BAA.isNoAlias(
1112 MemoryLocation::getBeforeOrAfter(Src.MemOpValue, Src.AATags),
1113 MemoryLocation::getBeforeOrAfter(Dst.MemOpValue, Dst.AATags)))
1114 return false;
1115
1116 // AliasAnalysis sometimes gives up on following the underlying
1117 // object. In such a case, separate checks for underlying objects may
1118 // prove that there are no aliases between two accesses.
1119 for (const Value *SrcObj : Src.UnderlyingObjs)
1120 for (const Value *DstObj : Dst.UnderlyingObjs)
1121 if (!BAA.isNoAlias(MemoryLocation::getBeforeOrAfter(SrcObj, Src.AATags),
1122 MemoryLocation::getBeforeOrAfter(DstObj, Dst.AATags)))
1123 return true;
1124
1125 return false;
1126}
1127
1128void LoopCarriedOrderDepsTracker::NoBarrierInstsChunk::append(SUnit *SU) {
1129 const MachineInstr *MI = SU->getInstr();
1130 if (MI->mayStore())
1131 Stores.emplace_back(SU);
1132 else if (MI->mayLoad())
1133 Loads.emplace_back(SU);
1134 else if (MI->mayRaiseFPException())
1135 FPExceptions.emplace_back(SU);
1136 else
1137 llvm_unreachable("Unexpected instruction type.");
1138}
1139
1141 SwingSchedulerDAG *SSD, BatchAAResults *BAA, const TargetInstrInfo *TII)
1142 : DAG(SSD), BAA(BAA), SUnits(DAG->SUnits), N(SUnits.size()),
1143 LoopCarried(N, BitVector(N)), TII(TII) {}
1144
1146 // Traverse all instructions and extract only what we are targetting.
1147 for (auto &SU : SUnits) {
1148 auto Tagged = getInstrTag(&SU);
1149
1150 // This instruction has no loop-carried order-dependencies.
1151 if (!Tagged)
1152 continue;
1153 TaggedSUnits.emplace_back(&SU, *Tagged);
1154 }
1155
1156 computeDependenciesAux();
1157}
1158
1159std::optional<LoopCarriedOrderDepsTracker::InstrTag>
1160LoopCarriedOrderDepsTracker::getInstrTag(SUnit *SU) const {
1161 MachineInstr *MI = SU->getInstr();
1162 if (TII->isGlobalMemoryObject(MI))
1163 return InstrTag::Barrier;
1164
1165 if (MI->mayStore() ||
1166 (MI->mayLoad() && !MI->isDereferenceableInvariantLoad()))
1167 return InstrTag::LoadOrStore;
1168
1169 if (MI->mayRaiseFPException())
1170 return InstrTag::FPExceptions;
1171
1172 return std::nullopt;
1173}
1174
1175void LoopCarriedOrderDepsTracker::addDependenciesBetweenSUs(
1176 const SUnitWithMemInfo &Src, const SUnitWithMemInfo &Dst) {
1177 // Avoid self-dependencies.
1178 if (Src.SU == Dst.SU)
1179 return;
1180
1181 if (hasLoopCarriedMemDep(Src, Dst, *BAA, TII))
1182 setLoopCarriedDep(Src.SU, Dst.SU);
1183}
1184
1185void LoopCarriedOrderDepsTracker::addLoopCarriedDepenenciesForChunks(
1186 const NoBarrierInstsChunk &From, const NoBarrierInstsChunk &To) {
1187 // Add load-to-store dependencies (WAR).
1188 for (const SUnitWithMemInfo &Src : From.Loads)
1189 for (const SUnitWithMemInfo &Dst : To.Stores)
1190 addDependenciesBetweenSUs(Src, Dst);
1191
1192 // Add store-to-load dependencies (RAW).
1193 for (const SUnitWithMemInfo &Src : From.Stores)
1194 for (const SUnitWithMemInfo &Dst : To.Loads)
1195 addDependenciesBetweenSUs(Src, Dst);
1196
1197 // Add store-to-store dependencies (WAW).
1198 for (const SUnitWithMemInfo &Src : From.Stores)
1199 for (const SUnitWithMemInfo &Dst : To.Stores)
1200 addDependenciesBetweenSUs(Src, Dst);
1201}
1202
1203void LoopCarriedOrderDepsTracker::computeDependenciesAux() {
1205 SUnit *FirstBarrier = nullptr;
1206 SUnit *LastBarrier = nullptr;
1207 for (const auto &TSU : TaggedSUnits) {
1208 InstrTag Tag = TSU.getTag();
1209 SUnit *SU = TSU.getPointer();
1210 switch (Tag) {
1211 case InstrTag::Barrier:
1212 if (!FirstBarrier)
1213 FirstBarrier = SU;
1214 LastBarrier = SU;
1215 Chunks.emplace_back();
1216 break;
1217 case InstrTag::LoadOrStore:
1218 case InstrTag::FPExceptions:
1219 Chunks.back().append(SU);
1220 break;
1221 }
1222 }
1223
1224 // Add dependencies between memory operations. If there are one or more
1225 // barrier events between two memory instructions, we don't add a
1226 // loop-carried dependence for them.
1227 for (const NoBarrierInstsChunk &Chunk : Chunks)
1228 addLoopCarriedDepenenciesForChunks(Chunk, Chunk);
1229
1230 // There is no barrier instruction between load/store/fp-exception
1231 // instructions in the same chunk. If there are one or more barrier
1232 // instructions, the instructions sequence is as follows:
1233 //
1234 // Loads/Stores/FPExceptions (Chunks.front())
1235 // Barrier (FirstBarrier)
1236 // Loads/Stores/FPExceptions
1237 // Barrier
1238 // ...
1239 // Loads/Stores/FPExceptions
1240 // Barrier (LastBarrier)
1241 // Loads/Stores/FPExceptions (Chunks.back())
1242 //
1243 // Since loads/stores/fp-exceptions must not be reordered across barrier
1244 // instructions, and the order of barrier instructions must be preserved, add
1245 // the following loop-carried dependences:
1246 //
1247 // Loads/Stores/FPExceptions (Chunks.front()) <-----+
1248 // +--> Barrier (FirstBarrier) <----------------------+ |
1249 // | Loads/Stores/FPExceptions | |
1250 // | Barrier | |
1251 // | ... | |
1252 // | Loads/Stores/FPExceptions | |
1253 // | Barrier (LastBarrier) ------------------------+--+
1254 // +--- Loads/Stores/FPExceptions (Chunks.back())
1255 //
1256 if (FirstBarrier) {
1257 assert(LastBarrier && "Both barriers should be set.");
1258
1259 // LastBarrier -> Loads/Stores/FPExceptions in Chunks.front()
1260 for (const SUnitWithMemInfo &Dst : Chunks.front().Loads)
1261 setLoopCarriedDep(LastBarrier, Dst.SU);
1262 for (const SUnitWithMemInfo &Dst : Chunks.front().Stores)
1263 setLoopCarriedDep(LastBarrier, Dst.SU);
1264 for (const SUnitWithMemInfo &Dst : Chunks.front().FPExceptions)
1265 setLoopCarriedDep(LastBarrier, Dst.SU);
1266
1267 // Loads/Stores/FPExceptions in Chunks.back() -> FirstBarrier
1268 for (const SUnitWithMemInfo &Src : Chunks.back().Loads)
1269 setLoopCarriedDep(Src.SU, FirstBarrier);
1270 for (const SUnitWithMemInfo &Src : Chunks.back().Stores)
1271 setLoopCarriedDep(Src.SU, FirstBarrier);
1272 for (const SUnitWithMemInfo &Src : Chunks.back().FPExceptions)
1273 setLoopCarriedDep(Src.SU, FirstBarrier);
1274
1275 // LastBarrier -> FirstBarrier (if they are different)
1276 if (FirstBarrier != LastBarrier)
1277 setLoopCarriedDep(LastBarrier, FirstBarrier);
1278 }
1279}
1280
1281/// Add a chain edge between a load and store if the store can be an
1282/// alias of the load on a subsequent iteration, i.e., a loop carried
1283/// dependence. This code is very similar to the code in ScheduleDAGInstrs
1284/// but that code doesn't create loop carried dependences.
1285/// TODO: Also compute output-dependencies.
1286LoopCarriedEdges SwingSchedulerDAG::addLoopCarriedDependences() {
1287 LoopCarriedEdges LCE;
1288
1289 // Add loop-carried order-dependencies
1290 LoopCarriedOrderDepsTracker LCODTracker(this, &BAA, TII);
1291 LCODTracker.computeDependencies();
1292 for (unsigned I = 0; I != SUnits.size(); I++)
1293 for (const int Succ : LCODTracker.getLoopCarried(I).set_bits())
1294 LCE.OrderDeps[&SUnits[I]].insert(&SUnits[Succ]);
1295
1296 LCE.modifySUnits(SUnits, TII);
1297 return LCE;
1298}
1299
1300/// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
1301/// processes dependences for PHIs. This function adds true dependences
1302/// from a PHI to a use, and a loop carried dependence from the use to the
1303/// PHI. The loop carried dependence is represented as an anti dependence
1304/// edge. This function also removes chain dependences between unrelated
1305/// PHIs.
1306void SwingSchedulerDAG::updatePhiDependences() {
1307 SmallVector<SDep, 4> RemoveDeps;
1308 const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
1309
1310 // Iterate over each DAG node.
1311 for (SUnit &I : SUnits) {
1312 RemoveDeps.clear();
1313 // Set to true if the instruction has an operand defined by a Phi.
1314 Register HasPhiUse;
1315 Register HasPhiDef;
1316 MachineInstr *MI = I.getInstr();
1317 // Iterate over each operand, and we process the definitions.
1318 for (const MachineOperand &MO : MI->operands()) {
1319 if (!MO.isReg())
1320 continue;
1321 Register Reg = MO.getReg();
1322 if (!Reg.isVirtual())
1323 continue;
1324
1325 if (MO.isDef()) {
1326 // If the register is used by a Phi, then create an anti dependence.
1328 UI = MRI.use_instr_begin(Reg),
1329 UE = MRI.use_instr_end();
1330 UI != UE; ++UI) {
1331 MachineInstr *UseMI = &*UI;
1332 SUnit *SU = getSUnit(UseMI);
1333 if (SU != nullptr && UseMI->isPHI()) {
1334 if (!MI->isPHI()) {
1335 SDep Dep(SU, SDep::Anti, Reg);
1336 Dep.setLatency(1);
1337 I.addPred(Dep);
1338 } else {
1339 HasPhiDef = Reg;
1340 // Add a chain edge to a dependent Phi that isn't an existing
1341 // predecessor.
1342
1343 // %3:intregs = PHI %21:intregs, %bb.6, %7:intregs, %bb.1 - SU0
1344 // %7:intregs = PHI %21:intregs, %bb.6, %13:intregs, %bb.1 - SU1
1345 // %27:intregs = A2_zxtb %3:intregs - SU2
1346 // %13:intregs = C2_muxri %45:predregs, 0, %46:intreg
1347 // If we have dependent phis, SU0 should be the successor of SU1
1348 // not the other way around. (it used to be SU1 is the successor
1349 // of SU0). In some cases, SU0 is scheduled earlier than SU1
1350 // resulting in bad IR as we do not have a value that can be used
1351 // by SU2.
1352
1353 if (SU->NodeNum < I.NodeNum && !SU->isPred(&I))
1354 SU->addPred(SDep(&I, SDep::Barrier));
1355 }
1356 }
1357 }
1358 } else if (MO.isUse()) {
1359 // If the register is defined by a Phi, then create a true dependence.
1360 MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
1361 if (DefMI == nullptr)
1362 continue;
1363 SUnit *SU = getSUnit(DefMI);
1364 if (SU != nullptr && DefMI->isPHI()) {
1365 if (!MI->isPHI()) {
1366 SDep Dep(SU, SDep::Data, Reg);
1367 Dep.setLatency(0);
1368 ST.adjustSchedDependency(SU, 0, &I, MO.getOperandNo(), Dep,
1369 &SchedModel);
1370 I.addPred(Dep);
1371 } else {
1372 HasPhiUse = Reg;
1373 // Add a chain edge to a dependent Phi that isn't an existing
1374 // predecessor.
1375 if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
1376 I.addPred(SDep(SU, SDep::Barrier));
1377 }
1378 }
1379 }
1380 }
1381 // Remove order dependences from an unrelated Phi.
1382 if (!Opts.pipeliner_prune_deps)
1383 continue;
1384 for (auto &PI : I.Preds) {
1385 MachineInstr *PMI = PI.getSUnit()->getInstr();
1386 if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1387 if (I.getInstr()->isPHI()) {
1388 if (PMI->getOperand(0).getReg() == HasPhiUse)
1389 continue;
1390 if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1391 continue;
1392 }
1393 RemoveDeps.push_back(PI);
1394 }
1395 }
1396 for (const SDep &D : RemoveDeps)
1397 I.removePred(D);
1398 }
1399}
1400
1401/// Iterate over each DAG node and see if we can change any dependences
1402/// in order to reduce the recurrence MII.
1403void SwingSchedulerDAG::changeDependences() {
1404 // See if an instruction can use a value from the previous iteration.
1405 // If so, we update the base and offset of the instruction and change
1406 // the dependences.
1407 for (SUnit &I : SUnits) {
1408 unsigned BasePos = 0, OffsetPos = 0;
1409 Register NewBase;
1410 int64_t NewOffset = 0;
1411 if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1412 NewOffset))
1413 continue;
1414
1415 // Get the MI and SUnit for the instruction that defines the original base.
1416 Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1417 MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1418 if (!DefMI)
1419 continue;
1420 SUnit *DefSU = getSUnit(DefMI);
1421 if (!DefSU)
1422 continue;
1423 // Get the MI and SUnit for the instruction that defins the new base.
1424 MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1425 if (!LastMI)
1426 continue;
1427 SUnit *LastSU = getSUnit(LastMI);
1428 if (!LastSU)
1429 continue;
1430
1431 if (Topo.IsReachable(&I, LastSU))
1432 continue;
1433
1434 // Remove the dependence. The value now depends on a prior iteration.
1436 for (const SDep &P : I.Preds)
1437 if (P.getSUnit() == DefSU)
1438 Deps.push_back(P);
1439 for (const SDep &D : Deps) {
1440 Topo.RemovePred(&I, D.getSUnit());
1441 I.removePred(D);
1442 }
1443 // Remove the chain dependence between the instructions.
1444 Deps.clear();
1445 for (auto &P : LastSU->Preds)
1446 if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1447 Deps.push_back(P);
1448 for (const SDep &D : Deps) {
1449 Topo.RemovePred(LastSU, D.getSUnit());
1450 LastSU->removePred(D);
1451 }
1452
1453 // Add a dependence between the new instruction and the instruction
1454 // that defines the new base.
1455 SDep Dep(&I, SDep::Anti, NewBase);
1456 Topo.AddPred(LastSU, &I);
1457 LastSU->addPred(Dep);
1458
1459 // Remember the base and offset information so that we can update the
1460 // instruction during code generation.
1461 InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1462 }
1463}
1464
1465/// Create an instruction stream that represents a single iteration and stage of
1466/// each instruction. This function differs from SMSchedule::finalizeSchedule in
1467/// that this doesn't have any side-effect to SwingSchedulerDAG. That is, this
1468/// function is an approximation of SMSchedule::finalizeSchedule with all
1469/// non-const operations removed.
1471 SMSchedule &Schedule,
1472 std::vector<MachineInstr *> &OrderedInsts,
1475
1476 // Move all instructions to the first stage from the later stages.
1477 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1478 ++Cycle) {
1479 for (int Stage = 0, LastStage = Schedule.getMaxStageCount();
1480 Stage <= LastStage; ++Stage) {
1481 for (SUnit *SU : llvm::reverse(Schedule.getInstructions(
1482 Cycle + Stage * Schedule.getInitiationInterval()))) {
1483 Instrs[Cycle].push_front(SU);
1484 }
1485 }
1486 }
1487
1488 for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
1489 ++Cycle) {
1490 std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
1491 CycleInstrs = Schedule.reorderInstructions(SSD, CycleInstrs);
1492 for (SUnit *SU : CycleInstrs) {
1493 MachineInstr *MI = SU->getInstr();
1494 OrderedInsts.push_back(MI);
1495 Stages[MI] = Schedule.stageScheduled(SU);
1496 }
1497 }
1498}
1499
1500namespace {
1501
1502// FuncUnitSorter - Comparison operator used to sort instructions by
1503// the number of functional unit choices.
1504struct FuncUnitSorter {
1505 const InstrItineraryData *InstrItins;
1506 const MCSubtargetInfo *STI;
1507 DenseMap<InstrStage::FuncUnits, unsigned> Resources;
1508
1509 FuncUnitSorter(const TargetSubtargetInfo &TSI)
1510 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
1511
1512 // Compute the number of functional unit alternatives needed
1513 // at each stage, and take the minimum value. We prioritize the
1514 // instructions by the least number of choices first.
1515 unsigned minFuncUnits(const MachineInstr *Inst,
1516 InstrStage::FuncUnits &F) const {
1517 unsigned SchedClass = Inst->getDesc().getSchedClass();
1518 unsigned min = UINT_MAX;
1519 if (InstrItins && !InstrItins->isEmpty()) {
1520 for (const InstrStage &IS :
1521 make_range(InstrItins->beginStage(SchedClass),
1522 InstrItins->endStage(SchedClass))) {
1523 InstrStage::FuncUnits funcUnits = IS.getUnits();
1524 unsigned numAlternatives = llvm::popcount(funcUnits);
1525 if (numAlternatives < min) {
1526 min = numAlternatives;
1527 F = funcUnits;
1528 }
1529 }
1530 return min;
1531 }
1532 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1533 const MCSchedClassDesc *SCDesc =
1534 STI->getSchedModel().getSchedClassDesc(SchedClass);
1535 if (!SCDesc->isValid())
1536 // No valid Schedule Class Desc for schedClass, should be
1537 // Pseudo/PostRAPseudo
1538 return min;
1539
1540 for (const MCWriteProcResEntry &PRE :
1541 make_range(STI->getWriteProcResBegin(SCDesc),
1542 STI->getWriteProcResEnd(SCDesc))) {
1543 if (!PRE.ReleaseAtCycle)
1544 continue;
1545 const MCProcResourceDesc *ProcResource =
1546 STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
1547 unsigned NumUnits = ProcResource->NumUnits;
1548 if (NumUnits < min) {
1549 min = NumUnits;
1550 F = PRE.ProcResourceIdx;
1551 }
1552 }
1553 return min;
1554 }
1555 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1556 }
1557
1558 // Compute the critical resources needed by the instruction. This
1559 // function records the functional units needed by instructions that
1560 // must use only one functional unit. We use this as a tie breaker
1561 // for computing the resource MII. The instructions that require
1562 // the same, highly used, functional unit have high priority.
1563 void calcCriticalResources(MachineInstr &MI) {
1564 unsigned SchedClass = MI.getDesc().getSchedClass();
1565 if (InstrItins && !InstrItins->isEmpty()) {
1566 for (const InstrStage &IS :
1567 make_range(InstrItins->beginStage(SchedClass),
1568 InstrItins->endStage(SchedClass))) {
1569 InstrStage::FuncUnits FuncUnits = IS.getUnits();
1570 if (llvm::popcount(FuncUnits) == 1)
1571 Resources[FuncUnits]++;
1572 }
1573 return;
1574 }
1575 if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1576 const MCSchedClassDesc *SCDesc =
1577 STI->getSchedModel().getSchedClassDesc(SchedClass);
1578 if (!SCDesc->isValid())
1579 // No valid Schedule Class Desc for schedClass, should be
1580 // Pseudo/PostRAPseudo
1581 return;
1582
1583 for (const MCWriteProcResEntry &PRE :
1584 make_range(STI->getWriteProcResBegin(SCDesc),
1585 STI->getWriteProcResEnd(SCDesc))) {
1586 if (!PRE.ReleaseAtCycle)
1587 continue;
1588 Resources[PRE.ProcResourceIdx]++;
1589 }
1590 return;
1591 }
1592 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1593 }
1594
1595 /// Return true if IS1 has less priority than IS2.
1596 bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1597 InstrStage::FuncUnits F1 = 0, F2 = 0;
1598 unsigned MFUs1 = minFuncUnits(IS1, F1);
1599 unsigned MFUs2 = minFuncUnits(IS2, F2);
1600 if (MFUs1 == MFUs2)
1601 return Resources.lookup(F1) < Resources.lookup(F2);
1602 return MFUs1 > MFUs2;
1603 }
1604};
1605
1606/// Calculate the maximum register pressure of the scheduled instructions stream
1607class HighRegisterPressureDetector {
1608 MachineBasicBlock *OrigMBB;
1609 const MachineRegisterInfo &MRI;
1610 const TargetRegisterInfo *TRI;
1611
1612 const unsigned PSetNum;
1613
1614 // Indexed by PSet ID
1615 // InitSetPressure takes into account the register pressure of live-in
1616 // registers. It's not depend on how the loop is scheduled, so it's enough to
1617 // calculate them once at the beginning.
1618 std::vector<unsigned> InitSetPressure;
1619
1620 // Indexed by PSet ID
1621 // Upper limit for each register pressure set
1622 std::vector<unsigned> PressureSetLimit;
1623
1624 DenseMap<MachineInstr *, RegisterOperands> ROMap;
1625
1626 using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallSet<VirtRegOrUnit, 4>>;
1627
1628public:
1629 using OrderedInstsTy = std::vector<MachineInstr *>;
1630 using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
1631
1632private:
1633 static void dumpRegisterPressures(const std::vector<unsigned> &Pressures) {
1634 if (Pressures.size() == 0) {
1635 dbgs() << "[]";
1636 } else {
1637 char Prefix = '[';
1638 for (unsigned P : Pressures) {
1639 dbgs() << Prefix << P;
1640 Prefix = ' ';
1641 }
1642 dbgs() << ']';
1643 }
1644 }
1645
1646 void dumpPSet(VirtRegOrUnit VRegOrUnit) const {
1647 dbgs() << "Reg=" << printVRegOrUnit(VRegOrUnit, TRI) << " PSet=";
1648 for (auto PSetIter = MRI.getPressureSets(VRegOrUnit); PSetIter.isValid();
1649 ++PSetIter) {
1650 dbgs() << *PSetIter << ' ';
1651 }
1652 dbgs() << '\n';
1653 }
1654
1655 void increaseRegisterPressure(std::vector<unsigned> &Pressure,
1656 VirtRegOrUnit VRegOrUnit) const {
1657 auto PSetIter = MRI.getPressureSets(VRegOrUnit);
1658 unsigned Weight = PSetIter.getWeight();
1659 for (; PSetIter.isValid(); ++PSetIter)
1660 Pressure[*PSetIter] += Weight;
1661 }
1662
1663 void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
1664 VirtRegOrUnit VRegOrUnit) const {
1665 auto PSetIter = MRI.getPressureSets(VRegOrUnit);
1666 unsigned Weight = PSetIter.getWeight();
1667 for (; PSetIter.isValid(); ++PSetIter) {
1668 auto &P = Pressure[*PSetIter];
1669 assert(P >= Weight &&
1670 "register pressure must be greater than or equal weight");
1671 P -= Weight;
1672 }
1673 }
1674
1675 /// Return true if \p VRegOrUnit is reserved one, for example, stack pointer
1676 bool isReservedRegUnit(VirtRegOrUnit VRegOrUnit) const {
1677 return !VRegOrUnit.isVirtualReg() &&
1678 MRI.isReservedRegUnit(VRegOrUnit.asMCRegUnit());
1679 }
1680
1681 bool isDefinedInThisLoop(VirtRegOrUnit VRegOrUnit) const {
1682 return VRegOrUnit.isVirtualReg() &&
1683 MRI.getDefBlock(VRegOrUnit.asVirtualReg()) == OrigMBB;
1684 }
1685
1686 // Search for live-in variables. They are factored into the register pressure
1687 // from the begining. Live-in variables used by every iteration should be
1688 // considered as alive throughout the loop. For example, the variable `c` in
1689 // following code. \code
1690 // int c = ...;
1691 // for (int i = 0; i < n; i++)
1692 // a[i] += b[i] + c;
1693 // \endcode
1694 void computeLiveIn() {
1695 SmallSet<VirtRegOrUnit, 8> Used;
1696 for (auto &MI : *OrigMBB) {
1697 if (MI.isDebugInstr())
1698 continue;
1699 for (auto &Use : ROMap[&MI].Uses) {
1700 VirtRegOrUnit Reg = Use.VRegOrUnit;
1701 // Ignore the variable that appears only on one side of phi instruction
1702 // because it's used only at the first iteration.
1703 if (MI.isPHI() && Reg.isVirtualReg() &&
1704 Reg.asVirtualReg() != getLoopPhiReg(MI, OrigMBB))
1705 continue;
1706 if (isReservedRegUnit(Reg))
1707 continue;
1708 if (isDefinedInThisLoop(Reg))
1709 continue;
1710 Used.insert(Reg);
1711 }
1712 }
1713
1714 for (auto LiveIn : Used)
1715 increaseRegisterPressure(InitSetPressure, LiveIn);
1716 }
1717
1718 // Calculate the upper limit of each pressure set
1719 void computePressureSetLimit(const RegisterClassInfo &RCI) {
1720 for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1721 PressureSetLimit[PSet] = RCI.getRegPressureSetLimit(PSet);
1722 }
1723
1724 // There are two patterns of last-use.
1725 // - by an instruction of the current iteration
1726 // - by a phi instruction of the next iteration (loop carried value)
1727 //
1728 // Furthermore, following two groups of instructions are executed
1729 // simultaneously
1730 // - next iteration's phi instructions in i-th stage
1731 // - current iteration's instructions in i+1-th stage
1732 //
1733 // This function calculates the last-use of each register while taking into
1734 // account the above two patterns.
1735 Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
1736 Instr2StageTy &Stages) const {
1737 // We treat virtual registers that are defined and used in this loop.
1738 // Following virtual register will be ignored
1739 // - live-in one
1740 // - defined but not used in the loop (potentially live-out)
1741 SmallSet<VirtRegOrUnit, 8> TargetRegs;
1742 const auto UpdateTargetRegs = [this, &TargetRegs](VirtRegOrUnit Reg) {
1743 if (isDefinedInThisLoop(Reg))
1744 TargetRegs.insert(Reg);
1745 };
1746 for (MachineInstr *MI : OrderedInsts) {
1747 if (MI->isPHI()) {
1748 Register Reg = getLoopPhiReg(*MI, OrigMBB);
1749 UpdateTargetRegs(VirtRegOrUnit(Reg));
1750 } else {
1751 for (auto &Use : ROMap.find(MI)->getSecond().Uses)
1752 UpdateTargetRegs(Use.VRegOrUnit);
1753 }
1754 }
1755
1756 const auto InstrScore = [&Stages](MachineInstr *MI) {
1757 return Stages[MI] + MI->isPHI();
1758 };
1759
1760 std::map<VirtRegOrUnit, MachineInstr *> LastUseMI;
1761 for (MachineInstr *MI : llvm::reverse(OrderedInsts)) {
1762 for (auto &Use : ROMap.find(MI)->getSecond().Uses) {
1763 VirtRegOrUnit Reg = Use.VRegOrUnit;
1764 if (!TargetRegs.contains(Reg))
1765 continue;
1766 auto [Ite, Inserted] = LastUseMI.try_emplace(Reg, MI);
1767 if (!Inserted) {
1768 MachineInstr *Orig = Ite->second;
1769 MachineInstr *New = MI;
1770 if (InstrScore(Orig) < InstrScore(New))
1771 Ite->second = New;
1772 }
1773 }
1774 }
1775
1776 Instr2LastUsesTy LastUses;
1777 for (auto [Reg, MI] : LastUseMI)
1778 LastUses[MI].insert(Reg);
1779 return LastUses;
1780 }
1781
1782 // Compute the maximum register pressure of the kernel. We'll simulate #Stage
1783 // iterations and check the register pressure at the point where all stages
1784 // overlapping.
1785 //
1786 // An example of unrolled loop where #Stage is 4..
1787 // Iter i+0 i+1 i+2 i+3
1788 // ------------------------
1789 // Stage 0
1790 // Stage 1 0
1791 // Stage 2 1 0
1792 // Stage 3 2 1 0 <- All stages overlap
1793 //
1794 std::vector<unsigned>
1795 computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
1796 Instr2StageTy &Stages,
1797 const unsigned StageCount) const {
1798 using RegSetTy = SmallSet<VirtRegOrUnit, 16>;
1799
1800 // Indexed by #Iter. To treat "local" variables of each stage separately, we
1801 // manage the liveness of the registers independently by iterations.
1802 SmallVector<RegSetTy> LiveRegSets(StageCount);
1803
1804 auto CurSetPressure = InitSetPressure;
1805 auto MaxSetPressure = InitSetPressure;
1806 auto LastUses = computeLastUses(OrderedInsts, Stages);
1807
1808 LLVM_DEBUG({
1809 dbgs() << "Ordered instructions:\n";
1810 for (MachineInstr *MI : OrderedInsts) {
1811 dbgs() << "Stage " << Stages[MI] << ": ";
1812 MI->dump();
1813 }
1814 });
1815
1816 const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
1817 VirtRegOrUnit Reg) {
1818 if (isReservedRegUnit(Reg))
1819 return;
1820
1821 bool Inserted = RegSet.insert(Reg).second;
1822 if (!Inserted)
1823 return;
1824
1825 LLVM_DEBUG(dbgs() << "insert " << printVRegOrUnit(Reg, TRI) << "\n");
1826 increaseRegisterPressure(CurSetPressure, Reg);
1827 LLVM_DEBUG(dumpPSet(Reg));
1828 };
1829
1830 const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
1831 VirtRegOrUnit Reg) {
1832 if (isReservedRegUnit(Reg))
1833 return;
1834
1835 // live-in register
1836 if (!RegSet.contains(Reg))
1837 return;
1838
1839 LLVM_DEBUG(dbgs() << "erase " << printVRegOrUnit(Reg, TRI) << "\n");
1840 RegSet.erase(Reg);
1841 decreaseRegisterPressure(CurSetPressure, Reg);
1842 LLVM_DEBUG(dumpPSet(Reg));
1843 };
1844
1845 for (unsigned I = 0; I < StageCount; I++) {
1846 for (MachineInstr *MI : OrderedInsts) {
1847 const auto Stage = Stages[MI];
1848 if (I < Stage)
1849 continue;
1850
1851 const unsigned Iter = I - Stage;
1852
1853 for (auto &Def : ROMap.find(MI)->getSecond().Defs)
1854 InsertReg(LiveRegSets[Iter], Def.VRegOrUnit);
1855
1856 for (auto LastUse : LastUses[MI]) {
1857 if (MI->isPHI()) {
1858 if (Iter != 0)
1859 EraseReg(LiveRegSets[Iter - 1], LastUse);
1860 } else {
1861 EraseReg(LiveRegSets[Iter], LastUse);
1862 }
1863 }
1864
1865 for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1866 MaxSetPressure[PSet] =
1867 std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
1868
1869 LLVM_DEBUG({
1870 dbgs() << "CurSetPressure=";
1871 dumpRegisterPressures(CurSetPressure);
1872 dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
1873 MI->dump();
1874 });
1875 }
1876 }
1877
1878 return MaxSetPressure;
1879 }
1880
1881public:
1882 HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
1883 const MachineFunction &MF)
1884 : OrigMBB(OrigMBB), MRI(MF.getRegInfo()),
1885 TRI(MF.getSubtarget().getRegisterInfo()),
1886 PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
1887 PressureSetLimit(PSetNum, 0) {}
1888
1889 // Used to calculate register pressure, which is independent of loop
1890 // scheduling.
1891 void init(const RegisterClassInfo &RCI) {
1892 for (MachineInstr &MI : *OrigMBB) {
1893 if (MI.isDebugInstr())
1894 continue;
1895 ROMap[&MI].collect(MI, *TRI, MRI, false, true);
1896 }
1897
1898 computeLiveIn();
1899 computePressureSetLimit(RCI);
1900 }
1901
1902 // Calculate the maximum register pressures of the loop and check if they
1903 // exceed the limit
1904 bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
1905 const unsigned MaxStage) const {
1906 const int RegPressureMargin = SSD->Opts.pipeliner_register_pressure_margin;
1907 assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
1908 "the percentage of the margin must be between 0 to 100");
1909
1910 OrderedInstsTy OrderedInsts;
1911 Instr2StageTy Stages;
1912 computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
1913 const auto MaxSetPressure =
1914 computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
1915
1916 LLVM_DEBUG({
1917 dbgs() << "Dump MaxSetPressure:\n";
1918 for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
1919 dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
1920 }
1921 dbgs() << '\n';
1922 });
1923
1924 for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
1925 unsigned Limit = PressureSetLimit[PSet];
1926 unsigned Margin = Limit * RegPressureMargin / 100;
1927 LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
1928 << " Margin=" << Margin << "\n");
1929 if (Limit < MaxSetPressure[PSet] + Margin) {
1930 LLVM_DEBUG(
1931 dbgs()
1932 << "Rejected the schedule because of too high register pressure\n");
1933 return true;
1934 }
1935 }
1936 return false;
1937 }
1938};
1939
1940} // end anonymous namespace
1941
1942/// Calculate the resource constrained minimum initiation interval for the
1943/// specified loop. We use the DFA to model the resources needed for
1944/// each instruction, and we ignore dependences. A different DFA is created
1945/// for each cycle that is required. When adding a new instruction, we attempt
1946/// to add it to each existing DFA, until a legal space is found. If the
1947/// instruction cannot be reserved in an existing DFA, we create a new one.
1948unsigned SwingSchedulerDAG::calculateResMII() {
1949 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1950 ResourceManager RM(&MF.getSubtarget(), this);
1951 return RM.calculateResMII();
1952}
1953
1954/// Calculate the recurrence-constrainted minimum initiation interval.
1955/// Iterate over each circuit. Compute the delay(c) and distance(c)
1956/// for each circuit. The II needs to satisfy the inequality
1957/// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1958/// II that satisfies the inequality, and the RecMII is the maximum
1959/// of those values.
1960unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1961 unsigned RecMII = 0;
1962
1963 for (NodeSet &Nodes : NodeSets) {
1964 if (Nodes.empty())
1965 continue;
1966
1967 unsigned Delay = Nodes.getLatency();
1968 unsigned Distance = 1;
1969
1970 // ii = ceil(delay / distance)
1971 unsigned CurMII = (Delay + Distance - 1) / Distance;
1972 Nodes.setRecMII(CurMII);
1973 if (CurMII > RecMII)
1974 RecMII = CurMII;
1975 }
1976
1977 return RecMII;
1978}
1979
1980/// Create the adjacency structure of the nodes in the graph.
1981void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1982 SwingSchedulerDDG *DDG) {
1983 BitVector Added(SUnits.size());
1984 DenseMap<int, int> OutputDeps;
1985 for (int i = 0, e = SUnits.size(); i != e; ++i) {
1986 Added.reset();
1987 // Add any successor to the adjacency matrix and exclude duplicates.
1988 for (auto &OE : DDG->getOutEdges(&SUnits[i])) {
1989 // Only create a back-edge on the first and last nodes of a dependence
1990 // chain. This records any chains and adds them later.
1991 if (OE.isOutputDep()) {
1992 int N = OE.getDst()->NodeNum;
1993 int BackEdge = i;
1994 auto Dep = OutputDeps.find(BackEdge);
1995 if (Dep != OutputDeps.end()) {
1996 BackEdge = Dep->second;
1997 OutputDeps.erase(Dep);
1998 }
1999 OutputDeps[N] = BackEdge;
2000 }
2001 // Do not process a boundary node, an artificial node.
2002 if (OE.getDst()->isBoundaryNode() || OE.isArtificial())
2003 continue;
2004
2005 // This code is retained o preserve previous behavior and prevent
2006 // regression. This condition means that anti-dependnecies within an
2007 // iteration are ignored when searching circuits. Therefore it's natural
2008 // to consider this dependence as well.
2009 // FIXME: Remove this code if it doesn't have significant impact on
2010 // performance.
2011 if (OE.isAntiDep())
2012 continue;
2013
2014 int N = OE.getDst()->NodeNum;
2015 if (!Added.test(N)) {
2016 AdjK[i].push_back(N);
2017 Added.set(N);
2018 }
2019 }
2020
2021 // Also add any extra out edges to the adjacency matrix.
2022 for (const SUnit *Dst : DDG->getExtraOutEdges(&SUnits[i])) {
2023 int N = Dst->NodeNum;
2024 if (!Added.test(N)) {
2025 AdjK[i].push_back(N);
2026 Added.set(N);
2027 }
2028 }
2029 }
2030
2031 // Add back-edges in the adjacency matrix for the output dependences.
2032 for (auto &OD : OutputDeps)
2033 if (!Added.test(OD.second)) {
2034 AdjK[OD.first].push_back(OD.second);
2035 Added.set(OD.second);
2036 }
2037}
2038
2039/// Identify an elementary circuit in the dependence graph starting at the
2040/// specified node.
2041bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
2042 const SwingSchedulerDAG *DAG,
2043 bool HasBackedge) {
2044 SUnit *SV = &SUnits[V];
2045 bool F = false;
2046 Stack.insert(SV);
2047 Blocked.set(V);
2048
2049 for (auto W : AdjK[V]) {
2050 if (NumPaths > MaxPaths)
2051 break;
2052 if (W < S)
2053 continue;
2054 if (W == S) {
2055 if (!HasBackedge)
2056 NodeSets.push_back(NodeSet(Stack.begin(), Stack.end(), DAG));
2057 F = true;
2058 ++NumPaths;
2059 break;
2060 }
2061 if (!Blocked.test(W)) {
2062 if (circuit(W, S, NodeSets, DAG,
2063 Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
2064 F = true;
2065 }
2066 }
2067
2068 if (F)
2069 unblock(V);
2070 else {
2071 for (auto W : AdjK[V]) {
2072 if (W < S)
2073 continue;
2074 B[W].insert(SV);
2075 }
2076 }
2077 Stack.pop_back();
2078 return F;
2079}
2080
2081/// Unblock a node in the circuit finding algorithm.
2082void SwingSchedulerDAG::Circuits::unblock(int U) {
2083 Blocked.reset(U);
2084 SmallPtrSet<SUnit *, 4> &BU = B[U];
2085 while (!BU.empty()) {
2086 SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
2087 assert(SI != BU.end() && "Invalid B set.");
2088 SUnit *W = *SI;
2089 BU.erase(W);
2090 if (Blocked.test(W->NodeNum))
2091 unblock(W->NodeNum);
2092 }
2093}
2094
2095/// Identify all the elementary circuits in the dependence graph using
2096/// Johnson's circuit algorithm.
2097void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
2098 Circuits Cir(SUnits, Topo);
2099 // Create the adjacency structure.
2100 Cir.createAdjacencyStructure(&*DDG);
2101 for (int I = 0, E = SUnits.size(); I != E; ++I) {
2102 Cir.reset();
2103 Cir.circuit(I, I, NodeSets, this);
2104 }
2105}
2106
2107// Create artificial dependencies between the source of COPY/REG_SEQUENCE that
2108// is loop-carried to the USE in next iteration. This will help pipeliner avoid
2109// additional copies that are needed across iterations. An artificial dependence
2110// edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
2111
2112// PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
2113// SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
2114// PHI-------True-Dep------> USEOfPhi
2115
2116// The mutation creates
2117// USEOfPHI -------Artificial-Dep---> SRCOfCopy
2118
2119// This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
2120// (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
2121// late to avoid additional copies across iterations. The possible scheduling
2122// order would be
2123// USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
2124
2125void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
2126 for (SUnit &SU : DAG->SUnits) {
2127 // Find the COPY/REG_SEQUENCE instruction.
2128 if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
2129 continue;
2130
2131 // Record the loop carried PHIs.
2133 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
2135
2136 for (auto &Dep : SU.Preds) {
2137 SUnit *TmpSU = Dep.getSUnit();
2138 MachineInstr *TmpMI = TmpSU->getInstr();
2139 SDep::Kind DepKind = Dep.getKind();
2140 // Save the loop carried PHI.
2141 if (DepKind == SDep::Anti && TmpMI->isPHI())
2142 PHISUs.push_back(TmpSU);
2143 // Save the source of COPY/REG_SEQUENCE.
2144 // If the source has no pre-decessors, we will end up creating cycles.
2145 else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
2146 SrcSUs.push_back(TmpSU);
2147 }
2148
2149 if (PHISUs.size() == 0 || SrcSUs.size() == 0)
2150 continue;
2151
2152 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
2153 // SUnit to the container.
2155 // Do not use iterator based loop here as we are updating the container.
2156 for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
2157 for (auto &Dep : PHISUs[Index]->Succs) {
2158 if (Dep.getKind() != SDep::Data)
2159 continue;
2160
2161 SUnit *TmpSU = Dep.getSUnit();
2162 MachineInstr *TmpMI = TmpSU->getInstr();
2163 if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
2164 PHISUs.push_back(TmpSU);
2165 continue;
2166 }
2167 UseSUs.push_back(TmpSU);
2168 }
2169 }
2170
2171 if (UseSUs.size() == 0)
2172 continue;
2173
2174 SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
2175 // Add the artificial dependencies if it does not form a cycle.
2176 for (auto *I : UseSUs) {
2177 for (auto *Src : SrcSUs) {
2178 if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
2179 Src->addPred(SDep(I, SDep::Artificial));
2180 SDAG->Topo.AddPred(Src, I);
2181 }
2182 }
2183 }
2184 }
2185}
2186
2187/// Compute several functions need to order the nodes for scheduling.
2188/// ASAP - Earliest time to schedule a node.
2189/// ALAP - Latest time to schedule a node.
2190/// MOV - Mobility function, difference between ALAP and ASAP.
2191/// D - Depth of each node.
2192/// H - Height of each node.
2193void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
2194 ScheduleInfo.resize(SUnits.size());
2195
2196 LLVM_DEBUG({
2197 for (int I : Topo) {
2198 const SUnit &SU = SUnits[I];
2199 dumpNode(SU);
2200 }
2201 });
2202
2203 int maxASAP = 0;
2204 // Compute ASAP and ZeroLatencyDepth.
2205 for (int I : Topo) {
2206 int asap = 0;
2207 int zeroLatencyDepth = 0;
2208 SUnit *SU = &SUnits[I];
2209 for (const auto &IE : DDG->getInEdges(SU)) {
2210 SUnit *Pred = IE.getSrc();
2211 if (IE.getLatency() == 0)
2212 zeroLatencyDepth =
2213 std::max(zeroLatencyDepth, getZeroLatencyDepth(Pred) + 1);
2214 if (IE.ignoreDependence(true))
2215 continue;
2216 asap = std::max(asap, (int)(getASAP(Pred) + IE.getLatency() -
2217 IE.getDistance() * MII));
2218 }
2219 maxASAP = std::max(maxASAP, asap);
2220 ScheduleInfo[I].ASAP = asap;
2221 ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
2222 }
2223
2224 // Compute ALAP, ZeroLatencyHeight, and MOV.
2225 for (int I : llvm::reverse(Topo)) {
2226 int alap = maxASAP;
2227 int zeroLatencyHeight = 0;
2228 SUnit *SU = &SUnits[I];
2229 for (const auto &OE : DDG->getOutEdges(SU)) {
2230 SUnit *Succ = OE.getDst();
2231 if (Succ->isBoundaryNode())
2232 continue;
2233 if (OE.getLatency() == 0)
2234 zeroLatencyHeight =
2235 std::max(zeroLatencyHeight, getZeroLatencyHeight(Succ) + 1);
2236 if (OE.ignoreDependence(true))
2237 continue;
2238 alap = std::min(alap, (int)(getALAP(Succ) - OE.getLatency() +
2239 OE.getDistance() * MII));
2240 }
2241
2242 ScheduleInfo[I].ALAP = alap;
2243 ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
2244 }
2245
2246 // After computing the node functions, compute the summary for each node set.
2247 for (NodeSet &I : NodeSets)
2248 I.computeNodeSetInfo(this);
2249
2250 LLVM_DEBUG({
2251 for (unsigned i = 0; i < SUnits.size(); i++) {
2252 dbgs() << "\tNode " << i << ":\n";
2253 dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
2254 dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
2255 dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
2256 dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
2257 dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
2258 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
2259 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
2260 }
2261 });
2262}
2263
2264/// Compute the Pred_L(O) set, as defined in the paper. The set is defined
2265/// as the predecessors of the elements of NodeOrder that are not also in
2266/// NodeOrder.
2269 const NodeSet *S = nullptr) {
2270 Preds.clear();
2271
2272 for (SUnit *SU : NodeOrder) {
2273 for (const auto &IE : DDG->getInEdges(SU)) {
2274 SUnit *PredSU = IE.getSrc();
2275 if (S && S->count(PredSU) == 0)
2276 continue;
2277 if (IE.ignoreDependence(true))
2278 continue;
2279 if (NodeOrder.count(PredSU) == 0)
2280 Preds.insert(PredSU);
2281 }
2282
2283 // FIXME: The following loop-carried dependencies may also need to be
2284 // considered.
2285 // - Physical register dependencies (true-dependence and WAW).
2286 // - Memory dependencies.
2287 for (const auto &OE : DDG->getOutEdges(SU)) {
2288 SUnit *SuccSU = OE.getDst();
2289 if (!OE.isAntiDep())
2290 continue;
2291 if (S && S->count(SuccSU) == 0)
2292 continue;
2293 if (NodeOrder.count(SuccSU) == 0)
2294 Preds.insert(SuccSU);
2295 }
2296 }
2297 return !Preds.empty();
2298}
2299
2300/// Compute the Succ_L(O) set, as defined in the paper. The set is defined
2301/// as the successors of the elements of NodeOrder that are not also in
2302/// NodeOrder.
2305 const NodeSet *S = nullptr) {
2306 Succs.clear();
2307
2308 for (SUnit *SU : NodeOrder) {
2309 for (const auto &OE : DDG->getOutEdges(SU)) {
2310 SUnit *SuccSU = OE.getDst();
2311 if (S && S->count(SuccSU) == 0)
2312 continue;
2313 if (OE.ignoreDependence(false))
2314 continue;
2315 if (NodeOrder.count(SuccSU) == 0)
2316 Succs.insert(SuccSU);
2317 }
2318
2319 // FIXME: The following loop-carried dependencies may also need to be
2320 // considered.
2321 // - Physical register dependnecies (true-dependnece and WAW).
2322 // - Memory dependencies.
2323 for (const auto &IE : DDG->getInEdges(SU)) {
2324 SUnit *PredSU = IE.getSrc();
2325 if (!IE.isAntiDep())
2326 continue;
2327 if (S && S->count(PredSU) == 0)
2328 continue;
2329 if (NodeOrder.count(PredSU) == 0)
2330 Succs.insert(PredSU);
2331 }
2332 }
2333 return !Succs.empty();
2334}
2335
2336/// Return true if there is a path from the specified node to any of the nodes
2337/// in DestNodes. Keep track and return the nodes in any path.
2338static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
2339 SetVector<SUnit *> &DestNodes,
2340 SetVector<SUnit *> &Exclude,
2341 SmallPtrSet<SUnit *, 8> &Visited,
2342 SwingSchedulerDDG *DDG) {
2343 if (Cur->isBoundaryNode())
2344 return false;
2345 if (Exclude.contains(Cur))
2346 return false;
2347 if (DestNodes.contains(Cur))
2348 return true;
2349 if (!Visited.insert(Cur).second)
2350 return Path.contains(Cur);
2351 bool FoundPath = false;
2352 for (const auto &OE : DDG->getOutEdges(Cur))
2353 if (!OE.ignoreDependence(false))
2354 FoundPath |=
2355 computePath(OE.getDst(), Path, DestNodes, Exclude, Visited, DDG);
2356 for (const auto &IE : DDG->getInEdges(Cur))
2357 if (IE.isAntiDep() && IE.getDistance() == 0)
2358 FoundPath |=
2359 computePath(IE.getSrc(), Path, DestNodes, Exclude, Visited, DDG);
2360 if (FoundPath)
2361 Path.insert(Cur);
2362 return FoundPath;
2363}
2364
2365/// Compute the live-out registers for the instructions in a node-set.
2366/// The live-out registers are those that are defined in the node-set,
2367/// but not used. Except for use operands of Phis.
2369 NodeSet &NS) {
2374 for (SUnit *SU : NS) {
2375 const MachineInstr *MI = SU->getInstr();
2376 if (MI->isPHI())
2377 continue;
2378 for (const MachineOperand &MO : MI->all_uses()) {
2379 Register Reg = MO.getReg();
2380 if (Reg.isVirtual())
2381 Uses.insert(VirtRegOrUnit(Reg));
2382 else if (MRI.isAllocatable(Reg))
2383 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2384 Uses.insert(VirtRegOrUnit(Unit));
2385 }
2386 }
2387 for (SUnit *SU : NS)
2388 for (const MachineOperand &MO : SU->getInstr()->all_defs())
2389 if (!MO.isDead()) {
2390 Register Reg = MO.getReg();
2391 if (Reg.isVirtual()) {
2392 if (!Uses.count(VirtRegOrUnit(Reg)))
2393 LiveOutRegs.emplace_back(VirtRegOrUnit(Reg),
2395 } else if (MRI.isAllocatable(Reg)) {
2396 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
2397 if (!Uses.count(VirtRegOrUnit(Unit)))
2398 LiveOutRegs.emplace_back(VirtRegOrUnit(Unit),
2400 }
2401 }
2402 RPTracker.addLiveRegs(LiveOutRegs);
2403}
2404
2405/// A heuristic to filter nodes in recurrent node-sets if the register
2406/// pressure of a set is too high.
2407void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2408 for (auto &NS : NodeSets) {
2409 // Skip small node-sets since they won't cause register pressure problems.
2410 if (NS.size() <= 2)
2411 continue;
2412 IntervalPressure RecRegPressure;
2413 RegPressureTracker RecRPTracker(RecRegPressure);
2414 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
2415 computeLiveOuts(MF, RecRPTracker, NS);
2416 RecRPTracker.closeBottom();
2417
2418 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2419 llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
2420 return A->NodeNum > B->NodeNum;
2421 });
2422
2423 for (auto &SU : SUnits) {
2424 // Since we're computing the register pressure for a subset of the
2425 // instructions in a block, we need to set the tracker for each
2426 // instruction in the node-set. The tracker is set to the instruction
2427 // just after the one we're interested in.
2429 RecRPTracker.setPos(std::next(CurInstI));
2430
2431 RegPressureDelta RPDelta;
2432 ArrayRef<PressureChange> CriticalPSets;
2433 RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
2434 CriticalPSets,
2435 RecRegPressure.MaxSetPressure);
2436 if (RPDelta.Excess.isValid()) {
2437 LLVM_DEBUG(
2438 dbgs() << "Excess register pressure: " << *SU << " "
2439 << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
2440 << ":" << RPDelta.Excess.getUnitInc() << "\n");
2441 NS.setExceedPressure(SU);
2442 break;
2443 }
2444 RecRPTracker.recede();
2445 }
2446 }
2447}
2448
2449/// A heuristic to colocate node sets that have the same set of
2450/// successors.
2451void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2452 unsigned Colocate = 0;
2453 for (int i = 0, e = NodeSets.size(); i < e; ++i) {
2454 NodeSet &N1 = NodeSets[i];
2455 SmallSetVector<SUnit *, 8> S1;
2456 if (N1.empty() || !succ_L(N1, S1, DDG.get()))
2457 continue;
2458 for (int j = i + 1; j < e; ++j) {
2459 NodeSet &N2 = NodeSets[j];
2460 if (N1.compareRecMII(N2) != 0)
2461 continue;
2462 SmallSetVector<SUnit *, 8> S2;
2463 if (N2.empty() || !succ_L(N2, S2, DDG.get()))
2464 continue;
2465 if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
2466 N1.setColocate(++Colocate);
2467 N2.setColocate(Colocate);
2468 break;
2469 }
2470 }
2471 }
2472}
2473
2474/// Check if the existing node-sets are profitable. If not, then ignore the
2475/// recurrent node-sets, and attempt to schedule all nodes together. This is
2476/// a heuristic. If the MII is large and all the recurrent node-sets are small,
2477/// then it's best to try to schedule all instructions together instead of
2478/// starting with the recurrent node-sets.
2479void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2480 // Look for loops with a large MII.
2481 if (MII < 17)
2482 return;
2483 // Check if the node-set contains only a simple add recurrence.
2484 for (auto &NS : NodeSets) {
2485 if (NS.getRecMII() > 2)
2486 return;
2487 if (NS.getMaxDepth() > MII)
2488 return;
2489 }
2490 NodeSets.clear();
2491 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
2492}
2493
2494/// Add the nodes that do not belong to a recurrence set into groups
2495/// based upon connected components.
2496void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2497 SetVector<SUnit *> NodesAdded;
2498 SmallPtrSet<SUnit *, 8> Visited;
2499 // Add the nodes that are on a path between the previous node sets and
2500 // the current node set.
2501 for (NodeSet &I : NodeSets) {
2502 SmallSetVector<SUnit *, 8> N;
2503 // Add the nodes from the current node set to the previous node set.
2504 if (succ_L(I, N, DDG.get())) {
2505 SetVector<SUnit *> Path;
2506 for (SUnit *NI : N) {
2507 Visited.clear();
2508 computePath(NI, Path, NodesAdded, I, Visited, DDG.get());
2509 }
2510 if (!Path.empty())
2511 I.insert(Path.begin(), Path.end());
2512 }
2513 // Add the nodes from the previous node set to the current node set.
2514 N.clear();
2515 if (succ_L(NodesAdded, N, DDG.get())) {
2516 SetVector<SUnit *> Path;
2517 for (SUnit *NI : N) {
2518 Visited.clear();
2519 computePath(NI, Path, I, NodesAdded, Visited, DDG.get());
2520 }
2521 if (!Path.empty())
2522 I.insert(Path.begin(), Path.end());
2523 }
2524 NodesAdded.insert_range(I);
2525 }
2526
2527 // Create a new node set with the connected nodes of any successor of a node
2528 // in a recurrent set.
2529 NodeSet NewSet;
2530 SmallSetVector<SUnit *, 8> N;
2531 if (succ_L(NodesAdded, N, DDG.get()))
2532 for (SUnit *I : N)
2533 addConnectedNodes(I, NewSet, NodesAdded);
2534 if (!NewSet.empty())
2535 NodeSets.push_back(NewSet);
2536
2537 // Create a new node set with the connected nodes of any predecessor of a node
2538 // in a recurrent set.
2539 NewSet.clear();
2540 if (pred_L(NodesAdded, N, DDG.get()))
2541 for (SUnit *I : N)
2542 addConnectedNodes(I, NewSet, NodesAdded);
2543 if (!NewSet.empty())
2544 NodeSets.push_back(NewSet);
2545
2546 // Create new nodes sets with the connected nodes any remaining node that
2547 // has no predecessor.
2548 for (SUnit &SU : SUnits) {
2549 if (NodesAdded.count(&SU) == 0) {
2550 NewSet.clear();
2551 addConnectedNodes(&SU, NewSet, NodesAdded);
2552 if (!NewSet.empty())
2553 NodeSets.push_back(NewSet);
2554 }
2555 }
2556}
2557
2558/// Add the node to the set, and add all of its connected nodes to the set.
2559void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2560 SetVector<SUnit *> &NodesAdded) {
2561 NewSet.insert(SU);
2562 NodesAdded.insert(SU);
2563 for (auto &OE : DDG->getOutEdges(SU)) {
2564 SUnit *Successor = OE.getDst();
2565 if (!OE.isArtificial() && !Successor->isBoundaryNode() &&
2566 NodesAdded.count(Successor) == 0)
2567 addConnectedNodes(Successor, NewSet, NodesAdded);
2568 }
2569 for (auto &IE : DDG->getInEdges(SU)) {
2570 SUnit *Predecessor = IE.getSrc();
2571 if (!IE.isArtificial() && NodesAdded.count(Predecessor) == 0)
2572 addConnectedNodes(Predecessor, NewSet, NodesAdded);
2573 }
2574}
2575
2576/// Return true if Set1 contains elements in Set2. The elements in common
2577/// are returned in a different container.
2578static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2580 Result.clear();
2581 for (SUnit *SU : Set1) {
2582 if (Set2.count(SU) != 0)
2583 Result.insert(SU);
2584 }
2585 return !Result.empty();
2586}
2587
2588/// Merge the recurrence node sets that have the same initial node.
2589void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2590 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2591 ++I) {
2592 NodeSet &NI = *I;
2593 for (NodeSetType::iterator J = I + 1; J != E;) {
2594 NodeSet &NJ = *J;
2595 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2596 if (NJ.compareRecMII(NI) > 0)
2597 NI.setRecMII(NJ.getRecMII());
2598 for (SUnit *SU : *J)
2599 I->insert(SU);
2600 NodeSets.erase(J);
2601 E = NodeSets.end();
2602 } else {
2603 ++J;
2604 }
2605 }
2606 }
2607}
2608
2609/// Remove nodes that have been scheduled in previous NodeSets.
2610void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2611 for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2612 ++I)
2613 for (NodeSetType::iterator J = I + 1; J != E;) {
2614 J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
2615
2616 if (J->empty()) {
2617 NodeSets.erase(J);
2618 E = NodeSets.end();
2619 } else {
2620 ++J;
2621 }
2622 }
2623}
2624
2625/// Compute an ordered list of the dependence graph nodes, which
2626/// indicates the order that the nodes will be scheduled. This is a
2627/// two-level algorithm. First, a partial order is created, which
2628/// consists of a list of sets ordered from highest to lowest priority.
2629void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2630 SmallSetVector<SUnit *, 8> R;
2631 NodeOrder.clear();
2632
2633 for (auto &Nodes : NodeSets) {
2634 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2635 OrderKind Order;
2636 SmallSetVector<SUnit *, 8> N;
2637 if (pred_L(NodeOrder, N, DDG.get()) && llvm::set_is_subset(N, Nodes)) {
2638 R.insert_range(N);
2639 Order = BottomUp;
2640 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
2641 } else if (succ_L(NodeOrder, N, DDG.get()) &&
2642 llvm::set_is_subset(N, Nodes)) {
2643 R.insert_range(N);
2644 Order = TopDown;
2645 LLVM_DEBUG(dbgs() << " Top down (succs) ");
2646 } else if (isIntersect(N, Nodes, R)) {
2647 // If some of the successors are in the existing node-set, then use the
2648 // top-down ordering.
2649 Order = TopDown;
2650 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
2651 } else if (NodeSets.size() == 1) {
2652 for (const auto &N : Nodes)
2653 if (N->Succs.size() == 0)
2654 R.insert(N);
2655 Order = BottomUp;
2656 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
2657 } else {
2658 // Find the node with the highest ASAP.
2659 SUnit *maxASAP = nullptr;
2660 for (SUnit *SU : Nodes) {
2661 if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
2662 (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2663 maxASAP = SU;
2664 }
2665 R.insert(maxASAP);
2666 Order = BottomUp;
2667 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
2668 }
2669
2670 while (!R.empty()) {
2671 if (Order == TopDown) {
2672 // Choose the node with the maximum height. If more than one, choose
2673 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2674 // choose the node with the lowest MOV.
2675 while (!R.empty()) {
2676 SUnit *maxHeight = nullptr;
2677 for (SUnit *I : R) {
2678 if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2679 maxHeight = I;
2680 else if (getHeight(I) == getHeight(maxHeight) &&
2681 getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
2682 maxHeight = I;
2683 else if (getHeight(I) == getHeight(maxHeight) &&
2684 getZeroLatencyHeight(I) ==
2685 getZeroLatencyHeight(maxHeight) &&
2686 getMOV(I) < getMOV(maxHeight))
2687 maxHeight = I;
2688 }
2689 NodeOrder.insert(maxHeight);
2690 LLVM_DEBUG(dbgs() << *maxHeight << " ");
2691 R.remove(maxHeight);
2692 for (const auto &OE : DDG->getOutEdges(maxHeight)) {
2693 SUnit *SU = OE.getDst();
2694 if (Nodes.count(SU) == 0)
2695 continue;
2696 if (NodeOrder.contains(SU))
2697 continue;
2698 if (OE.ignoreDependence(false))
2699 continue;
2700 R.insert(SU);
2701 }
2702
2703 // FIXME: The following loop-carried dependencies may also need to be
2704 // considered.
2705 // - Physical register dependnecies (true-dependnece and WAW).
2706 // - Memory dependencies.
2707 for (const auto &IE : DDG->getInEdges(maxHeight)) {
2708 SUnit *SU = IE.getSrc();
2709 if (!IE.isAntiDep())
2710 continue;
2711 if (Nodes.count(SU) == 0)
2712 continue;
2713 if (NodeOrder.contains(SU))
2714 continue;
2715 R.insert(SU);
2716 }
2717 }
2718 Order = BottomUp;
2719 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
2720 SmallSetVector<SUnit *, 8> N;
2721 if (pred_L(NodeOrder, N, DDG.get(), &Nodes))
2722 R.insert_range(N);
2723 } else {
2724 // Choose the node with the maximum depth. If more than one, choose
2725 // the node with the maximum ZeroLatencyDepth. If still more than one,
2726 // choose the node with the lowest MOV.
2727 while (!R.empty()) {
2728 SUnit *maxDepth = nullptr;
2729 for (SUnit *I : R) {
2730 if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2731 maxDepth = I;
2732 else if (getDepth(I) == getDepth(maxDepth) &&
2733 getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
2734 maxDepth = I;
2735 else if (getDepth(I) == getDepth(maxDepth) &&
2736 getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
2737 getMOV(I) < getMOV(maxDepth))
2738 maxDepth = I;
2739 }
2740 NodeOrder.insert(maxDepth);
2741 LLVM_DEBUG(dbgs() << *maxDepth << " ");
2742 R.remove(maxDepth);
2743 if (Nodes.isExceedSU(maxDepth)) {
2744 Order = TopDown;
2745 R.clear();
2746 R.insert(Nodes.getNode(0));
2747 break;
2748 }
2749 for (const auto &IE : DDG->getInEdges(maxDepth)) {
2750 SUnit *SU = IE.getSrc();
2751 if (Nodes.count(SU) == 0)
2752 continue;
2753 if (NodeOrder.contains(SU))
2754 continue;
2755 R.insert(SU);
2756 }
2757
2758 // FIXME: The following loop-carried dependencies may also need to be
2759 // considered.
2760 // - Physical register dependnecies (true-dependnece and WAW).
2761 // - Memory dependencies.
2762 for (const auto &OE : DDG->getOutEdges(maxDepth)) {
2763 SUnit *SU = OE.getDst();
2764 if (!OE.isAntiDep())
2765 continue;
2766 if (Nodes.count(SU) == 0)
2767 continue;
2768 if (NodeOrder.contains(SU))
2769 continue;
2770 R.insert(SU);
2771 }
2772 }
2773 Order = TopDown;
2774 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
2775 SmallSetVector<SUnit *, 8> N;
2776 if (succ_L(NodeOrder, N, DDG.get(), &Nodes))
2777 R.insert_range(N);
2778 }
2779 }
2780 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2781 }
2782
2783 LLVM_DEBUG({
2784 dbgs() << "Node order: ";
2785 for (SUnit *I : NodeOrder)
2786 dbgs() << " " << *I << " ";
2787 dbgs() << "\n";
2788 });
2789}
2790
2791/// Set the policy for this loop, allowing the target to override it.
2792void SwingSchedulerDAG::initPolicy() {
2794
2795 // After subtarget overrides, apply command line options.
2796 Policy.ShouldLimitRegPressure =
2797 valueOr(Opts.pipeliner_register_pressure, Policy.ShouldLimitRegPressure);
2798}
2799
2800/// Process the nodes in the computed order and create the pipelined schedule
2801/// of the instructions, if possible. Return true if a schedule is found.
2802bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2803
2804 if (NodeOrder.empty()){
2805 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2806 return false;
2807 }
2808
2809 bool scheduleFound = false;
2810 std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
2811 if (Policy.ShouldLimitRegPressure) {
2812 HRPDetector =
2813 std::make_unique<HighRegisterPressureDetector>(Loop.getHeader(), MF);
2814 HRPDetector->init(RegClassInfo);
2815 }
2816 // Keep increasing II until a valid schedule is found.
2817 for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2818 Schedule.reset();
2819 Schedule.setInitiationInterval(II);
2820 LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2821
2824 do {
2825 SUnit *SU = *NI;
2826
2827 // Compute the schedule time for the instruction, which is based
2828 // upon the scheduled time for any predecessors/successors.
2829 int EarlyStart = INT_MIN;
2830 int LateStart = INT_MAX;
2831 Schedule.computeStart(SU, &EarlyStart, &LateStart, II, this);
2832 LLVM_DEBUG({
2833 dbgs() << "\n";
2834 dbgs() << *SU << " ";
2835 SU->getInstr()->dump();
2836 dbgs() << "\n";
2837 });
2838 LLVM_DEBUG(
2839 dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2840
2841 if (EarlyStart > LateStart)
2842 scheduleFound = false;
2843 else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2844 scheduleFound =
2845 Schedule.insert(SU, EarlyStart, EarlyStart + (int)II - 1, II);
2846 else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2847 scheduleFound =
2848 Schedule.insert(SU, LateStart, LateStart - (int)II + 1, II);
2849 else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2850 LateStart = std::min(LateStart, EarlyStart + (int)II - 1);
2851 // When scheduling a Phi it is better to start at the late cycle and
2852 // go backwards. The default order may insert the Phi too far away
2853 // from its first dependence.
2854 // Also, do backward search when all scheduled predecessors are
2855 // loop-carried output/order dependencies. Empirically, there are also
2856 // cases where scheduling becomes possible with backward search.
2857 if (SU->getInstr()->isPHI() ||
2858 Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, this->getDDG()))
2859 scheduleFound = Schedule.insert(SU, LateStart, EarlyStart, II);
2860 else
2861 scheduleFound = Schedule.insert(SU, EarlyStart, LateStart, II);
2862 } else {
2863 int FirstCycle = Schedule.getFirstCycle();
2864 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2865 FirstCycle + getASAP(SU) + II - 1, II);
2866 }
2867
2868 // Even if we find a schedule, make sure the schedule doesn't exceed the
2869 // allowable number of stages. We keep trying if this happens.
2870 if (scheduleFound)
2871 if (Opts.pipeliner_max_stages > -1 &&
2872 Schedule.getMaxStageCount() > (unsigned)Opts.pipeliner_max_stages)
2873 scheduleFound = false;
2874
2875 LLVM_DEBUG({
2876 if (!scheduleFound)
2877 dbgs() << "\tCan't schedule\n";
2878 });
2879 } while (++NI != NE && scheduleFound);
2880
2881 // If a schedule is found, validate it against the validation-only
2882 // dependencies.
2883 if (scheduleFound)
2884 scheduleFound = DDG->isValidSchedule(Schedule);
2885
2886 // If a schedule is found, ensure non-pipelined instructions are in stage 0
2887 if (scheduleFound)
2888 scheduleFound =
2889 Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2890
2891 // If a schedule is found, check if it is a valid schedule too.
2892 if (scheduleFound)
2893 scheduleFound = Schedule.isValidSchedule(this);
2894
2895 // If a schedule was found and the detector is enabled, check if the
2896 // schedule might generate additional register spills/fills.
2897 if (scheduleFound && HRPDetector)
2898 scheduleFound =
2899 !HRPDetector->detect(this, Schedule, Schedule.getMaxStageCount());
2900 }
2901
2902 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2903 << " (II=" << Schedule.getInitiationInterval()
2904 << ")\n");
2905
2906 if (scheduleFound) {
2907 scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*this, Schedule);
2908 if (!scheduleFound)
2909 LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2910 }
2911
2912 if (scheduleFound) {
2913 Schedule.finalizeSchedule(this);
2914 ORE->emit([&]() {
2915 return MachineOptimizationRemarkAnalysis(
2916 DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2917 << "Schedule found with Initiation Interval: "
2918 << ore::NV("II", Schedule.getInitiationInterval())
2919 << ", MaxStageCount: "
2920 << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2921 });
2922 } else
2923 Schedule.reset();
2924
2925 return scheduleFound && Schedule.getMaxStageCount() > 0;
2926}
2927
2929 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2930 Register Result;
2931 for (const MachineOperand &Use : MI.all_uses()) {
2932 Register Reg = Use.getReg();
2933 if (!Reg.isVirtual())
2934 return Register();
2935 if (MRI.getDefBlock(Reg) != MI.getParent())
2936 continue;
2937 if (Result)
2938 return Register();
2939 Result = Reg;
2940 }
2941 return Result;
2942}
2943
2944/// When Op is a value that is incremented recursively in a loop and there is a
2945/// unique instruction that increments it, returns true and sets Value.
2947 const MachineOperand &Op, int &Value) {
2948 if (!Op.isReg() || !Op.getReg().isVirtual())
2949 return false;
2950
2951 Register OrgReg = Op.getReg();
2952 Register CurReg = OrgReg;
2953 const MachineBasicBlock *LoopBB = MI.getParent();
2954 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
2955
2956 const TargetInstrInfo *TII =
2957 LoopBB->getParent()->getSubtarget().getInstrInfo();
2958 MachineInstr *Phi = nullptr;
2959 MachineInstr *Increment = nullptr;
2960
2961 // Traverse definitions until it reaches Op or an instruction that does not
2962 // satisfy the condition.
2963 // Acceptable example:
2964 // bb.0:
2965 // %0 = PHI %3, %bb.0, ...
2966 // %2 = ADD %0, Value
2967 // ... = LOAD %2(Op)
2968 // %3 = COPY %2
2969 while (true) {
2970 if (!CurReg.isValid() || !CurReg.isVirtual())
2971 return false;
2972 MachineInstr *Def = MRI.getVRegDef(CurReg);
2973 if (!Def || Def->getParent() != LoopBB)
2974 return false;
2975
2976 if (Def->isCopy()) {
2977 // Ignore copy instructions unless they contain subregisters
2978 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
2979 return false;
2980 CurReg = Def->getOperand(1).getReg();
2981 } else if (Def->isPHI()) {
2982 // There must be just one Phi
2983 if (Phi)
2984 return false;
2985 Phi = Def;
2986 CurReg = getLoopPhiReg(*Def, LoopBB);
2987 } else if (TII->getIncrementValue(*Def, Value)) {
2988 // Potentially a unique increment
2989 if (Increment)
2990 // Multiple increments exist
2991 return false;
2992
2993 const MachineOperand *BaseOp;
2994 int64_t Offset;
2995 bool OffsetIsScalable;
2996 if (TII->getMemOperandWithOffset(*Def, BaseOp, Offset,
2997 OffsetIsScalable)) {
2998 // Pre/post increment instruction
2999 CurReg = BaseOp->getReg();
3000 } else {
3001 // If only one of the operands is defined within the loop, it is assumed
3002 // to be an incremented value.
3003 CurReg = findUniqueOperandDefinedInLoop(*Def);
3004 if (!CurReg.isValid())
3005 return false;
3006 }
3007 Increment = Def;
3008 } else {
3009 return false;
3010 }
3011 if (CurReg == OrgReg)
3012 break;
3013 }
3014
3015 if (!Phi || !Increment)
3016 return false;
3017
3018 return true;
3019}
3020
3021/// Return true if we can compute the amount the instruction changes
3022/// during each iteration. Set Delta to the amount of the change.
3024 int &Delta) {
3025 const MachineOperand *BaseOp;
3026 int64_t Offset;
3027 bool OffsetIsScalable;
3028 if (!TII.getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable))
3029 return false;
3030
3031 // FIXME: This algorithm assumes instructions have fixed-size offsets.
3032 if (OffsetIsScalable)
3033 return false;
3034
3035 if (!BaseOp->isReg())
3036 return false;
3037
3038 return findLoopIncrementValue(MI, *BaseOp, Delta);
3039}
3040
3041/// Check if we can change the instruction to use an offset value from the
3042/// previous iteration. If so, return true and set the base and offset values
3043/// so that we can rewrite the load, if necessary.
3044/// v1 = Phi(v0, v3)
3045/// v2 = load v1, 0
3046/// v3 = post_store v1, 4, x
3047/// This function enables the load to be rewritten as v2 = load v3, 4.
3048bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3049 unsigned &BasePos,
3050 unsigned &OffsetPos,
3051 Register &NewBase,
3052 int64_t &Offset) {
3053 // Get the load instruction.
3054 if (TII->isPostIncrement(*MI))
3055 return false;
3056 unsigned BasePosLd, OffsetPosLd;
3057 if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
3058 return false;
3059 Register BaseReg = MI->getOperand(BasePosLd).getReg();
3060
3061 // Look for the Phi instruction.
3062 MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
3063 MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3064 if (!Phi || !Phi->isPHI())
3065 return false;
3066 // Get the register defined in the loop block.
3067 Register PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3068 if (!PrevReg)
3069 return false;
3070
3071 // Check for the post-increment load/store instruction.
3072 MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3073 if (!PrevDef || PrevDef == MI)
3074 return false;
3075
3076 if (!TII->isPostIncrement(*PrevDef))
3077 return false;
3078
3079 unsigned BasePos1 = 0, OffsetPos1 = 0;
3080 if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3081 return false;
3082
3083 // Make sure that the instructions do not access the same memory location in
3084 // the next iteration.
3085 int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3086 int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
3087 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3088 NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
3089 bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
3090 MF.deleteMachineInstr(NewMI);
3091 if (!Disjoint)
3092 return false;
3093
3094 // Set the return value once we determine that we return true.
3095 BasePos = BasePosLd;
3096 OffsetPos = OffsetPosLd;
3097 NewBase = PrevReg;
3098 Offset = StoreOffset;
3099 return true;
3100}
3101
3102/// Apply changes to the instruction if needed. The changes are need
3103/// to improve the scheduling and depend up on the final schedule.
3105 SMSchedule &Schedule) {
3106 SUnit *SU = getSUnit(MI);
3108 InstrChanges.find(SU);
3109 if (It != InstrChanges.end()) {
3110 std::pair<Register, int64_t> RegAndOffset = It->second;
3111 unsigned BasePos, OffsetPos;
3112 if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3113 return;
3114 Register BaseReg = MI->getOperand(BasePos).getReg();
3115 MachineInstr *LoopDef = findDefInLoop(BaseReg);
3116 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3117 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3118 int BaseStageNum = Schedule.stageScheduled(SU);
3119 int BaseCycleNum = Schedule.cycleScheduled(SU);
3120 if (BaseStageNum < DefStageNum) {
3121 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3122 int OffsetDiff = DefStageNum - BaseStageNum;
3123 if (DefCycleNum < BaseCycleNum) {
3124 NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3125 if (OffsetDiff > 0)
3126 --OffsetDiff;
3127 }
3128 int64_t NewOffset =
3129 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3130 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3131 SU->setInstr(NewMI);
3132 MISUnitMap[NewMI] = SU;
3133 NewMIs[MI] = NewMI;
3134 }
3135 }
3136}
3137
3138/// Return the instruction in the loop that defines the register.
3139/// If the definition is a Phi, then follow the Phi operand to
3140/// the instruction in the loop.
3141MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
3143 MachineInstr *Def = MRI.getVRegDef(Reg);
3144 while (Def->isPHI()) {
3145 if (!Visited.insert(Def).second)
3146 break;
3147 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3148 if (Def->getOperand(i + 1).getMBB() == BB) {
3149 Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3150 break;
3151 }
3152 }
3153 return Def;
3154}
3155
3156/// Return false if there is no overlap between the region accessed by BaseMI in
3157/// an iteration and the region accessed by OtherMI in subsequent iterations.
3159 const MachineInstr *OtherMI,
3160 const MachineBasicBlock *LoopBB,
3161 const MachineRegisterInfo &MRI,
3162 const TargetInstrInfo &TII) {
3163 int DeltaB, DeltaO, Delta;
3164 if (!computeDelta(*BaseMI, TII, DeltaB) ||
3165 !computeDelta(*OtherMI, TII, DeltaO) || DeltaB != DeltaO)
3166 return true;
3167 Delta = DeltaB;
3168
3169 const MachineOperand *BaseOpB, *BaseOpO;
3170 int64_t OffsetB, OffsetO;
3171 bool OffsetBIsScalable, OffsetOIsScalable;
3172 if (!TII.getMemOperandWithOffset(*BaseMI, BaseOpB, OffsetB,
3173 OffsetBIsScalable) ||
3174 !TII.getMemOperandWithOffset(*OtherMI, BaseOpO, OffsetO,
3175 OffsetOIsScalable))
3176 return true;
3177
3178 if (OffsetBIsScalable || OffsetOIsScalable)
3179 return true;
3180
3181 if (!BaseOpB->isIdenticalTo(*BaseOpO)) {
3182 // Pass cases with different base operands but same initial values.
3183 // Typically for when pre/post increment is used.
3184
3185 if (!BaseOpB->isReg() || !BaseOpO->isReg())
3186 return true;
3187 Register RegB = BaseOpB->getReg(), RegO = BaseOpO->getReg();
3188 if (!RegB.isVirtual() || !RegO.isVirtual())
3189 return true;
3190
3191 MachineInstr *DefB = MRI.getVRegDef(RegB);
3192 MachineInstr *DefO = MRI.getVRegDef(RegO);
3193 if (!DefB || !DefO || !DefB->isPHI() || !DefO->isPHI())
3194 return true;
3195
3196 Register InitValB, LoopValB, InitValO, LoopValO;
3197 getPhiRegs(*DefB, LoopBB, InitValB, LoopValB);
3198 getPhiRegs(*DefO, LoopBB, InitValO, LoopValO);
3199 if (!InitValB.isValid() || !InitValO.isValid())
3200 return true;
3201 MachineInstr *InitDefB = MRI.getVRegDef(InitValB);
3202 MachineInstr *InitDefO = MRI.getVRegDef(InitValO);
3203 if (!InitDefB || !InitDefO || !InitDefB->isIdenticalTo(*InitDefO))
3204 return true;
3205 }
3206
3207 if (BaseMI->memoperands_empty() || OtherMI->memoperands_empty())
3208 return true;
3209 LocationSize AccessSizeB = (*BaseMI->memoperands_begin())->getSize();
3210 LocationSize AccessSizeO = (*OtherMI->memoperands_begin())->getSize();
3211
3212 // This is the main test, which checks the offset values and the loop
3213 // increment value to determine if the accesses may be loop carried.
3214 if (!AccessSizeB.hasValue() || !AccessSizeO.hasValue())
3215 return true;
3216
3217 LLVM_DEBUG({
3218 dbgs() << "Overlap check:\n";
3219 dbgs() << " BaseMI: ";
3220 BaseMI->dump();
3221 dbgs() << " Base + " << OffsetB << " + I * " << Delta
3222 << ", Len: " << AccessSizeB.getValue() << "\n";
3223 dbgs() << " OtherMI: ";
3224 OtherMI->dump();
3225 dbgs() << " Base + " << OffsetO << " + I * " << Delta
3226 << ", Len: " << AccessSizeO.getValue() << "\n";
3227 });
3228
3229 // Excessive overlap may be detected in strided patterns.
3230 // For example, the memory addresses of the store and the load in
3231 // for (i=0; i<n; i+=2) a[i+1] = a[i];
3232 // are assumed to overlap.
3233 if (Delta < 0) {
3234 int64_t BaseMinAddr = OffsetB;
3235 int64_t OhterNextIterMaxAddr = OffsetO + Delta + AccessSizeO.getValue() - 1;
3236 if (BaseMinAddr > OhterNextIterMaxAddr) {
3237 LLVM_DEBUG(dbgs() << " Result: No overlap\n");
3238 return false;
3239 }
3240 } else {
3241 int64_t BaseMaxAddr = OffsetB + AccessSizeB.getValue() - 1;
3242 int64_t OtherNextIterMinAddr = OffsetO + Delta;
3243 if (BaseMaxAddr < OtherNextIterMinAddr) {
3244 LLVM_DEBUG(dbgs() << " Result: No overlap\n");
3245 return false;
3246 }
3247 }
3248 LLVM_DEBUG(dbgs() << " Result: Overlap\n");
3249 return true;
3250}
3251
3252void SwingSchedulerDAG::postProcessDAG() {
3253 for (auto &M : Mutations)
3254 M->apply(this);
3255}
3256
3257/// Try to schedule the node at the specified StartCycle and continue
3258/// until the node is schedule or the EndCycle is reached. This function
3259/// returns true if the node is scheduled. This routine may search either
3260/// forward or backward for a place to insert the instruction based upon
3261/// the relative values of StartCycle and EndCycle.
3262bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3263 bool forward = true;
3264 LLVM_DEBUG({
3265 dbgs() << "Trying to insert node between " << StartCycle << " and "
3266 << EndCycle << " II: " << II << "\n";
3267 });
3268 if (StartCycle > EndCycle)
3269 forward = false;
3270
3271 // The terminating condition depends on the direction.
3272 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3273 for (int curCycle = StartCycle; curCycle != termCycle;
3274 forward ? ++curCycle : --curCycle) {
3275
3276 if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3277 ProcItinResources.canReserveResources(*SU, curCycle)) {
3278 LLVM_DEBUG({
3279 dbgs() << "\tinsert at cycle " << curCycle << " ";
3280 SU->getInstr()->dump();
3281 });
3282
3283 if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
3284 ProcItinResources.reserveResources(*SU, curCycle);
3285 ScheduledInstrs[curCycle].push_back(SU);
3286 InstrToCycle.insert(std::make_pair(SU, curCycle));
3287 if (curCycle > LastCycle)
3288 LastCycle = curCycle;
3289 if (curCycle < FirstCycle)
3290 FirstCycle = curCycle;
3291 return true;
3292 }
3293 LLVM_DEBUG({
3294 dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3295 SU->getInstr()->dump();
3296 });
3297 }
3298 return false;
3299}
3300
3301/// If an instruction has a use that spans multiple iterations, then
3302/// return true. These instructions are characterized by having a back-ege
3303/// to a Phi, which contains a reference to another Phi.
3305 for (auto &P : SU->Preds)
3306 if (P.getKind() == SDep::Anti && P.getSUnit()->getInstr()->isPHI())
3307 for (auto &S : P.getSUnit()->Succs)
3308 if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
3309 return P.getSUnit();
3310 return nullptr;
3311}
3312
3313/// Compute the scheduling start slot for the instruction. The start slot
3314/// depends on any predecessor or successor nodes scheduled already.
3315void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3316 int II, SwingSchedulerDAG *DAG) {
3317 const SwingSchedulerDDG *DDG = DAG->getDDG();
3318
3319 // Iterate over each instruction that has been scheduled already. The start
3320 // slot computation depends on whether the previously scheduled instruction
3321 // is a predecessor or successor of the specified instruction.
3322 for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3323 for (SUnit *I : getInstructions(cycle)) {
3324 for (const auto &IE : DDG->getInEdges(SU)) {
3325 if (IE.getSrc() == I) {
3326 int EarlyStart = cycle + IE.getLatency() - IE.getDistance() * II;
3327 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3328 }
3329 }
3330
3331 for (const auto &OE : DDG->getOutEdges(SU)) {
3332 if (OE.getDst() == I) {
3333 int LateStart = cycle - OE.getLatency() + OE.getDistance() * II;
3334 *MinLateStart = std::min(*MinLateStart, LateStart);
3335 }
3336 }
3337
3338 SUnit *BE = multipleIterations(I, DAG);
3339 for (const auto &Dep : SU->Preds) {
3340 // For instruction that requires multiple iterations, make sure that
3341 // the dependent instruction is not scheduled past the definition.
3342 if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3343 !SU->isPred(I))
3344 *MinLateStart = std::min(*MinLateStart, cycle);
3345 }
3346 }
3347 }
3348}
3349
3350/// Order the instructions within a cycle so that the definitions occur
3351/// before the uses. Returns true if the instruction is added to the start
3352/// of the list, or false if added to the end.
3354 std::deque<SUnit *> &Insts) const {
3355 MachineInstr *MI = SU->getInstr();
3356 bool OrderBeforeUse = false;
3357 bool OrderAfterDef = false;
3358 bool OrderBeforeDef = false;
3359 unsigned MoveDef = 0;
3360 unsigned MoveUse = 0;
3361 int StageInst1 = stageScheduled(SU);
3362 const SwingSchedulerDDG *DDG = SSD->getDDG();
3363
3364 unsigned Pos = 0;
3365 for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3366 ++I, ++Pos) {
3367 for (MachineOperand &MO : MI->operands()) {
3368 if (!MO.isReg() || !MO.getReg().isVirtual())
3369 continue;
3370
3371 Register Reg = MO.getReg();
3372 unsigned BasePos, OffsetPos;
3373 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3374 if (MI->getOperand(BasePos).getReg() == Reg)
3375 if (Register NewReg = SSD->getInstrBaseReg(SU))
3376 Reg = NewReg;
3377 bool Reads, Writes;
3378 std::tie(Reads, Writes) =
3379 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3380 if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3381 OrderBeforeUse = true;
3382 if (MoveUse == 0)
3383 MoveUse = Pos;
3384 } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3385 // Add the instruction after the scheduled instruction.
3386 OrderAfterDef = true;
3387 MoveDef = Pos;
3388 } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3389 if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3390 OrderBeforeUse = true;
3391 if (MoveUse == 0)
3392 MoveUse = Pos;
3393 } else {
3394 OrderAfterDef = true;
3395 MoveDef = Pos;
3396 }
3397 } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3398 OrderBeforeUse = true;
3399 if (MoveUse == 0)
3400 MoveUse = Pos;
3401 if (MoveUse != 0) {
3402 OrderAfterDef = true;
3403 MoveDef = Pos - 1;
3404 }
3405 } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3406 // Add the instruction before the scheduled instruction.
3407 OrderBeforeUse = true;
3408 if (MoveUse == 0)
3409 MoveUse = Pos;
3410 } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3411 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3412 if (MoveUse == 0) {
3413 OrderBeforeDef = true;
3414 MoveUse = Pos;
3415 }
3416 }
3417 }
3418 // Check for order dependences between instructions. Make sure the source
3419 // is ordered before the destination.
3420 for (auto &OE : DDG->getOutEdges(SU)) {
3421 if (OE.getDst() != *I)
3422 continue;
3423 if (OE.isOrderDep() && stageScheduled(*I) == StageInst1) {
3424 OrderBeforeUse = true;
3425 if (Pos < MoveUse)
3426 MoveUse = Pos;
3427 }
3428 // We did not handle HW dependences in previous for loop,
3429 // and we normally set Latency = 0 for Anti/Output deps,
3430 // so may have nodes in same cycle with Anti/Output dependent on HW regs.
3431 else if ((OE.isAntiDep() || OE.isOutputDep()) &&
3432 stageScheduled(*I) == StageInst1) {
3433 OrderBeforeUse = true;
3434 if ((MoveUse == 0) || (Pos < MoveUse))
3435 MoveUse = Pos;
3436 }
3437 }
3438 for (auto &IE : DDG->getInEdges(SU)) {
3439 if (IE.getSrc() != *I)
3440 continue;
3441 if ((IE.isAntiDep() || IE.isOutputDep() || IE.isOrderDep()) &&
3442 stageScheduled(*I) == StageInst1) {
3443 OrderAfterDef = true;
3444 MoveDef = Pos;
3445 }
3446 }
3447 }
3448
3449 // A circular dependence.
3450 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3451 OrderBeforeUse = false;
3452
3453 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3454 // to a loop-carried dependence.
3455 if (OrderBeforeDef)
3456 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3457
3458 // The uncommon case when the instruction order needs to be updated because
3459 // there is both a use and def.
3460 if (OrderBeforeUse && OrderAfterDef) {
3461 SUnit *UseSU = Insts.at(MoveUse);
3462 SUnit *DefSU = Insts.at(MoveDef);
3463 if (MoveUse > MoveDef) {
3464 Insts.erase(Insts.begin() + MoveUse);
3465 Insts.erase(Insts.begin() + MoveDef);
3466 } else {
3467 Insts.erase(Insts.begin() + MoveDef);
3468 Insts.erase(Insts.begin() + MoveUse);
3469 }
3470 orderDependence(SSD, UseSU, Insts);
3471 orderDependence(SSD, SU, Insts);
3472 orderDependence(SSD, DefSU, Insts);
3473 return;
3474 }
3475 // Put the new instruction first if there is a use in the list. Otherwise,
3476 // put it at the end of the list.
3477 if (OrderBeforeUse)
3478 Insts.push_front(SU);
3479 else
3480 Insts.push_back(SU);
3481}
3482
3483/// Return true if the scheduled Phi has a loop carried operand.
3485 MachineInstr &Phi) const {
3486 if (!Phi.isPHI())
3487 return false;
3488 assert(Phi.isPHI() && "Expecting a Phi.");
3489 SUnit *DefSU = SSD->getSUnit(&Phi);
3490 unsigned DefCycle = cycleScheduled(DefSU);
3491 int DefStage = stageScheduled(DefSU);
3492
3493 Register InitVal;
3494 Register LoopVal;
3495 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3496 SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3497 if (!UseSU)
3498 return true;
3499 if (UseSU->getInstr()->isPHI())
3500 return true;
3501 unsigned LoopCycle = cycleScheduled(UseSU);
3502 int LoopStage = stageScheduled(UseSU);
3503 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3504}
3505
3506/// Return true if the instruction is a definition that is loop carried
3507/// and defines the use on the next iteration.
3508/// v1 = phi(v2, v3)
3509/// (Def) v3 = op v1
3510/// (MO) = v1
3511/// If MO appears before Def, then v1 and v3 may get assigned to the same
3512/// register.
3514 MachineInstr *Def,
3515 MachineOperand &MO) const {
3516 if (!MO.isReg())
3517 return false;
3518 if (Def->isPHI())
3519 return false;
3520 MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3521 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3522 return false;
3523 if (!isLoopCarried(SSD, *Phi))
3524 return false;
3525 Register LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3526 for (MachineOperand &DMO : Def->all_defs()) {
3527 if (DMO.getReg() == LoopReg)
3528 return true;
3529 }
3530 return false;
3531}
3532
3533/// Return true if all scheduled predecessors are loop-carried output/order
3534/// dependencies.
3536 SUnit *SU, const SwingSchedulerDDG *DDG) const {
3537 for (const auto &IE : DDG->getInEdges(SU))
3538 if (InstrToCycle.count(IE.getSrc()))
3539 return false;
3540 return true;
3541}
3542
3543/// Determine transitive dependences of unpipelineable instructions
3546 SmallPtrSet<SUnit *, 8> DoNotPipeline;
3547 SmallVector<SUnit *, 8> Worklist;
3548
3549 for (auto &SU : SSD->SUnits)
3550 if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
3551 Worklist.push_back(&SU);
3552
3553 const SwingSchedulerDDG *DDG = SSD->getDDG();
3554 while (!Worklist.empty()) {
3555 auto SU = Worklist.pop_back_val();
3556 if (DoNotPipeline.count(SU))
3557 continue;
3558 LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
3559 DoNotPipeline.insert(SU);
3560 for (const auto &IE : DDG->getInEdges(SU))
3561 Worklist.push_back(IE.getSrc());
3562
3563 // To preserve previous behavior and prevent regression
3564 // FIXME: Remove if this doesn't have significant impact on
3565 for (const auto &OE : DDG->getOutEdges(SU))
3566 if (OE.getDistance() == 1)
3567 Worklist.push_back(OE.getDst());
3568 }
3569 return DoNotPipeline;
3570}
3571
3572// Determine all instructions upon which any unpipelineable instruction depends
3573// and ensure that they are in stage 0. If unable to do so, return false.
3577
3578 int NewLastCycle = INT_MIN;
3579 for (SUnit &SU : SSD->SUnits) {
3580 if (!SU.isInstr())
3581 continue;
3582 if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
3583 NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
3584 continue;
3585 }
3586
3587 // Put the non-pipelined instruction as early as possible in the schedule
3588 int NewCycle = getFirstCycle();
3589 for (const auto &IE : SSD->getDDG()->getInEdges(&SU))
3590 if (IE.getDistance() == 0)
3591 NewCycle = std::max(InstrToCycle[IE.getSrc()], NewCycle);
3592
3593 // To preserve previous behavior and prevent regression
3594 // FIXME: Remove if this doesn't have significant impact on performance
3595 for (auto &OE : SSD->getDDG()->getOutEdges(&SU))
3596 if (OE.getDistance() == 1)
3597 NewCycle = std::max(InstrToCycle[OE.getDst()], NewCycle);
3598
3599 int OldCycle = InstrToCycle[&SU];
3600 if (OldCycle != NewCycle) {
3601 InstrToCycle[&SU] = NewCycle;
3602 auto &OldS = getInstructions(OldCycle);
3603 llvm::erase(OldS, &SU);
3604 getInstructions(NewCycle).emplace_back(&SU);
3605 LLVM_DEBUG(dbgs() << SU << " is not pipelined; moving from cycle "
3606 << OldCycle << " to " << NewCycle
3607 << " Instr:" << *SU.getInstr());
3608 }
3609
3610 // We traverse the SUs in the order of the original basic block. Computing
3611 // NewCycle in this order normally works fine because all dependencies
3612 // (except for loop-carried dependencies) don't violate the original order.
3613 // However, an artificial dependency (e.g., added by CopyToPhiMutation) can
3614 // break it. That is, there may be exist an artificial dependency from
3615 // bottom to top. In such a case, NewCycle may become too large to be
3616 // scheduled in Stage 0. For example, assume that Inst0 is in DNP in the
3617 // following case:
3618 //
3619 // | Inst0 <-+
3620 // SU order | | artificial dep
3621 // | Inst1 --+
3622 // v
3623 //
3624 // If Inst1 is scheduled at cycle N and is not at Stage 0, then NewCycle of
3625 // Inst0 must be greater than or equal to N so that Inst0 is not be
3626 // scheduled at Stage 0. In such cases, we reject this schedule at this
3627 // time.
3628 // FIXME: The reason for this is the existence of artificial dependencies
3629 // that are contradict to the original SU order. If ignoring artificial
3630 // dependencies does not affect correctness, then it is better to ignore
3631 // them.
3632 if (FirstCycle + InitiationInterval <= NewCycle)
3633 return false;
3634
3635 NewLastCycle = std::max(NewLastCycle, NewCycle);
3636 }
3637 LastCycle = NewLastCycle;
3638 return true;
3639}
3640
3641// Check if the generated schedule is valid. This function checks if
3642// an instruction that uses a physical register is scheduled in a
3643// different stage than the definition. The pipeliner does not handle
3644// physical register values that may cross a basic block boundary.
3645// Furthermore, if a physical def/use pair is assigned to the same
3646// cycle, orderDependence does not guarantee def/use ordering, so that
3647// case should be considered invalid. (The test checks for both
3648// earlier and same-cycle use to be more robust.)
3650 for (SUnit &SU : SSD->SUnits) {
3651 if (!SU.hasPhysRegDefs)
3652 continue;
3653 int StageDef = stageScheduled(&SU);
3654 int CycleDef = InstrToCycle[&SU];
3655 assert(StageDef != -1 && "Instruction should have been scheduled.");
3656 for (auto &OE : SSD->getDDG()->getOutEdges(&SU)) {
3657 SUnit *Dst = OE.getDst();
3658 if (OE.isAssignedRegDep() && !Dst->isBoundaryNode())
3659 if (OE.getReg().isPhysical()) {
3660 if (stageScheduled(Dst) != StageDef)
3661 return false;
3662 if (InstrToCycle[Dst] <= CycleDef)
3663 return false;
3664 }
3665 }
3666 }
3667 return true;
3668}
3669
3670/// A property of the node order in swing-modulo-scheduling is
3671/// that for nodes outside circuits the following holds:
3672/// none of them is scheduled after both a successor and a
3673/// predecessor.
3674/// The method below checks whether the property is met.
3675/// If not, debug information is printed and statistics information updated.
3676/// Note that we do not use an assert statement.
3677/// The reason is that although an invalid node order may prevent
3678/// the pipeliner from finding a pipelined schedule for arbitrary II,
3679/// it does not lead to the generation of incorrect code.
3680void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3681
3682 // a sorted vector that maps each SUnit to its index in the NodeOrder
3683 typedef std::pair<SUnit *, unsigned> UnitIndex;
3684 std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3685
3686 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3687 Indices.push_back(std::make_pair(NodeOrder[i], i));
3688
3689 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3690 return std::get<0>(i1) < std::get<0>(i2);
3691 };
3692
3693 // sort, so that we can perform a binary search
3694 llvm::sort(Indices, CompareKey);
3695
3696 bool Valid = true;
3697 (void)Valid;
3698 // for each SUnit in the NodeOrder, check whether
3699 // it appears after both a successor and a predecessor
3700 // of the SUnit. If this is the case, and the SUnit
3701 // is not part of circuit, then the NodeOrder is not
3702 // valid.
3703 for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3704 SUnit *SU = NodeOrder[i];
3705 unsigned Index = i;
3706
3707 bool PredBefore = false;
3708 bool SuccBefore = false;
3709
3710 SUnit *Succ;
3711 SUnit *Pred;
3712 (void)Succ;
3713 (void)Pred;
3714
3715 for (const auto &IE : DDG->getInEdges(SU)) {
3716 SUnit *PredSU = IE.getSrc();
3717 unsigned PredIndex = std::get<1>(
3718 *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
3719 if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3720 PredBefore = true;
3721 Pred = PredSU;
3722 break;
3723 }
3724 }
3725
3726 for (const auto &OE : DDG->getOutEdges(SU)) {
3727 SUnit *SuccSU = OE.getDst();
3728 // Do not process a boundary node, it was not included in NodeOrder,
3729 // hence not in Indices either, call to std::lower_bound() below will
3730 // return Indices.end().
3731 if (SuccSU->isBoundaryNode())
3732 continue;
3733 unsigned SuccIndex = std::get<1>(
3734 *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
3735 if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3736 SuccBefore = true;
3737 Succ = SuccSU;
3738 break;
3739 }
3740 }
3741
3742 if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3743 // instructions in circuits are allowed to be scheduled
3744 // after both a successor and predecessor.
3745 bool InCircuit = llvm::any_of(
3746 Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3747 if (InCircuit)
3748 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ");
3749 else {
3750 Valid = false;
3751 NumNodeOrderIssues++;
3752 LLVM_DEBUG(dbgs() << "Predecessor ");
3753 }
3754 LLVM_DEBUG(dbgs() << *Pred << " and successor " << *Succ
3755 << " are scheduled before node " << *SU << "\n");
3756 }
3757 }
3758
3759 LLVM_DEBUG({
3760 if (!Valid)
3761 dbgs() << "Invalid node order found!\n";
3762 });
3763}
3764
3765/// Attempt to fix the degenerate cases when the instruction serialization
3766/// causes the register lifetimes to overlap. For example,
3767/// p' = store_pi(p, b)
3768/// = load p, offset
3769/// In this case p and p' overlap, which means that two registers are needed.
3770/// Instead, this function changes the load to use p' and updates the offset.
3771void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3772 Register OverlapReg;
3773 Register NewBaseReg;
3774 for (SUnit *SU : Instrs) {
3775 MachineInstr *MI = SU->getInstr();
3776 for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3777 const MachineOperand &MO = MI->getOperand(i);
3778 // Look for an instruction that uses p. The instruction occurs in the
3779 // same cycle but occurs later in the serialized order.
3780 if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3781 // Check that the instruction appears in the InstrChanges structure,
3782 // which contains instructions that can have the offset updated.
3784 InstrChanges.find(SU);
3785 if (It != InstrChanges.end()) {
3786 unsigned BasePos, OffsetPos;
3787 // Update the base register and adjust the offset.
3788 if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
3789 MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3790 NewMI->getOperand(BasePos).setReg(NewBaseReg);
3791 int64_t NewOffset =
3792 MI->getOperand(OffsetPos).getImm() - It->second.second;
3793 NewMI->getOperand(OffsetPos).setImm(NewOffset);
3794 SU->setInstr(NewMI);
3795 MISUnitMap[NewMI] = SU;
3796 NewMIs[MI] = NewMI;
3797 }
3798 }
3799 OverlapReg = Register();
3800 NewBaseReg = Register();
3801 break;
3802 }
3803 // Look for an instruction of the form p' = op(p), which uses and defines
3804 // two virtual registers that get allocated to the same physical register.
3805 unsigned TiedUseIdx = 0;
3806 if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3807 // OverlapReg is p in the example above.
3808 OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3809 // NewBaseReg is p' in the example above.
3810 NewBaseReg = MI->getOperand(i).getReg();
3811 break;
3812 }
3813 }
3814 }
3815}
3816
3817std::deque<SUnit *>
3819 const std::deque<SUnit *> &Instrs) const {
3820 std::deque<SUnit *> NewOrderPhi;
3821 for (SUnit *SU : Instrs) {
3822 if (SU->getInstr()->isPHI())
3823 NewOrderPhi.push_back(SU);
3824 }
3825 std::deque<SUnit *> NewOrderI;
3826 for (SUnit *SU : Instrs) {
3827 if (!SU->getInstr()->isPHI())
3828 orderDependence(SSD, SU, NewOrderI);
3829 }
3830 llvm::append_range(NewOrderPhi, NewOrderI);
3831 return NewOrderPhi;
3832}
3833
3834/// After the schedule has been formed, call this function to combine
3835/// the instructions from the different stages/cycles. That is, this
3836/// function creates a schedule that represents a single iteration.
3838 // Move all instructions to the first stage from later stages.
3839 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3840 for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3841 ++stage) {
3842 std::deque<SUnit *> &cycleInstrs =
3843 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3844 for (SUnit *SU : llvm::reverse(cycleInstrs))
3845 ScheduledInstrs[cycle].push_front(SU);
3846 }
3847 }
3848
3849 // Erase all the elements in the later stages. Only one iteration should
3850 // remain in the scheduled list, and it contains all the instructions.
3851 for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3852 ScheduledInstrs.erase(cycle);
3853
3854 // Change the registers in instruction as specified in the InstrChanges
3855 // map. We need to use the new registers to create the correct order.
3856 for (const SUnit &SU : SSD->SUnits)
3857 SSD->applyInstrChange(SU.getInstr(), *this);
3858
3859 // Reorder the instructions in each cycle to fix and improve the
3860 // generated code.
3861 for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3862 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3863 cycleInstrs = reorderInstructions(SSD, cycleInstrs);
3864 SSD->fixupRegisterOverlaps(cycleInstrs);
3865 }
3866
3867 LLVM_DEBUG(dump(););
3868}
3869
3870#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3872 os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3873 << " depth " << MaxDepth << " col " << Colocate << "\n";
3874 for (const auto &I : Nodes)
3875 os << " " << *I << " " << *(I->getInstr());
3876 os << "\n";
3877}
3878
3879/// Print the schedule information to the given output.
3881 // Iterate over each cycle.
3882 for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3883 // Iterate over each instruction in the cycle.
3884 const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3885 for (SUnit *CI : cycleInstrs->second) {
3886 os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3887 os << *CI << " ";
3888 CI->getInstr()->print(os);
3889 os << "\n";
3890 }
3891 }
3892}
3893
3894/// Utility function used for debugging to print the schedule.
3897
3898void ResourceManager::dumpMRT() const {
3899 LLVM_DEBUG({
3900 if (UseDFA)
3901 return;
3902 std::stringstream SS;
3903 SS << "MRT:\n";
3904 SS << std::setw(4) << "Slot";
3905 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3906 SS << std::setw(3) << I;
3907 SS << std::setw(7) << "#Mops"
3908 << "\n";
3909 for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3910 SS << std::setw(4) << Slot;
3911 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3912 SS << std::setw(3) << MRT[Slot][I];
3913 SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3914 }
3915 dbgs() << SS.str();
3916 });
3917}
3918#endif
3919
3921 ScheduleDAGInstrs *DAG)
3922 : STI(ST), SM(ST->getSchedModel()), ST(ST), TII(ST->getInstrInfo()),
3923 DAG(DAG), UseDFA(ST->useDFAforSMS()),
3924 ProcResourceMasks(SM.getNumProcResourceKinds(), 0),
3925 IssueWidth(SM.IssueWidth) {
3926 initProcResourceVectors(SM, ProcResourceMasks);
3927 if (IssueWidth <= 0)
3928 // If IssueWidth is not specified, set a sufficiently large value
3929 IssueWidth = 100;
3930 if (DAG->Opts.pipeliner_force_issue_width > 0)
3931 IssueWidth = DAG->Opts.pipeliner_force_issue_width;
3932}
3933
3935 const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3936 unsigned ProcResourceID = 0;
3937
3938 // We currently limit the resource kinds to 64 and below so that we can use
3939 // uint64_t for Masks
3940 assert(SM.getNumProcResourceKinds() < 64 &&
3941 "Too many kinds of resources, unsupported");
3942 // Create a unique bitmask for every processor resource unit.
3943 // Skip resource at index 0, since it always references 'InvalidUnit'.
3944 Masks.resize(SM.getNumProcResourceKinds());
3945 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3946 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3947 if (Desc.SubUnitsIdxBegin)
3948 continue;
3949 Masks[I] = 1ULL << ProcResourceID;
3950 ProcResourceID++;
3951 }
3952 // Create a unique bitmask for every processor resource group.
3953 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3954 const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3955 if (!Desc.SubUnitsIdxBegin)
3956 continue;
3957 Masks[I] = 1ULL << ProcResourceID;
3958 for (unsigned U = 0; U < Desc.NumUnits; ++U)
3959 Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3960 ProcResourceID++;
3961 }
3962 LLVM_DEBUG({
3963 if (DAG->Opts.pipeliner_show_mask) {
3964 dbgs() << "ProcResourceDesc:\n";
3965 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3966 const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3967 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3968 ProcResource->Name, I, Masks[I],
3969 ProcResource->NumUnits);
3970 }
3971 dbgs() << " -----------------\n";
3972 }
3973 });
3974}
3975
3977 LLVM_DEBUG({
3978 if (DAG->Opts.pipeliner_dbg_res)
3979 dbgs() << "canReserveResources:\n";
3980 });
3981 if (UseDFA)
3982 return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3983 ->canReserveResources(&SU.getInstr()->getDesc());
3984
3985 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3986 if (!SCDesc->isValid()) {
3987 LLVM_DEBUG({
3988 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3989 dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3990 });
3991 return true;
3992 }
3993
3994 reserveResources(SCDesc, Cycle);
3995 bool Result = !isOverbooked();
3996 unreserveResources(SCDesc, Cycle);
3997
3998 LLVM_DEBUG(if (DAG->Opts.pipeliner_dbg_res) dbgs()
3999 << "return " << Result << "\n\n");
4000 return Result;
4001}
4002
4003void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
4004 LLVM_DEBUG({
4005 if (DAG->Opts.pipeliner_dbg_res)
4006 dbgs() << "reserveResources:\n";
4007 });
4008 if (UseDFA)
4009 return DFAResources[positiveModulo(Cycle, InitiationInterval)]
4010 ->reserveResources(&SU.getInstr()->getDesc());
4011
4012 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
4013 if (!SCDesc->isValid()) {
4014 LLVM_DEBUG({
4015 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4016 dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
4017 });
4018 return;
4019 }
4020
4021 reserveResources(SCDesc, Cycle);
4022
4023 LLVM_DEBUG({
4024 if (DAG->Opts.pipeliner_dbg_res) {
4025 dumpMRT();
4026 dbgs() << "reserveResources: done!\n\n";
4027 }
4028 });
4029}
4030
4031void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
4032 int Cycle) {
4033 assert(!UseDFA);
4034 for (const MCWriteProcResEntry &PRE : make_range(
4035 STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
4036 for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
4037 ++MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
4038
4039 for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
4040 ++NumScheduledMops[positiveModulo(C, InitiationInterval)];
4041}
4042
4043void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
4044 int Cycle) {
4045 assert(!UseDFA);
4046 for (const MCWriteProcResEntry &PRE : make_range(
4047 STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
4048 for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
4049 --MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
4050
4051 for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
4052 --NumScheduledMops[positiveModulo(C, InitiationInterval)];
4053}
4054
4055bool ResourceManager::isOverbooked() const {
4056 assert(!UseDFA);
4057 for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
4058 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
4059 const MCProcResourceDesc *Desc = SM.getProcResource(I);
4060 if (MRT[Slot][I] > Desc->NumUnits)
4061 return true;
4062 }
4063 if (NumScheduledMops[Slot] > IssueWidth)
4064 return true;
4065 }
4066 return false;
4067}
4068
4069int ResourceManager::calculateResMIIDFA() const {
4070 assert(UseDFA);
4071
4072 // Sort the instructions by the number of available choices for scheduling,
4073 // least to most. Use the number of critical resources as the tie breaker.
4074 FuncUnitSorter FUS = FuncUnitSorter(*ST);
4075 for (SUnit &SU : DAG->SUnits)
4076 FUS.calcCriticalResources(*SU.getInstr());
4077 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
4078 FuncUnitOrder(FUS);
4079
4080 for (SUnit &SU : DAG->SUnits)
4081 FuncUnitOrder.push(SU.getInstr());
4082
4084 Resources.push_back(
4085 std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
4086
4087 while (!FuncUnitOrder.empty()) {
4088 MachineInstr *MI = FuncUnitOrder.top();
4089 FuncUnitOrder.pop();
4090 if (TII->isZeroCost(MI->getOpcode()))
4091 continue;
4092
4093 // Attempt to reserve the instruction in an existing DFA. At least one
4094 // DFA is needed for each cycle.
4095 unsigned NumCycles = DAG->getSUnit(MI)->Latency;
4096 unsigned ReservedCycles = 0;
4097 auto *RI = Resources.begin();
4098 auto *RE = Resources.end();
4099 LLVM_DEBUG({
4100 dbgs() << "Trying to reserve resource for " << NumCycles
4101 << " cycles for \n";
4102 MI->dump();
4103 });
4104 for (unsigned C = 0; C < NumCycles; ++C)
4105 while (RI != RE) {
4106 if ((*RI)->canReserveResources(*MI)) {
4107 (*RI)->reserveResources(*MI);
4108 ++ReservedCycles;
4109 break;
4110 }
4111 RI++;
4112 }
4113 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
4114 << ", NumCycles:" << NumCycles << "\n");
4115 // Add new DFAs, if needed, to reserve resources.
4116 for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
4117 LLVM_DEBUG(if (DAG->Opts.pipeliner_dbg_res) dbgs()
4118 << "NewResource created to reserve resources"
4119 << "\n");
4120 auto *NewResource = TII->CreateTargetScheduleState(*ST);
4121 assert(NewResource->canReserveResources(*MI) && "Reserve error.");
4122 NewResource->reserveResources(*MI);
4123 Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
4124 }
4125 }
4126
4127 int Resmii = Resources.size();
4128 LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
4129 return Resmii;
4130}
4131
4133 if (UseDFA)
4134 return calculateResMIIDFA();
4135
4136 // Count each resource consumption and divide it by the number of units.
4137 // ResMII is the max value among them.
4138
4139 int NumMops = 0;
4140 SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
4141 for (SUnit &SU : DAG->SUnits) {
4142 if (TII->isZeroCost(SU.getInstr()->getOpcode()))
4143 continue;
4144
4145 const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
4146 if (!SCDesc->isValid())
4147 continue;
4148
4149 LLVM_DEBUG({
4150 if (DAG->Opts.pipeliner_dbg_res) {
4151 DAG->dumpNode(SU);
4152 dbgs() << " #Mops: " << SCDesc->NumMicroOps << "\n"
4153 << " WriteProcRes: ";
4154 }
4155 });
4156 NumMops += SCDesc->NumMicroOps;
4157 for (const MCWriteProcResEntry &PRE :
4158 make_range(STI->getWriteProcResBegin(SCDesc),
4159 STI->getWriteProcResEnd(SCDesc))) {
4160 LLVM_DEBUG({
4161 if (DAG->Opts.pipeliner_dbg_res) {
4162 const MCProcResourceDesc *Desc =
4163 SM.getProcResource(PRE.ProcResourceIdx);
4164 dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
4165 }
4166 });
4167 ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
4168 }
4169 LLVM_DEBUG(if (DAG->Opts.pipeliner_dbg_res) dbgs() << "\n");
4170 }
4171
4172 int Result = (NumMops + IssueWidth - 1) / IssueWidth;
4173 LLVM_DEBUG({
4174 if (DAG->Opts.pipeliner_dbg_res)
4175 dbgs() << "#Mops: " << NumMops << ", "
4176 << "IssueWidth: " << IssueWidth << ", "
4177 << "Cycles: " << Result << "\n";
4178 });
4179
4180 LLVM_DEBUG({
4181 if (DAG->Opts.pipeliner_dbg_res) {
4182 std::stringstream SS;
4183 SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
4184 << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
4185 << "\n";
4186 dbgs() << SS.str();
4187 }
4188 });
4189 for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
4190 const MCProcResourceDesc *Desc = SM.getProcResource(I);
4191 int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
4192 LLVM_DEBUG({
4193 if (DAG->Opts.pipeliner_dbg_res) {
4194 std::stringstream SS;
4195 SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
4196 << Desc->NumUnits << std::setw(10) << ResourceCount[I]
4197 << std::setw(10) << Cycles << "\n";
4198 dbgs() << SS.str();
4199 }
4200 });
4201 if (Cycles > Result)
4202 Result = Cycles;
4203 }
4204 return Result;
4205}
4206
4208 InitiationInterval = II;
4209 DFAResources.clear();
4210 DFAResources.resize(II);
4211 for (auto &I : DFAResources)
4212 I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
4213 MRT.clear();
4214 MRT.resize(II, SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
4215 NumScheduledMops.clear();
4216 NumScheduledMops.resize(II);
4217}
4218
4219bool SwingSchedulerDDGEdge::ignoreDependence(bool IgnoreAnti) const {
4220 if (Pred.isArtificial() || Dst->isBoundaryNode())
4221 return true;
4222 // Currently, dependence that is an anti-dependences but not a loop-carried is
4223 // also ignored. This behavior is preserved to prevent regression.
4224 // FIXME: Remove if this doesn't have significant impact on performance
4225 return IgnoreAnti && (Pred.getKind() == SDep::Kind::Anti || Distance != 0);
4226}
4227
4228SwingSchedulerDDG::SwingSchedulerDDGEdges &
4229SwingSchedulerDDG::getEdges(const SUnit *SU) {
4230 if (SU == EntrySU)
4231 return EntrySUEdges;
4232 if (SU == ExitSU)
4233 return ExitSUEdges;
4234 return EdgesVec[SU->NodeNum];
4235}
4236
4237const SwingSchedulerDDG::SwingSchedulerDDGEdges &
4238SwingSchedulerDDG::getEdges(const SUnit *SU) const {
4239 if (SU == EntrySU)
4240 return EntrySUEdges;
4241 if (SU == ExitSU)
4242 return ExitSUEdges;
4243 return EdgesVec[SU->NodeNum];
4244}
4245
4246void SwingSchedulerDDG::addEdge(const SUnit *SU,
4247 const SwingSchedulerDDGEdge &Edge) {
4248 assert(!Edge.isValidationOnly() &&
4249 "Validation-only edges are not expected here.");
4250
4251 auto &Edges = getEdges(SU);
4252 if (Edge.getSrc() == SU)
4253 Edges.Succs.push_back(Edge);
4254 else
4255 Edges.Preds.push_back(Edge);
4256}
4257
4258void SwingSchedulerDDG::initEdges(SUnit *SU) {
4259 for (const auto &PI : SU->Preds) {
4260 SwingSchedulerDDGEdge Edge(SU, PI, /*IsSucc=*/false,
4261 /*IsValidationOnly=*/false);
4262 addEdge(SU, Edge);
4263 }
4264
4265 for (const auto &SI : SU->Succs) {
4266 SwingSchedulerDDGEdge Edge(SU, SI, /*IsSucc=*/true,
4267 /*IsValidationOnly=*/false);
4268 addEdge(SU, Edge);
4269 }
4270}
4271
4272SwingSchedulerDDG::SwingSchedulerDDG(std::vector<SUnit> &SUnits, SUnit *EntrySU,
4273 SUnit *ExitSU, const LoopCarriedEdges &LCE)
4274 : EntrySU(EntrySU), ExitSU(ExitSU) {
4275 EdgesVec.resize(SUnits.size());
4276
4277 // Add non-loop-carried edges based on the DAG.
4278 initEdges(EntrySU);
4279 initEdges(ExitSU);
4280 for (auto &SU : SUnits)
4281 initEdges(&SU);
4282
4283 // Add loop-carried edges, which are not represented in the DAG.
4284 for (SUnit &SU : SUnits) {
4285 SUnit *Src = &SU;
4286 if (const LoopCarriedEdges::OrderDep *OD = LCE.getOrderDepOrNull(Src)) {
4287 SDep Base(Src, SDep::Barrier);
4288 Base.setLatency(1);
4289 for (SUnit *Dst : *OD) {
4290 SwingSchedulerDDGEdge Edge(Dst, Base, /*IsSucc=*/false,
4291 /*IsValidationOnly=*/true);
4292 Edge.setDistance(1);
4293 ValidationOnlyEdges.push_back(Edge);
4294
4295 // Store the edge as an extra edge if it meets the following conditions:
4296 //
4297 // - The edge is a loop-carried order dependency.
4298 // - The edge is a back edge in terms of the original instruction
4299 // order.
4300 // - The destination instruction may load.
4301 // - The source instruction may store but does not load.
4302 //
4303 // These conditions are inherited from a previous implementation to
4304 // preserve the existing behavior and avoid regressions.
4305 bool UseAsExtraEdge = [&]() {
4306 if (Edge.getDistance() == 0 || !Edge.isOrderDep())
4307 return false;
4308
4309 SUnit *Src = Edge.getSrc();
4310 SUnit *Dst = Edge.getDst();
4311 if (Src->NodeNum < Dst->NodeNum)
4312 return false;
4313
4314 MachineInstr *SrcMI = Src->getInstr();
4315 MachineInstr *DstMI = Dst->getInstr();
4316 return DstMI->mayLoad() && !SrcMI->mayLoad() && SrcMI->mayStore();
4317 }();
4318 if (UseAsExtraEdge)
4319 getEdges(Edge.getSrc()).ExtraSuccs.push_back(Edge.getDst());
4320 }
4321 }
4322 }
4323}
4324
4325const SwingSchedulerDDG::EdgesType &
4327 return getEdges(SU).Preds;
4328}
4329
4330const SwingSchedulerDDG::EdgesType &
4332 return getEdges(SU).Succs;
4333}
4334
4336 return getEdges(SU).ExtraSuccs;
4337}
4338
4339/// Check if \p Schedule doesn't violate the validation-only dependencies.
4341 unsigned II = Schedule.getInitiationInterval();
4342
4343 auto ExpandCycle = [&](SUnit *SU) {
4344 int Stage = Schedule.stageScheduled(SU);
4345 int Cycle = Schedule.cycleScheduled(SU);
4346 return Cycle + (Stage * II);
4347 };
4348
4349 for (const SwingSchedulerDDGEdge &Edge : ValidationOnlyEdges) {
4350 SUnit *Src = Edge.getSrc();
4351 SUnit *Dst = Edge.getDst();
4352 if (!Src->isInstr() || !Dst->isInstr())
4353 continue;
4354 int CycleSrc = ExpandCycle(Src);
4355 int CycleDst = ExpandCycle(Dst);
4356 int MaxLateStart = CycleDst + Edge.getDistance() * II - Edge.getLatency();
4357 if (CycleSrc > MaxLateStart) {
4358 LLVM_DEBUG({
4359 dbgs() << "Validation failed for edge from " << *Src << " to " << *Dst
4360 << "\n";
4361 });
4362 return false;
4363 }
4364 }
4365 return true;
4366}
4367
4368void LoopCarriedEdges::modifySUnits(std::vector<SUnit> &SUnits,
4369 const TargetInstrInfo *TII) {
4370 for (SUnit &SU : SUnits) {
4371 SUnit *Src = &SU;
4372 if (auto *OrderDep = getOrderDepOrNull(Src)) {
4373 SDep Dep(Src, SDep::Barrier);
4374 Dep.setLatency(1);
4375 for (SUnit *Dst : *OrderDep) {
4376 SUnit *From = Src;
4377 SUnit *To = Dst;
4378 if (From->NodeNum > To->NodeNum)
4379 std::swap(From, To);
4380
4381 // Add a forward edge if the following conditions are met:
4382 //
4383 // - The instruction of the source node (FromMI) may read memory.
4384 // - The instruction of the target node (ToMI) may modify memory, but
4385 // does not read it.
4386 // - Neither instruction is a global barrier.
4387 // - The load appears before the store in the original basic block.
4388 // - There are no barrier or store instructions between the two nodes.
4389 // - The target node is unreachable from the source node in the current
4390 // DAG.
4391 //
4392 // TODO: These conditions are inherited from a previous implementation,
4393 // and some may no longer be necessary. For now, we conservatively
4394 // retain all of them to avoid regressions, but the logic could
4395 // potentially be simplified
4396 MachineInstr *FromMI = From->getInstr();
4397 MachineInstr *ToMI = To->getInstr();
4398 if (FromMI->mayLoad() && !ToMI->mayLoad() && ToMI->mayStore() &&
4399 !TII->isGlobalMemoryObject(FromMI) &&
4400 !TII->isGlobalMemoryObject(ToMI) && !isSuccOrder(From, To)) {
4401 SDep Pred = Dep;
4402 Pred.setSUnit(From);
4403 To->addPred(Pred);
4404 }
4405 }
4406 }
4407 }
4408}
4409
4410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4413 const MachineRegisterInfo *MRI) const {
4414 const auto *Order = getOrderDepOrNull(SU);
4415
4416 if (!Order)
4417 return;
4418
4419 const auto DumpSU = [](const SUnit *SU) {
4420 std::string S;
4421 raw_string_ostream OS(S);
4422 OS << *SU;
4423 return S;
4424 };
4425
4426 dbgs() << " Loop carried edges from " << DumpSU(SU) << "\n"
4427 << " Order\n";
4428 for (SUnit *Dst : *Order)
4429 dbgs() << " " << DumpSU(Dst) << "\n";
4430}
4431#endif
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static std::optional< unsigned > getTag(const TargetRegisterInfo *TRI, const MachineInstr &MI, const LoadInfo &LI)
SDValue Pred
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
constexpr LLT S1
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
DXIL Remove Unused Resources
This file defines the DenseMap class.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool hasPHICycleDFS(unsigned Reg, const DenseMap< unsigned, SmallVector< unsigned, 2 > > &PhiDeps, SmallSet< unsigned, 8 > &Visited, SmallSet< unsigned, 8 > &RecStack)
Depth-first search to detect cycles among PHI dependencies.
static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, NodeSet &NS)
Compute the live-out registers for the instructions in a node-set.
static void computeScheduledInsts(const SwingSchedulerDAG *SSD, SMSchedule &Schedule, std::vector< MachineInstr * > &OrderedInsts, DenseMap< MachineInstr *, unsigned > &Stages)
Create an instruction stream that represents a single iteration and stage of each instruction.
static bool findLoopIncrementValue(const MachineInstr &MI, const MachineOperand &Op, int &Value)
When Op is a value that is incremented recursively in a loop and there is a unique instruction that i...
static Register getLoopPhiReg(const MachineInstr &Phi, const MachineBasicBlock *LoopBB)
Return the Phi register value that comes the loop block.
static bool hasLoopCarriedMemDep(const SUnitWithMemInfo &Src, const SUnitWithMemInfo &Dst, BatchAAResults &BAA, const TargetInstrInfo *TII)
Returns true if there is a loop-carried order dependency from Src to Dst.
static bool isIntersect(SmallSetVector< SUnit *, 8 > &Set1, const NodeSet &Set2, SmallSetVector< SUnit *, 8 > &Result)
Return true if Set1 contains elements in Set2.
static bool computeDelta(const MachineInstr &MI, const TargetInstrInfo &TII, int &Delta)
Return true if we can compute the amount the instruction changes during each iteration.
static bool isSuccOrder(SUnit *SUa, SUnit *SUb)
Return true if SUb can be reached from SUa following the chain edges.
static bool hasPHICycle(const MachineBasicBlock *LoopHeader, const MachineRegisterInfo &MRI)
static bool runMachinePipeliner(MachineFunction &MF, function_ref< const MachineLoopInfo &()> GetMLI, function_ref< LiveIntervals &()> GetLIS, function_ref< AAResults &()> GetAA, function_ref< MachineOptimizationRemarkEmitter &()> GetORE, function_ref< RegisterClassInfo &()> GetRCI, function_ref< MachineDominatorTree *()> GetMDT)
static bool pred_L(SetVector< SUnit * > &NodeOrder, SmallSetVector< SUnit *, 8 > &Preds, SwingSchedulerDDG *DDG, const NodeSet *S=nullptr)
Compute the Pred_L(O) set, as defined in the paper.
static bool computePath(SUnit *Cur, SetVector< SUnit * > &Path, SetVector< SUnit * > &DestNodes, SetVector< SUnit * > &Exclude, SmallPtrSet< SUnit *, 8 > &Visited, SwingSchedulerDDG *DDG)
Return true if there is a path from the specified node to any of the nodes in DestNodes.
static bool succ_L(SetVector< SUnit * > &NodeOrder, SmallSetVector< SUnit *, 8 > &Succs, SwingSchedulerDDG *DDG, const NodeSet *S=nullptr)
Compute the Succ_L(O) set, as defined in the paper.
static SUnit * multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG)
If an instruction has a use that spans multiple iterations, then return true.
static Register findUniqueOperandDefinedInLoop(const MachineInstr &MI)
static void getPhiRegs(const MachineInstr &Phi, const MachineBasicBlock *Loop, Register &InitVal, Register &LoopVal)
Return the register values for the operands of a Phi instruction.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
#define P(N)
#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
This file defines the PriorityQueue class.
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
Add loop-carried chain dependencies.
void computeDependencies()
The main function to compute loop-carried order-dependencies.
LoopCarriedOrderDepsTracker(SwingSchedulerDAG *SSD, BatchAAResults *BAA, const TargetInstrInfo *TII)
const BitVector & getLoopCarried(unsigned Idx) const
MachineOptimizationRemarkEmitter * ORE
const TargetInstrInfo * TII
bool run()
Run the software pipeliner over all loops in the function.
const MachineLoopInfo * MLI
MachinePipelinerImpl(MachineFunction &MF, const MachineLoopInfo &MLI, LiveIntervals &LIS, AAResults &AA, MachineOptimizationRemarkEmitter &ORE, RegisterClassInfo &RegClassInfo, MachineDominatorTree *MDT)
const InstrItineraryData * InstrItins
const CodeGenOptions & Opts
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:197
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
Itinerary data supplied by a subtarget to be used by a target.
const InstrStage * beginStage(unsigned ItinClassIndx) const
Return the first stage of the itinerary.
const InstrStage * endStage(unsigned ItinClassIndx) const
Return the last+1 stage of the itinerary.
bool isEmpty() const
Returns true if there are no itineraries.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
bool hasValue() const
TypeSize getValue() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
unsigned getSchedClass() const
Return the scheduling class for this instruction.
const MCWriteProcResEntry * getWriteProcResEnd(const MCSchedClassDesc *SC) const
const MCWriteProcResEntry * getWriteProcResBegin(const MCSchedClassDesc *SC) const
Return an iterator at the first process resource consumed by the given scheduling class.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
MachineInstrBundleIterator< const MachineInstr > const_iterator
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
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...
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.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool memoperands_empty() const
Return true if we don't have any memory operands which described the memory access done by this instr...
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool isRegSequence() const
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
const Value * getValue() const
Return the base address of the memory access.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
Diagnostic information for optimization analysis remarks.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses 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 ...
use_instr_iterator use_instr_begin(Register RegNo) const
PSetIterator getPressureSets(VirtRegOrUnit VRegOrUnit) const
Get an iterator over the pressure sets affected by the virtual register or register unit.
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...
static use_instr_iterator use_instr_end()
const MachineFunction & getMF() const
LLVM_ABI bool isReservedRegUnit(MCRegUnit Unit) const
Returns true when the given register unit is considered reserved.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
Expand the kernel using modulo variable expansion algorithm (MVE).
static LLVM_ABI bool canApply(MachineLoop &L)
Check if ModuloScheduleExpanderMVE can be applied to L.
The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place, rewriting the old loop and...
LLVM_ABI void cleanup()
Performs final cleanup after expansion.
LLVM_ABI void expand()
Performs the actual expansion.
Expander that simply annotates each scheduled instruction with a post-instr symbol that can be consum...
LLVM_ABI void annotate()
Performs the annotation.
Represents a schedule for a single-block loop.
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
SUnit * getNode(unsigned i) const
LLVM_ABI void print(raw_ostream &os) const
void setRecMII(unsigned mii)
unsigned count(SUnit *SU) const
void setColocate(unsigned c)
int compareRecMII(NodeSet &RHS)
bool insert(SUnit *SU)
LLVM_DUMP_METHOD void dump() const
bool empty() const
unsigned getWeight() const
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A reimplementation of ModuloScheduleExpander.
PointerIntPair - This class implements a pair of a pointer and small integer.
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 & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
unsigned getPSet() const
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI void addLiveRegs(ArrayRef< VRegMaskOrUnit > Regs)
Force liveness of virtual registers or physical register units.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
LLVM_ABI int calculateResMII() const
LLVM_ABI void initProcResourceVectors(const MCSchedModel &SM, SmallVectorImpl< uint64_t > &Masks)
LLVM_ABI ResourceManager(const TargetSubtargetInfo *ST, ScheduleDAGInstrs *DAG)
LLVM_ABI void init(int II)
Initialize resources with the initiation interval II.
LLVM_ABI bool canReserveResources(SUnit &SU, int Cycle)
Check if the resources occupied by a machine instruction are available in the current state.
Scheduling dependency.
Definition ScheduleDAG.h:54
Kind
These are the different kinds of scheduling dependencies.
Definition ScheduleDAG.h:57
@ Order
Any other ordering dependency.
Definition ScheduleDAG.h:61
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
void setLatency(unsigned Lat)
Sets the latency for this edge.
@ Barrier
An unknown scheduling barrier.
Definition ScheduleDAG.h:74
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:77
void setSUnit(SUnit *SU)
This class represents the scheduled code.
LLVM_ABI std::deque< SUnit * > reorderInstructions(const SwingSchedulerDAG *SSD, const std::deque< SUnit * > &Instrs) const
void setInitiationInterval(int ii)
Set the initiation interval for this schedule.
LLVM_ABI void dump() const
Utility function used for debugging to print the schedule.
LLVM_ABI bool insert(SUnit *SU, int StartCycle, int EndCycle, int II)
Try to schedule the node at the specified StartCycle and continue until the node is schedule or the E...
unsigned getMaxStageCount()
Return the maximum stage count needed for this schedule.
LLVM_ABI void print(raw_ostream &os) const
Print the schedule information to the given output.
LLVM_ABI bool onlyHasLoopCarriedOutputOrOrderPreds(SUnit *SU, const SwingSchedulerDDG *DDG) const
Return true if all scheduled predecessors are loop-carried output/order dependencies.
int stageScheduled(SUnit *SU) const
Return the stage for a scheduled instruction.
LLVM_ABI void orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU, std::deque< SUnit * > &Insts) const
Order the instructions within a cycle so that the definitions occur before the uses.
LLVM_ABI bool isValidSchedule(SwingSchedulerDAG *SSD)
int getInitiationInterval() const
Return the initiation interval for this schedule.
std::deque< SUnit * > & getInstructions(int cycle)
Return the instructions that are scheduled at the specified cycle.
int getFirstCycle() const
Return the first cycle in the completed schedule.
DenseMap< int, std::deque< SUnit * > >::const_iterator const_sched_iterator
LLVM_ABI bool isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD, MachineInstr *Def, MachineOperand &MO) const
Return true if the instruction is a definition that is loop carried and defines the use on the next i...
unsigned cycleScheduled(SUnit *SU) const
Return the cycle for a scheduled instruction.
LLVM_ABI SmallPtrSet< SUnit *, 8 > computeUnpipelineableNodes(SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI)
Determine transitive dependences of unpipelineable instructions.
LLVM_ABI void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, int II, SwingSchedulerDAG *DAG)
Compute the scheduling start slot for the instruction.
LLVM_ABI bool normalizeNonPipelinedInstructions(SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI)
LLVM_ABI bool isLoopCarried(const SwingSchedulerDAG *SSD, MachineInstr &Phi) const
Return true if the scheduled Phi has a loop carried operand.
int getFinalCycle() const
Return the last cycle in the finalized schedule.
LLVM_ABI void finalizeSchedule(SwingSchedulerDAG *SSD)
After the schedule has been formed, call this function to combine the instructions from the different...
Scheduling unit. This is a node in the scheduling DAG.
unsigned NumPreds
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
unsigned NodeNum
Entry # of node in the node vector.
void setInstr(MachineInstr *MI)
Assigns the instruction for the SUnit.
LLVM_ABI void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
bool hasPhysRegDefs
Has physreg defs that are being used.
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
LLVM_ABI bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
DenseMap< MachineInstr *, SUnit * > MISUnitMap
After calling BuildSchedGraph, each machine instruction in the current scheduling region is mapped to...
virtual void finishBlock()
Cleans up after scheduling in the given block.
const CodeGenOptions & Opts
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
const MachineLoopInfo * MLI
void dump() const override
LLVM_ABI void AddPred(SUnit *Y, SUnit *X)
Updates the topological ordering to accommodate an edge to be added from SUnit X to SUnit Y.
LLVM_ABI bool IsReachable(const SUnit *SU, const SUnit *TargetSU)
Checks if SU is reachable from TargetSU.
MachineRegisterInfo & MRI
Virtual/real register map.
const TargetInstrInfo * TII
Target instruction information.
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
SUnit ExitSU
Special node for the region exit.
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
void insert_range(Range &&R)
Definition SetVector.h:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
typename vector_type::const_iterator iterator
Definition SetVector.h:72
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
iterator end() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
SwingSchedulerDAG(MachineFunction &MF, const MachineLoopInfo *MLI, MachineOptimizationRemarkEmitter *ORE, MachineLoop &L, LiveIntervals &lis, const RegisterClassInfo &rci, unsigned II, TargetInstrInfo::PipelinerLoopInfo *PLI, AliasAnalysis *AA, MachineDominatorTree *MDT=nullptr)
void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule)
Apply changes to the instruction if needed.
const SwingSchedulerDDG * getDDG() const
void finishBlock() override
Clean up after the software pipeliner runs.
void fixupRegisterOverlaps(std::deque< SUnit * > &Instrs)
Attempt to fix the degenerate cases when the instruction serialization causes the register lifetimes ...
void schedule() override
We override the schedule function in ScheduleDAGInstrs to implement the scheduling part of the Swing ...
Register getInstrBaseReg(SUnit *SU) const
Return the new base register that was stored away for the changed instruction.
Represents a dependence between two instruction.
LLVM_ABI bool ignoreDependence(bool IgnoreAnti) const
Returns true for DDG nodes that we ignore when computing the cost functions.
This class provides APIs to retrieve edges from/to an SUnit node, with a particular focus on loop-car...
LLVM_ABI SwingSchedulerDDG(std::vector< SUnit > &SUnits, SUnit *EntrySU, SUnit *ExitSU, const LoopCarriedEdges &LCE)
LLVM_ABI ArrayRef< SUnit * > getExtraOutEdges(const SUnit *SU) const
LLVM_ABI const EdgesType & getInEdges(const SUnit *SU) const
LLVM_ABI bool isValidSchedule(const SMSchedule &Schedule) const
Check if Schedule doesn't violate the validation-only dependencies.
LLVM_ABI const EdgesType & getOutEdges(const SUnit *SU) const
Object returned by analyzeLoopForPipelining.
virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const =0
Return true if the given instruction should not be pipelined and should be ignored.
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual void overridePipelinerPolicy(MachinePipelinerPolicy &Policy) const
Override generic software pipelining policy.
virtual bool enableMachinePipeliner() const
True if the subtarget should run MachinePipeliner.
virtual bool useDFAforSMS() const
Default to DFA for resource management, return false when target will use ProcResource in InstrSchedM...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const InstrItineraryData * getInstrItineraryData() const
getInstrItineraryData - Returns instruction itinerary data for the target or specific subtarget.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Wrapper class representing a virtual register or register unit.
Definition Register.h:172
constexpr bool isVirtualReg() const
Definition Register.h:188
constexpr MCRegUnit asMCRegUnit() const
Definition Register.h:192
constexpr Register asVirtualReg() const
Definition Register.h:197
The main class in the implementation of the target independent window scheduler.
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
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
constexpr double e
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
std::set< NodeId > NodeSet
Definition RDFGraph.h:551
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
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
@ Force
Turn off window algorithm.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ABI bool mayOverlapInLaterIter(const MachineInstr *BaseMI, const MachineInstr *OtherMI, const MachineBasicBlock *LoopBB, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Return true if BaseMI and OtherMI may access overlapping memory in a later iteration of the loop Loop...
@ Other
Any other memory.
Definition ModRef.h:68
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
LLVM_ABI char & MachinePipelinerID
This pass performs software pipelining on machine instructions.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
constexpr bool valueOr(BoolOrDefault X, bool Default)
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI Printable printVRegOrUnit(VirtRegOrUnit VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Cache the target analysis information about the loop.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > LoopPipelinerInfo
SmallVector< MachineOperand, 4 > BrCond
This class holds an SUnit corresponding to a memory operation and other information related to the in...
const Value * MemOpValue
The value of a memory operand.
SmallVector< const Value *, 2 > UnderlyingObjs
bool isTriviallyDisjoint(const SUnitWithMemInfo &Other) const
int64_t MemOpOffset
The offset of a memory operand.
bool IsAllIdentified
True if all the underlying objects are identified.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
uint64_t FuncUnits
Bitmask representing a set of functional units.
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Represents loop-carried dependencies.
SmallSetVector< SUnit *, 8 > OrderDep
LLVM_ABI void dump(SUnit *SU, const TargetRegisterInfo *TRI, const MachineRegisterInfo *MRI) const
const OrderDep * getOrderDepOrNull(SUnit *Key) const
LLVM_ABI void modifySUnits(std::vector< SUnit > &SUnits, const TargetInstrInfo *TII)
Adds some edges to the original DAG that correspond to loop-carried dependencies.
Define a kind of processor resource that will be modeled by the scheduler.
Definition MCSchedule.h:37
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
Definition MCSchedule.h:376
bool hasInstrSchedModel() const
Does this machine model include instruction-level scheduling.
Definition MCSchedule.h:350
const MCProcResourceDesc * getProcResource(unsigned ProcResourceIdx) const
Definition MCSchedule.h:369
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:69
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.