132a40564SEugene Zelenko //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===// 2254f889dSBrendon Cahoon // 3*2946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*2946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 5*2946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6254f889dSBrendon Cahoon // 7254f889dSBrendon Cahoon //===----------------------------------------------------------------------===// 8254f889dSBrendon Cahoon // 9254f889dSBrendon Cahoon // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner. 10254f889dSBrendon Cahoon // 11254f889dSBrendon Cahoon // This SMS implementation is a target-independent back-end pass. When enabled, 12254f889dSBrendon Cahoon // the pass runs just prior to the register allocation pass, while the machine 13254f889dSBrendon Cahoon // IR is in SSA form. If software pipelining is successful, then the original 14254f889dSBrendon Cahoon // loop is replaced by the optimized loop. The optimized loop contains one or 15254f889dSBrendon Cahoon // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If 16254f889dSBrendon Cahoon // the instructions cannot be scheduled in a given MII, we increase the MII by 17254f889dSBrendon Cahoon // one and try again. 18254f889dSBrendon Cahoon // 19254f889dSBrendon Cahoon // The SMS implementation is an extension of the ScheduleDAGInstrs class. We 20254f889dSBrendon Cahoon // represent loop carried dependences in the DAG as order edges to the Phi 21254f889dSBrendon Cahoon // nodes. We also perform several passes over the DAG to eliminate unnecessary 22254f889dSBrendon Cahoon // edges that inhibit the ability to pipeline. The implementation uses the 23254f889dSBrendon Cahoon // DFAPacketizer class to compute the minimum initiation interval and the check 24254f889dSBrendon Cahoon // where an instruction may be inserted in the pipelined schedule. 25254f889dSBrendon Cahoon // 26254f889dSBrendon Cahoon // In order for the SMS pass to work, several target specific hooks need to be 27254f889dSBrendon Cahoon // implemented to get information about the loop structure and to rewrite 28254f889dSBrendon Cahoon // instructions. 29254f889dSBrendon Cahoon // 30254f889dSBrendon Cahoon //===----------------------------------------------------------------------===// 31254f889dSBrendon Cahoon 32cdc71612SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 33cdc71612SEugene Zelenko #include "llvm/ADT/BitVector.h" 34254f889dSBrendon Cahoon #include "llvm/ADT/DenseMap.h" 35254f889dSBrendon Cahoon #include "llvm/ADT/MapVector.h" 36254f889dSBrendon Cahoon #include "llvm/ADT/PriorityQueue.h" 37254f889dSBrendon Cahoon #include "llvm/ADT/SetVector.h" 38254f889dSBrendon Cahoon #include "llvm/ADT/SmallPtrSet.h" 39254f889dSBrendon Cahoon #include "llvm/ADT/SmallSet.h" 40cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h" 41254f889dSBrendon Cahoon #include "llvm/ADT/Statistic.h" 426bda14b3SChandler Carruth #include "llvm/ADT/iterator_range.h" 43254f889dSBrendon Cahoon #include "llvm/Analysis/AliasAnalysis.h" 44cdc71612SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h" 45254f889dSBrendon Cahoon #include "llvm/Analysis/ValueTracking.h" 46254f889dSBrendon Cahoon #include "llvm/CodeGen/DFAPacketizer.h" 47f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h" 48254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineBasicBlock.h" 49254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineDominators.h" 50cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h" 51cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunctionPass.h" 52cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h" 53254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineInstrBuilder.h" 54254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineLoopInfo.h" 55cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineMemOperand.h" 56cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h" 57fa2e3583SAdrian Prantl #include "llvm/CodeGen/MachinePipeliner.h" 58254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineRegisterInfo.h" 59254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterPressure.h" 60cdc71612SEugene Zelenko #include "llvm/CodeGen/ScheduleDAG.h" 6188391248SKrzysztof Parzyszek #include "llvm/CodeGen/ScheduleDAGMutation.h" 62b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h" 63b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h" 64b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h" 65432a3883SNico Weber #include "llvm/Config/llvm-config.h" 66cdc71612SEugene Zelenko #include "llvm/IR/Attributes.h" 67cdc71612SEugene Zelenko #include "llvm/IR/DebugLoc.h" 6832a40564SEugene Zelenko #include "llvm/IR/Function.h" 6932a40564SEugene Zelenko #include "llvm/MC/LaneBitmask.h" 7032a40564SEugene Zelenko #include "llvm/MC/MCInstrDesc.h" 71254f889dSBrendon Cahoon #include "llvm/MC/MCInstrItineraries.h" 7232a40564SEugene Zelenko #include "llvm/MC/MCRegisterInfo.h" 7332a40564SEugene Zelenko #include "llvm/Pass.h" 74254f889dSBrendon Cahoon #include "llvm/Support/CommandLine.h" 7532a40564SEugene Zelenko #include "llvm/Support/Compiler.h" 76254f889dSBrendon Cahoon #include "llvm/Support/Debug.h" 77cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h" 78254f889dSBrendon Cahoon #include "llvm/Support/raw_ostream.h" 79cdc71612SEugene Zelenko #include <algorithm> 80cdc71612SEugene Zelenko #include <cassert> 81254f889dSBrendon Cahoon #include <climits> 82cdc71612SEugene Zelenko #include <cstdint> 83254f889dSBrendon Cahoon #include <deque> 84cdc71612SEugene Zelenko #include <functional> 85cdc71612SEugene Zelenko #include <iterator> 86254f889dSBrendon Cahoon #include <map> 8732a40564SEugene Zelenko #include <memory> 88cdc71612SEugene Zelenko #include <tuple> 89cdc71612SEugene Zelenko #include <utility> 90cdc71612SEugene Zelenko #include <vector> 91254f889dSBrendon Cahoon 92254f889dSBrendon Cahoon using namespace llvm; 93254f889dSBrendon Cahoon 94254f889dSBrendon Cahoon #define DEBUG_TYPE "pipeliner" 95254f889dSBrendon Cahoon 96254f889dSBrendon Cahoon STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline"); 97254f889dSBrendon Cahoon STATISTIC(NumPipelined, "Number of loops software pipelined"); 984b8bcf00SRoorda, Jan-Willem STATISTIC(NumNodeOrderIssues, "Number of node order issues found"); 99254f889dSBrendon Cahoon 100254f889dSBrendon Cahoon /// A command line option to turn software pipelining on or off. 101b7d3311cSBenjamin Kramer static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true), 102b7d3311cSBenjamin Kramer cl::ZeroOrMore, 103b7d3311cSBenjamin Kramer cl::desc("Enable Software Pipelining")); 104254f889dSBrendon Cahoon 105254f889dSBrendon Cahoon /// A command line option to enable SWP at -Os. 106254f889dSBrendon Cahoon static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size", 107254f889dSBrendon Cahoon cl::desc("Enable SWP at Os."), cl::Hidden, 108254f889dSBrendon Cahoon cl::init(false)); 109254f889dSBrendon Cahoon 110254f889dSBrendon Cahoon /// A command line argument to limit minimum initial interval for pipelining. 111254f889dSBrendon Cahoon static cl::opt<int> SwpMaxMii("pipeliner-max-mii", 1128f976ba0SHiroshi Inoue cl::desc("Size limit for the MII."), 113254f889dSBrendon Cahoon cl::Hidden, cl::init(27)); 114254f889dSBrendon Cahoon 115254f889dSBrendon Cahoon /// A command line argument to limit the number of stages in the pipeline. 116254f889dSBrendon Cahoon static cl::opt<int> 117254f889dSBrendon Cahoon SwpMaxStages("pipeliner-max-stages", 118254f889dSBrendon Cahoon cl::desc("Maximum stages allowed in the generated scheduled."), 119254f889dSBrendon Cahoon cl::Hidden, cl::init(3)); 120254f889dSBrendon Cahoon 121254f889dSBrendon Cahoon /// A command line option to disable the pruning of chain dependences due to 122254f889dSBrendon Cahoon /// an unrelated Phi. 123254f889dSBrendon Cahoon static cl::opt<bool> 124254f889dSBrendon Cahoon SwpPruneDeps("pipeliner-prune-deps", 125254f889dSBrendon Cahoon cl::desc("Prune dependences between unrelated Phi nodes."), 126254f889dSBrendon Cahoon cl::Hidden, cl::init(true)); 127254f889dSBrendon Cahoon 128254f889dSBrendon Cahoon /// A command line option to disable the pruning of loop carried order 129254f889dSBrendon Cahoon /// dependences. 130254f889dSBrendon Cahoon static cl::opt<bool> 131254f889dSBrendon Cahoon SwpPruneLoopCarried("pipeliner-prune-loop-carried", 132254f889dSBrendon Cahoon cl::desc("Prune loop carried order dependences."), 133254f889dSBrendon Cahoon cl::Hidden, cl::init(true)); 134254f889dSBrendon Cahoon 135254f889dSBrendon Cahoon #ifndef NDEBUG 136254f889dSBrendon Cahoon static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1)); 137254f889dSBrendon Cahoon #endif 138254f889dSBrendon Cahoon 139254f889dSBrendon Cahoon static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii", 140254f889dSBrendon Cahoon cl::ReallyHidden, cl::init(false), 141254f889dSBrendon Cahoon cl::ZeroOrMore, cl::desc("Ignore RecMII")); 142254f889dSBrendon Cahoon 143fa2e3583SAdrian Prantl namespace llvm { 144fa2e3583SAdrian Prantl 14562ac69d4SSumanth Gundapaneni // A command line option to enable the CopyToPhi DAG mutation. 146fa2e3583SAdrian Prantl cl::opt<bool> 14700d4c386SAleksandr Urakov SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden, 14862ac69d4SSumanth Gundapaneni cl::init(true), cl::ZeroOrMore, 14962ac69d4SSumanth Gundapaneni cl::desc("Enable CopyToPhi DAG Mutation")); 15062ac69d4SSumanth Gundapaneni 151fa2e3583SAdrian Prantl } // end namespace llvm 152254f889dSBrendon Cahoon 153254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5; 154254f889dSBrendon Cahoon char MachinePipeliner::ID = 0; 155254f889dSBrendon Cahoon #ifndef NDEBUG 156254f889dSBrendon Cahoon int MachinePipeliner::NumTries = 0; 157254f889dSBrendon Cahoon #endif 158254f889dSBrendon Cahoon char &llvm::MachinePipelinerID = MachinePipeliner::ID; 15932a40564SEugene Zelenko 1601527baabSMatthias Braun INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE, 161254f889dSBrendon Cahoon "Modulo Software Pipelining", false, false) 162254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 163254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 164254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 165254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 1661527baabSMatthias Braun INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE, 167254f889dSBrendon Cahoon "Modulo Software Pipelining", false, false) 168254f889dSBrendon Cahoon 169254f889dSBrendon Cahoon /// The "main" function for implementing Swing Modulo Scheduling. 170254f889dSBrendon Cahoon bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) { 171f1caa283SMatthias Braun if (skipFunction(mf.getFunction())) 172254f889dSBrendon Cahoon return false; 173254f889dSBrendon Cahoon 174254f889dSBrendon Cahoon if (!EnableSWP) 175254f889dSBrendon Cahoon return false; 176254f889dSBrendon Cahoon 177f1caa283SMatthias Braun if (mf.getFunction().getAttributes().hasAttribute( 178b518054bSReid Kleckner AttributeList::FunctionIndex, Attribute::OptimizeForSize) && 179254f889dSBrendon Cahoon !EnableSWPOptSize.getPosition()) 180254f889dSBrendon Cahoon return false; 181254f889dSBrendon Cahoon 182254f889dSBrendon Cahoon MF = &mf; 183254f889dSBrendon Cahoon MLI = &getAnalysis<MachineLoopInfo>(); 184254f889dSBrendon Cahoon MDT = &getAnalysis<MachineDominatorTree>(); 185254f889dSBrendon Cahoon TII = MF->getSubtarget().getInstrInfo(); 186254f889dSBrendon Cahoon RegClassInfo.runOnMachineFunction(*MF); 187254f889dSBrendon Cahoon 188254f889dSBrendon Cahoon for (auto &L : *MLI) 189254f889dSBrendon Cahoon scheduleLoop(*L); 190254f889dSBrendon Cahoon 191254f889dSBrendon Cahoon return false; 192254f889dSBrendon Cahoon } 193254f889dSBrendon Cahoon 194254f889dSBrendon Cahoon /// Attempt to perform the SMS algorithm on the specified loop. This function is 195254f889dSBrendon Cahoon /// the main entry point for the algorithm. The function identifies candidate 196254f889dSBrendon Cahoon /// loops, calculates the minimum initiation interval, and attempts to schedule 197254f889dSBrendon Cahoon /// the loop. 198254f889dSBrendon Cahoon bool MachinePipeliner::scheduleLoop(MachineLoop &L) { 199254f889dSBrendon Cahoon bool Changed = false; 200254f889dSBrendon Cahoon for (auto &InnerLoop : L) 201254f889dSBrendon Cahoon Changed |= scheduleLoop(*InnerLoop); 202254f889dSBrendon Cahoon 203254f889dSBrendon Cahoon #ifndef NDEBUG 204254f889dSBrendon Cahoon // Stop trying after reaching the limit (if any). 205254f889dSBrendon Cahoon int Limit = SwpLoopLimit; 206254f889dSBrendon Cahoon if (Limit >= 0) { 207254f889dSBrendon Cahoon if (NumTries >= SwpLoopLimit) 208254f889dSBrendon Cahoon return Changed; 209254f889dSBrendon Cahoon NumTries++; 210254f889dSBrendon Cahoon } 211254f889dSBrendon Cahoon #endif 212254f889dSBrendon Cahoon 213254f889dSBrendon Cahoon if (!canPipelineLoop(L)) 214254f889dSBrendon Cahoon return Changed; 215254f889dSBrendon Cahoon 216254f889dSBrendon Cahoon ++NumTrytoPipeline; 217254f889dSBrendon Cahoon 218254f889dSBrendon Cahoon Changed = swingModuloScheduler(L); 219254f889dSBrendon Cahoon 220254f889dSBrendon Cahoon return Changed; 221254f889dSBrendon Cahoon } 222254f889dSBrendon Cahoon 223254f889dSBrendon Cahoon /// Return true if the loop can be software pipelined. The algorithm is 224254f889dSBrendon Cahoon /// restricted to loops with a single basic block. Make sure that the 225254f889dSBrendon Cahoon /// branch in the loop can be analyzed. 226254f889dSBrendon Cahoon bool MachinePipeliner::canPipelineLoop(MachineLoop &L) { 227254f889dSBrendon Cahoon if (L.getNumBlocks() != 1) 228254f889dSBrendon Cahoon return false; 229254f889dSBrendon Cahoon 230254f889dSBrendon Cahoon // Check if the branch can't be understood because we can't do pipelining 231254f889dSBrendon Cahoon // if that's the case. 232254f889dSBrendon Cahoon LI.TBB = nullptr; 233254f889dSBrendon Cahoon LI.FBB = nullptr; 234254f889dSBrendon Cahoon LI.BrCond.clear(); 235254f889dSBrendon Cahoon if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) 236254f889dSBrendon Cahoon return false; 237254f889dSBrendon Cahoon 238254f889dSBrendon Cahoon LI.LoopInductionVar = nullptr; 239254f889dSBrendon Cahoon LI.LoopCompare = nullptr; 240254f889dSBrendon Cahoon if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) 241254f889dSBrendon Cahoon return false; 242254f889dSBrendon Cahoon 243254f889dSBrendon Cahoon if (!L.getLoopPreheader()) 244254f889dSBrendon Cahoon return false; 245254f889dSBrendon Cahoon 246c715a5d2SKrzysztof Parzyszek // Remove any subregisters from inputs to phi nodes. 247c715a5d2SKrzysztof Parzyszek preprocessPhiNodes(*L.getHeader()); 248254f889dSBrendon Cahoon return true; 249254f889dSBrendon Cahoon } 250254f889dSBrendon Cahoon 251c715a5d2SKrzysztof Parzyszek void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) { 252c715a5d2SKrzysztof Parzyszek MachineRegisterInfo &MRI = MF->getRegInfo(); 253c715a5d2SKrzysztof Parzyszek SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes(); 254c715a5d2SKrzysztof Parzyszek 255c715a5d2SKrzysztof Parzyszek for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) { 256c715a5d2SKrzysztof Parzyszek MachineOperand &DefOp = PI.getOperand(0); 257c715a5d2SKrzysztof Parzyszek assert(DefOp.getSubReg() == 0); 258c715a5d2SKrzysztof Parzyszek auto *RC = MRI.getRegClass(DefOp.getReg()); 259c715a5d2SKrzysztof Parzyszek 260c715a5d2SKrzysztof Parzyszek for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) { 261c715a5d2SKrzysztof Parzyszek MachineOperand &RegOp = PI.getOperand(i); 262c715a5d2SKrzysztof Parzyszek if (RegOp.getSubReg() == 0) 263c715a5d2SKrzysztof Parzyszek continue; 264c715a5d2SKrzysztof Parzyszek 265c715a5d2SKrzysztof Parzyszek // If the operand uses a subregister, replace it with a new register 266c715a5d2SKrzysztof Parzyszek // without subregisters, and generate a copy to the new register. 267c715a5d2SKrzysztof Parzyszek unsigned NewReg = MRI.createVirtualRegister(RC); 268c715a5d2SKrzysztof Parzyszek MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB(); 269c715a5d2SKrzysztof Parzyszek MachineBasicBlock::iterator At = PredB.getFirstTerminator(); 270c715a5d2SKrzysztof Parzyszek const DebugLoc &DL = PredB.findDebugLoc(At); 271c715a5d2SKrzysztof Parzyszek auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg) 272c715a5d2SKrzysztof Parzyszek .addReg(RegOp.getReg(), getRegState(RegOp), 273c715a5d2SKrzysztof Parzyszek RegOp.getSubReg()); 274c715a5d2SKrzysztof Parzyszek Slots.insertMachineInstrInMaps(*Copy); 275c715a5d2SKrzysztof Parzyszek RegOp.setReg(NewReg); 276c715a5d2SKrzysztof Parzyszek RegOp.setSubReg(0); 277c715a5d2SKrzysztof Parzyszek } 278c715a5d2SKrzysztof Parzyszek } 279c715a5d2SKrzysztof Parzyszek } 280c715a5d2SKrzysztof Parzyszek 281254f889dSBrendon Cahoon /// The SMS algorithm consists of the following main steps: 282254f889dSBrendon Cahoon /// 1. Computation and analysis of the dependence graph. 283254f889dSBrendon Cahoon /// 2. Ordering of the nodes (instructions). 284254f889dSBrendon Cahoon /// 3. Attempt to Schedule the loop. 285254f889dSBrendon Cahoon bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) { 286254f889dSBrendon Cahoon assert(L.getBlocks().size() == 1 && "SMS works on single blocks only."); 287254f889dSBrendon Cahoon 288254f889dSBrendon Cahoon SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo); 289254f889dSBrendon Cahoon 290254f889dSBrendon Cahoon MachineBasicBlock *MBB = L.getHeader(); 291254f889dSBrendon Cahoon // The kernel should not include any terminator instructions. These 292254f889dSBrendon Cahoon // will be added back later. 293254f889dSBrendon Cahoon SMS.startBlock(MBB); 294254f889dSBrendon Cahoon 295254f889dSBrendon Cahoon // Compute the number of 'real' instructions in the basic block by 296254f889dSBrendon Cahoon // ignoring terminators. 297254f889dSBrendon Cahoon unsigned size = MBB->size(); 298254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(), 299254f889dSBrendon Cahoon E = MBB->instr_end(); 300254f889dSBrendon Cahoon I != E; ++I, --size) 301254f889dSBrendon Cahoon ; 302254f889dSBrendon Cahoon 303254f889dSBrendon Cahoon SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size); 304254f889dSBrendon Cahoon SMS.schedule(); 305254f889dSBrendon Cahoon SMS.exitRegion(); 306254f889dSBrendon Cahoon 307254f889dSBrendon Cahoon SMS.finishBlock(); 308254f889dSBrendon Cahoon return SMS.hasNewSchedule(); 309254f889dSBrendon Cahoon } 310254f889dSBrendon Cahoon 311254f889dSBrendon Cahoon /// We override the schedule function in ScheduleDAGInstrs to implement the 312254f889dSBrendon Cahoon /// scheduling part of the Swing Modulo Scheduling algorithm. 313254f889dSBrendon Cahoon void SwingSchedulerDAG::schedule() { 314254f889dSBrendon Cahoon AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults(); 315254f889dSBrendon Cahoon buildSchedGraph(AA); 316254f889dSBrendon Cahoon addLoopCarriedDependences(AA); 317254f889dSBrendon Cahoon updatePhiDependences(); 318254f889dSBrendon Cahoon Topo.InitDAGTopologicalSorting(); 319254f889dSBrendon Cahoon changeDependences(); 32062ac69d4SSumanth Gundapaneni postprocessDAG(); 321726e12cfSMatthias Braun LLVM_DEBUG(dump()); 322254f889dSBrendon Cahoon 323254f889dSBrendon Cahoon NodeSetType NodeSets; 324254f889dSBrendon Cahoon findCircuits(NodeSets); 3254b8bcf00SRoorda, Jan-Willem NodeSetType Circuits = NodeSets; 326254f889dSBrendon Cahoon 327254f889dSBrendon Cahoon // Calculate the MII. 328254f889dSBrendon Cahoon unsigned ResMII = calculateResMII(); 329254f889dSBrendon Cahoon unsigned RecMII = calculateRecMII(NodeSets); 330254f889dSBrendon Cahoon 331254f889dSBrendon Cahoon fuseRecs(NodeSets); 332254f889dSBrendon Cahoon 333254f889dSBrendon Cahoon // This flag is used for testing and can cause correctness problems. 334254f889dSBrendon Cahoon if (SwpIgnoreRecMII) 335254f889dSBrendon Cahoon RecMII = 0; 336254f889dSBrendon Cahoon 337254f889dSBrendon Cahoon MII = std::max(ResMII, RecMII); 338d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "MII = " << MII << " (rec=" << RecMII 339d34e60caSNicola Zaghen << ", res=" << ResMII << ")\n"); 340254f889dSBrendon Cahoon 341254f889dSBrendon Cahoon // Can't schedule a loop without a valid MII. 342254f889dSBrendon Cahoon if (MII == 0) 343254f889dSBrendon Cahoon return; 344254f889dSBrendon Cahoon 345254f889dSBrendon Cahoon // Don't pipeline large loops. 346254f889dSBrendon Cahoon if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) 347254f889dSBrendon Cahoon return; 348254f889dSBrendon Cahoon 349254f889dSBrendon Cahoon computeNodeFunctions(NodeSets); 350254f889dSBrendon Cahoon 351254f889dSBrendon Cahoon registerPressureFilter(NodeSets); 352254f889dSBrendon Cahoon 353254f889dSBrendon Cahoon colocateNodeSets(NodeSets); 354254f889dSBrendon Cahoon 355254f889dSBrendon Cahoon checkNodeSets(NodeSets); 356254f889dSBrendon Cahoon 357d34e60caSNicola Zaghen LLVM_DEBUG({ 358254f889dSBrendon Cahoon for (auto &I : NodeSets) { 359254f889dSBrendon Cahoon dbgs() << " Rec NodeSet "; 360254f889dSBrendon Cahoon I.dump(); 361254f889dSBrendon Cahoon } 362254f889dSBrendon Cahoon }); 363254f889dSBrendon Cahoon 3646c2f868bSKrzysztof Parzyszek std::stable_sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>()); 365254f889dSBrendon Cahoon 366254f889dSBrendon Cahoon groupRemainingNodes(NodeSets); 367254f889dSBrendon Cahoon 368254f889dSBrendon Cahoon removeDuplicateNodes(NodeSets); 369254f889dSBrendon Cahoon 370d34e60caSNicola Zaghen LLVM_DEBUG({ 371254f889dSBrendon Cahoon for (auto &I : NodeSets) { 372254f889dSBrendon Cahoon dbgs() << " NodeSet "; 373254f889dSBrendon Cahoon I.dump(); 374254f889dSBrendon Cahoon } 375254f889dSBrendon Cahoon }); 376254f889dSBrendon Cahoon 377254f889dSBrendon Cahoon computeNodeOrder(NodeSets); 378254f889dSBrendon Cahoon 3794b8bcf00SRoorda, Jan-Willem // check for node order issues 3804b8bcf00SRoorda, Jan-Willem checkValidNodeOrder(Circuits); 3814b8bcf00SRoorda, Jan-Willem 382254f889dSBrendon Cahoon SMSchedule Schedule(Pass.MF); 383254f889dSBrendon Cahoon Scheduled = schedulePipeline(Schedule); 384254f889dSBrendon Cahoon 385254f889dSBrendon Cahoon if (!Scheduled) 386254f889dSBrendon Cahoon return; 387254f889dSBrendon Cahoon 388254f889dSBrendon Cahoon unsigned numStages = Schedule.getMaxStageCount(); 389254f889dSBrendon Cahoon // No need to generate pipeline if there are no overlapped iterations. 390254f889dSBrendon Cahoon if (numStages == 0) 391254f889dSBrendon Cahoon return; 392254f889dSBrendon Cahoon 393254f889dSBrendon Cahoon // Check that the maximum stage count is less than user-defined limit. 394254f889dSBrendon Cahoon if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) 395254f889dSBrendon Cahoon return; 396254f889dSBrendon Cahoon 397254f889dSBrendon Cahoon generatePipelinedLoop(Schedule); 398254f889dSBrendon Cahoon ++NumPipelined; 399254f889dSBrendon Cahoon } 400254f889dSBrendon Cahoon 401254f889dSBrendon Cahoon /// Clean up after the software pipeliner runs. 402254f889dSBrendon Cahoon void SwingSchedulerDAG::finishBlock() { 403254f889dSBrendon Cahoon for (MachineInstr *I : NewMIs) 404254f889dSBrendon Cahoon MF.DeleteMachineInstr(I); 405254f889dSBrendon Cahoon NewMIs.clear(); 406254f889dSBrendon Cahoon 407254f889dSBrendon Cahoon // Call the superclass. 408254f889dSBrendon Cahoon ScheduleDAGInstrs::finishBlock(); 409254f889dSBrendon Cahoon } 410254f889dSBrendon Cahoon 411254f889dSBrendon Cahoon /// Return the register values for the operands of a Phi instruction. 412254f889dSBrendon Cahoon /// This function assume the instruction is a Phi. 413254f889dSBrendon Cahoon static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop, 414254f889dSBrendon Cahoon unsigned &InitVal, unsigned &LoopVal) { 415254f889dSBrendon Cahoon assert(Phi.isPHI() && "Expecting a Phi."); 416254f889dSBrendon Cahoon 417254f889dSBrendon Cahoon InitVal = 0; 418254f889dSBrendon Cahoon LoopVal = 0; 419254f889dSBrendon Cahoon for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) 420254f889dSBrendon Cahoon if (Phi.getOperand(i + 1).getMBB() != Loop) 421254f889dSBrendon Cahoon InitVal = Phi.getOperand(i).getReg(); 422fbfb19b1SSimon Pilgrim else 423254f889dSBrendon Cahoon LoopVal = Phi.getOperand(i).getReg(); 424254f889dSBrendon Cahoon 425254f889dSBrendon Cahoon assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure."); 426254f889dSBrendon Cahoon } 427254f889dSBrendon Cahoon 428254f889dSBrendon Cahoon /// Return the Phi register value that comes from the incoming block. 429254f889dSBrendon Cahoon static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) { 430254f889dSBrendon Cahoon for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) 431254f889dSBrendon Cahoon if (Phi.getOperand(i + 1).getMBB() != LoopBB) 432254f889dSBrendon Cahoon return Phi.getOperand(i).getReg(); 433254f889dSBrendon Cahoon return 0; 434254f889dSBrendon Cahoon } 435254f889dSBrendon Cahoon 4368f976ba0SHiroshi Inoue /// Return the Phi register value that comes the loop block. 437254f889dSBrendon Cahoon static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) { 438254f889dSBrendon Cahoon for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2) 439254f889dSBrendon Cahoon if (Phi.getOperand(i + 1).getMBB() == LoopBB) 440254f889dSBrendon Cahoon return Phi.getOperand(i).getReg(); 441254f889dSBrendon Cahoon return 0; 442254f889dSBrendon Cahoon } 443254f889dSBrendon Cahoon 444254f889dSBrendon Cahoon /// Return true if SUb can be reached from SUa following the chain edges. 445254f889dSBrendon Cahoon static bool isSuccOrder(SUnit *SUa, SUnit *SUb) { 446254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 447254f889dSBrendon Cahoon SmallVector<SUnit *, 8> Worklist; 448254f889dSBrendon Cahoon Worklist.push_back(SUa); 449254f889dSBrendon Cahoon while (!Worklist.empty()) { 450254f889dSBrendon Cahoon const SUnit *SU = Worklist.pop_back_val(); 451254f889dSBrendon Cahoon for (auto &SI : SU->Succs) { 452254f889dSBrendon Cahoon SUnit *SuccSU = SI.getSUnit(); 453254f889dSBrendon Cahoon if (SI.getKind() == SDep::Order) { 454254f889dSBrendon Cahoon if (Visited.count(SuccSU)) 455254f889dSBrendon Cahoon continue; 456254f889dSBrendon Cahoon if (SuccSU == SUb) 457254f889dSBrendon Cahoon return true; 458254f889dSBrendon Cahoon Worklist.push_back(SuccSU); 459254f889dSBrendon Cahoon Visited.insert(SuccSU); 460254f889dSBrendon Cahoon } 461254f889dSBrendon Cahoon } 462254f889dSBrendon Cahoon } 463254f889dSBrendon Cahoon return false; 464254f889dSBrendon Cahoon } 465254f889dSBrendon Cahoon 466254f889dSBrendon Cahoon /// Return true if the instruction causes a chain between memory 467254f889dSBrendon Cahoon /// references before and after it. 468254f889dSBrendon Cahoon static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) { 469254f889dSBrendon Cahoon return MI.isCall() || MI.hasUnmodeledSideEffects() || 470254f889dSBrendon Cahoon (MI.hasOrderedMemoryRef() && 471d98cf00cSJustin Lebar (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA))); 472254f889dSBrendon Cahoon } 473254f889dSBrendon Cahoon 474254f889dSBrendon Cahoon /// Return the underlying objects for the memory references of an instruction. 475254f889dSBrendon Cahoon /// This function calls the code in ValueTracking, but first checks that the 476254f889dSBrendon Cahoon /// instruction has a memory operand. 477254f889dSBrendon Cahoon static void getUnderlyingObjects(MachineInstr *MI, 478254f889dSBrendon Cahoon SmallVectorImpl<Value *> &Objs, 479254f889dSBrendon Cahoon const DataLayout &DL) { 480254f889dSBrendon Cahoon if (!MI->hasOneMemOperand()) 481254f889dSBrendon Cahoon return; 482254f889dSBrendon Cahoon MachineMemOperand *MM = *MI->memoperands_begin(); 483254f889dSBrendon Cahoon if (!MM->getValue()) 484254f889dSBrendon Cahoon return; 485254f889dSBrendon Cahoon GetUnderlyingObjects(const_cast<Value *>(MM->getValue()), Objs, DL); 4869f041b18SKrzysztof Parzyszek for (Value *V : Objs) { 4879f041b18SKrzysztof Parzyszek if (!isIdentifiedObject(V)) { 4889f041b18SKrzysztof Parzyszek Objs.clear(); 4899f041b18SKrzysztof Parzyszek return; 4909f041b18SKrzysztof Parzyszek } 4919f041b18SKrzysztof Parzyszek Objs.push_back(V); 4929f041b18SKrzysztof Parzyszek } 493254f889dSBrendon Cahoon } 494254f889dSBrendon Cahoon 495254f889dSBrendon Cahoon /// Add a chain edge between a load and store if the store can be an 496254f889dSBrendon Cahoon /// alias of the load on a subsequent iteration, i.e., a loop carried 497254f889dSBrendon Cahoon /// dependence. This code is very similar to the code in ScheduleDAGInstrs 498254f889dSBrendon Cahoon /// but that code doesn't create loop carried dependences. 499254f889dSBrendon Cahoon void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) { 500254f889dSBrendon Cahoon MapVector<Value *, SmallVector<SUnit *, 4>> PendingLoads; 5019f041b18SKrzysztof Parzyszek Value *UnknownValue = 5029f041b18SKrzysztof Parzyszek UndefValue::get(Type::getVoidTy(MF.getFunction().getContext())); 503254f889dSBrendon Cahoon for (auto &SU : SUnits) { 504254f889dSBrendon Cahoon MachineInstr &MI = *SU.getInstr(); 505254f889dSBrendon Cahoon if (isDependenceBarrier(MI, AA)) 506254f889dSBrendon Cahoon PendingLoads.clear(); 507254f889dSBrendon Cahoon else if (MI.mayLoad()) { 508254f889dSBrendon Cahoon SmallVector<Value *, 4> Objs; 509254f889dSBrendon Cahoon getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); 5109f041b18SKrzysztof Parzyszek if (Objs.empty()) 5119f041b18SKrzysztof Parzyszek Objs.push_back(UnknownValue); 512254f889dSBrendon Cahoon for (auto V : Objs) { 513254f889dSBrendon Cahoon SmallVector<SUnit *, 4> &SUs = PendingLoads[V]; 514254f889dSBrendon Cahoon SUs.push_back(&SU); 515254f889dSBrendon Cahoon } 516254f889dSBrendon Cahoon } else if (MI.mayStore()) { 517254f889dSBrendon Cahoon SmallVector<Value *, 4> Objs; 518254f889dSBrendon Cahoon getUnderlyingObjects(&MI, Objs, MF.getDataLayout()); 5199f041b18SKrzysztof Parzyszek if (Objs.empty()) 5209f041b18SKrzysztof Parzyszek Objs.push_back(UnknownValue); 521254f889dSBrendon Cahoon for (auto V : Objs) { 522254f889dSBrendon Cahoon MapVector<Value *, SmallVector<SUnit *, 4>>::iterator I = 523254f889dSBrendon Cahoon PendingLoads.find(V); 524254f889dSBrendon Cahoon if (I == PendingLoads.end()) 525254f889dSBrendon Cahoon continue; 526254f889dSBrendon Cahoon for (auto Load : I->second) { 527254f889dSBrendon Cahoon if (isSuccOrder(Load, &SU)) 528254f889dSBrendon Cahoon continue; 529254f889dSBrendon Cahoon MachineInstr &LdMI = *Load->getInstr(); 530254f889dSBrendon Cahoon // First, perform the cheaper check that compares the base register. 531254f889dSBrendon Cahoon // If they are the same and the load offset is less than the store 532254f889dSBrendon Cahoon // offset, then mark the dependence as loop carried potentially. 533d7eebd6dSFrancis Visoiu Mistrih MachineOperand *BaseOp1, *BaseOp2; 534254f889dSBrendon Cahoon int64_t Offset1, Offset2; 535d7eebd6dSFrancis Visoiu Mistrih if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) && 536d7eebd6dSFrancis Visoiu Mistrih TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) { 537d7eebd6dSFrancis Visoiu Mistrih if (BaseOp1->isIdenticalTo(*BaseOp2) && 538d7eebd6dSFrancis Visoiu Mistrih (int)Offset1 < (int)Offset2) { 539254f889dSBrendon Cahoon assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) && 540254f889dSBrendon Cahoon "What happened to the chain edge?"); 541c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 542c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 543c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 544254f889dSBrendon Cahoon continue; 545254f889dSBrendon Cahoon } 5469f041b18SKrzysztof Parzyszek } 547254f889dSBrendon Cahoon // Second, the more expensive check that uses alias analysis on the 548254f889dSBrendon Cahoon // base registers. If they alias, and the load offset is less than 549254f889dSBrendon Cahoon // the store offset, the mark the dependence as loop carried. 550254f889dSBrendon Cahoon if (!AA) { 551c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 552c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 553c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 554254f889dSBrendon Cahoon continue; 555254f889dSBrendon Cahoon } 556254f889dSBrendon Cahoon MachineMemOperand *MMO1 = *LdMI.memoperands_begin(); 557254f889dSBrendon Cahoon MachineMemOperand *MMO2 = *MI.memoperands_begin(); 558254f889dSBrendon Cahoon if (!MMO1->getValue() || !MMO2->getValue()) { 559c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 560c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 561c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 562254f889dSBrendon Cahoon continue; 563254f889dSBrendon Cahoon } 564254f889dSBrendon Cahoon if (MMO1->getValue() == MMO2->getValue() && 565254f889dSBrendon Cahoon MMO1->getOffset() <= MMO2->getOffset()) { 566c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 567c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 568c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 569254f889dSBrendon Cahoon continue; 570254f889dSBrendon Cahoon } 571254f889dSBrendon Cahoon AliasResult AAResult = AA->alias( 5726ef8002cSGeorge Burgess IV MemoryLocation(MMO1->getValue(), LocationSize::unknown(), 573254f889dSBrendon Cahoon MMO1->getAAInfo()), 5746ef8002cSGeorge Burgess IV MemoryLocation(MMO2->getValue(), LocationSize::unknown(), 575254f889dSBrendon Cahoon MMO2->getAAInfo())); 576254f889dSBrendon Cahoon 577c715a5d2SKrzysztof Parzyszek if (AAResult != NoAlias) { 578c715a5d2SKrzysztof Parzyszek SDep Dep(Load, SDep::Barrier); 579c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 580c715a5d2SKrzysztof Parzyszek SU.addPred(Dep); 581c715a5d2SKrzysztof Parzyszek } 582254f889dSBrendon Cahoon } 583254f889dSBrendon Cahoon } 584254f889dSBrendon Cahoon } 585254f889dSBrendon Cahoon } 586254f889dSBrendon Cahoon } 587254f889dSBrendon Cahoon 588254f889dSBrendon Cahoon /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer 589254f889dSBrendon Cahoon /// processes dependences for PHIs. This function adds true dependences 590254f889dSBrendon Cahoon /// from a PHI to a use, and a loop carried dependence from the use to the 591254f889dSBrendon Cahoon /// PHI. The loop carried dependence is represented as an anti dependence 592254f889dSBrendon Cahoon /// edge. This function also removes chain dependences between unrelated 593254f889dSBrendon Cahoon /// PHIs. 594254f889dSBrendon Cahoon void SwingSchedulerDAG::updatePhiDependences() { 595254f889dSBrendon Cahoon SmallVector<SDep, 4> RemoveDeps; 596254f889dSBrendon Cahoon const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>(); 597254f889dSBrendon Cahoon 598254f889dSBrendon Cahoon // Iterate over each DAG node. 599254f889dSBrendon Cahoon for (SUnit &I : SUnits) { 600254f889dSBrendon Cahoon RemoveDeps.clear(); 601254f889dSBrendon Cahoon // Set to true if the instruction has an operand defined by a Phi. 602254f889dSBrendon Cahoon unsigned HasPhiUse = 0; 603254f889dSBrendon Cahoon unsigned HasPhiDef = 0; 604254f889dSBrendon Cahoon MachineInstr *MI = I.getInstr(); 605254f889dSBrendon Cahoon // Iterate over each operand, and we process the definitions. 606254f889dSBrendon Cahoon for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 607254f889dSBrendon Cahoon MOE = MI->operands_end(); 608254f889dSBrendon Cahoon MOI != MOE; ++MOI) { 609254f889dSBrendon Cahoon if (!MOI->isReg()) 610254f889dSBrendon Cahoon continue; 611254f889dSBrendon Cahoon unsigned Reg = MOI->getReg(); 612254f889dSBrendon Cahoon if (MOI->isDef()) { 613254f889dSBrendon Cahoon // If the register is used by a Phi, then create an anti dependence. 614254f889dSBrendon Cahoon for (MachineRegisterInfo::use_instr_iterator 615254f889dSBrendon Cahoon UI = MRI.use_instr_begin(Reg), 616254f889dSBrendon Cahoon UE = MRI.use_instr_end(); 617254f889dSBrendon Cahoon UI != UE; ++UI) { 618254f889dSBrendon Cahoon MachineInstr *UseMI = &*UI; 619254f889dSBrendon Cahoon SUnit *SU = getSUnit(UseMI); 620cdc71612SEugene Zelenko if (SU != nullptr && UseMI->isPHI()) { 621254f889dSBrendon Cahoon if (!MI->isPHI()) { 622254f889dSBrendon Cahoon SDep Dep(SU, SDep::Anti, Reg); 623c715a5d2SKrzysztof Parzyszek Dep.setLatency(1); 624254f889dSBrendon Cahoon I.addPred(Dep); 625254f889dSBrendon Cahoon } else { 626254f889dSBrendon Cahoon HasPhiDef = Reg; 627254f889dSBrendon Cahoon // Add a chain edge to a dependent Phi that isn't an existing 628254f889dSBrendon Cahoon // predecessor. 629254f889dSBrendon Cahoon if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) 630254f889dSBrendon Cahoon I.addPred(SDep(SU, SDep::Barrier)); 631254f889dSBrendon Cahoon } 632254f889dSBrendon Cahoon } 633254f889dSBrendon Cahoon } 634254f889dSBrendon Cahoon } else if (MOI->isUse()) { 635254f889dSBrendon Cahoon // If the register is defined by a Phi, then create a true dependence. 636254f889dSBrendon Cahoon MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg); 637cdc71612SEugene Zelenko if (DefMI == nullptr) 638254f889dSBrendon Cahoon continue; 639254f889dSBrendon Cahoon SUnit *SU = getSUnit(DefMI); 640cdc71612SEugene Zelenko if (SU != nullptr && DefMI->isPHI()) { 641254f889dSBrendon Cahoon if (!MI->isPHI()) { 642254f889dSBrendon Cahoon SDep Dep(SU, SDep::Data, Reg); 643254f889dSBrendon Cahoon Dep.setLatency(0); 644254f889dSBrendon Cahoon ST.adjustSchedDependency(SU, &I, Dep); 645254f889dSBrendon Cahoon I.addPred(Dep); 646254f889dSBrendon Cahoon } else { 647254f889dSBrendon Cahoon HasPhiUse = Reg; 648254f889dSBrendon Cahoon // Add a chain edge to a dependent Phi that isn't an existing 649254f889dSBrendon Cahoon // predecessor. 650254f889dSBrendon Cahoon if (SU->NodeNum < I.NodeNum && !I.isPred(SU)) 651254f889dSBrendon Cahoon I.addPred(SDep(SU, SDep::Barrier)); 652254f889dSBrendon Cahoon } 653254f889dSBrendon Cahoon } 654254f889dSBrendon Cahoon } 655254f889dSBrendon Cahoon } 656254f889dSBrendon Cahoon // Remove order dependences from an unrelated Phi. 657254f889dSBrendon Cahoon if (!SwpPruneDeps) 658254f889dSBrendon Cahoon continue; 659254f889dSBrendon Cahoon for (auto &PI : I.Preds) { 660254f889dSBrendon Cahoon MachineInstr *PMI = PI.getSUnit()->getInstr(); 661254f889dSBrendon Cahoon if (PMI->isPHI() && PI.getKind() == SDep::Order) { 662254f889dSBrendon Cahoon if (I.getInstr()->isPHI()) { 663254f889dSBrendon Cahoon if (PMI->getOperand(0).getReg() == HasPhiUse) 664254f889dSBrendon Cahoon continue; 665254f889dSBrendon Cahoon if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef) 666254f889dSBrendon Cahoon continue; 667254f889dSBrendon Cahoon } 668254f889dSBrendon Cahoon RemoveDeps.push_back(PI); 669254f889dSBrendon Cahoon } 670254f889dSBrendon Cahoon } 671254f889dSBrendon Cahoon for (int i = 0, e = RemoveDeps.size(); i != e; ++i) 672254f889dSBrendon Cahoon I.removePred(RemoveDeps[i]); 673254f889dSBrendon Cahoon } 674254f889dSBrendon Cahoon } 675254f889dSBrendon Cahoon 676254f889dSBrendon Cahoon /// Iterate over each DAG node and see if we can change any dependences 677254f889dSBrendon Cahoon /// in order to reduce the recurrence MII. 678254f889dSBrendon Cahoon void SwingSchedulerDAG::changeDependences() { 679254f889dSBrendon Cahoon // See if an instruction can use a value from the previous iteration. 680254f889dSBrendon Cahoon // If so, we update the base and offset of the instruction and change 681254f889dSBrendon Cahoon // the dependences. 682254f889dSBrendon Cahoon for (SUnit &I : SUnits) { 683254f889dSBrendon Cahoon unsigned BasePos = 0, OffsetPos = 0, NewBase = 0; 684254f889dSBrendon Cahoon int64_t NewOffset = 0; 685254f889dSBrendon Cahoon if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase, 686254f889dSBrendon Cahoon NewOffset)) 687254f889dSBrendon Cahoon continue; 688254f889dSBrendon Cahoon 689254f889dSBrendon Cahoon // Get the MI and SUnit for the instruction that defines the original base. 690254f889dSBrendon Cahoon unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg(); 691254f889dSBrendon Cahoon MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase); 692254f889dSBrendon Cahoon if (!DefMI) 693254f889dSBrendon Cahoon continue; 694254f889dSBrendon Cahoon SUnit *DefSU = getSUnit(DefMI); 695254f889dSBrendon Cahoon if (!DefSU) 696254f889dSBrendon Cahoon continue; 697254f889dSBrendon Cahoon // Get the MI and SUnit for the instruction that defins the new base. 698254f889dSBrendon Cahoon MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase); 699254f889dSBrendon Cahoon if (!LastMI) 700254f889dSBrendon Cahoon continue; 701254f889dSBrendon Cahoon SUnit *LastSU = getSUnit(LastMI); 702254f889dSBrendon Cahoon if (!LastSU) 703254f889dSBrendon Cahoon continue; 704254f889dSBrendon Cahoon 705254f889dSBrendon Cahoon if (Topo.IsReachable(&I, LastSU)) 706254f889dSBrendon Cahoon continue; 707254f889dSBrendon Cahoon 708254f889dSBrendon Cahoon // Remove the dependence. The value now depends on a prior iteration. 709254f889dSBrendon Cahoon SmallVector<SDep, 4> Deps; 710254f889dSBrendon Cahoon for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E; 711254f889dSBrendon Cahoon ++P) 712254f889dSBrendon Cahoon if (P->getSUnit() == DefSU) 713254f889dSBrendon Cahoon Deps.push_back(*P); 714254f889dSBrendon Cahoon for (int i = 0, e = Deps.size(); i != e; i++) { 715254f889dSBrendon Cahoon Topo.RemovePred(&I, Deps[i].getSUnit()); 716254f889dSBrendon Cahoon I.removePred(Deps[i]); 717254f889dSBrendon Cahoon } 718254f889dSBrendon Cahoon // Remove the chain dependence between the instructions. 719254f889dSBrendon Cahoon Deps.clear(); 720254f889dSBrendon Cahoon for (auto &P : LastSU->Preds) 721254f889dSBrendon Cahoon if (P.getSUnit() == &I && P.getKind() == SDep::Order) 722254f889dSBrendon Cahoon Deps.push_back(P); 723254f889dSBrendon Cahoon for (int i = 0, e = Deps.size(); i != e; i++) { 724254f889dSBrendon Cahoon Topo.RemovePred(LastSU, Deps[i].getSUnit()); 725254f889dSBrendon Cahoon LastSU->removePred(Deps[i]); 726254f889dSBrendon Cahoon } 727254f889dSBrendon Cahoon 728254f889dSBrendon Cahoon // Add a dependence between the new instruction and the instruction 729254f889dSBrendon Cahoon // that defines the new base. 730254f889dSBrendon Cahoon SDep Dep(&I, SDep::Anti, NewBase); 7318916e438SSumanth Gundapaneni Topo.AddPred(LastSU, &I); 732254f889dSBrendon Cahoon LastSU->addPred(Dep); 733254f889dSBrendon Cahoon 734254f889dSBrendon Cahoon // Remember the base and offset information so that we can update the 735254f889dSBrendon Cahoon // instruction during code generation. 736254f889dSBrendon Cahoon InstrChanges[&I] = std::make_pair(NewBase, NewOffset); 737254f889dSBrendon Cahoon } 738254f889dSBrendon Cahoon } 739254f889dSBrendon Cahoon 740254f889dSBrendon Cahoon namespace { 741cdc71612SEugene Zelenko 742254f889dSBrendon Cahoon // FuncUnitSorter - Comparison operator used to sort instructions by 743254f889dSBrendon Cahoon // the number of functional unit choices. 744254f889dSBrendon Cahoon struct FuncUnitSorter { 745254f889dSBrendon Cahoon const InstrItineraryData *InstrItins; 746254f889dSBrendon Cahoon DenseMap<unsigned, unsigned> Resources; 747254f889dSBrendon Cahoon 74832a40564SEugene Zelenko FuncUnitSorter(const InstrItineraryData *IID) : InstrItins(IID) {} 74932a40564SEugene Zelenko 750254f889dSBrendon Cahoon // Compute the number of functional unit alternatives needed 751254f889dSBrendon Cahoon // at each stage, and take the minimum value. We prioritize the 752254f889dSBrendon Cahoon // instructions by the least number of choices first. 753254f889dSBrendon Cahoon unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const { 754254f889dSBrendon Cahoon unsigned schedClass = Inst->getDesc().getSchedClass(); 755254f889dSBrendon Cahoon unsigned min = UINT_MAX; 756254f889dSBrendon Cahoon for (const InstrStage *IS = InstrItins->beginStage(schedClass), 757254f889dSBrendon Cahoon *IE = InstrItins->endStage(schedClass); 758254f889dSBrendon Cahoon IS != IE; ++IS) { 759254f889dSBrendon Cahoon unsigned funcUnits = IS->getUnits(); 760254f889dSBrendon Cahoon unsigned numAlternatives = countPopulation(funcUnits); 761254f889dSBrendon Cahoon if (numAlternatives < min) { 762254f889dSBrendon Cahoon min = numAlternatives; 763254f889dSBrendon Cahoon F = funcUnits; 764254f889dSBrendon Cahoon } 765254f889dSBrendon Cahoon } 766254f889dSBrendon Cahoon return min; 767254f889dSBrendon Cahoon } 768254f889dSBrendon Cahoon 769254f889dSBrendon Cahoon // Compute the critical resources needed by the instruction. This 770254f889dSBrendon Cahoon // function records the functional units needed by instructions that 771254f889dSBrendon Cahoon // must use only one functional unit. We use this as a tie breaker 772254f889dSBrendon Cahoon // for computing the resource MII. The instrutions that require 773254f889dSBrendon Cahoon // the same, highly used, functional unit have high priority. 774254f889dSBrendon Cahoon void calcCriticalResources(MachineInstr &MI) { 775254f889dSBrendon Cahoon unsigned SchedClass = MI.getDesc().getSchedClass(); 776254f889dSBrendon Cahoon for (const InstrStage *IS = InstrItins->beginStage(SchedClass), 777254f889dSBrendon Cahoon *IE = InstrItins->endStage(SchedClass); 778254f889dSBrendon Cahoon IS != IE; ++IS) { 779254f889dSBrendon Cahoon unsigned FuncUnits = IS->getUnits(); 780254f889dSBrendon Cahoon if (countPopulation(FuncUnits) == 1) 781254f889dSBrendon Cahoon Resources[FuncUnits]++; 782254f889dSBrendon Cahoon } 783254f889dSBrendon Cahoon } 784254f889dSBrendon Cahoon 785254f889dSBrendon Cahoon /// Return true if IS1 has less priority than IS2. 786254f889dSBrendon Cahoon bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const { 787254f889dSBrendon Cahoon unsigned F1 = 0, F2 = 0; 788254f889dSBrendon Cahoon unsigned MFUs1 = minFuncUnits(IS1, F1); 789254f889dSBrendon Cahoon unsigned MFUs2 = minFuncUnits(IS2, F2); 790254f889dSBrendon Cahoon if (MFUs1 == 1 && MFUs2 == 1) 791254f889dSBrendon Cahoon return Resources.lookup(F1) < Resources.lookup(F2); 792254f889dSBrendon Cahoon return MFUs1 > MFUs2; 793254f889dSBrendon Cahoon } 794254f889dSBrendon Cahoon }; 795cdc71612SEugene Zelenko 796cdc71612SEugene Zelenko } // end anonymous namespace 797254f889dSBrendon Cahoon 798254f889dSBrendon Cahoon /// Calculate the resource constrained minimum initiation interval for the 799254f889dSBrendon Cahoon /// specified loop. We use the DFA to model the resources needed for 800254f889dSBrendon Cahoon /// each instruction, and we ignore dependences. A different DFA is created 801254f889dSBrendon Cahoon /// for each cycle that is required. When adding a new instruction, we attempt 802254f889dSBrendon Cahoon /// to add it to each existing DFA, until a legal space is found. If the 803254f889dSBrendon Cahoon /// instruction cannot be reserved in an existing DFA, we create a new one. 804254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateResMII() { 805254f889dSBrendon Cahoon SmallVector<DFAPacketizer *, 8> Resources; 806254f889dSBrendon Cahoon MachineBasicBlock *MBB = Loop.getHeader(); 807254f889dSBrendon Cahoon Resources.push_back(TII->CreateTargetScheduleState(MF.getSubtarget())); 808254f889dSBrendon Cahoon 809254f889dSBrendon Cahoon // Sort the instructions by the number of available choices for scheduling, 810254f889dSBrendon Cahoon // least to most. Use the number of critical resources as the tie breaker. 811254f889dSBrendon Cahoon FuncUnitSorter FUS = 812254f889dSBrendon Cahoon FuncUnitSorter(MF.getSubtarget().getInstrItineraryData()); 813254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), 814254f889dSBrendon Cahoon E = MBB->getFirstTerminator(); 815254f889dSBrendon Cahoon I != E; ++I) 816254f889dSBrendon Cahoon FUS.calcCriticalResources(*I); 817254f889dSBrendon Cahoon PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter> 818254f889dSBrendon Cahoon FuncUnitOrder(FUS); 819254f889dSBrendon Cahoon 820254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(), 821254f889dSBrendon Cahoon E = MBB->getFirstTerminator(); 822254f889dSBrendon Cahoon I != E; ++I) 823254f889dSBrendon Cahoon FuncUnitOrder.push(&*I); 824254f889dSBrendon Cahoon 825254f889dSBrendon Cahoon while (!FuncUnitOrder.empty()) { 826254f889dSBrendon Cahoon MachineInstr *MI = FuncUnitOrder.top(); 827254f889dSBrendon Cahoon FuncUnitOrder.pop(); 828254f889dSBrendon Cahoon if (TII->isZeroCost(MI->getOpcode())) 829254f889dSBrendon Cahoon continue; 830254f889dSBrendon Cahoon // Attempt to reserve the instruction in an existing DFA. At least one 831254f889dSBrendon Cahoon // DFA is needed for each cycle. 832254f889dSBrendon Cahoon unsigned NumCycles = getSUnit(MI)->Latency; 833254f889dSBrendon Cahoon unsigned ReservedCycles = 0; 834254f889dSBrendon Cahoon SmallVectorImpl<DFAPacketizer *>::iterator RI = Resources.begin(); 835254f889dSBrendon Cahoon SmallVectorImpl<DFAPacketizer *>::iterator RE = Resources.end(); 836254f889dSBrendon Cahoon for (unsigned C = 0; C < NumCycles; ++C) 837254f889dSBrendon Cahoon while (RI != RE) { 838254f889dSBrendon Cahoon if ((*RI++)->canReserveResources(*MI)) { 839254f889dSBrendon Cahoon ++ReservedCycles; 840254f889dSBrendon Cahoon break; 841254f889dSBrendon Cahoon } 842254f889dSBrendon Cahoon } 843254f889dSBrendon Cahoon // Start reserving resources using existing DFAs. 844254f889dSBrendon Cahoon for (unsigned C = 0; C < ReservedCycles; ++C) { 845254f889dSBrendon Cahoon --RI; 846254f889dSBrendon Cahoon (*RI)->reserveResources(*MI); 847254f889dSBrendon Cahoon } 848254f889dSBrendon Cahoon // Add new DFAs, if needed, to reserve resources. 849254f889dSBrendon Cahoon for (unsigned C = ReservedCycles; C < NumCycles; ++C) { 850254f889dSBrendon Cahoon DFAPacketizer *NewResource = 851254f889dSBrendon Cahoon TII->CreateTargetScheduleState(MF.getSubtarget()); 852254f889dSBrendon Cahoon assert(NewResource->canReserveResources(*MI) && "Reserve error."); 853254f889dSBrendon Cahoon NewResource->reserveResources(*MI); 854254f889dSBrendon Cahoon Resources.push_back(NewResource); 855254f889dSBrendon Cahoon } 856254f889dSBrendon Cahoon } 857254f889dSBrendon Cahoon int Resmii = Resources.size(); 858254f889dSBrendon Cahoon // Delete the memory for each of the DFAs that were created earlier. 859254f889dSBrendon Cahoon for (DFAPacketizer *RI : Resources) { 860254f889dSBrendon Cahoon DFAPacketizer *D = RI; 861254f889dSBrendon Cahoon delete D; 862254f889dSBrendon Cahoon } 863254f889dSBrendon Cahoon Resources.clear(); 864254f889dSBrendon Cahoon return Resmii; 865254f889dSBrendon Cahoon } 866254f889dSBrendon Cahoon 867254f889dSBrendon Cahoon /// Calculate the recurrence-constrainted minimum initiation interval. 868254f889dSBrendon Cahoon /// Iterate over each circuit. Compute the delay(c) and distance(c) 869254f889dSBrendon Cahoon /// for each circuit. The II needs to satisfy the inequality 870254f889dSBrendon Cahoon /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest 871c73b6d6bSHiroshi Inoue /// II that satisfies the inequality, and the RecMII is the maximum 872254f889dSBrendon Cahoon /// of those values. 873254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) { 874254f889dSBrendon Cahoon unsigned RecMII = 0; 875254f889dSBrendon Cahoon 876254f889dSBrendon Cahoon for (NodeSet &Nodes : NodeSets) { 87732a40564SEugene Zelenko if (Nodes.empty()) 878254f889dSBrendon Cahoon continue; 879254f889dSBrendon Cahoon 880a2122044SKrzysztof Parzyszek unsigned Delay = Nodes.getLatency(); 881254f889dSBrendon Cahoon unsigned Distance = 1; 882254f889dSBrendon Cahoon 883254f889dSBrendon Cahoon // ii = ceil(delay / distance) 884254f889dSBrendon Cahoon unsigned CurMII = (Delay + Distance - 1) / Distance; 885254f889dSBrendon Cahoon Nodes.setRecMII(CurMII); 886254f889dSBrendon Cahoon if (CurMII > RecMII) 887254f889dSBrendon Cahoon RecMII = CurMII; 888254f889dSBrendon Cahoon } 889254f889dSBrendon Cahoon 890254f889dSBrendon Cahoon return RecMII; 891254f889dSBrendon Cahoon } 892254f889dSBrendon Cahoon 893254f889dSBrendon Cahoon /// Swap all the anti dependences in the DAG. That means it is no longer a DAG, 894254f889dSBrendon Cahoon /// but we do this to find the circuits, and then change them back. 895254f889dSBrendon Cahoon static void swapAntiDependences(std::vector<SUnit> &SUnits) { 896254f889dSBrendon Cahoon SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded; 897254f889dSBrendon Cahoon for (unsigned i = 0, e = SUnits.size(); i != e; ++i) { 898254f889dSBrendon Cahoon SUnit *SU = &SUnits[i]; 899254f889dSBrendon Cahoon for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end(); 900254f889dSBrendon Cahoon IP != EP; ++IP) { 901254f889dSBrendon Cahoon if (IP->getKind() != SDep::Anti) 902254f889dSBrendon Cahoon continue; 903254f889dSBrendon Cahoon DepsAdded.push_back(std::make_pair(SU, *IP)); 904254f889dSBrendon Cahoon } 905254f889dSBrendon Cahoon } 906254f889dSBrendon Cahoon for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(), 907254f889dSBrendon Cahoon E = DepsAdded.end(); 908254f889dSBrendon Cahoon I != E; ++I) { 909254f889dSBrendon Cahoon // Remove this anti dependency and add one in the reverse direction. 910254f889dSBrendon Cahoon SUnit *SU = I->first; 911254f889dSBrendon Cahoon SDep &D = I->second; 912254f889dSBrendon Cahoon SUnit *TargetSU = D.getSUnit(); 913254f889dSBrendon Cahoon unsigned Reg = D.getReg(); 914254f889dSBrendon Cahoon unsigned Lat = D.getLatency(); 915254f889dSBrendon Cahoon SU->removePred(D); 916254f889dSBrendon Cahoon SDep Dep(SU, SDep::Anti, Reg); 917254f889dSBrendon Cahoon Dep.setLatency(Lat); 918254f889dSBrendon Cahoon TargetSU->addPred(Dep); 919254f889dSBrendon Cahoon } 920254f889dSBrendon Cahoon } 921254f889dSBrendon Cahoon 922254f889dSBrendon Cahoon /// Create the adjacency structure of the nodes in the graph. 923254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::createAdjacencyStructure( 924254f889dSBrendon Cahoon SwingSchedulerDAG *DAG) { 925254f889dSBrendon Cahoon BitVector Added(SUnits.size()); 9268e1363dfSKrzysztof Parzyszek DenseMap<int, int> OutputDeps; 927254f889dSBrendon Cahoon for (int i = 0, e = SUnits.size(); i != e; ++i) { 928254f889dSBrendon Cahoon Added.reset(); 929254f889dSBrendon Cahoon // Add any successor to the adjacency matrix and exclude duplicates. 930254f889dSBrendon Cahoon for (auto &SI : SUnits[i].Succs) { 9318e1363dfSKrzysztof Parzyszek // Only create a back-edge on the first and last nodes of a dependence 9328e1363dfSKrzysztof Parzyszek // chain. This records any chains and adds them later. 9338e1363dfSKrzysztof Parzyszek if (SI.getKind() == SDep::Output) { 9348e1363dfSKrzysztof Parzyszek int N = SI.getSUnit()->NodeNum; 9358e1363dfSKrzysztof Parzyszek int BackEdge = i; 9368e1363dfSKrzysztof Parzyszek auto Dep = OutputDeps.find(BackEdge); 9378e1363dfSKrzysztof Parzyszek if (Dep != OutputDeps.end()) { 9388e1363dfSKrzysztof Parzyszek BackEdge = Dep->second; 9398e1363dfSKrzysztof Parzyszek OutputDeps.erase(Dep); 9408e1363dfSKrzysztof Parzyszek } 9418e1363dfSKrzysztof Parzyszek OutputDeps[N] = BackEdge; 9428e1363dfSKrzysztof Parzyszek } 943ada0f511SSumanth Gundapaneni // Do not process a boundary node, an artificial node. 944ada0f511SSumanth Gundapaneni // A back-edge is processed only if it goes to a Phi. 945ada0f511SSumanth Gundapaneni if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() || 946254f889dSBrendon Cahoon (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI())) 947254f889dSBrendon Cahoon continue; 948254f889dSBrendon Cahoon int N = SI.getSUnit()->NodeNum; 949254f889dSBrendon Cahoon if (!Added.test(N)) { 950254f889dSBrendon Cahoon AdjK[i].push_back(N); 951254f889dSBrendon Cahoon Added.set(N); 952254f889dSBrendon Cahoon } 953254f889dSBrendon Cahoon } 954254f889dSBrendon Cahoon // A chain edge between a store and a load is treated as a back-edge in the 955254f889dSBrendon Cahoon // adjacency matrix. 956254f889dSBrendon Cahoon for (auto &PI : SUnits[i].Preds) { 957254f889dSBrendon Cahoon if (!SUnits[i].getInstr()->mayStore() || 9588e1363dfSKrzysztof Parzyszek !DAG->isLoopCarriedDep(&SUnits[i], PI, false)) 959254f889dSBrendon Cahoon continue; 960254f889dSBrendon Cahoon if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) { 961254f889dSBrendon Cahoon int N = PI.getSUnit()->NodeNum; 962254f889dSBrendon Cahoon if (!Added.test(N)) { 963254f889dSBrendon Cahoon AdjK[i].push_back(N); 964254f889dSBrendon Cahoon Added.set(N); 965254f889dSBrendon Cahoon } 966254f889dSBrendon Cahoon } 967254f889dSBrendon Cahoon } 968254f889dSBrendon Cahoon } 969dad8c6a1SHiroshi Inoue // Add back-edges in the adjacency matrix for the output dependences. 9708e1363dfSKrzysztof Parzyszek for (auto &OD : OutputDeps) 9718e1363dfSKrzysztof Parzyszek if (!Added.test(OD.second)) { 9728e1363dfSKrzysztof Parzyszek AdjK[OD.first].push_back(OD.second); 9738e1363dfSKrzysztof Parzyszek Added.set(OD.second); 9748e1363dfSKrzysztof Parzyszek } 975254f889dSBrendon Cahoon } 976254f889dSBrendon Cahoon 977254f889dSBrendon Cahoon /// Identify an elementary circuit in the dependence graph starting at the 978254f889dSBrendon Cahoon /// specified node. 979254f889dSBrendon Cahoon bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets, 980254f889dSBrendon Cahoon bool HasBackedge) { 981254f889dSBrendon Cahoon SUnit *SV = &SUnits[V]; 982254f889dSBrendon Cahoon bool F = false; 983254f889dSBrendon Cahoon Stack.insert(SV); 984254f889dSBrendon Cahoon Blocked.set(V); 985254f889dSBrendon Cahoon 986254f889dSBrendon Cahoon for (auto W : AdjK[V]) { 987254f889dSBrendon Cahoon if (NumPaths > MaxPaths) 988254f889dSBrendon Cahoon break; 989254f889dSBrendon Cahoon if (W < S) 990254f889dSBrendon Cahoon continue; 991254f889dSBrendon Cahoon if (W == S) { 992254f889dSBrendon Cahoon if (!HasBackedge) 993254f889dSBrendon Cahoon NodeSets.push_back(NodeSet(Stack.begin(), Stack.end())); 994254f889dSBrendon Cahoon F = true; 995254f889dSBrendon Cahoon ++NumPaths; 996254f889dSBrendon Cahoon break; 997254f889dSBrendon Cahoon } else if (!Blocked.test(W)) { 99877418a37SSumanth Gundapaneni if (circuit(W, S, NodeSets, 99977418a37SSumanth Gundapaneni Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge)) 1000254f889dSBrendon Cahoon F = true; 1001254f889dSBrendon Cahoon } 1002254f889dSBrendon Cahoon } 1003254f889dSBrendon Cahoon 1004254f889dSBrendon Cahoon if (F) 1005254f889dSBrendon Cahoon unblock(V); 1006254f889dSBrendon Cahoon else { 1007254f889dSBrendon Cahoon for (auto W : AdjK[V]) { 1008254f889dSBrendon Cahoon if (W < S) 1009254f889dSBrendon Cahoon continue; 1010254f889dSBrendon Cahoon if (B[W].count(SV) == 0) 1011254f889dSBrendon Cahoon B[W].insert(SV); 1012254f889dSBrendon Cahoon } 1013254f889dSBrendon Cahoon } 1014254f889dSBrendon Cahoon Stack.pop_back(); 1015254f889dSBrendon Cahoon return F; 1016254f889dSBrendon Cahoon } 1017254f889dSBrendon Cahoon 1018254f889dSBrendon Cahoon /// Unblock a node in the circuit finding algorithm. 1019254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::unblock(int U) { 1020254f889dSBrendon Cahoon Blocked.reset(U); 1021254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 4> &BU = B[U]; 1022254f889dSBrendon Cahoon while (!BU.empty()) { 1023254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin(); 1024254f889dSBrendon Cahoon assert(SI != BU.end() && "Invalid B set."); 1025254f889dSBrendon Cahoon SUnit *W = *SI; 1026254f889dSBrendon Cahoon BU.erase(W); 1027254f889dSBrendon Cahoon if (Blocked.test(W->NodeNum)) 1028254f889dSBrendon Cahoon unblock(W->NodeNum); 1029254f889dSBrendon Cahoon } 1030254f889dSBrendon Cahoon } 1031254f889dSBrendon Cahoon 1032254f889dSBrendon Cahoon /// Identify all the elementary circuits in the dependence graph using 1033254f889dSBrendon Cahoon /// Johnson's circuit algorithm. 1034254f889dSBrendon Cahoon void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) { 1035254f889dSBrendon Cahoon // Swap all the anti dependences in the DAG. That means it is no longer a DAG, 1036254f889dSBrendon Cahoon // but we do this to find the circuits, and then change them back. 1037254f889dSBrendon Cahoon swapAntiDependences(SUnits); 1038254f889dSBrendon Cahoon 103977418a37SSumanth Gundapaneni Circuits Cir(SUnits, Topo); 1040254f889dSBrendon Cahoon // Create the adjacency structure. 1041254f889dSBrendon Cahoon Cir.createAdjacencyStructure(this); 1042254f889dSBrendon Cahoon for (int i = 0, e = SUnits.size(); i != e; ++i) { 1043254f889dSBrendon Cahoon Cir.reset(); 1044254f889dSBrendon Cahoon Cir.circuit(i, i, NodeSets); 1045254f889dSBrendon Cahoon } 1046254f889dSBrendon Cahoon 1047254f889dSBrendon Cahoon // Change the dependences back so that we've created a DAG again. 1048254f889dSBrendon Cahoon swapAntiDependences(SUnits); 1049254f889dSBrendon Cahoon } 1050254f889dSBrendon Cahoon 105162ac69d4SSumanth Gundapaneni // Create artificial dependencies between the source of COPY/REG_SEQUENCE that 105262ac69d4SSumanth Gundapaneni // is loop-carried to the USE in next iteration. This will help pipeliner avoid 105362ac69d4SSumanth Gundapaneni // additional copies that are needed across iterations. An artificial dependence 105462ac69d4SSumanth Gundapaneni // edge is added from USE to SOURCE of COPY/REG_SEQUENCE. 105562ac69d4SSumanth Gundapaneni 105662ac69d4SSumanth Gundapaneni // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried) 105762ac69d4SSumanth Gundapaneni // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE 105862ac69d4SSumanth Gundapaneni // PHI-------True-Dep------> USEOfPhi 105962ac69d4SSumanth Gundapaneni 106062ac69d4SSumanth Gundapaneni // The mutation creates 106162ac69d4SSumanth Gundapaneni // USEOfPHI -------Artificial-Dep---> SRCOfCopy 106262ac69d4SSumanth Gundapaneni 106362ac69d4SSumanth Gundapaneni // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy 106462ac69d4SSumanth Gundapaneni // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled 106562ac69d4SSumanth Gundapaneni // late to avoid additional copies across iterations. The possible scheduling 106662ac69d4SSumanth Gundapaneni // order would be 106762ac69d4SSumanth Gundapaneni // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE. 106862ac69d4SSumanth Gundapaneni 106962ac69d4SSumanth Gundapaneni void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) { 107062ac69d4SSumanth Gundapaneni for (SUnit &SU : DAG->SUnits) { 107162ac69d4SSumanth Gundapaneni // Find the COPY/REG_SEQUENCE instruction. 107262ac69d4SSumanth Gundapaneni if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence()) 107362ac69d4SSumanth Gundapaneni continue; 107462ac69d4SSumanth Gundapaneni 107562ac69d4SSumanth Gundapaneni // Record the loop carried PHIs. 107662ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 4> PHISUs; 107762ac69d4SSumanth Gundapaneni // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions. 107862ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 4> SrcSUs; 107962ac69d4SSumanth Gundapaneni 108062ac69d4SSumanth Gundapaneni for (auto &Dep : SU.Preds) { 108162ac69d4SSumanth Gundapaneni SUnit *TmpSU = Dep.getSUnit(); 108262ac69d4SSumanth Gundapaneni MachineInstr *TmpMI = TmpSU->getInstr(); 108362ac69d4SSumanth Gundapaneni SDep::Kind DepKind = Dep.getKind(); 108462ac69d4SSumanth Gundapaneni // Save the loop carried PHI. 108562ac69d4SSumanth Gundapaneni if (DepKind == SDep::Anti && TmpMI->isPHI()) 108662ac69d4SSumanth Gundapaneni PHISUs.push_back(TmpSU); 108762ac69d4SSumanth Gundapaneni // Save the source of COPY/REG_SEQUENCE. 108862ac69d4SSumanth Gundapaneni // If the source has no pre-decessors, we will end up creating cycles. 108962ac69d4SSumanth Gundapaneni else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0) 109062ac69d4SSumanth Gundapaneni SrcSUs.push_back(TmpSU); 109162ac69d4SSumanth Gundapaneni } 109262ac69d4SSumanth Gundapaneni 109362ac69d4SSumanth Gundapaneni if (PHISUs.size() == 0 || SrcSUs.size() == 0) 109462ac69d4SSumanth Gundapaneni continue; 109562ac69d4SSumanth Gundapaneni 109662ac69d4SSumanth Gundapaneni // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this 109762ac69d4SSumanth Gundapaneni // SUnit to the container. 109862ac69d4SSumanth Gundapaneni SmallVector<SUnit *, 8> UseSUs; 109962ac69d4SSumanth Gundapaneni for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) { 110062ac69d4SSumanth Gundapaneni for (auto &Dep : (*I)->Succs) { 110162ac69d4SSumanth Gundapaneni if (Dep.getKind() != SDep::Data) 110262ac69d4SSumanth Gundapaneni continue; 110362ac69d4SSumanth Gundapaneni 110462ac69d4SSumanth Gundapaneni SUnit *TmpSU = Dep.getSUnit(); 110562ac69d4SSumanth Gundapaneni MachineInstr *TmpMI = TmpSU->getInstr(); 110662ac69d4SSumanth Gundapaneni if (TmpMI->isPHI() || TmpMI->isRegSequence()) { 110762ac69d4SSumanth Gundapaneni PHISUs.push_back(TmpSU); 110862ac69d4SSumanth Gundapaneni continue; 110962ac69d4SSumanth Gundapaneni } 111062ac69d4SSumanth Gundapaneni UseSUs.push_back(TmpSU); 111162ac69d4SSumanth Gundapaneni } 111262ac69d4SSumanth Gundapaneni } 111362ac69d4SSumanth Gundapaneni 111462ac69d4SSumanth Gundapaneni if (UseSUs.size() == 0) 111562ac69d4SSumanth Gundapaneni continue; 111662ac69d4SSumanth Gundapaneni 111762ac69d4SSumanth Gundapaneni SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG); 111862ac69d4SSumanth Gundapaneni // Add the artificial dependencies if it does not form a cycle. 111962ac69d4SSumanth Gundapaneni for (auto I : UseSUs) { 112062ac69d4SSumanth Gundapaneni for (auto Src : SrcSUs) { 112162ac69d4SSumanth Gundapaneni if (!SDAG->Topo.IsReachable(I, Src) && Src != I) { 112262ac69d4SSumanth Gundapaneni Src->addPred(SDep(I, SDep::Artificial)); 112362ac69d4SSumanth Gundapaneni SDAG->Topo.AddPred(Src, I); 112462ac69d4SSumanth Gundapaneni } 112562ac69d4SSumanth Gundapaneni } 112662ac69d4SSumanth Gundapaneni } 112762ac69d4SSumanth Gundapaneni } 112862ac69d4SSumanth Gundapaneni } 112962ac69d4SSumanth Gundapaneni 1130254f889dSBrendon Cahoon /// Return true for DAG nodes that we ignore when computing the cost functions. 1131c73b6d6bSHiroshi Inoue /// We ignore the back-edge recurrence in order to avoid unbounded recursion 1132254f889dSBrendon Cahoon /// in the calculation of the ASAP, ALAP, etc functions. 1133254f889dSBrendon Cahoon static bool ignoreDependence(const SDep &D, bool isPred) { 1134254f889dSBrendon Cahoon if (D.isArtificial()) 1135254f889dSBrendon Cahoon return true; 1136254f889dSBrendon Cahoon return D.getKind() == SDep::Anti && isPred; 1137254f889dSBrendon Cahoon } 1138254f889dSBrendon Cahoon 1139254f889dSBrendon Cahoon /// Compute several functions need to order the nodes for scheduling. 1140254f889dSBrendon Cahoon /// ASAP - Earliest time to schedule a node. 1141254f889dSBrendon Cahoon /// ALAP - Latest time to schedule a node. 1142254f889dSBrendon Cahoon /// MOV - Mobility function, difference between ALAP and ASAP. 1143254f889dSBrendon Cahoon /// D - Depth of each node. 1144254f889dSBrendon Cahoon /// H - Height of each node. 1145254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) { 1146254f889dSBrendon Cahoon ScheduleInfo.resize(SUnits.size()); 1147254f889dSBrendon Cahoon 1148d34e60caSNicola Zaghen LLVM_DEBUG({ 1149254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), 1150254f889dSBrendon Cahoon E = Topo.end(); 1151254f889dSBrendon Cahoon I != E; ++I) { 1152726e12cfSMatthias Braun const SUnit &SU = SUnits[*I]; 1153726e12cfSMatthias Braun dumpNode(SU); 1154254f889dSBrendon Cahoon } 1155254f889dSBrendon Cahoon }); 1156254f889dSBrendon Cahoon 1157254f889dSBrendon Cahoon int maxASAP = 0; 11584b8bcf00SRoorda, Jan-Willem // Compute ASAP and ZeroLatencyDepth. 1159254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(), 1160254f889dSBrendon Cahoon E = Topo.end(); 1161254f889dSBrendon Cahoon I != E; ++I) { 1162254f889dSBrendon Cahoon int asap = 0; 11634b8bcf00SRoorda, Jan-Willem int zeroLatencyDepth = 0; 1164254f889dSBrendon Cahoon SUnit *SU = &SUnits[*I]; 1165254f889dSBrendon Cahoon for (SUnit::const_pred_iterator IP = SU->Preds.begin(), 1166254f889dSBrendon Cahoon EP = SU->Preds.end(); 1167254f889dSBrendon Cahoon IP != EP; ++IP) { 11684b8bcf00SRoorda, Jan-Willem SUnit *pred = IP->getSUnit(); 1169c715a5d2SKrzysztof Parzyszek if (IP->getLatency() == 0) 11704b8bcf00SRoorda, Jan-Willem zeroLatencyDepth = 11714b8bcf00SRoorda, Jan-Willem std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1); 1172254f889dSBrendon Cahoon if (ignoreDependence(*IP, true)) 1173254f889dSBrendon Cahoon continue; 1174c715a5d2SKrzysztof Parzyszek asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() - 1175254f889dSBrendon Cahoon getDistance(pred, SU, *IP) * MII)); 1176254f889dSBrendon Cahoon } 1177254f889dSBrendon Cahoon maxASAP = std::max(maxASAP, asap); 1178254f889dSBrendon Cahoon ScheduleInfo[*I].ASAP = asap; 11794b8bcf00SRoorda, Jan-Willem ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth; 1180254f889dSBrendon Cahoon } 1181254f889dSBrendon Cahoon 11824b8bcf00SRoorda, Jan-Willem // Compute ALAP, ZeroLatencyHeight, and MOV. 1183254f889dSBrendon Cahoon for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(), 1184254f889dSBrendon Cahoon E = Topo.rend(); 1185254f889dSBrendon Cahoon I != E; ++I) { 1186254f889dSBrendon Cahoon int alap = maxASAP; 11874b8bcf00SRoorda, Jan-Willem int zeroLatencyHeight = 0; 1188254f889dSBrendon Cahoon SUnit *SU = &SUnits[*I]; 1189254f889dSBrendon Cahoon for (SUnit::const_succ_iterator IS = SU->Succs.begin(), 1190254f889dSBrendon Cahoon ES = SU->Succs.end(); 1191254f889dSBrendon Cahoon IS != ES; ++IS) { 11924b8bcf00SRoorda, Jan-Willem SUnit *succ = IS->getSUnit(); 1193c715a5d2SKrzysztof Parzyszek if (IS->getLatency() == 0) 11944b8bcf00SRoorda, Jan-Willem zeroLatencyHeight = 11954b8bcf00SRoorda, Jan-Willem std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1); 1196254f889dSBrendon Cahoon if (ignoreDependence(*IS, true)) 1197254f889dSBrendon Cahoon continue; 1198c715a5d2SKrzysztof Parzyszek alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() + 1199254f889dSBrendon Cahoon getDistance(SU, succ, *IS) * MII)); 1200254f889dSBrendon Cahoon } 1201254f889dSBrendon Cahoon 1202254f889dSBrendon Cahoon ScheduleInfo[*I].ALAP = alap; 12034b8bcf00SRoorda, Jan-Willem ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight; 1204254f889dSBrendon Cahoon } 1205254f889dSBrendon Cahoon 1206254f889dSBrendon Cahoon // After computing the node functions, compute the summary for each node set. 1207254f889dSBrendon Cahoon for (NodeSet &I : NodeSets) 1208254f889dSBrendon Cahoon I.computeNodeSetInfo(this); 1209254f889dSBrendon Cahoon 1210d34e60caSNicola Zaghen LLVM_DEBUG({ 1211254f889dSBrendon Cahoon for (unsigned i = 0; i < SUnits.size(); i++) { 1212254f889dSBrendon Cahoon dbgs() << "\tNode " << i << ":\n"; 1213254f889dSBrendon Cahoon dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n"; 1214254f889dSBrendon Cahoon dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n"; 1215254f889dSBrendon Cahoon dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n"; 1216254f889dSBrendon Cahoon dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n"; 1217254f889dSBrendon Cahoon dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n"; 12184b8bcf00SRoorda, Jan-Willem dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n"; 12194b8bcf00SRoorda, Jan-Willem dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n"; 1220254f889dSBrendon Cahoon } 1221254f889dSBrendon Cahoon }); 1222254f889dSBrendon Cahoon } 1223254f889dSBrendon Cahoon 1224254f889dSBrendon Cahoon /// Compute the Pred_L(O) set, as defined in the paper. The set is defined 1225254f889dSBrendon Cahoon /// as the predecessors of the elements of NodeOrder that are not also in 1226254f889dSBrendon Cahoon /// NodeOrder. 1227254f889dSBrendon Cahoon static bool pred_L(SetVector<SUnit *> &NodeOrder, 1228254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Preds, 1229254f889dSBrendon Cahoon const NodeSet *S = nullptr) { 1230254f889dSBrendon Cahoon Preds.clear(); 1231254f889dSBrendon Cahoon for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); 1232254f889dSBrendon Cahoon I != E; ++I) { 1233254f889dSBrendon Cahoon for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end(); 1234254f889dSBrendon Cahoon PI != PE; ++PI) { 1235254f889dSBrendon Cahoon if (S && S->count(PI->getSUnit()) == 0) 1236254f889dSBrendon Cahoon continue; 1237254f889dSBrendon Cahoon if (ignoreDependence(*PI, true)) 1238254f889dSBrendon Cahoon continue; 1239254f889dSBrendon Cahoon if (NodeOrder.count(PI->getSUnit()) == 0) 1240254f889dSBrendon Cahoon Preds.insert(PI->getSUnit()); 1241254f889dSBrendon Cahoon } 1242254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1243254f889dSBrendon Cahoon for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(), 1244254f889dSBrendon Cahoon ES = (*I)->Succs.end(); 1245254f889dSBrendon Cahoon IS != ES; ++IS) { 1246254f889dSBrendon Cahoon if (IS->getKind() != SDep::Anti) 1247254f889dSBrendon Cahoon continue; 1248254f889dSBrendon Cahoon if (S && S->count(IS->getSUnit()) == 0) 1249254f889dSBrendon Cahoon continue; 1250254f889dSBrendon Cahoon if (NodeOrder.count(IS->getSUnit()) == 0) 1251254f889dSBrendon Cahoon Preds.insert(IS->getSUnit()); 1252254f889dSBrendon Cahoon } 1253254f889dSBrendon Cahoon } 125432a40564SEugene Zelenko return !Preds.empty(); 1255254f889dSBrendon Cahoon } 1256254f889dSBrendon Cahoon 1257254f889dSBrendon Cahoon /// Compute the Succ_L(O) set, as defined in the paper. The set is defined 1258254f889dSBrendon Cahoon /// as the successors of the elements of NodeOrder that are not also in 1259254f889dSBrendon Cahoon /// NodeOrder. 1260254f889dSBrendon Cahoon static bool succ_L(SetVector<SUnit *> &NodeOrder, 1261254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Succs, 1262254f889dSBrendon Cahoon const NodeSet *S = nullptr) { 1263254f889dSBrendon Cahoon Succs.clear(); 1264254f889dSBrendon Cahoon for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end(); 1265254f889dSBrendon Cahoon I != E; ++I) { 1266254f889dSBrendon Cahoon for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end(); 1267254f889dSBrendon Cahoon SI != SE; ++SI) { 1268254f889dSBrendon Cahoon if (S && S->count(SI->getSUnit()) == 0) 1269254f889dSBrendon Cahoon continue; 1270254f889dSBrendon Cahoon if (ignoreDependence(*SI, false)) 1271254f889dSBrendon Cahoon continue; 1272254f889dSBrendon Cahoon if (NodeOrder.count(SI->getSUnit()) == 0) 1273254f889dSBrendon Cahoon Succs.insert(SI->getSUnit()); 1274254f889dSBrendon Cahoon } 1275254f889dSBrendon Cahoon for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(), 1276254f889dSBrendon Cahoon PE = (*I)->Preds.end(); 1277254f889dSBrendon Cahoon PI != PE; ++PI) { 1278254f889dSBrendon Cahoon if (PI->getKind() != SDep::Anti) 1279254f889dSBrendon Cahoon continue; 1280254f889dSBrendon Cahoon if (S && S->count(PI->getSUnit()) == 0) 1281254f889dSBrendon Cahoon continue; 1282254f889dSBrendon Cahoon if (NodeOrder.count(PI->getSUnit()) == 0) 1283254f889dSBrendon Cahoon Succs.insert(PI->getSUnit()); 1284254f889dSBrendon Cahoon } 1285254f889dSBrendon Cahoon } 128632a40564SEugene Zelenko return !Succs.empty(); 1287254f889dSBrendon Cahoon } 1288254f889dSBrendon Cahoon 1289254f889dSBrendon Cahoon /// Return true if there is a path from the specified node to any of the nodes 1290254f889dSBrendon Cahoon /// in DestNodes. Keep track and return the nodes in any path. 1291254f889dSBrendon Cahoon static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path, 1292254f889dSBrendon Cahoon SetVector<SUnit *> &DestNodes, 1293254f889dSBrendon Cahoon SetVector<SUnit *> &Exclude, 1294254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> &Visited) { 1295254f889dSBrendon Cahoon if (Cur->isBoundaryNode()) 1296254f889dSBrendon Cahoon return false; 1297254f889dSBrendon Cahoon if (Exclude.count(Cur) != 0) 1298254f889dSBrendon Cahoon return false; 1299254f889dSBrendon Cahoon if (DestNodes.count(Cur) != 0) 1300254f889dSBrendon Cahoon return true; 1301254f889dSBrendon Cahoon if (!Visited.insert(Cur).second) 1302254f889dSBrendon Cahoon return Path.count(Cur) != 0; 1303254f889dSBrendon Cahoon bool FoundPath = false; 1304254f889dSBrendon Cahoon for (auto &SI : Cur->Succs) 1305254f889dSBrendon Cahoon FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited); 1306254f889dSBrendon Cahoon for (auto &PI : Cur->Preds) 1307254f889dSBrendon Cahoon if (PI.getKind() == SDep::Anti) 1308254f889dSBrendon Cahoon FoundPath |= 1309254f889dSBrendon Cahoon computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited); 1310254f889dSBrendon Cahoon if (FoundPath) 1311254f889dSBrendon Cahoon Path.insert(Cur); 1312254f889dSBrendon Cahoon return FoundPath; 1313254f889dSBrendon Cahoon } 1314254f889dSBrendon Cahoon 1315254f889dSBrendon Cahoon /// Return true if Set1 is a subset of Set2. 1316254f889dSBrendon Cahoon template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) { 1317254f889dSBrendon Cahoon for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I) 1318254f889dSBrendon Cahoon if (Set2.count(*I) == 0) 1319254f889dSBrendon Cahoon return false; 1320254f889dSBrendon Cahoon return true; 1321254f889dSBrendon Cahoon } 1322254f889dSBrendon Cahoon 1323254f889dSBrendon Cahoon /// Compute the live-out registers for the instructions in a node-set. 1324254f889dSBrendon Cahoon /// The live-out registers are those that are defined in the node-set, 1325254f889dSBrendon Cahoon /// but not used. Except for use operands of Phis. 1326254f889dSBrendon Cahoon static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, 1327254f889dSBrendon Cahoon NodeSet &NS) { 1328254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1329254f889dSBrendon Cahoon MachineRegisterInfo &MRI = MF.getRegInfo(); 1330254f889dSBrendon Cahoon SmallVector<RegisterMaskPair, 8> LiveOutRegs; 1331254f889dSBrendon Cahoon SmallSet<unsigned, 4> Uses; 1332254f889dSBrendon Cahoon for (SUnit *SU : NS) { 1333254f889dSBrendon Cahoon const MachineInstr *MI = SU->getInstr(); 1334254f889dSBrendon Cahoon if (MI->isPHI()) 1335254f889dSBrendon Cahoon continue; 1336fc371558SMatthias Braun for (const MachineOperand &MO : MI->operands()) 1337fc371558SMatthias Braun if (MO.isReg() && MO.isUse()) { 1338fc371558SMatthias Braun unsigned Reg = MO.getReg(); 1339254f889dSBrendon Cahoon if (TargetRegisterInfo::isVirtualRegister(Reg)) 1340254f889dSBrendon Cahoon Uses.insert(Reg); 1341254f889dSBrendon Cahoon else if (MRI.isAllocatable(Reg)) 1342254f889dSBrendon Cahoon for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1343254f889dSBrendon Cahoon Uses.insert(*Units); 1344254f889dSBrendon Cahoon } 1345254f889dSBrendon Cahoon } 1346254f889dSBrendon Cahoon for (SUnit *SU : NS) 1347fc371558SMatthias Braun for (const MachineOperand &MO : SU->getInstr()->operands()) 1348fc371558SMatthias Braun if (MO.isReg() && MO.isDef() && !MO.isDead()) { 1349fc371558SMatthias Braun unsigned Reg = MO.getReg(); 1350254f889dSBrendon Cahoon if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1351254f889dSBrendon Cahoon if (!Uses.count(Reg)) 135291b5cf84SKrzysztof Parzyszek LiveOutRegs.push_back(RegisterMaskPair(Reg, 135391b5cf84SKrzysztof Parzyszek LaneBitmask::getNone())); 1354254f889dSBrendon Cahoon } else if (MRI.isAllocatable(Reg)) { 1355254f889dSBrendon Cahoon for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) 1356254f889dSBrendon Cahoon if (!Uses.count(*Units)) 135791b5cf84SKrzysztof Parzyszek LiveOutRegs.push_back(RegisterMaskPair(*Units, 135891b5cf84SKrzysztof Parzyszek LaneBitmask::getNone())); 1359254f889dSBrendon Cahoon } 1360254f889dSBrendon Cahoon } 1361254f889dSBrendon Cahoon RPTracker.addLiveRegs(LiveOutRegs); 1362254f889dSBrendon Cahoon } 1363254f889dSBrendon Cahoon 1364254f889dSBrendon Cahoon /// A heuristic to filter nodes in recurrent node-sets if the register 1365254f889dSBrendon Cahoon /// pressure of a set is too high. 1366254f889dSBrendon Cahoon void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) { 1367254f889dSBrendon Cahoon for (auto &NS : NodeSets) { 1368254f889dSBrendon Cahoon // Skip small node-sets since they won't cause register pressure problems. 1369254f889dSBrendon Cahoon if (NS.size() <= 2) 1370254f889dSBrendon Cahoon continue; 1371254f889dSBrendon Cahoon IntervalPressure RecRegPressure; 1372254f889dSBrendon Cahoon RegPressureTracker RecRPTracker(RecRegPressure); 1373254f889dSBrendon Cahoon RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true); 1374254f889dSBrendon Cahoon computeLiveOuts(MF, RecRPTracker, NS); 1375254f889dSBrendon Cahoon RecRPTracker.closeBottom(); 1376254f889dSBrendon Cahoon 1377254f889dSBrendon Cahoon std::vector<SUnit *> SUnits(NS.begin(), NS.end()); 13780cac726aSFangrui Song llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) { 1379254f889dSBrendon Cahoon return A->NodeNum > B->NodeNum; 1380254f889dSBrendon Cahoon }); 1381254f889dSBrendon Cahoon 1382254f889dSBrendon Cahoon for (auto &SU : SUnits) { 1383254f889dSBrendon Cahoon // Since we're computing the register pressure for a subset of the 1384254f889dSBrendon Cahoon // instructions in a block, we need to set the tracker for each 1385254f889dSBrendon Cahoon // instruction in the node-set. The tracker is set to the instruction 1386254f889dSBrendon Cahoon // just after the one we're interested in. 1387254f889dSBrendon Cahoon MachineBasicBlock::const_iterator CurInstI = SU->getInstr(); 1388254f889dSBrendon Cahoon RecRPTracker.setPos(std::next(CurInstI)); 1389254f889dSBrendon Cahoon 1390254f889dSBrendon Cahoon RegPressureDelta RPDelta; 1391254f889dSBrendon Cahoon ArrayRef<PressureChange> CriticalPSets; 1392254f889dSBrendon Cahoon RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta, 1393254f889dSBrendon Cahoon CriticalPSets, 1394254f889dSBrendon Cahoon RecRegPressure.MaxSetPressure); 1395254f889dSBrendon Cahoon if (RPDelta.Excess.isValid()) { 1396d34e60caSNicola Zaghen LLVM_DEBUG( 1397d34e60caSNicola Zaghen dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") " 1398254f889dSBrendon Cahoon << TRI->getRegPressureSetName(RPDelta.Excess.getPSet()) 1399254f889dSBrendon Cahoon << ":" << RPDelta.Excess.getUnitInc()); 1400254f889dSBrendon Cahoon NS.setExceedPressure(SU); 1401254f889dSBrendon Cahoon break; 1402254f889dSBrendon Cahoon } 1403254f889dSBrendon Cahoon RecRPTracker.recede(); 1404254f889dSBrendon Cahoon } 1405254f889dSBrendon Cahoon } 1406254f889dSBrendon Cahoon } 1407254f889dSBrendon Cahoon 1408254f889dSBrendon Cahoon /// A heuristic to colocate node sets that have the same set of 1409254f889dSBrendon Cahoon /// successors. 1410254f889dSBrendon Cahoon void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) { 1411254f889dSBrendon Cahoon unsigned Colocate = 0; 1412254f889dSBrendon Cahoon for (int i = 0, e = NodeSets.size(); i < e; ++i) { 1413254f889dSBrendon Cahoon NodeSet &N1 = NodeSets[i]; 1414254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> S1; 1415254f889dSBrendon Cahoon if (N1.empty() || !succ_L(N1, S1)) 1416254f889dSBrendon Cahoon continue; 1417254f889dSBrendon Cahoon for (int j = i + 1; j < e; ++j) { 1418254f889dSBrendon Cahoon NodeSet &N2 = NodeSets[j]; 1419254f889dSBrendon Cahoon if (N1.compareRecMII(N2) != 0) 1420254f889dSBrendon Cahoon continue; 1421254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> S2; 1422254f889dSBrendon Cahoon if (N2.empty() || !succ_L(N2, S2)) 1423254f889dSBrendon Cahoon continue; 1424254f889dSBrendon Cahoon if (isSubset(S1, S2) && S1.size() == S2.size()) { 1425254f889dSBrendon Cahoon N1.setColocate(++Colocate); 1426254f889dSBrendon Cahoon N2.setColocate(Colocate); 1427254f889dSBrendon Cahoon break; 1428254f889dSBrendon Cahoon } 1429254f889dSBrendon Cahoon } 1430254f889dSBrendon Cahoon } 1431254f889dSBrendon Cahoon } 1432254f889dSBrendon Cahoon 1433254f889dSBrendon Cahoon /// Check if the existing node-sets are profitable. If not, then ignore the 1434254f889dSBrendon Cahoon /// recurrent node-sets, and attempt to schedule all nodes together. This is 14353ca23341SKrzysztof Parzyszek /// a heuristic. If the MII is large and all the recurrent node-sets are small, 14363ca23341SKrzysztof Parzyszek /// then it's best to try to schedule all instructions together instead of 14373ca23341SKrzysztof Parzyszek /// starting with the recurrent node-sets. 1438254f889dSBrendon Cahoon void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) { 1439254f889dSBrendon Cahoon // Look for loops with a large MII. 14403ca23341SKrzysztof Parzyszek if (MII < 17) 1441254f889dSBrendon Cahoon return; 1442254f889dSBrendon Cahoon // Check if the node-set contains only a simple add recurrence. 14433ca23341SKrzysztof Parzyszek for (auto &NS : NodeSets) { 14443ca23341SKrzysztof Parzyszek if (NS.getRecMII() > 2) 1445254f889dSBrendon Cahoon return; 14463ca23341SKrzysztof Parzyszek if (NS.getMaxDepth() > MII) 14473ca23341SKrzysztof Parzyszek return; 14483ca23341SKrzysztof Parzyszek } 1449254f889dSBrendon Cahoon NodeSets.clear(); 1450d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n"); 1451254f889dSBrendon Cahoon return; 1452254f889dSBrendon Cahoon } 1453254f889dSBrendon Cahoon 1454254f889dSBrendon Cahoon /// Add the nodes that do not belong to a recurrence set into groups 1455254f889dSBrendon Cahoon /// based upon connected componenets. 1456254f889dSBrendon Cahoon void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) { 1457254f889dSBrendon Cahoon SetVector<SUnit *> NodesAdded; 1458254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 1459254f889dSBrendon Cahoon // Add the nodes that are on a path between the previous node sets and 1460254f889dSBrendon Cahoon // the current node set. 1461254f889dSBrendon Cahoon for (NodeSet &I : NodeSets) { 1462254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1463254f889dSBrendon Cahoon // Add the nodes from the current node set to the previous node set. 1464254f889dSBrendon Cahoon if (succ_L(I, N)) { 1465254f889dSBrendon Cahoon SetVector<SUnit *> Path; 1466254f889dSBrendon Cahoon for (SUnit *NI : N) { 1467254f889dSBrendon Cahoon Visited.clear(); 1468254f889dSBrendon Cahoon computePath(NI, Path, NodesAdded, I, Visited); 1469254f889dSBrendon Cahoon } 147032a40564SEugene Zelenko if (!Path.empty()) 1471254f889dSBrendon Cahoon I.insert(Path.begin(), Path.end()); 1472254f889dSBrendon Cahoon } 1473254f889dSBrendon Cahoon // Add the nodes from the previous node set to the current node set. 1474254f889dSBrendon Cahoon N.clear(); 1475254f889dSBrendon Cahoon if (succ_L(NodesAdded, N)) { 1476254f889dSBrendon Cahoon SetVector<SUnit *> Path; 1477254f889dSBrendon Cahoon for (SUnit *NI : N) { 1478254f889dSBrendon Cahoon Visited.clear(); 1479254f889dSBrendon Cahoon computePath(NI, Path, I, NodesAdded, Visited); 1480254f889dSBrendon Cahoon } 148132a40564SEugene Zelenko if (!Path.empty()) 1482254f889dSBrendon Cahoon I.insert(Path.begin(), Path.end()); 1483254f889dSBrendon Cahoon } 1484254f889dSBrendon Cahoon NodesAdded.insert(I.begin(), I.end()); 1485254f889dSBrendon Cahoon } 1486254f889dSBrendon Cahoon 1487254f889dSBrendon Cahoon // Create a new node set with the connected nodes of any successor of a node 1488254f889dSBrendon Cahoon // in a recurrent set. 1489254f889dSBrendon Cahoon NodeSet NewSet; 1490254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1491254f889dSBrendon Cahoon if (succ_L(NodesAdded, N)) 1492254f889dSBrendon Cahoon for (SUnit *I : N) 1493254f889dSBrendon Cahoon addConnectedNodes(I, NewSet, NodesAdded); 149432a40564SEugene Zelenko if (!NewSet.empty()) 1495254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1496254f889dSBrendon Cahoon 1497254f889dSBrendon Cahoon // Create a new node set with the connected nodes of any predecessor of a node 1498254f889dSBrendon Cahoon // in a recurrent set. 1499254f889dSBrendon Cahoon NewSet.clear(); 1500254f889dSBrendon Cahoon if (pred_L(NodesAdded, N)) 1501254f889dSBrendon Cahoon for (SUnit *I : N) 1502254f889dSBrendon Cahoon addConnectedNodes(I, NewSet, NodesAdded); 150332a40564SEugene Zelenko if (!NewSet.empty()) 1504254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1505254f889dSBrendon Cahoon 1506372ffa15SHiroshi Inoue // Create new nodes sets with the connected nodes any remaining node that 1507254f889dSBrendon Cahoon // has no predecessor. 1508254f889dSBrendon Cahoon for (unsigned i = 0; i < SUnits.size(); ++i) { 1509254f889dSBrendon Cahoon SUnit *SU = &SUnits[i]; 1510254f889dSBrendon Cahoon if (NodesAdded.count(SU) == 0) { 1511254f889dSBrendon Cahoon NewSet.clear(); 1512254f889dSBrendon Cahoon addConnectedNodes(SU, NewSet, NodesAdded); 151332a40564SEugene Zelenko if (!NewSet.empty()) 1514254f889dSBrendon Cahoon NodeSets.push_back(NewSet); 1515254f889dSBrendon Cahoon } 1516254f889dSBrendon Cahoon } 1517254f889dSBrendon Cahoon } 1518254f889dSBrendon Cahoon 1519254f889dSBrendon Cahoon /// Add the node to the set, and add all is its connected nodes to the set. 1520254f889dSBrendon Cahoon void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet, 1521254f889dSBrendon Cahoon SetVector<SUnit *> &NodesAdded) { 1522254f889dSBrendon Cahoon NewSet.insert(SU); 1523254f889dSBrendon Cahoon NodesAdded.insert(SU); 1524254f889dSBrendon Cahoon for (auto &SI : SU->Succs) { 1525254f889dSBrendon Cahoon SUnit *Successor = SI.getSUnit(); 1526254f889dSBrendon Cahoon if (!SI.isArtificial() && NodesAdded.count(Successor) == 0) 1527254f889dSBrendon Cahoon addConnectedNodes(Successor, NewSet, NodesAdded); 1528254f889dSBrendon Cahoon } 1529254f889dSBrendon Cahoon for (auto &PI : SU->Preds) { 1530254f889dSBrendon Cahoon SUnit *Predecessor = PI.getSUnit(); 1531254f889dSBrendon Cahoon if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0) 1532254f889dSBrendon Cahoon addConnectedNodes(Predecessor, NewSet, NodesAdded); 1533254f889dSBrendon Cahoon } 1534254f889dSBrendon Cahoon } 1535254f889dSBrendon Cahoon 1536254f889dSBrendon Cahoon /// Return true if Set1 contains elements in Set2. The elements in common 1537254f889dSBrendon Cahoon /// are returned in a different container. 1538254f889dSBrendon Cahoon static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2, 1539254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> &Result) { 1540254f889dSBrendon Cahoon Result.clear(); 1541254f889dSBrendon Cahoon for (unsigned i = 0, e = Set1.size(); i != e; ++i) { 1542254f889dSBrendon Cahoon SUnit *SU = Set1[i]; 1543254f889dSBrendon Cahoon if (Set2.count(SU) != 0) 1544254f889dSBrendon Cahoon Result.insert(SU); 1545254f889dSBrendon Cahoon } 1546254f889dSBrendon Cahoon return !Result.empty(); 1547254f889dSBrendon Cahoon } 1548254f889dSBrendon Cahoon 1549254f889dSBrendon Cahoon /// Merge the recurrence node sets that have the same initial node. 1550254f889dSBrendon Cahoon void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) { 1551254f889dSBrendon Cahoon for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; 1552254f889dSBrendon Cahoon ++I) { 1553254f889dSBrendon Cahoon NodeSet &NI = *I; 1554254f889dSBrendon Cahoon for (NodeSetType::iterator J = I + 1; J != E;) { 1555254f889dSBrendon Cahoon NodeSet &NJ = *J; 1556254f889dSBrendon Cahoon if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) { 1557254f889dSBrendon Cahoon if (NJ.compareRecMII(NI) > 0) 1558254f889dSBrendon Cahoon NI.setRecMII(NJ.getRecMII()); 1559254f889dSBrendon Cahoon for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI; 1560254f889dSBrendon Cahoon ++NII) 1561254f889dSBrendon Cahoon I->insert(*NII); 1562254f889dSBrendon Cahoon NodeSets.erase(J); 1563254f889dSBrendon Cahoon E = NodeSets.end(); 1564254f889dSBrendon Cahoon } else { 1565254f889dSBrendon Cahoon ++J; 1566254f889dSBrendon Cahoon } 1567254f889dSBrendon Cahoon } 1568254f889dSBrendon Cahoon } 1569254f889dSBrendon Cahoon } 1570254f889dSBrendon Cahoon 1571254f889dSBrendon Cahoon /// Remove nodes that have been scheduled in previous NodeSets. 1572254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) { 1573254f889dSBrendon Cahoon for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E; 1574254f889dSBrendon Cahoon ++I) 1575254f889dSBrendon Cahoon for (NodeSetType::iterator J = I + 1; J != E;) { 1576254f889dSBrendon Cahoon J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); }); 1577254f889dSBrendon Cahoon 157832a40564SEugene Zelenko if (J->empty()) { 1579254f889dSBrendon Cahoon NodeSets.erase(J); 1580254f889dSBrendon Cahoon E = NodeSets.end(); 1581254f889dSBrendon Cahoon } else { 1582254f889dSBrendon Cahoon ++J; 1583254f889dSBrendon Cahoon } 1584254f889dSBrendon Cahoon } 1585254f889dSBrendon Cahoon } 1586254f889dSBrendon Cahoon 1587254f889dSBrendon Cahoon /// Compute an ordered list of the dependence graph nodes, which 1588254f889dSBrendon Cahoon /// indicates the order that the nodes will be scheduled. This is a 1589254f889dSBrendon Cahoon /// two-level algorithm. First, a partial order is created, which 1590254f889dSBrendon Cahoon /// consists of a list of sets ordered from highest to lowest priority. 1591254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) { 1592254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> R; 1593254f889dSBrendon Cahoon NodeOrder.clear(); 1594254f889dSBrendon Cahoon 1595254f889dSBrendon Cahoon for (auto &Nodes : NodeSets) { 1596d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n"); 1597254f889dSBrendon Cahoon OrderKind Order; 1598254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1599254f889dSBrendon Cahoon if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) { 1600254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1601254f889dSBrendon Cahoon Order = BottomUp; 1602d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (preds) "); 1603254f889dSBrendon Cahoon } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) { 1604254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1605254f889dSBrendon Cahoon Order = TopDown; 1606d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Top down (succs) "); 1607254f889dSBrendon Cahoon } else if (isIntersect(N, Nodes, R)) { 1608254f889dSBrendon Cahoon // If some of the successors are in the existing node-set, then use the 1609254f889dSBrendon Cahoon // top-down ordering. 1610254f889dSBrendon Cahoon Order = TopDown; 1611d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Top down (intersect) "); 1612254f889dSBrendon Cahoon } else if (NodeSets.size() == 1) { 1613254f889dSBrendon Cahoon for (auto &N : Nodes) 1614254f889dSBrendon Cahoon if (N->Succs.size() == 0) 1615254f889dSBrendon Cahoon R.insert(N); 1616254f889dSBrendon Cahoon Order = BottomUp; 1617d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (all) "); 1618254f889dSBrendon Cahoon } else { 1619254f889dSBrendon Cahoon // Find the node with the highest ASAP. 1620254f889dSBrendon Cahoon SUnit *maxASAP = nullptr; 1621254f889dSBrendon Cahoon for (SUnit *SU : Nodes) { 1622a2122044SKrzysztof Parzyszek if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) || 1623a2122044SKrzysztof Parzyszek (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum)) 1624254f889dSBrendon Cahoon maxASAP = SU; 1625254f889dSBrendon Cahoon } 1626254f889dSBrendon Cahoon R.insert(maxASAP); 1627254f889dSBrendon Cahoon Order = BottomUp; 1628d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Bottom up (default) "); 1629254f889dSBrendon Cahoon } 1630254f889dSBrendon Cahoon 1631254f889dSBrendon Cahoon while (!R.empty()) { 1632254f889dSBrendon Cahoon if (Order == TopDown) { 1633254f889dSBrendon Cahoon // Choose the node with the maximum height. If more than one, choose 1634a2122044SKrzysztof Parzyszek // the node wiTH the maximum ZeroLatencyHeight. If still more than one, 16354b8bcf00SRoorda, Jan-Willem // choose the node with the lowest MOV. 1636254f889dSBrendon Cahoon while (!R.empty()) { 1637254f889dSBrendon Cahoon SUnit *maxHeight = nullptr; 1638254f889dSBrendon Cahoon for (SUnit *I : R) { 1639cdc71612SEugene Zelenko if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight)) 1640254f889dSBrendon Cahoon maxHeight = I; 1641254f889dSBrendon Cahoon else if (getHeight(I) == getHeight(maxHeight) && 16424b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight)) 1643254f889dSBrendon Cahoon maxHeight = I; 16444b8bcf00SRoorda, Jan-Willem else if (getHeight(I) == getHeight(maxHeight) && 16454b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(I) == 16464b8bcf00SRoorda, Jan-Willem getZeroLatencyHeight(maxHeight) && 16474b8bcf00SRoorda, Jan-Willem getMOV(I) < getMOV(maxHeight)) 1648254f889dSBrendon Cahoon maxHeight = I; 1649254f889dSBrendon Cahoon } 1650254f889dSBrendon Cahoon NodeOrder.insert(maxHeight); 1651d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " "); 1652254f889dSBrendon Cahoon R.remove(maxHeight); 1653254f889dSBrendon Cahoon for (const auto &I : maxHeight->Succs) { 1654254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1655254f889dSBrendon Cahoon continue; 1656254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1657254f889dSBrendon Cahoon continue; 1658254f889dSBrendon Cahoon if (ignoreDependence(I, false)) 1659254f889dSBrendon Cahoon continue; 1660254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1661254f889dSBrendon Cahoon } 1662254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1663254f889dSBrendon Cahoon for (const auto &I : maxHeight->Preds) { 1664254f889dSBrendon Cahoon if (I.getKind() != SDep::Anti) 1665254f889dSBrendon Cahoon continue; 1666254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1667254f889dSBrendon Cahoon continue; 1668254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1669254f889dSBrendon Cahoon continue; 1670254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1671254f889dSBrendon Cahoon } 1672254f889dSBrendon Cahoon } 1673254f889dSBrendon Cahoon Order = BottomUp; 1674d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n Switching order to bottom up "); 1675254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1676254f889dSBrendon Cahoon if (pred_L(NodeOrder, N, &Nodes)) 1677254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1678254f889dSBrendon Cahoon } else { 1679254f889dSBrendon Cahoon // Choose the node with the maximum depth. If more than one, choose 16804b8bcf00SRoorda, Jan-Willem // the node with the maximum ZeroLatencyDepth. If still more than one, 16814b8bcf00SRoorda, Jan-Willem // choose the node with the lowest MOV. 1682254f889dSBrendon Cahoon while (!R.empty()) { 1683254f889dSBrendon Cahoon SUnit *maxDepth = nullptr; 1684254f889dSBrendon Cahoon for (SUnit *I : R) { 1685cdc71612SEugene Zelenko if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth)) 1686254f889dSBrendon Cahoon maxDepth = I; 1687254f889dSBrendon Cahoon else if (getDepth(I) == getDepth(maxDepth) && 16884b8bcf00SRoorda, Jan-Willem getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth)) 1689254f889dSBrendon Cahoon maxDepth = I; 16904b8bcf00SRoorda, Jan-Willem else if (getDepth(I) == getDepth(maxDepth) && 16914b8bcf00SRoorda, Jan-Willem getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) && 16924b8bcf00SRoorda, Jan-Willem getMOV(I) < getMOV(maxDepth)) 1693254f889dSBrendon Cahoon maxDepth = I; 1694254f889dSBrendon Cahoon } 1695254f889dSBrendon Cahoon NodeOrder.insert(maxDepth); 1696d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " "); 1697254f889dSBrendon Cahoon R.remove(maxDepth); 1698254f889dSBrendon Cahoon if (Nodes.isExceedSU(maxDepth)) { 1699254f889dSBrendon Cahoon Order = TopDown; 1700254f889dSBrendon Cahoon R.clear(); 1701254f889dSBrendon Cahoon R.insert(Nodes.getNode(0)); 1702254f889dSBrendon Cahoon break; 1703254f889dSBrendon Cahoon } 1704254f889dSBrendon Cahoon for (const auto &I : maxDepth->Preds) { 1705254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1706254f889dSBrendon Cahoon continue; 1707254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1708254f889dSBrendon Cahoon continue; 1709254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1710254f889dSBrendon Cahoon } 1711254f889dSBrendon Cahoon // Back-edges are predecessors with an anti-dependence. 1712254f889dSBrendon Cahoon for (const auto &I : maxDepth->Succs) { 1713254f889dSBrendon Cahoon if (I.getKind() != SDep::Anti) 1714254f889dSBrendon Cahoon continue; 1715254f889dSBrendon Cahoon if (Nodes.count(I.getSUnit()) == 0) 1716254f889dSBrendon Cahoon continue; 1717254f889dSBrendon Cahoon if (NodeOrder.count(I.getSUnit()) != 0) 1718254f889dSBrendon Cahoon continue; 1719254f889dSBrendon Cahoon R.insert(I.getSUnit()); 1720254f889dSBrendon Cahoon } 1721254f889dSBrendon Cahoon } 1722254f889dSBrendon Cahoon Order = TopDown; 1723d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n Switching order to top down "); 1724254f889dSBrendon Cahoon SmallSetVector<SUnit *, 8> N; 1725254f889dSBrendon Cahoon if (succ_L(NodeOrder, N, &Nodes)) 1726254f889dSBrendon Cahoon R.insert(N.begin(), N.end()); 1727254f889dSBrendon Cahoon } 1728254f889dSBrendon Cahoon } 1729d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n"); 1730254f889dSBrendon Cahoon } 1731254f889dSBrendon Cahoon 1732d34e60caSNicola Zaghen LLVM_DEBUG({ 1733254f889dSBrendon Cahoon dbgs() << "Node order: "; 1734254f889dSBrendon Cahoon for (SUnit *I : NodeOrder) 1735254f889dSBrendon Cahoon dbgs() << " " << I->NodeNum << " "; 1736254f889dSBrendon Cahoon dbgs() << "\n"; 1737254f889dSBrendon Cahoon }); 1738254f889dSBrendon Cahoon } 1739254f889dSBrendon Cahoon 1740254f889dSBrendon Cahoon /// Process the nodes in the computed order and create the pipelined schedule 1741254f889dSBrendon Cahoon /// of the instructions, if possible. Return true if a schedule is found. 1742254f889dSBrendon Cahoon bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) { 174332a40564SEugene Zelenko if (NodeOrder.empty()) 1744254f889dSBrendon Cahoon return false; 1745254f889dSBrendon Cahoon 1746254f889dSBrendon Cahoon bool scheduleFound = false; 1747254f889dSBrendon Cahoon // Keep increasing II until a valid schedule is found. 1748254f889dSBrendon Cahoon for (unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) { 1749254f889dSBrendon Cahoon Schedule.reset(); 1750254f889dSBrendon Cahoon Schedule.setInitiationInterval(II); 1751d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n"); 1752254f889dSBrendon Cahoon 1753254f889dSBrendon Cahoon SetVector<SUnit *>::iterator NI = NodeOrder.begin(); 1754254f889dSBrendon Cahoon SetVector<SUnit *>::iterator NE = NodeOrder.end(); 1755254f889dSBrendon Cahoon do { 1756254f889dSBrendon Cahoon SUnit *SU = *NI; 1757254f889dSBrendon Cahoon 1758254f889dSBrendon Cahoon // Compute the schedule time for the instruction, which is based 1759254f889dSBrendon Cahoon // upon the scheduled time for any predecessors/successors. 1760254f889dSBrendon Cahoon int EarlyStart = INT_MIN; 1761254f889dSBrendon Cahoon int LateStart = INT_MAX; 1762254f889dSBrendon Cahoon // These values are set when the size of the schedule window is limited 1763254f889dSBrendon Cahoon // due to chain dependences. 1764254f889dSBrendon Cahoon int SchedEnd = INT_MAX; 1765254f889dSBrendon Cahoon int SchedStart = INT_MIN; 1766254f889dSBrendon Cahoon Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart, 1767254f889dSBrendon Cahoon II, this); 1768d34e60caSNicola Zaghen LLVM_DEBUG({ 1769254f889dSBrendon Cahoon dbgs() << "Inst (" << SU->NodeNum << ") "; 1770254f889dSBrendon Cahoon SU->getInstr()->dump(); 1771254f889dSBrendon Cahoon dbgs() << "\n"; 1772254f889dSBrendon Cahoon }); 1773d34e60caSNicola Zaghen LLVM_DEBUG({ 1774254f889dSBrendon Cahoon dbgs() << "\tes: " << EarlyStart << " ls: " << LateStart 1775254f889dSBrendon Cahoon << " me: " << SchedEnd << " ms: " << SchedStart << "\n"; 1776254f889dSBrendon Cahoon }); 1777254f889dSBrendon Cahoon 1778254f889dSBrendon Cahoon if (EarlyStart > LateStart || SchedEnd < EarlyStart || 1779254f889dSBrendon Cahoon SchedStart > LateStart) 1780254f889dSBrendon Cahoon scheduleFound = false; 1781254f889dSBrendon Cahoon else if (EarlyStart != INT_MIN && LateStart == INT_MAX) { 1782254f889dSBrendon Cahoon SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1); 1783254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); 1784254f889dSBrendon Cahoon } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) { 1785254f889dSBrendon Cahoon SchedStart = std::max(SchedStart, LateStart - (int)II + 1); 1786254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II); 1787254f889dSBrendon Cahoon } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) { 1788254f889dSBrendon Cahoon SchedEnd = 1789254f889dSBrendon Cahoon std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1)); 1790254f889dSBrendon Cahoon // When scheduling a Phi it is better to start at the late cycle and go 1791254f889dSBrendon Cahoon // backwards. The default order may insert the Phi too far away from 1792254f889dSBrendon Cahoon // its first dependence. 1793254f889dSBrendon Cahoon if (SU->getInstr()->isPHI()) 1794254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II); 1795254f889dSBrendon Cahoon else 1796254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II); 1797254f889dSBrendon Cahoon } else { 1798254f889dSBrendon Cahoon int FirstCycle = Schedule.getFirstCycle(); 1799254f889dSBrendon Cahoon scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU), 1800254f889dSBrendon Cahoon FirstCycle + getASAP(SU) + II - 1, II); 1801254f889dSBrendon Cahoon } 1802254f889dSBrendon Cahoon // Even if we find a schedule, make sure the schedule doesn't exceed the 1803254f889dSBrendon Cahoon // allowable number of stages. We keep trying if this happens. 1804254f889dSBrendon Cahoon if (scheduleFound) 1805254f889dSBrendon Cahoon if (SwpMaxStages > -1 && 1806254f889dSBrendon Cahoon Schedule.getMaxStageCount() > (unsigned)SwpMaxStages) 1807254f889dSBrendon Cahoon scheduleFound = false; 1808254f889dSBrendon Cahoon 1809d34e60caSNicola Zaghen LLVM_DEBUG({ 1810254f889dSBrendon Cahoon if (!scheduleFound) 1811254f889dSBrendon Cahoon dbgs() << "\tCan't schedule\n"; 1812254f889dSBrendon Cahoon }); 1813254f889dSBrendon Cahoon } while (++NI != NE && scheduleFound); 1814254f889dSBrendon Cahoon 1815254f889dSBrendon Cahoon // If a schedule is found, check if it is a valid schedule too. 1816254f889dSBrendon Cahoon if (scheduleFound) 1817254f889dSBrendon Cahoon scheduleFound = Schedule.isValidSchedule(this); 1818254f889dSBrendon Cahoon } 1819254f889dSBrendon Cahoon 1820d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << "\n"); 1821254f889dSBrendon Cahoon 1822254f889dSBrendon Cahoon if (scheduleFound) 1823254f889dSBrendon Cahoon Schedule.finalizeSchedule(this); 1824254f889dSBrendon Cahoon else 1825254f889dSBrendon Cahoon Schedule.reset(); 1826254f889dSBrendon Cahoon 1827254f889dSBrendon Cahoon return scheduleFound && Schedule.getMaxStageCount() > 0; 1828254f889dSBrendon Cahoon } 1829254f889dSBrendon Cahoon 1830254f889dSBrendon Cahoon /// Given a schedule for the loop, generate a new version of the loop, 1831254f889dSBrendon Cahoon /// and replace the old version. This function generates a prolog 1832254f889dSBrendon Cahoon /// that contains the initial iterations in the pipeline, and kernel 1833254f889dSBrendon Cahoon /// loop, and the epilogue that contains the code for the final 1834254f889dSBrendon Cahoon /// iterations. 1835254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) { 1836254f889dSBrendon Cahoon // Create a new basic block for the kernel and add it to the CFG. 1837254f889dSBrendon Cahoon MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock()); 1838254f889dSBrendon Cahoon 1839254f889dSBrendon Cahoon unsigned MaxStageCount = Schedule.getMaxStageCount(); 1840254f889dSBrendon Cahoon 1841254f889dSBrendon Cahoon // Remember the registers that are used in different stages. The index is 1842254f889dSBrendon Cahoon // the iteration, or stage, that the instruction is scheduled in. This is 1843c73b6d6bSHiroshi Inoue // a map between register names in the original block and the names created 1844254f889dSBrendon Cahoon // in each stage of the pipelined loop. 1845254f889dSBrendon Cahoon ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2]; 1846254f889dSBrendon Cahoon InstrMapTy InstrMap; 1847254f889dSBrendon Cahoon 1848254f889dSBrendon Cahoon SmallVector<MachineBasicBlock *, 4> PrologBBs; 1849254f889dSBrendon Cahoon // Generate the prolog instructions that set up the pipeline. 1850254f889dSBrendon Cahoon generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs); 1851254f889dSBrendon Cahoon MF.insert(BB->getIterator(), KernelBB); 1852254f889dSBrendon Cahoon 1853254f889dSBrendon Cahoon // Rearrange the instructions to generate the new, pipelined loop, 1854254f889dSBrendon Cahoon // and update register names as needed. 1855254f889dSBrendon Cahoon for (int Cycle = Schedule.getFirstCycle(), 1856254f889dSBrendon Cahoon LastCycle = Schedule.getFinalCycle(); 1857254f889dSBrendon Cahoon Cycle <= LastCycle; ++Cycle) { 1858254f889dSBrendon Cahoon std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle); 1859254f889dSBrendon Cahoon // This inner loop schedules each instruction in the cycle. 1860254f889dSBrendon Cahoon for (SUnit *CI : CycleInstrs) { 1861254f889dSBrendon Cahoon if (CI->getInstr()->isPHI()) 1862254f889dSBrendon Cahoon continue; 1863254f889dSBrendon Cahoon unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr())); 1864254f889dSBrendon Cahoon MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum); 1865254f889dSBrendon Cahoon updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap); 1866254f889dSBrendon Cahoon KernelBB->push_back(NewMI); 1867254f889dSBrendon Cahoon InstrMap[NewMI] = CI->getInstr(); 1868254f889dSBrendon Cahoon } 1869254f889dSBrendon Cahoon } 1870254f889dSBrendon Cahoon 1871254f889dSBrendon Cahoon // Copy any terminator instructions to the new kernel, and update 1872254f889dSBrendon Cahoon // names as needed. 1873254f889dSBrendon Cahoon for (MachineBasicBlock::iterator I = BB->getFirstTerminator(), 1874254f889dSBrendon Cahoon E = BB->instr_end(); 1875254f889dSBrendon Cahoon I != E; ++I) { 1876254f889dSBrendon Cahoon MachineInstr *NewMI = MF.CloneMachineInstr(&*I); 1877254f889dSBrendon Cahoon updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap); 1878254f889dSBrendon Cahoon KernelBB->push_back(NewMI); 1879254f889dSBrendon Cahoon InstrMap[NewMI] = &*I; 1880254f889dSBrendon Cahoon } 1881254f889dSBrendon Cahoon 1882254f889dSBrendon Cahoon KernelBB->transferSuccessors(BB); 1883254f889dSBrendon Cahoon KernelBB->replaceSuccessor(BB, KernelBB); 1884254f889dSBrendon Cahoon 1885254f889dSBrendon Cahoon generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, 1886254f889dSBrendon Cahoon VRMap, InstrMap, MaxStageCount, MaxStageCount, false); 1887254f889dSBrendon Cahoon generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap, 1888254f889dSBrendon Cahoon InstrMap, MaxStageCount, MaxStageCount, false); 1889254f889dSBrendon Cahoon 1890d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump();); 1891254f889dSBrendon Cahoon 1892254f889dSBrendon Cahoon SmallVector<MachineBasicBlock *, 4> EpilogBBs; 1893254f889dSBrendon Cahoon // Generate the epilog instructions to complete the pipeline. 1894254f889dSBrendon Cahoon generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs, 1895254f889dSBrendon Cahoon PrologBBs); 1896254f889dSBrendon Cahoon 1897254f889dSBrendon Cahoon // We need this step because the register allocation doesn't handle some 1898254f889dSBrendon Cahoon // situations well, so we insert copies to help out. 1899254f889dSBrendon Cahoon splitLifetimes(KernelBB, EpilogBBs, Schedule); 1900254f889dSBrendon Cahoon 1901254f889dSBrendon Cahoon // Remove dead instructions due to loop induction variables. 1902254f889dSBrendon Cahoon removeDeadInstructions(KernelBB, EpilogBBs); 1903254f889dSBrendon Cahoon 1904254f889dSBrendon Cahoon // Add branches between prolog and epilog blocks. 1905254f889dSBrendon Cahoon addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap); 1906254f889dSBrendon Cahoon 1907254f889dSBrendon Cahoon // Remove the original loop since it's no longer referenced. 1908c715a5d2SKrzysztof Parzyszek for (auto &I : *BB) 1909c715a5d2SKrzysztof Parzyszek LIS.RemoveMachineInstrFromMaps(I); 1910254f889dSBrendon Cahoon BB->clear(); 1911254f889dSBrendon Cahoon BB->eraseFromParent(); 1912254f889dSBrendon Cahoon 1913254f889dSBrendon Cahoon delete[] VRMap; 1914254f889dSBrendon Cahoon } 1915254f889dSBrendon Cahoon 1916254f889dSBrendon Cahoon /// Generate the pipeline prolog code. 1917254f889dSBrendon Cahoon void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage, 1918254f889dSBrendon Cahoon MachineBasicBlock *KernelBB, 1919254f889dSBrendon Cahoon ValueMapTy *VRMap, 1920254f889dSBrendon Cahoon MBBVectorTy &PrologBBs) { 1921254f889dSBrendon Cahoon MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader(); 192232a40564SEugene Zelenko assert(PreheaderBB != nullptr && 1923254f889dSBrendon Cahoon "Need to add code to handle loops w/o preheader"); 1924254f889dSBrendon Cahoon MachineBasicBlock *PredBB = PreheaderBB; 1925254f889dSBrendon Cahoon InstrMapTy InstrMap; 1926254f889dSBrendon Cahoon 1927254f889dSBrendon Cahoon // Generate a basic block for each stage, not including the last stage, 1928254f889dSBrendon Cahoon // which will be generated in the kernel. Each basic block may contain 1929254f889dSBrendon Cahoon // instructions from multiple stages/iterations. 1930254f889dSBrendon Cahoon for (unsigned i = 0; i < LastStage; ++i) { 1931254f889dSBrendon Cahoon // Create and insert the prolog basic block prior to the original loop 1932254f889dSBrendon Cahoon // basic block. The original loop is removed later. 1933254f889dSBrendon Cahoon MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock()); 1934254f889dSBrendon Cahoon PrologBBs.push_back(NewBB); 1935254f889dSBrendon Cahoon MF.insert(BB->getIterator(), NewBB); 1936254f889dSBrendon Cahoon NewBB->transferSuccessors(PredBB); 1937254f889dSBrendon Cahoon PredBB->addSuccessor(NewBB); 1938254f889dSBrendon Cahoon PredBB = NewBB; 1939254f889dSBrendon Cahoon 1940254f889dSBrendon Cahoon // Generate instructions for each appropriate stage. Process instructions 1941254f889dSBrendon Cahoon // in original program order. 1942254f889dSBrendon Cahoon for (int StageNum = i; StageNum >= 0; --StageNum) { 1943254f889dSBrendon Cahoon for (MachineBasicBlock::iterator BBI = BB->instr_begin(), 1944254f889dSBrendon Cahoon BBE = BB->getFirstTerminator(); 1945254f889dSBrendon Cahoon BBI != BBE; ++BBI) { 1946254f889dSBrendon Cahoon if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) { 1947254f889dSBrendon Cahoon if (BBI->isPHI()) 1948254f889dSBrendon Cahoon continue; 1949254f889dSBrendon Cahoon MachineInstr *NewMI = 1950254f889dSBrendon Cahoon cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule); 1951254f889dSBrendon Cahoon updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule, 1952254f889dSBrendon Cahoon VRMap); 1953254f889dSBrendon Cahoon NewBB->push_back(NewMI); 1954254f889dSBrendon Cahoon InstrMap[NewMI] = &*BBI; 1955254f889dSBrendon Cahoon } 1956254f889dSBrendon Cahoon } 1957254f889dSBrendon Cahoon } 1958254f889dSBrendon Cahoon rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap); 1959d34e60caSNicola Zaghen LLVM_DEBUG({ 1960254f889dSBrendon Cahoon dbgs() << "prolog:\n"; 1961254f889dSBrendon Cahoon NewBB->dump(); 1962254f889dSBrendon Cahoon }); 1963254f889dSBrendon Cahoon } 1964254f889dSBrendon Cahoon 1965254f889dSBrendon Cahoon PredBB->replaceSuccessor(BB, KernelBB); 1966254f889dSBrendon Cahoon 1967254f889dSBrendon Cahoon // Check if we need to remove the branch from the preheader to the original 1968254f889dSBrendon Cahoon // loop, and replace it with a branch to the new loop. 19691b9fc8edSMatt Arsenault unsigned numBranches = TII->removeBranch(*PreheaderBB); 1970254f889dSBrendon Cahoon if (numBranches) { 1971254f889dSBrendon Cahoon SmallVector<MachineOperand, 0> Cond; 1972e8e0f5caSMatt Arsenault TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc()); 1973254f889dSBrendon Cahoon } 1974254f889dSBrendon Cahoon } 1975254f889dSBrendon Cahoon 1976254f889dSBrendon Cahoon /// Generate the pipeline epilog code. The epilog code finishes the iterations 1977254f889dSBrendon Cahoon /// that were started in either the prolog or the kernel. We create a basic 1978254f889dSBrendon Cahoon /// block for each stage that needs to complete. 1979254f889dSBrendon Cahoon void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage, 1980254f889dSBrendon Cahoon MachineBasicBlock *KernelBB, 1981254f889dSBrendon Cahoon ValueMapTy *VRMap, 1982254f889dSBrendon Cahoon MBBVectorTy &EpilogBBs, 1983254f889dSBrendon Cahoon MBBVectorTy &PrologBBs) { 1984254f889dSBrendon Cahoon // We need to change the branch from the kernel to the first epilog block, so 1985254f889dSBrendon Cahoon // this call to analyze branch uses the kernel rather than the original BB. 1986254f889dSBrendon Cahoon MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1987254f889dSBrendon Cahoon SmallVector<MachineOperand, 4> Cond; 1988254f889dSBrendon Cahoon bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond); 1989254f889dSBrendon Cahoon assert(!checkBranch && "generateEpilog must be able to analyze the branch"); 1990254f889dSBrendon Cahoon if (checkBranch) 1991254f889dSBrendon Cahoon return; 1992254f889dSBrendon Cahoon 1993254f889dSBrendon Cahoon MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin(); 1994254f889dSBrendon Cahoon if (*LoopExitI == KernelBB) 1995254f889dSBrendon Cahoon ++LoopExitI; 1996254f889dSBrendon Cahoon assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor"); 1997254f889dSBrendon Cahoon MachineBasicBlock *LoopExitBB = *LoopExitI; 1998254f889dSBrendon Cahoon 1999254f889dSBrendon Cahoon MachineBasicBlock *PredBB = KernelBB; 2000254f889dSBrendon Cahoon MachineBasicBlock *EpilogStart = LoopExitBB; 2001254f889dSBrendon Cahoon InstrMapTy InstrMap; 2002254f889dSBrendon Cahoon 2003254f889dSBrendon Cahoon // Generate a basic block for each stage, not including the last stage, 2004254f889dSBrendon Cahoon // which was generated for the kernel. Each basic block may contain 2005254f889dSBrendon Cahoon // instructions from multiple stages/iterations. 2006254f889dSBrendon Cahoon int EpilogStage = LastStage + 1; 2007254f889dSBrendon Cahoon for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) { 2008254f889dSBrendon Cahoon MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(); 2009254f889dSBrendon Cahoon EpilogBBs.push_back(NewBB); 2010254f889dSBrendon Cahoon MF.insert(BB->getIterator(), NewBB); 2011254f889dSBrendon Cahoon 2012254f889dSBrendon Cahoon PredBB->replaceSuccessor(LoopExitBB, NewBB); 2013254f889dSBrendon Cahoon NewBB->addSuccessor(LoopExitBB); 2014254f889dSBrendon Cahoon 2015254f889dSBrendon Cahoon if (EpilogStart == LoopExitBB) 2016254f889dSBrendon Cahoon EpilogStart = NewBB; 2017254f889dSBrendon Cahoon 2018254f889dSBrendon Cahoon // Add instructions to the epilog depending on the current block. 2019254f889dSBrendon Cahoon // Process instructions in original program order. 2020254f889dSBrendon Cahoon for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) { 2021254f889dSBrendon Cahoon for (auto &BBI : *BB) { 2022254f889dSBrendon Cahoon if (BBI.isPHI()) 2023254f889dSBrendon Cahoon continue; 2024254f889dSBrendon Cahoon MachineInstr *In = &BBI; 2025254f889dSBrendon Cahoon if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) { 2026785b6cecSKrzysztof Parzyszek // Instructions with memoperands in the epilog are updated with 2027785b6cecSKrzysztof Parzyszek // conservative values. 2028785b6cecSKrzysztof Parzyszek MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0); 2029254f889dSBrendon Cahoon updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap); 2030254f889dSBrendon Cahoon NewBB->push_back(NewMI); 2031254f889dSBrendon Cahoon InstrMap[NewMI] = In; 2032254f889dSBrendon Cahoon } 2033254f889dSBrendon Cahoon } 2034254f889dSBrendon Cahoon } 2035254f889dSBrendon Cahoon generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, 2036254f889dSBrendon Cahoon VRMap, InstrMap, LastStage, EpilogStage, i == 1); 2037254f889dSBrendon Cahoon generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap, 2038254f889dSBrendon Cahoon InstrMap, LastStage, EpilogStage, i == 1); 2039254f889dSBrendon Cahoon PredBB = NewBB; 2040254f889dSBrendon Cahoon 2041d34e60caSNicola Zaghen LLVM_DEBUG({ 2042254f889dSBrendon Cahoon dbgs() << "epilog:\n"; 2043254f889dSBrendon Cahoon NewBB->dump(); 2044254f889dSBrendon Cahoon }); 2045254f889dSBrendon Cahoon } 2046254f889dSBrendon Cahoon 2047254f889dSBrendon Cahoon // Fix any Phi nodes in the loop exit block. 2048254f889dSBrendon Cahoon for (MachineInstr &MI : *LoopExitBB) { 2049254f889dSBrendon Cahoon if (!MI.isPHI()) 2050254f889dSBrendon Cahoon break; 2051254f889dSBrendon Cahoon for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) { 2052254f889dSBrendon Cahoon MachineOperand &MO = MI.getOperand(i); 2053254f889dSBrendon Cahoon if (MO.getMBB() == BB) 2054254f889dSBrendon Cahoon MO.setMBB(PredBB); 2055254f889dSBrendon Cahoon } 2056254f889dSBrendon Cahoon } 2057254f889dSBrendon Cahoon 2058254f889dSBrendon Cahoon // Create a branch to the new epilog from the kernel. 2059254f889dSBrendon Cahoon // Remove the original branch and add a new branch to the epilog. 20601b9fc8edSMatt Arsenault TII->removeBranch(*KernelBB); 2061e8e0f5caSMatt Arsenault TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc()); 2062254f889dSBrendon Cahoon // Add a branch to the loop exit. 2063254f889dSBrendon Cahoon if (EpilogBBs.size() > 0) { 2064254f889dSBrendon Cahoon MachineBasicBlock *LastEpilogBB = EpilogBBs.back(); 2065254f889dSBrendon Cahoon SmallVector<MachineOperand, 4> Cond1; 2066e8e0f5caSMatt Arsenault TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc()); 2067254f889dSBrendon Cahoon } 2068254f889dSBrendon Cahoon } 2069254f889dSBrendon Cahoon 2070254f889dSBrendon Cahoon /// Replace all uses of FromReg that appear outside the specified 2071254f889dSBrendon Cahoon /// basic block with ToReg. 2072254f889dSBrendon Cahoon static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg, 2073254f889dSBrendon Cahoon MachineBasicBlock *MBB, 2074254f889dSBrendon Cahoon MachineRegisterInfo &MRI, 2075254f889dSBrendon Cahoon LiveIntervals &LIS) { 2076254f889dSBrendon Cahoon for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg), 2077254f889dSBrendon Cahoon E = MRI.use_end(); 2078254f889dSBrendon Cahoon I != E;) { 2079254f889dSBrendon Cahoon MachineOperand &O = *I; 2080254f889dSBrendon Cahoon ++I; 2081254f889dSBrendon Cahoon if (O.getParent()->getParent() != MBB) 2082254f889dSBrendon Cahoon O.setReg(ToReg); 2083254f889dSBrendon Cahoon } 2084254f889dSBrendon Cahoon if (!LIS.hasInterval(ToReg)) 2085254f889dSBrendon Cahoon LIS.createEmptyInterval(ToReg); 2086254f889dSBrendon Cahoon } 2087254f889dSBrendon Cahoon 2088254f889dSBrendon Cahoon /// Return true if the register has a use that occurs outside the 2089254f889dSBrendon Cahoon /// specified loop. 2090254f889dSBrendon Cahoon static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB, 2091254f889dSBrendon Cahoon MachineRegisterInfo &MRI) { 2092254f889dSBrendon Cahoon for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg), 2093254f889dSBrendon Cahoon E = MRI.use_end(); 2094254f889dSBrendon Cahoon I != E; ++I) 2095254f889dSBrendon Cahoon if (I->getParent()->getParent() != BB) 2096254f889dSBrendon Cahoon return true; 2097254f889dSBrendon Cahoon return false; 2098254f889dSBrendon Cahoon } 2099254f889dSBrendon Cahoon 2100254f889dSBrendon Cahoon /// Generate Phis for the specific block in the generated pipelined code. 2101254f889dSBrendon Cahoon /// This function looks at the Phis from the original code to guide the 2102254f889dSBrendon Cahoon /// creation of new Phis. 2103254f889dSBrendon Cahoon void SwingSchedulerDAG::generateExistingPhis( 2104254f889dSBrendon Cahoon MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2, 2105254f889dSBrendon Cahoon MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap, 2106254f889dSBrendon Cahoon InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum, 2107254f889dSBrendon Cahoon bool IsLast) { 21086bdc7555SSimon Pilgrim // Compute the stage number for the initial value of the Phi, which 2109254f889dSBrendon Cahoon // comes from the prolog. The prolog to use depends on to which kernel/ 2110254f889dSBrendon Cahoon // epilog that we're adding the Phi. 2111254f889dSBrendon Cahoon unsigned PrologStage = 0; 2112254f889dSBrendon Cahoon unsigned PrevStage = 0; 2113254f889dSBrendon Cahoon bool InKernel = (LastStageNum == CurStageNum); 2114254f889dSBrendon Cahoon if (InKernel) { 2115254f889dSBrendon Cahoon PrologStage = LastStageNum - 1; 2116254f889dSBrendon Cahoon PrevStage = CurStageNum; 2117254f889dSBrendon Cahoon } else { 2118254f889dSBrendon Cahoon PrologStage = LastStageNum - (CurStageNum - LastStageNum); 2119254f889dSBrendon Cahoon PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1; 2120254f889dSBrendon Cahoon } 2121254f889dSBrendon Cahoon 2122254f889dSBrendon Cahoon for (MachineBasicBlock::iterator BBI = BB->instr_begin(), 2123254f889dSBrendon Cahoon BBE = BB->getFirstNonPHI(); 2124254f889dSBrendon Cahoon BBI != BBE; ++BBI) { 2125254f889dSBrendon Cahoon unsigned Def = BBI->getOperand(0).getReg(); 2126254f889dSBrendon Cahoon 2127254f889dSBrendon Cahoon unsigned InitVal = 0; 2128254f889dSBrendon Cahoon unsigned LoopVal = 0; 2129254f889dSBrendon Cahoon getPhiRegs(*BBI, BB, InitVal, LoopVal); 2130254f889dSBrendon Cahoon 2131254f889dSBrendon Cahoon unsigned PhiOp1 = 0; 2132254f889dSBrendon Cahoon // The Phi value from the loop body typically is defined in the loop, but 2133254f889dSBrendon Cahoon // not always. So, we need to check if the value is defined in the loop. 2134254f889dSBrendon Cahoon unsigned PhiOp2 = LoopVal; 2135254f889dSBrendon Cahoon if (VRMap[LastStageNum].count(LoopVal)) 2136254f889dSBrendon Cahoon PhiOp2 = VRMap[LastStageNum][LoopVal]; 2137254f889dSBrendon Cahoon 2138254f889dSBrendon Cahoon int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI)); 2139254f889dSBrendon Cahoon int LoopValStage = 2140254f889dSBrendon Cahoon Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal))); 2141254f889dSBrendon Cahoon unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum); 2142254f889dSBrendon Cahoon if (NumStages == 0) { 2143254f889dSBrendon Cahoon // We don't need to generate a Phi anymore, but we need to rename any uses 2144254f889dSBrendon Cahoon // of the Phi value. 2145254f889dSBrendon Cahoon unsigned NewReg = VRMap[PrevStage][LoopVal]; 2146254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI, 214716e66f59SKrzysztof Parzyszek Def, InitVal, NewReg); 2148254f889dSBrendon Cahoon if (VRMap[CurStageNum].count(LoopVal)) 2149254f889dSBrendon Cahoon VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal]; 2150254f889dSBrendon Cahoon } 2151254f889dSBrendon Cahoon // Adjust the number of Phis needed depending on the number of prologs left, 21523f72a6b7SKrzysztof Parzyszek // and the distance from where the Phi is first scheduled. The number of 21533f72a6b7SKrzysztof Parzyszek // Phis cannot exceed the number of prolog stages. Each stage can 21543f72a6b7SKrzysztof Parzyszek // potentially define two values. 21553f72a6b7SKrzysztof Parzyszek unsigned MaxPhis = PrologStage + 2; 21563f72a6b7SKrzysztof Parzyszek if (!InKernel && (int)PrologStage <= LoopValStage) 21573f72a6b7SKrzysztof Parzyszek MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1); 21583f72a6b7SKrzysztof Parzyszek unsigned NumPhis = std::min(NumStages, MaxPhis); 2159254f889dSBrendon Cahoon 2160254f889dSBrendon Cahoon unsigned NewReg = 0; 2161254f889dSBrendon Cahoon unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled; 2162254f889dSBrendon Cahoon // In the epilog, we may need to look back one stage to get the correct 2163254f889dSBrendon Cahoon // Phi name because the epilog and prolog blocks execute the same stage. 2164254f889dSBrendon Cahoon // The correct name is from the previous block only when the Phi has 2165254f889dSBrendon Cahoon // been completely scheduled prior to the epilog, and Phi value is not 2166254f889dSBrendon Cahoon // needed in multiple stages. 2167254f889dSBrendon Cahoon int StageDiff = 0; 2168254f889dSBrendon Cahoon if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 && 2169254f889dSBrendon Cahoon NumPhis == 1) 2170254f889dSBrendon Cahoon StageDiff = 1; 2171254f889dSBrendon Cahoon // Adjust the computations below when the phi and the loop definition 2172254f889dSBrendon Cahoon // are scheduled in different stages. 2173254f889dSBrendon Cahoon if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage) 2174254f889dSBrendon Cahoon StageDiff = StageScheduled - LoopValStage; 2175254f889dSBrendon Cahoon for (unsigned np = 0; np < NumPhis; ++np) { 2176254f889dSBrendon Cahoon // If the Phi hasn't been scheduled, then use the initial Phi operand 2177254f889dSBrendon Cahoon // value. Otherwise, use the scheduled version of the instruction. This 2178254f889dSBrendon Cahoon // is a little complicated when a Phi references another Phi. 2179254f889dSBrendon Cahoon if (np > PrologStage || StageScheduled >= (int)LastStageNum) 2180254f889dSBrendon Cahoon PhiOp1 = InitVal; 2181254f889dSBrendon Cahoon // Check if the Phi has already been scheduled in a prolog stage. 2182254f889dSBrendon Cahoon else if (PrologStage >= AccessStage + StageDiff + np && 2183254f889dSBrendon Cahoon VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0) 2184254f889dSBrendon Cahoon PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal]; 2185dad8c6a1SHiroshi Inoue // Check if the Phi has already been scheduled, but the loop instruction 2186254f889dSBrendon Cahoon // is either another Phi, or doesn't occur in the loop. 2187254f889dSBrendon Cahoon else if (PrologStage >= AccessStage + StageDiff + np) { 2188254f889dSBrendon Cahoon // If the Phi references another Phi, we need to examine the other 2189254f889dSBrendon Cahoon // Phi to get the correct value. 2190254f889dSBrendon Cahoon PhiOp1 = LoopVal; 2191254f889dSBrendon Cahoon MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1); 2192254f889dSBrendon Cahoon int Indirects = 1; 2193254f889dSBrendon Cahoon while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) { 2194254f889dSBrendon Cahoon int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1)); 2195254f889dSBrendon Cahoon if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects) 2196254f889dSBrendon Cahoon PhiOp1 = getInitPhiReg(*InstOp1, BB); 2197254f889dSBrendon Cahoon else 2198254f889dSBrendon Cahoon PhiOp1 = getLoopPhiReg(*InstOp1, BB); 2199254f889dSBrendon Cahoon InstOp1 = MRI.getVRegDef(PhiOp1); 2200254f889dSBrendon Cahoon int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1)); 2201254f889dSBrendon Cahoon int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0); 2202254f889dSBrendon Cahoon if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np && 2203254f889dSBrendon Cahoon VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) { 2204254f889dSBrendon Cahoon PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1]; 2205254f889dSBrendon Cahoon break; 2206254f889dSBrendon Cahoon } 2207254f889dSBrendon Cahoon ++Indirects; 2208254f889dSBrendon Cahoon } 2209254f889dSBrendon Cahoon } else 2210254f889dSBrendon Cahoon PhiOp1 = InitVal; 2211254f889dSBrendon Cahoon // If this references a generated Phi in the kernel, get the Phi operand 2212254f889dSBrendon Cahoon // from the incoming block. 2213254f889dSBrendon Cahoon if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) 2214254f889dSBrendon Cahoon if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB) 2215254f889dSBrendon Cahoon PhiOp1 = getInitPhiReg(*InstOp1, KernelBB); 2216254f889dSBrendon Cahoon 2217254f889dSBrendon Cahoon MachineInstr *PhiInst = MRI.getVRegDef(LoopVal); 2218254f889dSBrendon Cahoon bool LoopDefIsPhi = PhiInst && PhiInst->isPHI(); 2219254f889dSBrendon Cahoon // In the epilog, a map lookup is needed to get the value from the kernel, 2220254f889dSBrendon Cahoon // or previous epilog block. How is does this depends on if the 2221254f889dSBrendon Cahoon // instruction is scheduled in the previous block. 2222254f889dSBrendon Cahoon if (!InKernel) { 2223254f889dSBrendon Cahoon int StageDiffAdj = 0; 2224254f889dSBrendon Cahoon if (LoopValStage != -1 && StageScheduled > LoopValStage) 2225254f889dSBrendon Cahoon StageDiffAdj = StageScheduled - LoopValStage; 2226254f889dSBrendon Cahoon // Use the loop value defined in the kernel, unless the kernel 2227254f889dSBrendon Cahoon // contains the last definition of the Phi. 2228254f889dSBrendon Cahoon if (np == 0 && PrevStage == LastStageNum && 2229254f889dSBrendon Cahoon (StageScheduled != 0 || LoopValStage != 0) && 2230254f889dSBrendon Cahoon VRMap[PrevStage - StageDiffAdj].count(LoopVal)) 2231254f889dSBrendon Cahoon PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal]; 2232254f889dSBrendon Cahoon // Use the value defined by the Phi. We add one because we switch 2233254f889dSBrendon Cahoon // from looking at the loop value to the Phi definition. 2234254f889dSBrendon Cahoon else if (np > 0 && PrevStage == LastStageNum && 2235254f889dSBrendon Cahoon VRMap[PrevStage - np + 1].count(Def)) 2236254f889dSBrendon Cahoon PhiOp2 = VRMap[PrevStage - np + 1][Def]; 2237254f889dSBrendon Cahoon // Use the loop value defined in the kernel. 2238e3841eeaSBrendon Cahoon else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 && 2239254f889dSBrendon Cahoon VRMap[PrevStage - StageDiffAdj - np].count(LoopVal)) 2240254f889dSBrendon Cahoon PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal]; 2241254f889dSBrendon Cahoon // Use the value defined by the Phi, unless we're generating the first 2242254f889dSBrendon Cahoon // epilog and the Phi refers to a Phi in a different stage. 2243254f889dSBrendon Cahoon else if (VRMap[PrevStage - np].count(Def) && 2244254f889dSBrendon Cahoon (!LoopDefIsPhi || PrevStage != LastStageNum)) 2245254f889dSBrendon Cahoon PhiOp2 = VRMap[PrevStage - np][Def]; 2246254f889dSBrendon Cahoon } 2247254f889dSBrendon Cahoon 2248254f889dSBrendon Cahoon // Check if we can reuse an existing Phi. This occurs when a Phi 2249254f889dSBrendon Cahoon // references another Phi, and the other Phi is scheduled in an 2250254f889dSBrendon Cahoon // earlier stage. We can try to reuse an existing Phi up until the last 2251254f889dSBrendon Cahoon // stage of the current Phi. 2252e3841eeaSBrendon Cahoon if (LoopDefIsPhi) { 2253e3841eeaSBrendon Cahoon if (static_cast<int>(PrologStage - np) >= StageScheduled) { 2254254f889dSBrendon Cahoon int LVNumStages = Schedule.getStagesForPhi(LoopVal); 2255254f889dSBrendon Cahoon int StageDiff = (StageScheduled - LoopValStage); 2256254f889dSBrendon Cahoon LVNumStages -= StageDiff; 22573a0a15afSKrzysztof Parzyszek // Make sure the loop value Phi has been processed already. 22583a0a15afSKrzysztof Parzyszek if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) { 2259254f889dSBrendon Cahoon NewReg = PhiOp2; 2260254f889dSBrendon Cahoon unsigned ReuseStage = CurStageNum; 2261254f889dSBrendon Cahoon if (Schedule.isLoopCarried(this, *PhiInst)) 2262254f889dSBrendon Cahoon ReuseStage -= LVNumStages; 2263254f889dSBrendon Cahoon // Check if the Phi to reuse has been generated yet. If not, then 2264254f889dSBrendon Cahoon // there is nothing to reuse. 226555cb4986SKrzysztof Parzyszek if (VRMap[ReuseStage - np].count(LoopVal)) { 226655cb4986SKrzysztof Parzyszek NewReg = VRMap[ReuseStage - np][LoopVal]; 2267254f889dSBrendon Cahoon 2268254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, 2269254f889dSBrendon Cahoon &*BBI, Def, NewReg); 2270254f889dSBrendon Cahoon // Update the map with the new Phi name. 2271254f889dSBrendon Cahoon VRMap[CurStageNum - np][Def] = NewReg; 2272254f889dSBrendon Cahoon PhiOp2 = NewReg; 2273254f889dSBrendon Cahoon if (VRMap[LastStageNum - np - 1].count(LoopVal)) 2274254f889dSBrendon Cahoon PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal]; 2275254f889dSBrendon Cahoon 2276254f889dSBrendon Cahoon if (IsLast && np == NumPhis - 1) 2277254f889dSBrendon Cahoon replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); 2278254f889dSBrendon Cahoon continue; 2279254f889dSBrendon Cahoon } 2280e3841eeaSBrendon Cahoon } 2281e3841eeaSBrendon Cahoon } 2282e3841eeaSBrendon Cahoon if (InKernel && StageDiff > 0 && 2283254f889dSBrendon Cahoon VRMap[CurStageNum - StageDiff - np].count(LoopVal)) 2284254f889dSBrendon Cahoon PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal]; 2285254f889dSBrendon Cahoon } 2286254f889dSBrendon Cahoon 2287254f889dSBrendon Cahoon const TargetRegisterClass *RC = MRI.getRegClass(Def); 2288254f889dSBrendon Cahoon NewReg = MRI.createVirtualRegister(RC); 2289254f889dSBrendon Cahoon 2290254f889dSBrendon Cahoon MachineInstrBuilder NewPhi = 2291254f889dSBrendon Cahoon BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(), 2292254f889dSBrendon Cahoon TII->get(TargetOpcode::PHI), NewReg); 2293254f889dSBrendon Cahoon NewPhi.addReg(PhiOp1).addMBB(BB1); 2294254f889dSBrendon Cahoon NewPhi.addReg(PhiOp2).addMBB(BB2); 2295254f889dSBrendon Cahoon if (np == 0) 2296254f889dSBrendon Cahoon InstrMap[NewPhi] = &*BBI; 2297254f889dSBrendon Cahoon 2298254f889dSBrendon Cahoon // We define the Phis after creating the new pipelined code, so 2299254f889dSBrendon Cahoon // we need to rename the Phi values in scheduled instructions. 2300254f889dSBrendon Cahoon 2301254f889dSBrendon Cahoon unsigned PrevReg = 0; 2302254f889dSBrendon Cahoon if (InKernel && VRMap[PrevStage - np].count(LoopVal)) 2303254f889dSBrendon Cahoon PrevReg = VRMap[PrevStage - np][LoopVal]; 2304254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI, 2305254f889dSBrendon Cahoon Def, NewReg, PrevReg); 2306254f889dSBrendon Cahoon // If the Phi has been scheduled, use the new name for rewriting. 2307254f889dSBrendon Cahoon if (VRMap[CurStageNum - np].count(Def)) { 2308254f889dSBrendon Cahoon unsigned R = VRMap[CurStageNum - np][Def]; 2309254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI, 2310254f889dSBrendon Cahoon R, NewReg); 2311254f889dSBrendon Cahoon } 2312254f889dSBrendon Cahoon 2313254f889dSBrendon Cahoon // Check if we need to rename any uses that occurs after the loop. The 2314254f889dSBrendon Cahoon // register to replace depends on whether the Phi is scheduled in the 2315254f889dSBrendon Cahoon // epilog. 2316254f889dSBrendon Cahoon if (IsLast && np == NumPhis - 1) 2317254f889dSBrendon Cahoon replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); 2318254f889dSBrendon Cahoon 2319254f889dSBrendon Cahoon // In the kernel, a dependent Phi uses the value from this Phi. 2320254f889dSBrendon Cahoon if (InKernel) 2321254f889dSBrendon Cahoon PhiOp2 = NewReg; 2322254f889dSBrendon Cahoon 2323254f889dSBrendon Cahoon // Update the map with the new Phi name. 2324254f889dSBrendon Cahoon VRMap[CurStageNum - np][Def] = NewReg; 2325254f889dSBrendon Cahoon } 2326254f889dSBrendon Cahoon 2327254f889dSBrendon Cahoon while (NumPhis++ < NumStages) { 2328254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis, 2329254f889dSBrendon Cahoon &*BBI, Def, NewReg, 0); 2330254f889dSBrendon Cahoon } 2331254f889dSBrendon Cahoon 2332254f889dSBrendon Cahoon // Check if we need to rename a Phi that has been eliminated due to 2333254f889dSBrendon Cahoon // scheduling. 2334254f889dSBrendon Cahoon if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal)) 2335254f889dSBrendon Cahoon replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS); 2336254f889dSBrendon Cahoon } 2337254f889dSBrendon Cahoon } 2338254f889dSBrendon Cahoon 2339254f889dSBrendon Cahoon /// Generate Phis for the specified block in the generated pipelined code. 2340254f889dSBrendon Cahoon /// These are new Phis needed because the definition is scheduled after the 2341c73b6d6bSHiroshi Inoue /// use in the pipelined sequence. 2342254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePhis( 2343254f889dSBrendon Cahoon MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2, 2344254f889dSBrendon Cahoon MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap, 2345254f889dSBrendon Cahoon InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum, 2346254f889dSBrendon Cahoon bool IsLast) { 2347254f889dSBrendon Cahoon // Compute the stage number that contains the initial Phi value, and 2348254f889dSBrendon Cahoon // the Phi from the previous stage. 2349254f889dSBrendon Cahoon unsigned PrologStage = 0; 2350254f889dSBrendon Cahoon unsigned PrevStage = 0; 2351254f889dSBrendon Cahoon unsigned StageDiff = CurStageNum - LastStageNum; 2352254f889dSBrendon Cahoon bool InKernel = (StageDiff == 0); 2353254f889dSBrendon Cahoon if (InKernel) { 2354254f889dSBrendon Cahoon PrologStage = LastStageNum - 1; 2355254f889dSBrendon Cahoon PrevStage = CurStageNum; 2356254f889dSBrendon Cahoon } else { 2357254f889dSBrendon Cahoon PrologStage = LastStageNum - StageDiff; 2358254f889dSBrendon Cahoon PrevStage = LastStageNum + StageDiff - 1; 2359254f889dSBrendon Cahoon } 2360254f889dSBrendon Cahoon 2361254f889dSBrendon Cahoon for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(), 2362254f889dSBrendon Cahoon BBE = BB->instr_end(); 2363254f889dSBrendon Cahoon BBI != BBE; ++BBI) { 2364254f889dSBrendon Cahoon for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) { 2365254f889dSBrendon Cahoon MachineOperand &MO = BBI->getOperand(i); 2366254f889dSBrendon Cahoon if (!MO.isReg() || !MO.isDef() || 2367254f889dSBrendon Cahoon !TargetRegisterInfo::isVirtualRegister(MO.getReg())) 2368254f889dSBrendon Cahoon continue; 2369254f889dSBrendon Cahoon 2370254f889dSBrendon Cahoon int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI)); 2371254f889dSBrendon Cahoon assert(StageScheduled != -1 && "Expecting scheduled instruction."); 2372254f889dSBrendon Cahoon unsigned Def = MO.getReg(); 2373254f889dSBrendon Cahoon unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum); 2374254f889dSBrendon Cahoon // An instruction scheduled in stage 0 and is used after the loop 2375254f889dSBrendon Cahoon // requires a phi in the epilog for the last definition from either 2376254f889dSBrendon Cahoon // the kernel or prolog. 2377254f889dSBrendon Cahoon if (!InKernel && NumPhis == 0 && StageScheduled == 0 && 2378254f889dSBrendon Cahoon hasUseAfterLoop(Def, BB, MRI)) 2379254f889dSBrendon Cahoon NumPhis = 1; 2380254f889dSBrendon Cahoon if (!InKernel && (unsigned)StageScheduled > PrologStage) 2381254f889dSBrendon Cahoon continue; 2382254f889dSBrendon Cahoon 2383254f889dSBrendon Cahoon unsigned PhiOp2 = VRMap[PrevStage][Def]; 2384254f889dSBrendon Cahoon if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2)) 2385254f889dSBrendon Cahoon if (InstOp2->isPHI() && InstOp2->getParent() == NewBB) 2386254f889dSBrendon Cahoon PhiOp2 = getLoopPhiReg(*InstOp2, BB2); 2387254f889dSBrendon Cahoon // The number of Phis can't exceed the number of prolog stages. The 2388254f889dSBrendon Cahoon // prolog stage number is zero based. 2389254f889dSBrendon Cahoon if (NumPhis > PrologStage + 1 - StageScheduled) 2390254f889dSBrendon Cahoon NumPhis = PrologStage + 1 - StageScheduled; 2391254f889dSBrendon Cahoon for (unsigned np = 0; np < NumPhis; ++np) { 2392254f889dSBrendon Cahoon unsigned PhiOp1 = VRMap[PrologStage][Def]; 2393254f889dSBrendon Cahoon if (np <= PrologStage) 2394254f889dSBrendon Cahoon PhiOp1 = VRMap[PrologStage - np][Def]; 2395254f889dSBrendon Cahoon if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) { 2396254f889dSBrendon Cahoon if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB) 2397254f889dSBrendon Cahoon PhiOp1 = getInitPhiReg(*InstOp1, KernelBB); 2398254f889dSBrendon Cahoon if (InstOp1->isPHI() && InstOp1->getParent() == NewBB) 2399254f889dSBrendon Cahoon PhiOp1 = getInitPhiReg(*InstOp1, NewBB); 2400254f889dSBrendon Cahoon } 2401254f889dSBrendon Cahoon if (!InKernel) 2402254f889dSBrendon Cahoon PhiOp2 = VRMap[PrevStage - np][Def]; 2403254f889dSBrendon Cahoon 2404254f889dSBrendon Cahoon const TargetRegisterClass *RC = MRI.getRegClass(Def); 2405254f889dSBrendon Cahoon unsigned NewReg = MRI.createVirtualRegister(RC); 2406254f889dSBrendon Cahoon 2407254f889dSBrendon Cahoon MachineInstrBuilder NewPhi = 2408254f889dSBrendon Cahoon BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(), 2409254f889dSBrendon Cahoon TII->get(TargetOpcode::PHI), NewReg); 2410254f889dSBrendon Cahoon NewPhi.addReg(PhiOp1).addMBB(BB1); 2411254f889dSBrendon Cahoon NewPhi.addReg(PhiOp2).addMBB(BB2); 2412254f889dSBrendon Cahoon if (np == 0) 2413254f889dSBrendon Cahoon InstrMap[NewPhi] = &*BBI; 2414254f889dSBrendon Cahoon 2415254f889dSBrendon Cahoon // Rewrite uses and update the map. The actions depend upon whether 2416254f889dSBrendon Cahoon // we generating code for the kernel or epilog blocks. 2417254f889dSBrendon Cahoon if (InKernel) { 2418254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, 2419254f889dSBrendon Cahoon &*BBI, PhiOp1, NewReg); 2420254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, 2421254f889dSBrendon Cahoon &*BBI, PhiOp2, NewReg); 2422254f889dSBrendon Cahoon 2423254f889dSBrendon Cahoon PhiOp2 = NewReg; 2424254f889dSBrendon Cahoon VRMap[PrevStage - np - 1][Def] = NewReg; 2425254f889dSBrendon Cahoon } else { 2426254f889dSBrendon Cahoon VRMap[CurStageNum - np][Def] = NewReg; 2427254f889dSBrendon Cahoon if (np == NumPhis - 1) 2428254f889dSBrendon Cahoon rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, 2429254f889dSBrendon Cahoon &*BBI, Def, NewReg); 2430254f889dSBrendon Cahoon } 2431254f889dSBrendon Cahoon if (IsLast && np == NumPhis - 1) 2432254f889dSBrendon Cahoon replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS); 2433254f889dSBrendon Cahoon } 2434254f889dSBrendon Cahoon } 2435254f889dSBrendon Cahoon } 2436254f889dSBrendon Cahoon } 2437254f889dSBrendon Cahoon 2438254f889dSBrendon Cahoon /// Remove instructions that generate values with no uses. 2439254f889dSBrendon Cahoon /// Typically, these are induction variable operations that generate values 2440254f889dSBrendon Cahoon /// used in the loop itself. A dead instruction has a definition with 2441254f889dSBrendon Cahoon /// no uses, or uses that occur in the original loop only. 2442254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB, 2443254f889dSBrendon Cahoon MBBVectorTy &EpilogBBs) { 2444254f889dSBrendon Cahoon // For each epilog block, check that the value defined by each instruction 2445254f889dSBrendon Cahoon // is used. If not, delete it. 2446254f889dSBrendon Cahoon for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(), 2447254f889dSBrendon Cahoon MBE = EpilogBBs.rend(); 2448254f889dSBrendon Cahoon MBB != MBE; ++MBB) 2449254f889dSBrendon Cahoon for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(), 2450254f889dSBrendon Cahoon ME = (*MBB)->instr_rend(); 2451254f889dSBrendon Cahoon MI != ME;) { 2452254f889dSBrendon Cahoon // From DeadMachineInstructionElem. Don't delete inline assembly. 2453254f889dSBrendon Cahoon if (MI->isInlineAsm()) { 2454254f889dSBrendon Cahoon ++MI; 2455254f889dSBrendon Cahoon continue; 2456254f889dSBrendon Cahoon } 2457254f889dSBrendon Cahoon bool SawStore = false; 2458254f889dSBrendon Cahoon // Check if it's safe to remove the instruction due to side effects. 2459254f889dSBrendon Cahoon // We can, and want to, remove Phis here. 2460254f889dSBrendon Cahoon if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) { 2461254f889dSBrendon Cahoon ++MI; 2462254f889dSBrendon Cahoon continue; 2463254f889dSBrendon Cahoon } 2464254f889dSBrendon Cahoon bool used = true; 2465254f889dSBrendon Cahoon for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 2466254f889dSBrendon Cahoon MOE = MI->operands_end(); 2467254f889dSBrendon Cahoon MOI != MOE; ++MOI) { 2468254f889dSBrendon Cahoon if (!MOI->isReg() || !MOI->isDef()) 2469254f889dSBrendon Cahoon continue; 2470254f889dSBrendon Cahoon unsigned reg = MOI->getReg(); 2471b9b75b8cSKrzysztof Parzyszek // Assume physical registers are used, unless they are marked dead. 2472b9b75b8cSKrzysztof Parzyszek if (TargetRegisterInfo::isPhysicalRegister(reg)) { 2473b9b75b8cSKrzysztof Parzyszek used = !MOI->isDead(); 2474b9b75b8cSKrzysztof Parzyszek if (used) 2475b9b75b8cSKrzysztof Parzyszek break; 2476b9b75b8cSKrzysztof Parzyszek continue; 2477b9b75b8cSKrzysztof Parzyszek } 2478254f889dSBrendon Cahoon unsigned realUses = 0; 2479254f889dSBrendon Cahoon for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg), 2480254f889dSBrendon Cahoon EI = MRI.use_end(); 2481254f889dSBrendon Cahoon UI != EI; ++UI) { 2482254f889dSBrendon Cahoon // Check if there are any uses that occur only in the original 2483254f889dSBrendon Cahoon // loop. If so, that's not a real use. 2484254f889dSBrendon Cahoon if (UI->getParent()->getParent() != BB) { 2485254f889dSBrendon Cahoon realUses++; 2486254f889dSBrendon Cahoon used = true; 2487254f889dSBrendon Cahoon break; 2488254f889dSBrendon Cahoon } 2489254f889dSBrendon Cahoon } 2490254f889dSBrendon Cahoon if (realUses > 0) 2491254f889dSBrendon Cahoon break; 2492254f889dSBrendon Cahoon used = false; 2493254f889dSBrendon Cahoon } 2494254f889dSBrendon Cahoon if (!used) { 2495c715a5d2SKrzysztof Parzyszek LIS.RemoveMachineInstrFromMaps(*MI); 24965c001c36SDuncan P. N. Exon Smith MI++->eraseFromParent(); 2497254f889dSBrendon Cahoon continue; 2498254f889dSBrendon Cahoon } 2499254f889dSBrendon Cahoon ++MI; 2500254f889dSBrendon Cahoon } 2501254f889dSBrendon Cahoon // In the kernel block, check if we can remove a Phi that generates a value 2502254f889dSBrendon Cahoon // used in an instruction removed in the epilog block. 2503254f889dSBrendon Cahoon for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(), 2504254f889dSBrendon Cahoon BBE = KernelBB->getFirstNonPHI(); 2505254f889dSBrendon Cahoon BBI != BBE;) { 2506254f889dSBrendon Cahoon MachineInstr *MI = &*BBI; 2507254f889dSBrendon Cahoon ++BBI; 2508254f889dSBrendon Cahoon unsigned reg = MI->getOperand(0).getReg(); 2509254f889dSBrendon Cahoon if (MRI.use_begin(reg) == MRI.use_end()) { 2510c715a5d2SKrzysztof Parzyszek LIS.RemoveMachineInstrFromMaps(*MI); 2511254f889dSBrendon Cahoon MI->eraseFromParent(); 2512254f889dSBrendon Cahoon } 2513254f889dSBrendon Cahoon } 2514254f889dSBrendon Cahoon } 2515254f889dSBrendon Cahoon 2516254f889dSBrendon Cahoon /// For loop carried definitions, we split the lifetime of a virtual register 2517254f889dSBrendon Cahoon /// that has uses past the definition in the next iteration. A copy with a new 2518254f889dSBrendon Cahoon /// virtual register is inserted before the definition, which helps with 2519254f889dSBrendon Cahoon /// generating a better register assignment. 2520254f889dSBrendon Cahoon /// 2521254f889dSBrendon Cahoon /// v1 = phi(a, v2) v1 = phi(a, v2) 2522254f889dSBrendon Cahoon /// v2 = phi(b, v3) v2 = phi(b, v3) 2523254f889dSBrendon Cahoon /// v3 = .. v4 = copy v1 2524254f889dSBrendon Cahoon /// .. = V1 v3 = .. 2525254f889dSBrendon Cahoon /// .. = v4 2526254f889dSBrendon Cahoon void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB, 2527254f889dSBrendon Cahoon MBBVectorTy &EpilogBBs, 2528254f889dSBrendon Cahoon SMSchedule &Schedule) { 2529254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 253090ecac01SBob Wilson for (auto &PHI : KernelBB->phis()) { 253190ecac01SBob Wilson unsigned Def = PHI.getOperand(0).getReg(); 2532254f889dSBrendon Cahoon // Check for any Phi definition that used as an operand of another Phi 2533254f889dSBrendon Cahoon // in the same block. 2534254f889dSBrendon Cahoon for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def), 2535254f889dSBrendon Cahoon E = MRI.use_instr_end(); 2536254f889dSBrendon Cahoon I != E; ++I) { 2537254f889dSBrendon Cahoon if (I->isPHI() && I->getParent() == KernelBB) { 2538254f889dSBrendon Cahoon // Get the loop carried definition. 253990ecac01SBob Wilson unsigned LCDef = getLoopPhiReg(PHI, KernelBB); 2540254f889dSBrendon Cahoon if (!LCDef) 2541254f889dSBrendon Cahoon continue; 2542254f889dSBrendon Cahoon MachineInstr *MI = MRI.getVRegDef(LCDef); 2543254f889dSBrendon Cahoon if (!MI || MI->getParent() != KernelBB || MI->isPHI()) 2544254f889dSBrendon Cahoon continue; 2545254f889dSBrendon Cahoon // Search through the rest of the block looking for uses of the Phi 2546254f889dSBrendon Cahoon // definition. If one occurs, then split the lifetime. 2547254f889dSBrendon Cahoon unsigned SplitReg = 0; 2548254f889dSBrendon Cahoon for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI), 2549254f889dSBrendon Cahoon KernelBB->instr_end())) 2550254f889dSBrendon Cahoon if (BBJ.readsRegister(Def)) { 2551254f889dSBrendon Cahoon // We split the lifetime when we find the first use. 2552254f889dSBrendon Cahoon if (SplitReg == 0) { 2553254f889dSBrendon Cahoon SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def)); 2554254f889dSBrendon Cahoon BuildMI(*KernelBB, MI, MI->getDebugLoc(), 2555254f889dSBrendon Cahoon TII->get(TargetOpcode::COPY), SplitReg) 2556254f889dSBrendon Cahoon .addReg(Def); 2557254f889dSBrendon Cahoon } 2558254f889dSBrendon Cahoon BBJ.substituteRegister(Def, SplitReg, 0, *TRI); 2559254f889dSBrendon Cahoon } 2560254f889dSBrendon Cahoon if (!SplitReg) 2561254f889dSBrendon Cahoon continue; 2562254f889dSBrendon Cahoon // Search through each of the epilog blocks for any uses to be renamed. 2563254f889dSBrendon Cahoon for (auto &Epilog : EpilogBBs) 2564254f889dSBrendon Cahoon for (auto &I : *Epilog) 2565254f889dSBrendon Cahoon if (I.readsRegister(Def)) 2566254f889dSBrendon Cahoon I.substituteRegister(Def, SplitReg, 0, *TRI); 2567254f889dSBrendon Cahoon break; 2568254f889dSBrendon Cahoon } 2569254f889dSBrendon Cahoon } 2570254f889dSBrendon Cahoon } 2571254f889dSBrendon Cahoon } 2572254f889dSBrendon Cahoon 2573254f889dSBrendon Cahoon /// Remove the incoming block from the Phis in a basic block. 2574254f889dSBrendon Cahoon static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) { 2575254f889dSBrendon Cahoon for (MachineInstr &MI : *BB) { 2576254f889dSBrendon Cahoon if (!MI.isPHI()) 2577254f889dSBrendon Cahoon break; 2578254f889dSBrendon Cahoon for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) 2579254f889dSBrendon Cahoon if (MI.getOperand(i + 1).getMBB() == Incoming) { 2580254f889dSBrendon Cahoon MI.RemoveOperand(i + 1); 2581254f889dSBrendon Cahoon MI.RemoveOperand(i); 2582254f889dSBrendon Cahoon break; 2583254f889dSBrendon Cahoon } 2584254f889dSBrendon Cahoon } 2585254f889dSBrendon Cahoon } 2586254f889dSBrendon Cahoon 2587254f889dSBrendon Cahoon /// Create branches from each prolog basic block to the appropriate epilog 2588254f889dSBrendon Cahoon /// block. These edges are needed if the loop ends before reaching the 2589254f889dSBrendon Cahoon /// kernel. 2590254f889dSBrendon Cahoon void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs, 2591254f889dSBrendon Cahoon MachineBasicBlock *KernelBB, 2592254f889dSBrendon Cahoon MBBVectorTy &EpilogBBs, 2593254f889dSBrendon Cahoon SMSchedule &Schedule, ValueMapTy *VRMap) { 2594254f889dSBrendon Cahoon assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch"); 2595254f889dSBrendon Cahoon MachineInstr *IndVar = Pass.LI.LoopInductionVar; 2596254f889dSBrendon Cahoon MachineInstr *Cmp = Pass.LI.LoopCompare; 2597254f889dSBrendon Cahoon MachineBasicBlock *LastPro = KernelBB; 2598254f889dSBrendon Cahoon MachineBasicBlock *LastEpi = KernelBB; 2599254f889dSBrendon Cahoon 2600254f889dSBrendon Cahoon // Start from the blocks connected to the kernel and work "out" 2601254f889dSBrendon Cahoon // to the first prolog and the last epilog blocks. 2602254f889dSBrendon Cahoon SmallVector<MachineInstr *, 4> PrevInsts; 2603254f889dSBrendon Cahoon unsigned MaxIter = PrologBBs.size() - 1; 2604254f889dSBrendon Cahoon unsigned LC = UINT_MAX; 2605254f889dSBrendon Cahoon unsigned LCMin = UINT_MAX; 2606254f889dSBrendon Cahoon for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) { 2607254f889dSBrendon Cahoon // Add branches to the prolog that go to the corresponding 2608254f889dSBrendon Cahoon // epilog, and the fall-thru prolog/kernel block. 2609254f889dSBrendon Cahoon MachineBasicBlock *Prolog = PrologBBs[j]; 2610254f889dSBrendon Cahoon MachineBasicBlock *Epilog = EpilogBBs[i]; 2611254f889dSBrendon Cahoon // We've executed one iteration, so decrement the loop count and check for 2612254f889dSBrendon Cahoon // the loop end. 2613254f889dSBrendon Cahoon SmallVector<MachineOperand, 4> Cond; 2614254f889dSBrendon Cahoon // Check if the LOOP0 has already been removed. If so, then there is no need 2615254f889dSBrendon Cahoon // to reduce the trip count. 2616254f889dSBrendon Cahoon if (LC != 0) 26178fb181caSKrzysztof Parzyszek LC = TII->reduceLoopCount(*Prolog, IndVar, *Cmp, Cond, PrevInsts, j, 2618254f889dSBrendon Cahoon MaxIter); 2619254f889dSBrendon Cahoon 2620254f889dSBrendon Cahoon // Record the value of the first trip count, which is used to determine if 2621254f889dSBrendon Cahoon // branches and blocks can be removed for constant trip counts. 2622254f889dSBrendon Cahoon if (LCMin == UINT_MAX) 2623254f889dSBrendon Cahoon LCMin = LC; 2624254f889dSBrendon Cahoon 2625254f889dSBrendon Cahoon unsigned numAdded = 0; 2626254f889dSBrendon Cahoon if (TargetRegisterInfo::isVirtualRegister(LC)) { 2627254f889dSBrendon Cahoon Prolog->addSuccessor(Epilog); 2628e8e0f5caSMatt Arsenault numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc()); 2629254f889dSBrendon Cahoon } else if (j >= LCMin) { 2630254f889dSBrendon Cahoon Prolog->addSuccessor(Epilog); 2631254f889dSBrendon Cahoon Prolog->removeSuccessor(LastPro); 2632254f889dSBrendon Cahoon LastEpi->removeSuccessor(Epilog); 2633e8e0f5caSMatt Arsenault numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc()); 2634254f889dSBrendon Cahoon removePhis(Epilog, LastEpi); 2635254f889dSBrendon Cahoon // Remove the blocks that are no longer referenced. 2636254f889dSBrendon Cahoon if (LastPro != LastEpi) { 2637254f889dSBrendon Cahoon LastEpi->clear(); 2638254f889dSBrendon Cahoon LastEpi->eraseFromParent(); 2639254f889dSBrendon Cahoon } 2640254f889dSBrendon Cahoon LastPro->clear(); 2641254f889dSBrendon Cahoon LastPro->eraseFromParent(); 2642254f889dSBrendon Cahoon } else { 2643e8e0f5caSMatt Arsenault numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc()); 2644254f889dSBrendon Cahoon removePhis(Epilog, Prolog); 2645254f889dSBrendon Cahoon } 2646254f889dSBrendon Cahoon LastPro = Prolog; 2647254f889dSBrendon Cahoon LastEpi = Epilog; 2648254f889dSBrendon Cahoon for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(), 2649254f889dSBrendon Cahoon E = Prolog->instr_rend(); 2650254f889dSBrendon Cahoon I != E && numAdded > 0; ++I, --numAdded) 2651254f889dSBrendon Cahoon updateInstruction(&*I, false, j, 0, Schedule, VRMap); 2652254f889dSBrendon Cahoon } 2653254f889dSBrendon Cahoon } 2654254f889dSBrendon Cahoon 2655254f889dSBrendon Cahoon /// Return true if we can compute the amount the instruction changes 2656254f889dSBrendon Cahoon /// during each iteration. Set Delta to the amount of the change. 2657254f889dSBrendon Cahoon bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) { 2658254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2659d7eebd6dSFrancis Visoiu Mistrih MachineOperand *BaseOp; 2660254f889dSBrendon Cahoon int64_t Offset; 2661d7eebd6dSFrancis Visoiu Mistrih if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI)) 2662254f889dSBrendon Cahoon return false; 2663254f889dSBrendon Cahoon 2664d7eebd6dSFrancis Visoiu Mistrih if (!BaseOp->isReg()) 2665d7eebd6dSFrancis Visoiu Mistrih return false; 2666d7eebd6dSFrancis Visoiu Mistrih 2667d7eebd6dSFrancis Visoiu Mistrih unsigned BaseReg = BaseOp->getReg(); 2668d7eebd6dSFrancis Visoiu Mistrih 2669254f889dSBrendon Cahoon MachineRegisterInfo &MRI = MF.getRegInfo(); 2670254f889dSBrendon Cahoon // Check if there is a Phi. If so, get the definition in the loop. 2671254f889dSBrendon Cahoon MachineInstr *BaseDef = MRI.getVRegDef(BaseReg); 2672254f889dSBrendon Cahoon if (BaseDef && BaseDef->isPHI()) { 2673254f889dSBrendon Cahoon BaseReg = getLoopPhiReg(*BaseDef, MI.getParent()); 2674254f889dSBrendon Cahoon BaseDef = MRI.getVRegDef(BaseReg); 2675254f889dSBrendon Cahoon } 2676254f889dSBrendon Cahoon if (!BaseDef) 2677254f889dSBrendon Cahoon return false; 2678254f889dSBrendon Cahoon 2679254f889dSBrendon Cahoon int D = 0; 26808fb181caSKrzysztof Parzyszek if (!TII->getIncrementValue(*BaseDef, D) && D >= 0) 2681254f889dSBrendon Cahoon return false; 2682254f889dSBrendon Cahoon 2683254f889dSBrendon Cahoon Delta = D; 2684254f889dSBrendon Cahoon return true; 2685254f889dSBrendon Cahoon } 2686254f889dSBrendon Cahoon 2687254f889dSBrendon Cahoon /// Update the memory operand with a new offset when the pipeliner 2688cf56e92cSJustin Lebar /// generates a new copy of the instruction that refers to a 2689254f889dSBrendon Cahoon /// different memory location. 2690254f889dSBrendon Cahoon void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI, 2691254f889dSBrendon Cahoon MachineInstr &OldMI, unsigned Num) { 2692254f889dSBrendon Cahoon if (Num == 0) 2693254f889dSBrendon Cahoon return; 2694254f889dSBrendon Cahoon // If the instruction has memory operands, then adjust the offset 2695254f889dSBrendon Cahoon // when the instruction appears in different stages. 2696c73c0307SChandler Carruth if (NewMI.memoperands_empty()) 2697254f889dSBrendon Cahoon return; 2698c73c0307SChandler Carruth SmallVector<MachineMemOperand *, 2> NewMMOs; 26990a33a7aeSJustin Lebar for (MachineMemOperand *MMO : NewMI.memoperands()) { 2700adbf09e8SJustin Lebar if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) || 2701adbf09e8SJustin Lebar (!MMO->getValue())) { 2702c73c0307SChandler Carruth NewMMOs.push_back(MMO); 2703254f889dSBrendon Cahoon continue; 2704254f889dSBrendon Cahoon } 2705254f889dSBrendon Cahoon unsigned Delta; 2706785b6cecSKrzysztof Parzyszek if (Num != UINT_MAX && computeDelta(OldMI, Delta)) { 2707254f889dSBrendon Cahoon int64_t AdjOffset = Delta * Num; 2708c73c0307SChandler Carruth NewMMOs.push_back( 2709c73c0307SChandler Carruth MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize())); 27102d79017dSKrzysztof Parzyszek } else { 2711cc3f6302SKrzysztof Parzyszek NewMMOs.push_back( 2712cc3f6302SKrzysztof Parzyszek MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize)); 27132d79017dSKrzysztof Parzyszek } 2714254f889dSBrendon Cahoon } 2715c73c0307SChandler Carruth NewMI.setMemRefs(MF, NewMMOs); 2716254f889dSBrendon Cahoon } 2717254f889dSBrendon Cahoon 2718254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop and update the 2719254f889dSBrendon Cahoon /// memory operands, if needed. 2720254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI, 2721254f889dSBrendon Cahoon unsigned CurStageNum, 2722254f889dSBrendon Cahoon unsigned InstStageNum) { 2723254f889dSBrendon Cahoon MachineInstr *NewMI = MF.CloneMachineInstr(OldMI); 2724254f889dSBrendon Cahoon // Check for tied operands in inline asm instructions. This should be handled 2725254f889dSBrendon Cahoon // elsewhere, but I'm not sure of the best solution. 2726254f889dSBrendon Cahoon if (OldMI->isInlineAsm()) 2727254f889dSBrendon Cahoon for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) { 2728254f889dSBrendon Cahoon const auto &MO = OldMI->getOperand(i); 2729254f889dSBrendon Cahoon if (MO.isReg() && MO.isUse()) 2730254f889dSBrendon Cahoon break; 2731254f889dSBrendon Cahoon unsigned UseIdx; 2732254f889dSBrendon Cahoon if (OldMI->isRegTiedToUseOperand(i, &UseIdx)) 2733254f889dSBrendon Cahoon NewMI->tieOperands(i, UseIdx); 2734254f889dSBrendon Cahoon } 2735254f889dSBrendon Cahoon updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum); 2736254f889dSBrendon Cahoon return NewMI; 2737254f889dSBrendon Cahoon } 2738254f889dSBrendon Cahoon 2739254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop. If needed, this 2740254f889dSBrendon Cahoon /// function updates the instruction using the values saved in the 2741254f889dSBrendon Cahoon /// InstrChanges structure. 2742254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI, 2743254f889dSBrendon Cahoon unsigned CurStageNum, 2744254f889dSBrendon Cahoon unsigned InstStageNum, 2745254f889dSBrendon Cahoon SMSchedule &Schedule) { 2746254f889dSBrendon Cahoon MachineInstr *NewMI = MF.CloneMachineInstr(OldMI); 2747254f889dSBrendon Cahoon DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = 2748254f889dSBrendon Cahoon InstrChanges.find(getSUnit(OldMI)); 2749254f889dSBrendon Cahoon if (It != InstrChanges.end()) { 2750254f889dSBrendon Cahoon std::pair<unsigned, int64_t> RegAndOffset = It->second; 2751254f889dSBrendon Cahoon unsigned BasePos, OffsetPos; 27528fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos)) 2753254f889dSBrendon Cahoon return nullptr; 2754254f889dSBrendon Cahoon int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm(); 2755254f889dSBrendon Cahoon MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first); 2756254f889dSBrendon Cahoon if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum) 2757254f889dSBrendon Cahoon NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum); 2758254f889dSBrendon Cahoon NewMI->getOperand(OffsetPos).setImm(NewOffset); 2759254f889dSBrendon Cahoon } 2760254f889dSBrendon Cahoon updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum); 2761254f889dSBrendon Cahoon return NewMI; 2762254f889dSBrendon Cahoon } 2763254f889dSBrendon Cahoon 2764254f889dSBrendon Cahoon /// Update the machine instruction with new virtual registers. This 2765254f889dSBrendon Cahoon /// function may change the defintions and/or uses. 2766254f889dSBrendon Cahoon void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef, 2767254f889dSBrendon Cahoon unsigned CurStageNum, 2768254f889dSBrendon Cahoon unsigned InstrStageNum, 2769254f889dSBrendon Cahoon SMSchedule &Schedule, 2770254f889dSBrendon Cahoon ValueMapTy *VRMap) { 2771254f889dSBrendon Cahoon for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) { 2772254f889dSBrendon Cahoon MachineOperand &MO = NewMI->getOperand(i); 2773254f889dSBrendon Cahoon if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg())) 2774254f889dSBrendon Cahoon continue; 2775254f889dSBrendon Cahoon unsigned reg = MO.getReg(); 2776254f889dSBrendon Cahoon if (MO.isDef()) { 2777254f889dSBrendon Cahoon // Create a new virtual register for the definition. 2778254f889dSBrendon Cahoon const TargetRegisterClass *RC = MRI.getRegClass(reg); 2779254f889dSBrendon Cahoon unsigned NewReg = MRI.createVirtualRegister(RC); 2780254f889dSBrendon Cahoon MO.setReg(NewReg); 2781254f889dSBrendon Cahoon VRMap[CurStageNum][reg] = NewReg; 2782254f889dSBrendon Cahoon if (LastDef) 2783254f889dSBrendon Cahoon replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS); 2784254f889dSBrendon Cahoon } else if (MO.isUse()) { 2785254f889dSBrendon Cahoon MachineInstr *Def = MRI.getVRegDef(reg); 2786254f889dSBrendon Cahoon // Compute the stage that contains the last definition for instruction. 2787254f889dSBrendon Cahoon int DefStageNum = Schedule.stageScheduled(getSUnit(Def)); 2788254f889dSBrendon Cahoon unsigned StageNum = CurStageNum; 2789254f889dSBrendon Cahoon if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) { 2790254f889dSBrendon Cahoon // Compute the difference in stages between the defintion and the use. 2791254f889dSBrendon Cahoon unsigned StageDiff = (InstrStageNum - DefStageNum); 2792254f889dSBrendon Cahoon // Make an adjustment to get the last definition. 2793254f889dSBrendon Cahoon StageNum -= StageDiff; 2794254f889dSBrendon Cahoon } 2795254f889dSBrendon Cahoon if (VRMap[StageNum].count(reg)) 2796254f889dSBrendon Cahoon MO.setReg(VRMap[StageNum][reg]); 2797254f889dSBrendon Cahoon } 2798254f889dSBrendon Cahoon } 2799254f889dSBrendon Cahoon } 2800254f889dSBrendon Cahoon 2801254f889dSBrendon Cahoon /// Return the instruction in the loop that defines the register. 2802254f889dSBrendon Cahoon /// If the definition is a Phi, then follow the Phi operand to 2803254f889dSBrendon Cahoon /// the instruction in the loop. 2804254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) { 2805254f889dSBrendon Cahoon SmallPtrSet<MachineInstr *, 8> Visited; 2806254f889dSBrendon Cahoon MachineInstr *Def = MRI.getVRegDef(Reg); 2807254f889dSBrendon Cahoon while (Def->isPHI()) { 2808254f889dSBrendon Cahoon if (!Visited.insert(Def).second) 2809254f889dSBrendon Cahoon break; 2810254f889dSBrendon Cahoon for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) 2811254f889dSBrendon Cahoon if (Def->getOperand(i + 1).getMBB() == BB) { 2812254f889dSBrendon Cahoon Def = MRI.getVRegDef(Def->getOperand(i).getReg()); 2813254f889dSBrendon Cahoon break; 2814254f889dSBrendon Cahoon } 2815254f889dSBrendon Cahoon } 2816254f889dSBrendon Cahoon return Def; 2817254f889dSBrendon Cahoon } 2818254f889dSBrendon Cahoon 2819254f889dSBrendon Cahoon /// Return the new name for the value from the previous stage. 2820254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage, 2821254f889dSBrendon Cahoon unsigned LoopVal, unsigned LoopStage, 2822254f889dSBrendon Cahoon ValueMapTy *VRMap, 2823254f889dSBrendon Cahoon MachineBasicBlock *BB) { 2824254f889dSBrendon Cahoon unsigned PrevVal = 0; 2825254f889dSBrendon Cahoon if (StageNum > PhiStage) { 2826254f889dSBrendon Cahoon MachineInstr *LoopInst = MRI.getVRegDef(LoopVal); 2827254f889dSBrendon Cahoon if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal)) 2828254f889dSBrendon Cahoon // The name is defined in the previous stage. 2829254f889dSBrendon Cahoon PrevVal = VRMap[StageNum - 1][LoopVal]; 2830254f889dSBrendon Cahoon else if (VRMap[StageNum].count(LoopVal)) 2831254f889dSBrendon Cahoon // The previous name is defined in the current stage when the instruction 2832254f889dSBrendon Cahoon // order is swapped. 2833254f889dSBrendon Cahoon PrevVal = VRMap[StageNum][LoopVal]; 2834df24da22SKrzysztof Parzyszek else if (!LoopInst->isPHI() || LoopInst->getParent() != BB) 2835254f889dSBrendon Cahoon // The loop value hasn't yet been scheduled. 2836254f889dSBrendon Cahoon PrevVal = LoopVal; 2837254f889dSBrendon Cahoon else if (StageNum == PhiStage + 1) 2838254f889dSBrendon Cahoon // The loop value is another phi, which has not been scheduled. 2839254f889dSBrendon Cahoon PrevVal = getInitPhiReg(*LoopInst, BB); 2840254f889dSBrendon Cahoon else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB) 2841254f889dSBrendon Cahoon // The loop value is another phi, which has been scheduled. 2842254f889dSBrendon Cahoon PrevVal = 2843254f889dSBrendon Cahoon getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB), 2844254f889dSBrendon Cahoon LoopStage, VRMap, BB); 2845254f889dSBrendon Cahoon } 2846254f889dSBrendon Cahoon return PrevVal; 2847254f889dSBrendon Cahoon } 2848254f889dSBrendon Cahoon 2849254f889dSBrendon Cahoon /// Rewrite the Phi values in the specified block to use the mappings 2850254f889dSBrendon Cahoon /// from the initial operand. Once the Phi is scheduled, we switch 2851254f889dSBrendon Cahoon /// to using the loop value instead of the Phi value, so those names 2852254f889dSBrendon Cahoon /// do not need to be rewritten. 2853254f889dSBrendon Cahoon void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB, 2854254f889dSBrendon Cahoon unsigned StageNum, 2855254f889dSBrendon Cahoon SMSchedule &Schedule, 2856254f889dSBrendon Cahoon ValueMapTy *VRMap, 2857254f889dSBrendon Cahoon InstrMapTy &InstrMap) { 285890ecac01SBob Wilson for (auto &PHI : BB->phis()) { 2859254f889dSBrendon Cahoon unsigned InitVal = 0; 2860254f889dSBrendon Cahoon unsigned LoopVal = 0; 286190ecac01SBob Wilson getPhiRegs(PHI, BB, InitVal, LoopVal); 286290ecac01SBob Wilson unsigned PhiDef = PHI.getOperand(0).getReg(); 2863254f889dSBrendon Cahoon 2864254f889dSBrendon Cahoon unsigned PhiStage = 2865254f889dSBrendon Cahoon (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef))); 2866254f889dSBrendon Cahoon unsigned LoopStage = 2867254f889dSBrendon Cahoon (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal))); 2868254f889dSBrendon Cahoon unsigned NumPhis = Schedule.getStagesForPhi(PhiDef); 2869254f889dSBrendon Cahoon if (NumPhis > StageNum) 2870254f889dSBrendon Cahoon NumPhis = StageNum; 2871254f889dSBrendon Cahoon for (unsigned np = 0; np <= NumPhis; ++np) { 2872254f889dSBrendon Cahoon unsigned NewVal = 2873254f889dSBrendon Cahoon getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB); 2874254f889dSBrendon Cahoon if (!NewVal) 2875254f889dSBrendon Cahoon NewVal = InitVal; 287690ecac01SBob Wilson rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI, 2877254f889dSBrendon Cahoon PhiDef, NewVal); 2878254f889dSBrendon Cahoon } 2879254f889dSBrendon Cahoon } 2880254f889dSBrendon Cahoon } 2881254f889dSBrendon Cahoon 2882254f889dSBrendon Cahoon /// Rewrite a previously scheduled instruction to use the register value 2883254f889dSBrendon Cahoon /// from the new instruction. Make sure the instruction occurs in the 2884254f889dSBrendon Cahoon /// basic block, and we don't change the uses in the new instruction. 2885254f889dSBrendon Cahoon void SwingSchedulerDAG::rewriteScheduledInstr( 2886254f889dSBrendon Cahoon MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap, 2887254f889dSBrendon Cahoon unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, 2888254f889dSBrendon Cahoon unsigned NewReg, unsigned PrevReg) { 2889254f889dSBrendon Cahoon bool InProlog = (CurStageNum < Schedule.getMaxStageCount()); 2890254f889dSBrendon Cahoon int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum; 2891254f889dSBrendon Cahoon // Rewrite uses that have been scheduled already to use the new 2892254f889dSBrendon Cahoon // Phi register. 2893254f889dSBrendon Cahoon for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg), 2894254f889dSBrendon Cahoon EI = MRI.use_end(); 2895254f889dSBrendon Cahoon UI != EI;) { 2896254f889dSBrendon Cahoon MachineOperand &UseOp = *UI; 2897254f889dSBrendon Cahoon MachineInstr *UseMI = UseOp.getParent(); 2898254f889dSBrendon Cahoon ++UI; 2899254f889dSBrendon Cahoon if (UseMI->getParent() != BB) 2900254f889dSBrendon Cahoon continue; 2901254f889dSBrendon Cahoon if (UseMI->isPHI()) { 2902254f889dSBrendon Cahoon if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg) 2903254f889dSBrendon Cahoon continue; 2904254f889dSBrendon Cahoon if (getLoopPhiReg(*UseMI, BB) != OldReg) 2905254f889dSBrendon Cahoon continue; 2906254f889dSBrendon Cahoon } 2907254f889dSBrendon Cahoon InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI); 2908254f889dSBrendon Cahoon assert(OrigInstr != InstrMap.end() && "Instruction not scheduled."); 2909254f889dSBrendon Cahoon SUnit *OrigMISU = getSUnit(OrigInstr->second); 2910254f889dSBrendon Cahoon int StageSched = Schedule.stageScheduled(OrigMISU); 2911254f889dSBrendon Cahoon int CycleSched = Schedule.cycleScheduled(OrigMISU); 2912254f889dSBrendon Cahoon unsigned ReplaceReg = 0; 2913254f889dSBrendon Cahoon // This is the stage for the scheduled instruction. 2914254f889dSBrendon Cahoon if (StagePhi == StageSched && Phi->isPHI()) { 2915254f889dSBrendon Cahoon int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi)); 2916254f889dSBrendon Cahoon if (PrevReg && InProlog) 2917254f889dSBrendon Cahoon ReplaceReg = PrevReg; 2918254f889dSBrendon Cahoon else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) && 2919254f889dSBrendon Cahoon (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI())) 2920254f889dSBrendon Cahoon ReplaceReg = PrevReg; 2921254f889dSBrendon Cahoon else 2922254f889dSBrendon Cahoon ReplaceReg = NewReg; 2923254f889dSBrendon Cahoon } 2924254f889dSBrendon Cahoon // The scheduled instruction occurs before the scheduled Phi, and the 2925254f889dSBrendon Cahoon // Phi is not loop carried. 2926254f889dSBrendon Cahoon if (!InProlog && StagePhi + 1 == StageSched && 2927254f889dSBrendon Cahoon !Schedule.isLoopCarried(this, *Phi)) 2928254f889dSBrendon Cahoon ReplaceReg = NewReg; 2929254f889dSBrendon Cahoon if (StagePhi > StageSched && Phi->isPHI()) 2930254f889dSBrendon Cahoon ReplaceReg = NewReg; 2931254f889dSBrendon Cahoon if (!InProlog && !Phi->isPHI() && StagePhi < StageSched) 2932254f889dSBrendon Cahoon ReplaceReg = NewReg; 2933254f889dSBrendon Cahoon if (ReplaceReg) { 2934254f889dSBrendon Cahoon MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg)); 2935254f889dSBrendon Cahoon UseOp.setReg(ReplaceReg); 2936254f889dSBrendon Cahoon } 2937254f889dSBrendon Cahoon } 2938254f889dSBrendon Cahoon } 2939254f889dSBrendon Cahoon 2940254f889dSBrendon Cahoon /// Check if we can change the instruction to use an offset value from the 2941254f889dSBrendon Cahoon /// previous iteration. If so, return true and set the base and offset values 2942254f889dSBrendon Cahoon /// so that we can rewrite the load, if necessary. 2943254f889dSBrendon Cahoon /// v1 = Phi(v0, v3) 2944254f889dSBrendon Cahoon /// v2 = load v1, 0 2945254f889dSBrendon Cahoon /// v3 = post_store v1, 4, x 2946254f889dSBrendon Cahoon /// This function enables the load to be rewritten as v2 = load v3, 4. 2947254f889dSBrendon Cahoon bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI, 2948254f889dSBrendon Cahoon unsigned &BasePos, 2949254f889dSBrendon Cahoon unsigned &OffsetPos, 2950254f889dSBrendon Cahoon unsigned &NewBase, 2951254f889dSBrendon Cahoon int64_t &Offset) { 2952254f889dSBrendon Cahoon // Get the load instruction. 29538fb181caSKrzysztof Parzyszek if (TII->isPostIncrement(*MI)) 2954254f889dSBrendon Cahoon return false; 2955254f889dSBrendon Cahoon unsigned BasePosLd, OffsetPosLd; 29568fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd)) 2957254f889dSBrendon Cahoon return false; 2958254f889dSBrendon Cahoon unsigned BaseReg = MI->getOperand(BasePosLd).getReg(); 2959254f889dSBrendon Cahoon 2960254f889dSBrendon Cahoon // Look for the Phi instruction. 2961fdf9bf4fSJustin Bogner MachineRegisterInfo &MRI = MI->getMF()->getRegInfo(); 2962254f889dSBrendon Cahoon MachineInstr *Phi = MRI.getVRegDef(BaseReg); 2963254f889dSBrendon Cahoon if (!Phi || !Phi->isPHI()) 2964254f889dSBrendon Cahoon return false; 2965254f889dSBrendon Cahoon // Get the register defined in the loop block. 2966254f889dSBrendon Cahoon unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent()); 2967254f889dSBrendon Cahoon if (!PrevReg) 2968254f889dSBrendon Cahoon return false; 2969254f889dSBrendon Cahoon 2970254f889dSBrendon Cahoon // Check for the post-increment load/store instruction. 2971254f889dSBrendon Cahoon MachineInstr *PrevDef = MRI.getVRegDef(PrevReg); 2972254f889dSBrendon Cahoon if (!PrevDef || PrevDef == MI) 2973254f889dSBrendon Cahoon return false; 2974254f889dSBrendon Cahoon 29758fb181caSKrzysztof Parzyszek if (!TII->isPostIncrement(*PrevDef)) 2976254f889dSBrendon Cahoon return false; 2977254f889dSBrendon Cahoon 2978254f889dSBrendon Cahoon unsigned BasePos1 = 0, OffsetPos1 = 0; 29798fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1)) 2980254f889dSBrendon Cahoon return false; 2981254f889dSBrendon Cahoon 298240df8a2bSKrzysztof Parzyszek // Make sure that the instructions do not access the same memory location in 298340df8a2bSKrzysztof Parzyszek // the next iteration. 2984254f889dSBrendon Cahoon int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm(); 2985254f889dSBrendon Cahoon int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm(); 298640df8a2bSKrzysztof Parzyszek MachineInstr *NewMI = MF.CloneMachineInstr(MI); 298740df8a2bSKrzysztof Parzyszek NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset); 298840df8a2bSKrzysztof Parzyszek bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef); 298940df8a2bSKrzysztof Parzyszek MF.DeleteMachineInstr(NewMI); 299040df8a2bSKrzysztof Parzyszek if (!Disjoint) 2991254f889dSBrendon Cahoon return false; 2992254f889dSBrendon Cahoon 2993254f889dSBrendon Cahoon // Set the return value once we determine that we return true. 2994254f889dSBrendon Cahoon BasePos = BasePosLd; 2995254f889dSBrendon Cahoon OffsetPos = OffsetPosLd; 2996254f889dSBrendon Cahoon NewBase = PrevReg; 2997254f889dSBrendon Cahoon Offset = StoreOffset; 2998254f889dSBrendon Cahoon return true; 2999254f889dSBrendon Cahoon } 3000254f889dSBrendon Cahoon 3001254f889dSBrendon Cahoon /// Apply changes to the instruction if needed. The changes are need 3002254f889dSBrendon Cahoon /// to improve the scheduling and depend up on the final schedule. 30038f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI, 30048f174ddeSKrzysztof Parzyszek SMSchedule &Schedule) { 3005254f889dSBrendon Cahoon SUnit *SU = getSUnit(MI); 3006254f889dSBrendon Cahoon DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = 3007254f889dSBrendon Cahoon InstrChanges.find(SU); 3008254f889dSBrendon Cahoon if (It != InstrChanges.end()) { 3009254f889dSBrendon Cahoon std::pair<unsigned, int64_t> RegAndOffset = It->second; 3010254f889dSBrendon Cahoon unsigned BasePos, OffsetPos; 30118fb181caSKrzysztof Parzyszek if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) 30128f174ddeSKrzysztof Parzyszek return; 3013254f889dSBrendon Cahoon unsigned BaseReg = MI->getOperand(BasePos).getReg(); 3014254f889dSBrendon Cahoon MachineInstr *LoopDef = findDefInLoop(BaseReg); 3015254f889dSBrendon Cahoon int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef)); 3016254f889dSBrendon Cahoon int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef)); 3017254f889dSBrendon Cahoon int BaseStageNum = Schedule.stageScheduled(SU); 3018254f889dSBrendon Cahoon int BaseCycleNum = Schedule.cycleScheduled(SU); 3019254f889dSBrendon Cahoon if (BaseStageNum < DefStageNum) { 3020254f889dSBrendon Cahoon MachineInstr *NewMI = MF.CloneMachineInstr(MI); 3021254f889dSBrendon Cahoon int OffsetDiff = DefStageNum - BaseStageNum; 3022254f889dSBrendon Cahoon if (DefCycleNum < BaseCycleNum) { 3023254f889dSBrendon Cahoon NewMI->getOperand(BasePos).setReg(RegAndOffset.first); 3024254f889dSBrendon Cahoon if (OffsetDiff > 0) 3025254f889dSBrendon Cahoon --OffsetDiff; 3026254f889dSBrendon Cahoon } 3027254f889dSBrendon Cahoon int64_t NewOffset = 3028254f889dSBrendon Cahoon MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff; 3029254f889dSBrendon Cahoon NewMI->getOperand(OffsetPos).setImm(NewOffset); 3030254f889dSBrendon Cahoon SU->setInstr(NewMI); 3031254f889dSBrendon Cahoon MISUnitMap[NewMI] = SU; 3032254f889dSBrendon Cahoon NewMIs.insert(NewMI); 3033254f889dSBrendon Cahoon } 3034254f889dSBrendon Cahoon } 3035254f889dSBrendon Cahoon } 3036254f889dSBrendon Cahoon 30378e1363dfSKrzysztof Parzyszek /// Return true for an order or output dependence that is loop carried 30388e1363dfSKrzysztof Parzyszek /// potentially. A dependence is loop carried if the destination defines a valu 30398e1363dfSKrzysztof Parzyszek /// that may be used or defined by the source in a subsequent iteration. 30408e1363dfSKrzysztof Parzyszek bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep, 3041254f889dSBrendon Cahoon bool isSucc) { 30428e1363dfSKrzysztof Parzyszek if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) || 30438e1363dfSKrzysztof Parzyszek Dep.isArtificial()) 3044254f889dSBrendon Cahoon return false; 3045254f889dSBrendon Cahoon 3046254f889dSBrendon Cahoon if (!SwpPruneLoopCarried) 3047254f889dSBrendon Cahoon return true; 3048254f889dSBrendon Cahoon 30498e1363dfSKrzysztof Parzyszek if (Dep.getKind() == SDep::Output) 30508e1363dfSKrzysztof Parzyszek return true; 30518e1363dfSKrzysztof Parzyszek 3052254f889dSBrendon Cahoon MachineInstr *SI = Source->getInstr(); 3053254f889dSBrendon Cahoon MachineInstr *DI = Dep.getSUnit()->getInstr(); 3054254f889dSBrendon Cahoon if (!isSucc) 3055254f889dSBrendon Cahoon std::swap(SI, DI); 3056254f889dSBrendon Cahoon assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI."); 3057254f889dSBrendon Cahoon 3058254f889dSBrendon Cahoon // Assume ordered loads and stores may have a loop carried dependence. 3059254f889dSBrendon Cahoon if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() || 3060254f889dSBrendon Cahoon SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef()) 3061254f889dSBrendon Cahoon return true; 3062254f889dSBrendon Cahoon 3063254f889dSBrendon Cahoon // Only chain dependences between a load and store can be loop carried. 3064254f889dSBrendon Cahoon if (!DI->mayStore() || !SI->mayLoad()) 3065254f889dSBrendon Cahoon return false; 3066254f889dSBrendon Cahoon 3067254f889dSBrendon Cahoon unsigned DeltaS, DeltaD; 3068254f889dSBrendon Cahoon if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD)) 3069254f889dSBrendon Cahoon return true; 3070254f889dSBrendon Cahoon 3071d7eebd6dSFrancis Visoiu Mistrih MachineOperand *BaseOpS, *BaseOpD; 3072254f889dSBrendon Cahoon int64_t OffsetS, OffsetD; 3073254f889dSBrendon Cahoon const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 3074d7eebd6dSFrancis Visoiu Mistrih if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) || 3075d7eebd6dSFrancis Visoiu Mistrih !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI)) 3076254f889dSBrendon Cahoon return true; 3077254f889dSBrendon Cahoon 3078d7eebd6dSFrancis Visoiu Mistrih if (!BaseOpS->isIdenticalTo(*BaseOpD)) 3079254f889dSBrendon Cahoon return true; 3080254f889dSBrendon Cahoon 30818c07d0c4SKrzysztof Parzyszek // Check that the base register is incremented by a constant value for each 30828c07d0c4SKrzysztof Parzyszek // iteration. 3083d7eebd6dSFrancis Visoiu Mistrih MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg()); 30848c07d0c4SKrzysztof Parzyszek if (!Def || !Def->isPHI()) 30858c07d0c4SKrzysztof Parzyszek return true; 30868c07d0c4SKrzysztof Parzyszek unsigned InitVal = 0; 30878c07d0c4SKrzysztof Parzyszek unsigned LoopVal = 0; 30888c07d0c4SKrzysztof Parzyszek getPhiRegs(*Def, BB, InitVal, LoopVal); 30898c07d0c4SKrzysztof Parzyszek MachineInstr *LoopDef = MRI.getVRegDef(LoopVal); 30908c07d0c4SKrzysztof Parzyszek int D = 0; 30918c07d0c4SKrzysztof Parzyszek if (!LoopDef || !TII->getIncrementValue(*LoopDef, D)) 30928c07d0c4SKrzysztof Parzyszek return true; 30938c07d0c4SKrzysztof Parzyszek 3094254f889dSBrendon Cahoon uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize(); 3095254f889dSBrendon Cahoon uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize(); 3096254f889dSBrendon Cahoon 3097254f889dSBrendon Cahoon // This is the main test, which checks the offset values and the loop 3098254f889dSBrendon Cahoon // increment value to determine if the accesses may be loop carried. 3099254f889dSBrendon Cahoon if (OffsetS >= OffsetD) 3100254f889dSBrendon Cahoon return OffsetS + AccessSizeS > DeltaS; 3101fbfb19b1SSimon Pilgrim else 3102254f889dSBrendon Cahoon return OffsetD + AccessSizeD > DeltaD; 3103254f889dSBrendon Cahoon 3104254f889dSBrendon Cahoon return true; 3105254f889dSBrendon Cahoon } 3106254f889dSBrendon Cahoon 310788391248SKrzysztof Parzyszek void SwingSchedulerDAG::postprocessDAG() { 310888391248SKrzysztof Parzyszek for (auto &M : Mutations) 310988391248SKrzysztof Parzyszek M->apply(this); 311088391248SKrzysztof Parzyszek } 311188391248SKrzysztof Parzyszek 3112254f889dSBrendon Cahoon /// Try to schedule the node at the specified StartCycle and continue 3113254f889dSBrendon Cahoon /// until the node is schedule or the EndCycle is reached. This function 3114254f889dSBrendon Cahoon /// returns true if the node is scheduled. This routine may search either 3115254f889dSBrendon Cahoon /// forward or backward for a place to insert the instruction based upon 3116254f889dSBrendon Cahoon /// the relative values of StartCycle and EndCycle. 3117254f889dSBrendon Cahoon bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) { 3118254f889dSBrendon Cahoon bool forward = true; 3119254f889dSBrendon Cahoon if (StartCycle > EndCycle) 3120254f889dSBrendon Cahoon forward = false; 3121254f889dSBrendon Cahoon 3122254f889dSBrendon Cahoon // The terminating condition depends on the direction. 3123254f889dSBrendon Cahoon int termCycle = forward ? EndCycle + 1 : EndCycle - 1; 3124254f889dSBrendon Cahoon for (int curCycle = StartCycle; curCycle != termCycle; 3125254f889dSBrendon Cahoon forward ? ++curCycle : --curCycle) { 3126254f889dSBrendon Cahoon 3127254f889dSBrendon Cahoon // Add the already scheduled instructions at the specified cycle to the DFA. 3128254f889dSBrendon Cahoon Resources->clearResources(); 3129254f889dSBrendon Cahoon for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II); 3130254f889dSBrendon Cahoon checkCycle <= LastCycle; checkCycle += II) { 3131254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle]; 3132254f889dSBrendon Cahoon 3133254f889dSBrendon Cahoon for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(), 3134254f889dSBrendon Cahoon E = cycleInstrs.end(); 3135254f889dSBrendon Cahoon I != E; ++I) { 3136254f889dSBrendon Cahoon if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode())) 3137254f889dSBrendon Cahoon continue; 3138254f889dSBrendon Cahoon assert(Resources->canReserveResources(*(*I)->getInstr()) && 3139254f889dSBrendon Cahoon "These instructions have already been scheduled."); 3140254f889dSBrendon Cahoon Resources->reserveResources(*(*I)->getInstr()); 3141254f889dSBrendon Cahoon } 3142254f889dSBrendon Cahoon } 3143254f889dSBrendon Cahoon if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) || 3144254f889dSBrendon Cahoon Resources->canReserveResources(*SU->getInstr())) { 3145d34e60caSNicola Zaghen LLVM_DEBUG({ 3146254f889dSBrendon Cahoon dbgs() << "\tinsert at cycle " << curCycle << " "; 3147254f889dSBrendon Cahoon SU->getInstr()->dump(); 3148254f889dSBrendon Cahoon }); 3149254f889dSBrendon Cahoon 3150254f889dSBrendon Cahoon ScheduledInstrs[curCycle].push_back(SU); 3151254f889dSBrendon Cahoon InstrToCycle.insert(std::make_pair(SU, curCycle)); 3152254f889dSBrendon Cahoon if (curCycle > LastCycle) 3153254f889dSBrendon Cahoon LastCycle = curCycle; 3154254f889dSBrendon Cahoon if (curCycle < FirstCycle) 3155254f889dSBrendon Cahoon FirstCycle = curCycle; 3156254f889dSBrendon Cahoon return true; 3157254f889dSBrendon Cahoon } 3158d34e60caSNicola Zaghen LLVM_DEBUG({ 3159254f889dSBrendon Cahoon dbgs() << "\tfailed to insert at cycle " << curCycle << " "; 3160254f889dSBrendon Cahoon SU->getInstr()->dump(); 3161254f889dSBrendon Cahoon }); 3162254f889dSBrendon Cahoon } 3163254f889dSBrendon Cahoon return false; 3164254f889dSBrendon Cahoon } 3165254f889dSBrendon Cahoon 3166254f889dSBrendon Cahoon // Return the cycle of the earliest scheduled instruction in the chain. 3167254f889dSBrendon Cahoon int SMSchedule::earliestCycleInChain(const SDep &Dep) { 3168254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 3169254f889dSBrendon Cahoon SmallVector<SDep, 8> Worklist; 3170254f889dSBrendon Cahoon Worklist.push_back(Dep); 3171254f889dSBrendon Cahoon int EarlyCycle = INT_MAX; 3172254f889dSBrendon Cahoon while (!Worklist.empty()) { 3173254f889dSBrendon Cahoon const SDep &Cur = Worklist.pop_back_val(); 3174254f889dSBrendon Cahoon SUnit *PrevSU = Cur.getSUnit(); 3175254f889dSBrendon Cahoon if (Visited.count(PrevSU)) 3176254f889dSBrendon Cahoon continue; 3177254f889dSBrendon Cahoon std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU); 3178254f889dSBrendon Cahoon if (it == InstrToCycle.end()) 3179254f889dSBrendon Cahoon continue; 3180254f889dSBrendon Cahoon EarlyCycle = std::min(EarlyCycle, it->second); 3181254f889dSBrendon Cahoon for (const auto &PI : PrevSU->Preds) 31828e1363dfSKrzysztof Parzyszek if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output) 3183254f889dSBrendon Cahoon Worklist.push_back(PI); 3184254f889dSBrendon Cahoon Visited.insert(PrevSU); 3185254f889dSBrendon Cahoon } 3186254f889dSBrendon Cahoon return EarlyCycle; 3187254f889dSBrendon Cahoon } 3188254f889dSBrendon Cahoon 3189254f889dSBrendon Cahoon // Return the cycle of the latest scheduled instruction in the chain. 3190254f889dSBrendon Cahoon int SMSchedule::latestCycleInChain(const SDep &Dep) { 3191254f889dSBrendon Cahoon SmallPtrSet<SUnit *, 8> Visited; 3192254f889dSBrendon Cahoon SmallVector<SDep, 8> Worklist; 3193254f889dSBrendon Cahoon Worklist.push_back(Dep); 3194254f889dSBrendon Cahoon int LateCycle = INT_MIN; 3195254f889dSBrendon Cahoon while (!Worklist.empty()) { 3196254f889dSBrendon Cahoon const SDep &Cur = Worklist.pop_back_val(); 3197254f889dSBrendon Cahoon SUnit *SuccSU = Cur.getSUnit(); 3198254f889dSBrendon Cahoon if (Visited.count(SuccSU)) 3199254f889dSBrendon Cahoon continue; 3200254f889dSBrendon Cahoon std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU); 3201254f889dSBrendon Cahoon if (it == InstrToCycle.end()) 3202254f889dSBrendon Cahoon continue; 3203254f889dSBrendon Cahoon LateCycle = std::max(LateCycle, it->second); 3204254f889dSBrendon Cahoon for (const auto &SI : SuccSU->Succs) 32058e1363dfSKrzysztof Parzyszek if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output) 3206254f889dSBrendon Cahoon Worklist.push_back(SI); 3207254f889dSBrendon Cahoon Visited.insert(SuccSU); 3208254f889dSBrendon Cahoon } 3209254f889dSBrendon Cahoon return LateCycle; 3210254f889dSBrendon Cahoon } 3211254f889dSBrendon Cahoon 3212254f889dSBrendon Cahoon /// If an instruction has a use that spans multiple iterations, then 3213254f889dSBrendon Cahoon /// return true. These instructions are characterized by having a back-ege 3214254f889dSBrendon Cahoon /// to a Phi, which contains a reference to another Phi. 3215254f889dSBrendon Cahoon static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) { 3216254f889dSBrendon Cahoon for (auto &P : SU->Preds) 3217254f889dSBrendon Cahoon if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI()) 3218254f889dSBrendon Cahoon for (auto &S : P.getSUnit()->Succs) 3219b9b75b8cSKrzysztof Parzyszek if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI()) 3220254f889dSBrendon Cahoon return P.getSUnit(); 3221254f889dSBrendon Cahoon return nullptr; 3222254f889dSBrendon Cahoon } 3223254f889dSBrendon Cahoon 3224254f889dSBrendon Cahoon /// Compute the scheduling start slot for the instruction. The start slot 3225254f889dSBrendon Cahoon /// depends on any predecessor or successor nodes scheduled already. 3226254f889dSBrendon Cahoon void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, 3227254f889dSBrendon Cahoon int *MinEnd, int *MaxStart, int II, 3228254f889dSBrendon Cahoon SwingSchedulerDAG *DAG) { 3229254f889dSBrendon Cahoon // Iterate over each instruction that has been scheduled already. The start 3230c73b6d6bSHiroshi Inoue // slot computation depends on whether the previously scheduled instruction 3231254f889dSBrendon Cahoon // is a predecessor or successor of the specified instruction. 3232254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) { 3233254f889dSBrendon Cahoon 3234254f889dSBrendon Cahoon // Iterate over each instruction in the current cycle. 3235254f889dSBrendon Cahoon for (SUnit *I : getInstructions(cycle)) { 3236254f889dSBrendon Cahoon // Because we're processing a DAG for the dependences, we recognize 3237254f889dSBrendon Cahoon // the back-edge in recurrences by anti dependences. 3238254f889dSBrendon Cahoon for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) { 3239254f889dSBrendon Cahoon const SDep &Dep = SU->Preds[i]; 3240254f889dSBrendon Cahoon if (Dep.getSUnit() == I) { 3241254f889dSBrendon Cahoon if (!DAG->isBackedge(SU, Dep)) { 3242c715a5d2SKrzysztof Parzyszek int EarlyStart = cycle + Dep.getLatency() - 3243254f889dSBrendon Cahoon DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; 3244254f889dSBrendon Cahoon *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); 32458e1363dfSKrzysztof Parzyszek if (DAG->isLoopCarriedDep(SU, Dep, false)) { 3246254f889dSBrendon Cahoon int End = earliestCycleInChain(Dep) + (II - 1); 3247254f889dSBrendon Cahoon *MinEnd = std::min(*MinEnd, End); 3248254f889dSBrendon Cahoon } 3249254f889dSBrendon Cahoon } else { 3250c715a5d2SKrzysztof Parzyszek int LateStart = cycle - Dep.getLatency() + 3251254f889dSBrendon Cahoon DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; 3252254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, LateStart); 3253254f889dSBrendon Cahoon } 3254254f889dSBrendon Cahoon } 3255254f889dSBrendon Cahoon // For instruction that requires multiple iterations, make sure that 3256254f889dSBrendon Cahoon // the dependent instruction is not scheduled past the definition. 3257254f889dSBrendon Cahoon SUnit *BE = multipleIterations(I, DAG); 3258254f889dSBrendon Cahoon if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() && 3259254f889dSBrendon Cahoon !SU->isPred(I)) 3260254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, cycle); 3261254f889dSBrendon Cahoon } 3262a2122044SKrzysztof Parzyszek for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) { 3263254f889dSBrendon Cahoon if (SU->Succs[i].getSUnit() == I) { 3264254f889dSBrendon Cahoon const SDep &Dep = SU->Succs[i]; 3265254f889dSBrendon Cahoon if (!DAG->isBackedge(SU, Dep)) { 3266c715a5d2SKrzysztof Parzyszek int LateStart = cycle - Dep.getLatency() + 3267254f889dSBrendon Cahoon DAG->getDistance(SU, Dep.getSUnit(), Dep) * II; 3268254f889dSBrendon Cahoon *MinLateStart = std::min(*MinLateStart, LateStart); 32698e1363dfSKrzysztof Parzyszek if (DAG->isLoopCarriedDep(SU, Dep)) { 3270254f889dSBrendon Cahoon int Start = latestCycleInChain(Dep) + 1 - II; 3271254f889dSBrendon Cahoon *MaxStart = std::max(*MaxStart, Start); 3272254f889dSBrendon Cahoon } 3273254f889dSBrendon Cahoon } else { 3274c715a5d2SKrzysztof Parzyszek int EarlyStart = cycle + Dep.getLatency() - 3275254f889dSBrendon Cahoon DAG->getDistance(Dep.getSUnit(), SU, Dep) * II; 3276254f889dSBrendon Cahoon *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart); 3277254f889dSBrendon Cahoon } 3278254f889dSBrendon Cahoon } 3279254f889dSBrendon Cahoon } 3280254f889dSBrendon Cahoon } 3281254f889dSBrendon Cahoon } 3282a2122044SKrzysztof Parzyszek } 3283254f889dSBrendon Cahoon 3284254f889dSBrendon Cahoon /// Order the instructions within a cycle so that the definitions occur 3285254f889dSBrendon Cahoon /// before the uses. Returns true if the instruction is added to the start 3286254f889dSBrendon Cahoon /// of the list, or false if added to the end. 3287f13bbf1dSKrzysztof Parzyszek void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU, 3288254f889dSBrendon Cahoon std::deque<SUnit *> &Insts) { 3289254f889dSBrendon Cahoon MachineInstr *MI = SU->getInstr(); 3290254f889dSBrendon Cahoon bool OrderBeforeUse = false; 3291254f889dSBrendon Cahoon bool OrderAfterDef = false; 3292254f889dSBrendon Cahoon bool OrderBeforeDef = false; 3293254f889dSBrendon Cahoon unsigned MoveDef = 0; 3294254f889dSBrendon Cahoon unsigned MoveUse = 0; 3295254f889dSBrendon Cahoon int StageInst1 = stageScheduled(SU); 3296254f889dSBrendon Cahoon 3297254f889dSBrendon Cahoon unsigned Pos = 0; 3298254f889dSBrendon Cahoon for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E; 3299254f889dSBrendon Cahoon ++I, ++Pos) { 3300254f889dSBrendon Cahoon for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { 3301254f889dSBrendon Cahoon MachineOperand &MO = MI->getOperand(i); 3302254f889dSBrendon Cahoon if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg())) 3303254f889dSBrendon Cahoon continue; 3304f13bbf1dSKrzysztof Parzyszek 3305254f889dSBrendon Cahoon unsigned Reg = MO.getReg(); 3306254f889dSBrendon Cahoon unsigned BasePos, OffsetPos; 33078fb181caSKrzysztof Parzyszek if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) 3308254f889dSBrendon Cahoon if (MI->getOperand(BasePos).getReg() == Reg) 3309254f889dSBrendon Cahoon if (unsigned NewReg = SSD->getInstrBaseReg(SU)) 3310254f889dSBrendon Cahoon Reg = NewReg; 3311254f889dSBrendon Cahoon bool Reads, Writes; 3312254f889dSBrendon Cahoon std::tie(Reads, Writes) = 3313254f889dSBrendon Cahoon (*I)->getInstr()->readsWritesVirtualRegister(Reg); 3314254f889dSBrendon Cahoon if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) { 3315254f889dSBrendon Cahoon OrderBeforeUse = true; 3316f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 3317254f889dSBrendon Cahoon MoveUse = Pos; 3318254f889dSBrendon Cahoon } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) { 3319254f889dSBrendon Cahoon // Add the instruction after the scheduled instruction. 3320254f889dSBrendon Cahoon OrderAfterDef = true; 3321254f889dSBrendon Cahoon MoveDef = Pos; 3322254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) { 3323254f889dSBrendon Cahoon if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) { 3324254f889dSBrendon Cahoon OrderBeforeUse = true; 3325f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 3326254f889dSBrendon Cahoon MoveUse = Pos; 3327254f889dSBrendon Cahoon } else { 3328254f889dSBrendon Cahoon OrderAfterDef = true; 3329254f889dSBrendon Cahoon MoveDef = Pos; 3330254f889dSBrendon Cahoon } 3331254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) { 3332254f889dSBrendon Cahoon OrderBeforeUse = true; 3333f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 3334254f889dSBrendon Cahoon MoveUse = Pos; 3335254f889dSBrendon Cahoon if (MoveUse != 0) { 3336254f889dSBrendon Cahoon OrderAfterDef = true; 3337254f889dSBrendon Cahoon MoveDef = Pos - 1; 3338254f889dSBrendon Cahoon } 3339254f889dSBrendon Cahoon } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) { 3340254f889dSBrendon Cahoon // Add the instruction before the scheduled instruction. 3341254f889dSBrendon Cahoon OrderBeforeUse = true; 3342f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) 3343254f889dSBrendon Cahoon MoveUse = Pos; 3344254f889dSBrendon Cahoon } else if (MO.isUse() && stageScheduled(*I) == StageInst1 && 3345254f889dSBrendon Cahoon isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) { 3346f13bbf1dSKrzysztof Parzyszek if (MoveUse == 0) { 3347254f889dSBrendon Cahoon OrderBeforeDef = true; 3348254f889dSBrendon Cahoon MoveUse = Pos; 3349254f889dSBrendon Cahoon } 3350254f889dSBrendon Cahoon } 3351f13bbf1dSKrzysztof Parzyszek } 3352254f889dSBrendon Cahoon // Check for order dependences between instructions. Make sure the source 3353254f889dSBrendon Cahoon // is ordered before the destination. 33548e1363dfSKrzysztof Parzyszek for (auto &S : SU->Succs) { 33558e1363dfSKrzysztof Parzyszek if (S.getSUnit() != *I) 33568e1363dfSKrzysztof Parzyszek continue; 33578e1363dfSKrzysztof Parzyszek if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) { 3358254f889dSBrendon Cahoon OrderBeforeUse = true; 33598e1363dfSKrzysztof Parzyszek if (Pos < MoveUse) 3360254f889dSBrendon Cahoon MoveUse = Pos; 3361254f889dSBrendon Cahoon } 3362254f889dSBrendon Cahoon } 33638e1363dfSKrzysztof Parzyszek for (auto &P : SU->Preds) { 33648e1363dfSKrzysztof Parzyszek if (P.getSUnit() != *I) 33658e1363dfSKrzysztof Parzyszek continue; 33668e1363dfSKrzysztof Parzyszek if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) { 3367254f889dSBrendon Cahoon OrderAfterDef = true; 3368254f889dSBrendon Cahoon MoveDef = Pos; 3369254f889dSBrendon Cahoon } 3370254f889dSBrendon Cahoon } 3371254f889dSBrendon Cahoon } 3372254f889dSBrendon Cahoon 3373254f889dSBrendon Cahoon // A circular dependence. 3374254f889dSBrendon Cahoon if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef) 3375254f889dSBrendon Cahoon OrderBeforeUse = false; 3376254f889dSBrendon Cahoon 3377254f889dSBrendon Cahoon // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due 3378254f889dSBrendon Cahoon // to a loop-carried dependence. 3379254f889dSBrendon Cahoon if (OrderBeforeDef) 3380254f889dSBrendon Cahoon OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef); 3381254f889dSBrendon Cahoon 3382254f889dSBrendon Cahoon // The uncommon case when the instruction order needs to be updated because 3383254f889dSBrendon Cahoon // there is both a use and def. 3384254f889dSBrendon Cahoon if (OrderBeforeUse && OrderAfterDef) { 3385254f889dSBrendon Cahoon SUnit *UseSU = Insts.at(MoveUse); 3386254f889dSBrendon Cahoon SUnit *DefSU = Insts.at(MoveDef); 3387254f889dSBrendon Cahoon if (MoveUse > MoveDef) { 3388254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveUse); 3389254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveDef); 3390254f889dSBrendon Cahoon } else { 3391254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveDef); 3392254f889dSBrendon Cahoon Insts.erase(Insts.begin() + MoveUse); 3393254f889dSBrendon Cahoon } 3394f13bbf1dSKrzysztof Parzyszek orderDependence(SSD, UseSU, Insts); 3395f13bbf1dSKrzysztof Parzyszek orderDependence(SSD, SU, Insts); 3396254f889dSBrendon Cahoon orderDependence(SSD, DefSU, Insts); 3397f13bbf1dSKrzysztof Parzyszek return; 3398254f889dSBrendon Cahoon } 3399254f889dSBrendon Cahoon // Put the new instruction first if there is a use in the list. Otherwise, 3400254f889dSBrendon Cahoon // put it at the end of the list. 3401254f889dSBrendon Cahoon if (OrderBeforeUse) 3402254f889dSBrendon Cahoon Insts.push_front(SU); 3403254f889dSBrendon Cahoon else 3404254f889dSBrendon Cahoon Insts.push_back(SU); 3405254f889dSBrendon Cahoon } 3406254f889dSBrendon Cahoon 3407254f889dSBrendon Cahoon /// Return true if the scheduled Phi has a loop carried operand. 3408254f889dSBrendon Cahoon bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) { 3409254f889dSBrendon Cahoon if (!Phi.isPHI()) 3410254f889dSBrendon Cahoon return false; 3411c73b6d6bSHiroshi Inoue assert(Phi.isPHI() && "Expecting a Phi."); 3412254f889dSBrendon Cahoon SUnit *DefSU = SSD->getSUnit(&Phi); 3413254f889dSBrendon Cahoon unsigned DefCycle = cycleScheduled(DefSU); 3414254f889dSBrendon Cahoon int DefStage = stageScheduled(DefSU); 3415254f889dSBrendon Cahoon 3416254f889dSBrendon Cahoon unsigned InitVal = 0; 3417254f889dSBrendon Cahoon unsigned LoopVal = 0; 3418254f889dSBrendon Cahoon getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal); 3419254f889dSBrendon Cahoon SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal)); 3420254f889dSBrendon Cahoon if (!UseSU) 3421254f889dSBrendon Cahoon return true; 3422254f889dSBrendon Cahoon if (UseSU->getInstr()->isPHI()) 3423254f889dSBrendon Cahoon return true; 3424254f889dSBrendon Cahoon unsigned LoopCycle = cycleScheduled(UseSU); 3425254f889dSBrendon Cahoon int LoopStage = stageScheduled(UseSU); 34263d8482a8SSimon Pilgrim return (LoopCycle > DefCycle) || (LoopStage <= DefStage); 3427254f889dSBrendon Cahoon } 3428254f889dSBrendon Cahoon 3429254f889dSBrendon Cahoon /// Return true if the instruction is a definition that is loop carried 3430254f889dSBrendon Cahoon /// and defines the use on the next iteration. 3431254f889dSBrendon Cahoon /// v1 = phi(v2, v3) 3432254f889dSBrendon Cahoon /// (Def) v3 = op v1 3433254f889dSBrendon Cahoon /// (MO) = v1 3434254f889dSBrendon Cahoon /// If MO appears before Def, then then v1 and v3 may get assigned to the same 3435254f889dSBrendon Cahoon /// register. 3436254f889dSBrendon Cahoon bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD, 3437254f889dSBrendon Cahoon MachineInstr *Def, MachineOperand &MO) { 3438254f889dSBrendon Cahoon if (!MO.isReg()) 3439254f889dSBrendon Cahoon return false; 3440254f889dSBrendon Cahoon if (Def->isPHI()) 3441254f889dSBrendon Cahoon return false; 3442254f889dSBrendon Cahoon MachineInstr *Phi = MRI.getVRegDef(MO.getReg()); 3443254f889dSBrendon Cahoon if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent()) 3444254f889dSBrendon Cahoon return false; 3445254f889dSBrendon Cahoon if (!isLoopCarried(SSD, *Phi)) 3446254f889dSBrendon Cahoon return false; 3447254f889dSBrendon Cahoon unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent()); 3448254f889dSBrendon Cahoon for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) { 3449254f889dSBrendon Cahoon MachineOperand &DMO = Def->getOperand(i); 3450254f889dSBrendon Cahoon if (!DMO.isReg() || !DMO.isDef()) 3451254f889dSBrendon Cahoon continue; 3452254f889dSBrendon Cahoon if (DMO.getReg() == LoopReg) 3453254f889dSBrendon Cahoon return true; 3454254f889dSBrendon Cahoon } 3455254f889dSBrendon Cahoon return false; 3456254f889dSBrendon Cahoon } 3457254f889dSBrendon Cahoon 3458254f889dSBrendon Cahoon // Check if the generated schedule is valid. This function checks if 3459254f889dSBrendon Cahoon // an instruction that uses a physical register is scheduled in a 3460254f889dSBrendon Cahoon // different stage than the definition. The pipeliner does not handle 3461254f889dSBrendon Cahoon // physical register values that may cross a basic block boundary. 3462254f889dSBrendon Cahoon bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) { 3463254f889dSBrendon Cahoon for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) { 3464254f889dSBrendon Cahoon SUnit &SU = SSD->SUnits[i]; 3465254f889dSBrendon Cahoon if (!SU.hasPhysRegDefs) 3466254f889dSBrendon Cahoon continue; 3467254f889dSBrendon Cahoon int StageDef = stageScheduled(&SU); 3468254f889dSBrendon Cahoon assert(StageDef != -1 && "Instruction should have been scheduled."); 3469254f889dSBrendon Cahoon for (auto &SI : SU.Succs) 3470254f889dSBrendon Cahoon if (SI.isAssignedRegDep()) 3471b39236b6SSimon Pilgrim if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg())) 3472254f889dSBrendon Cahoon if (stageScheduled(SI.getSUnit()) != StageDef) 3473254f889dSBrendon Cahoon return false; 3474254f889dSBrendon Cahoon } 3475254f889dSBrendon Cahoon return true; 3476254f889dSBrendon Cahoon } 3477254f889dSBrendon Cahoon 34784b8bcf00SRoorda, Jan-Willem /// A property of the node order in swing-modulo-scheduling is 34794b8bcf00SRoorda, Jan-Willem /// that for nodes outside circuits the following holds: 34804b8bcf00SRoorda, Jan-Willem /// none of them is scheduled after both a successor and a 34814b8bcf00SRoorda, Jan-Willem /// predecessor. 34824b8bcf00SRoorda, Jan-Willem /// The method below checks whether the property is met. 34834b8bcf00SRoorda, Jan-Willem /// If not, debug information is printed and statistics information updated. 34844b8bcf00SRoorda, Jan-Willem /// Note that we do not use an assert statement. 34854b8bcf00SRoorda, Jan-Willem /// The reason is that although an invalid node oder may prevent 34864b8bcf00SRoorda, Jan-Willem /// the pipeliner from finding a pipelined schedule for arbitrary II, 34874b8bcf00SRoorda, Jan-Willem /// it does not lead to the generation of incorrect code. 34884b8bcf00SRoorda, Jan-Willem void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const { 34894b8bcf00SRoorda, Jan-Willem 34904b8bcf00SRoorda, Jan-Willem // a sorted vector that maps each SUnit to its index in the NodeOrder 34914b8bcf00SRoorda, Jan-Willem typedef std::pair<SUnit *, unsigned> UnitIndex; 34924b8bcf00SRoorda, Jan-Willem std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0)); 34934b8bcf00SRoorda, Jan-Willem 34944b8bcf00SRoorda, Jan-Willem for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) 34954b8bcf00SRoorda, Jan-Willem Indices.push_back(std::make_pair(NodeOrder[i], i)); 34964b8bcf00SRoorda, Jan-Willem 34974b8bcf00SRoorda, Jan-Willem auto CompareKey = [](UnitIndex i1, UnitIndex i2) { 34984b8bcf00SRoorda, Jan-Willem return std::get<0>(i1) < std::get<0>(i2); 34994b8bcf00SRoorda, Jan-Willem }; 35004b8bcf00SRoorda, Jan-Willem 35014b8bcf00SRoorda, Jan-Willem // sort, so that we can perform a binary search 35020cac726aSFangrui Song llvm::sort(Indices, CompareKey); 35034b8bcf00SRoorda, Jan-Willem 35044b8bcf00SRoorda, Jan-Willem bool Valid = true; 3505febf70a9SDavid L Kreitzer (void)Valid; 35064b8bcf00SRoorda, Jan-Willem // for each SUnit in the NodeOrder, check whether 35074b8bcf00SRoorda, Jan-Willem // it appears after both a successor and a predecessor 35084b8bcf00SRoorda, Jan-Willem // of the SUnit. If this is the case, and the SUnit 35094b8bcf00SRoorda, Jan-Willem // is not part of circuit, then the NodeOrder is not 35104b8bcf00SRoorda, Jan-Willem // valid. 35114b8bcf00SRoorda, Jan-Willem for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) { 35124b8bcf00SRoorda, Jan-Willem SUnit *SU = NodeOrder[i]; 35134b8bcf00SRoorda, Jan-Willem unsigned Index = i; 35144b8bcf00SRoorda, Jan-Willem 35154b8bcf00SRoorda, Jan-Willem bool PredBefore = false; 35164b8bcf00SRoorda, Jan-Willem bool SuccBefore = false; 35174b8bcf00SRoorda, Jan-Willem 35184b8bcf00SRoorda, Jan-Willem SUnit *Succ; 35194b8bcf00SRoorda, Jan-Willem SUnit *Pred; 3520febf70a9SDavid L Kreitzer (void)Succ; 3521febf70a9SDavid L Kreitzer (void)Pred; 35224b8bcf00SRoorda, Jan-Willem 35234b8bcf00SRoorda, Jan-Willem for (SDep &PredEdge : SU->Preds) { 35244b8bcf00SRoorda, Jan-Willem SUnit *PredSU = PredEdge.getSUnit(); 35254b8bcf00SRoorda, Jan-Willem unsigned PredIndex = 35264b8bcf00SRoorda, Jan-Willem std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(), 35274b8bcf00SRoorda, Jan-Willem std::make_pair(PredSU, 0), CompareKey)); 35284b8bcf00SRoorda, Jan-Willem if (!PredSU->getInstr()->isPHI() && PredIndex < Index) { 35294b8bcf00SRoorda, Jan-Willem PredBefore = true; 35304b8bcf00SRoorda, Jan-Willem Pred = PredSU; 35314b8bcf00SRoorda, Jan-Willem break; 35324b8bcf00SRoorda, Jan-Willem } 35334b8bcf00SRoorda, Jan-Willem } 35344b8bcf00SRoorda, Jan-Willem 35354b8bcf00SRoorda, Jan-Willem for (SDep &SuccEdge : SU->Succs) { 35364b8bcf00SRoorda, Jan-Willem SUnit *SuccSU = SuccEdge.getSUnit(); 35374b8bcf00SRoorda, Jan-Willem unsigned SuccIndex = 35384b8bcf00SRoorda, Jan-Willem std::get<1>(*std::lower_bound(Indices.begin(), Indices.end(), 35394b8bcf00SRoorda, Jan-Willem std::make_pair(SuccSU, 0), CompareKey)); 35404b8bcf00SRoorda, Jan-Willem if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) { 35414b8bcf00SRoorda, Jan-Willem SuccBefore = true; 35424b8bcf00SRoorda, Jan-Willem Succ = SuccSU; 35434b8bcf00SRoorda, Jan-Willem break; 35444b8bcf00SRoorda, Jan-Willem } 35454b8bcf00SRoorda, Jan-Willem } 35464b8bcf00SRoorda, Jan-Willem 35474b8bcf00SRoorda, Jan-Willem if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) { 35484b8bcf00SRoorda, Jan-Willem // instructions in circuits are allowed to be scheduled 35494b8bcf00SRoorda, Jan-Willem // after both a successor and predecessor. 35504b8bcf00SRoorda, Jan-Willem bool InCircuit = std::any_of( 35514b8bcf00SRoorda, Jan-Willem Circuits.begin(), Circuits.end(), 35524b8bcf00SRoorda, Jan-Willem [SU](const NodeSet &Circuit) { return Circuit.count(SU); }); 35534b8bcf00SRoorda, Jan-Willem if (InCircuit) 3554d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";); 35554b8bcf00SRoorda, Jan-Willem else { 35564b8bcf00SRoorda, Jan-Willem Valid = false; 35574b8bcf00SRoorda, Jan-Willem NumNodeOrderIssues++; 3558d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Predecessor ";); 35594b8bcf00SRoorda, Jan-Willem } 3560d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum 3561d34e60caSNicola Zaghen << " are scheduled before node " << SU->NodeNum 3562d34e60caSNicola Zaghen << "\n";); 35634b8bcf00SRoorda, Jan-Willem } 35644b8bcf00SRoorda, Jan-Willem } 35654b8bcf00SRoorda, Jan-Willem 3566d34e60caSNicola Zaghen LLVM_DEBUG({ 35674b8bcf00SRoorda, Jan-Willem if (!Valid) 35684b8bcf00SRoorda, Jan-Willem dbgs() << "Invalid node order found!\n"; 35694b8bcf00SRoorda, Jan-Willem }); 35704b8bcf00SRoorda, Jan-Willem } 35714b8bcf00SRoorda, Jan-Willem 35728f174ddeSKrzysztof Parzyszek /// Attempt to fix the degenerate cases when the instruction serialization 35738f174ddeSKrzysztof Parzyszek /// causes the register lifetimes to overlap. For example, 35748f174ddeSKrzysztof Parzyszek /// p' = store_pi(p, b) 35758f174ddeSKrzysztof Parzyszek /// = load p, offset 35768f174ddeSKrzysztof Parzyszek /// In this case p and p' overlap, which means that two registers are needed. 35778f174ddeSKrzysztof Parzyszek /// Instead, this function changes the load to use p' and updates the offset. 35788f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) { 35798f174ddeSKrzysztof Parzyszek unsigned OverlapReg = 0; 35808f174ddeSKrzysztof Parzyszek unsigned NewBaseReg = 0; 35818f174ddeSKrzysztof Parzyszek for (SUnit *SU : Instrs) { 35828f174ddeSKrzysztof Parzyszek MachineInstr *MI = SU->getInstr(); 35838f174ddeSKrzysztof Parzyszek for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { 35848f174ddeSKrzysztof Parzyszek const MachineOperand &MO = MI->getOperand(i); 35858f174ddeSKrzysztof Parzyszek // Look for an instruction that uses p. The instruction occurs in the 35868f174ddeSKrzysztof Parzyszek // same cycle but occurs later in the serialized order. 35878f174ddeSKrzysztof Parzyszek if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) { 35888f174ddeSKrzysztof Parzyszek // Check that the instruction appears in the InstrChanges structure, 35898f174ddeSKrzysztof Parzyszek // which contains instructions that can have the offset updated. 35908f174ddeSKrzysztof Parzyszek DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It = 35918f174ddeSKrzysztof Parzyszek InstrChanges.find(SU); 35928f174ddeSKrzysztof Parzyszek if (It != InstrChanges.end()) { 35938f174ddeSKrzysztof Parzyszek unsigned BasePos, OffsetPos; 35948f174ddeSKrzysztof Parzyszek // Update the base register and adjust the offset. 35958f174ddeSKrzysztof Parzyszek if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) { 359612bdcab5SKrzysztof Parzyszek MachineInstr *NewMI = MF.CloneMachineInstr(MI); 359712bdcab5SKrzysztof Parzyszek NewMI->getOperand(BasePos).setReg(NewBaseReg); 359812bdcab5SKrzysztof Parzyszek int64_t NewOffset = 359912bdcab5SKrzysztof Parzyszek MI->getOperand(OffsetPos).getImm() - It->second.second; 360012bdcab5SKrzysztof Parzyszek NewMI->getOperand(OffsetPos).setImm(NewOffset); 360112bdcab5SKrzysztof Parzyszek SU->setInstr(NewMI); 360212bdcab5SKrzysztof Parzyszek MISUnitMap[NewMI] = SU; 360312bdcab5SKrzysztof Parzyszek NewMIs.insert(NewMI); 36048f174ddeSKrzysztof Parzyszek } 36058f174ddeSKrzysztof Parzyszek } 36068f174ddeSKrzysztof Parzyszek OverlapReg = 0; 36078f174ddeSKrzysztof Parzyszek NewBaseReg = 0; 36088f174ddeSKrzysztof Parzyszek break; 36098f174ddeSKrzysztof Parzyszek } 36108f174ddeSKrzysztof Parzyszek // Look for an instruction of the form p' = op(p), which uses and defines 36118f174ddeSKrzysztof Parzyszek // two virtual registers that get allocated to the same physical register. 36128f174ddeSKrzysztof Parzyszek unsigned TiedUseIdx = 0; 36138f174ddeSKrzysztof Parzyszek if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) { 36148f174ddeSKrzysztof Parzyszek // OverlapReg is p in the example above. 36158f174ddeSKrzysztof Parzyszek OverlapReg = MI->getOperand(TiedUseIdx).getReg(); 36168f174ddeSKrzysztof Parzyszek // NewBaseReg is p' in the example above. 36178f174ddeSKrzysztof Parzyszek NewBaseReg = MI->getOperand(i).getReg(); 36188f174ddeSKrzysztof Parzyszek break; 36198f174ddeSKrzysztof Parzyszek } 36208f174ddeSKrzysztof Parzyszek } 36218f174ddeSKrzysztof Parzyszek } 36228f174ddeSKrzysztof Parzyszek } 36238f174ddeSKrzysztof Parzyszek 3624254f889dSBrendon Cahoon /// After the schedule has been formed, call this function to combine 3625254f889dSBrendon Cahoon /// the instructions from the different stages/cycles. That is, this 3626254f889dSBrendon Cahoon /// function creates a schedule that represents a single iteration. 3627254f889dSBrendon Cahoon void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) { 3628254f889dSBrendon Cahoon // Move all instructions to the first stage from later stages. 3629254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { 3630254f889dSBrendon Cahoon for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage; 3631254f889dSBrendon Cahoon ++stage) { 3632254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = 3633254f889dSBrendon Cahoon ScheduledInstrs[cycle + (stage * InitiationInterval)]; 3634254f889dSBrendon Cahoon for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(), 3635254f889dSBrendon Cahoon E = cycleInstrs.rend(); 3636254f889dSBrendon Cahoon I != E; ++I) 3637254f889dSBrendon Cahoon ScheduledInstrs[cycle].push_front(*I); 3638254f889dSBrendon Cahoon } 3639254f889dSBrendon Cahoon } 3640254f889dSBrendon Cahoon // Iterate over the definitions in each instruction, and compute the 3641254f889dSBrendon Cahoon // stage difference for each use. Keep the maximum value. 3642254f889dSBrendon Cahoon for (auto &I : InstrToCycle) { 3643254f889dSBrendon Cahoon int DefStage = stageScheduled(I.first); 3644254f889dSBrendon Cahoon MachineInstr *MI = I.first->getInstr(); 3645254f889dSBrendon Cahoon for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) { 3646254f889dSBrendon Cahoon MachineOperand &Op = MI->getOperand(i); 3647254f889dSBrendon Cahoon if (!Op.isReg() || !Op.isDef()) 3648254f889dSBrendon Cahoon continue; 3649254f889dSBrendon Cahoon 3650254f889dSBrendon Cahoon unsigned Reg = Op.getReg(); 3651254f889dSBrendon Cahoon unsigned MaxDiff = 0; 3652254f889dSBrendon Cahoon bool PhiIsSwapped = false; 3653254f889dSBrendon Cahoon for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg), 3654254f889dSBrendon Cahoon EI = MRI.use_end(); 3655254f889dSBrendon Cahoon UI != EI; ++UI) { 3656254f889dSBrendon Cahoon MachineOperand &UseOp = *UI; 3657254f889dSBrendon Cahoon MachineInstr *UseMI = UseOp.getParent(); 3658254f889dSBrendon Cahoon SUnit *SUnitUse = SSD->getSUnit(UseMI); 3659254f889dSBrendon Cahoon int UseStage = stageScheduled(SUnitUse); 3660254f889dSBrendon Cahoon unsigned Diff = 0; 3661254f889dSBrendon Cahoon if (UseStage != -1 && UseStage >= DefStage) 3662254f889dSBrendon Cahoon Diff = UseStage - DefStage; 3663254f889dSBrendon Cahoon if (MI->isPHI()) { 3664254f889dSBrendon Cahoon if (isLoopCarried(SSD, *MI)) 3665254f889dSBrendon Cahoon ++Diff; 3666254f889dSBrendon Cahoon else 3667254f889dSBrendon Cahoon PhiIsSwapped = true; 3668254f889dSBrendon Cahoon } 3669254f889dSBrendon Cahoon MaxDiff = std::max(Diff, MaxDiff); 3670254f889dSBrendon Cahoon } 3671254f889dSBrendon Cahoon RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped); 3672254f889dSBrendon Cahoon } 3673254f889dSBrendon Cahoon } 3674254f889dSBrendon Cahoon 3675254f889dSBrendon Cahoon // Erase all the elements in the later stages. Only one iteration should 3676254f889dSBrendon Cahoon // remain in the scheduled list, and it contains all the instructions. 3677254f889dSBrendon Cahoon for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle) 3678254f889dSBrendon Cahoon ScheduledInstrs.erase(cycle); 3679254f889dSBrendon Cahoon 3680254f889dSBrendon Cahoon // Change the registers in instruction as specified in the InstrChanges 3681254f889dSBrendon Cahoon // map. We need to use the new registers to create the correct order. 3682254f889dSBrendon Cahoon for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) { 3683254f889dSBrendon Cahoon SUnit *SU = &SSD->SUnits[i]; 36848f174ddeSKrzysztof Parzyszek SSD->applyInstrChange(SU->getInstr(), *this); 3685254f889dSBrendon Cahoon } 3686254f889dSBrendon Cahoon 3687254f889dSBrendon Cahoon // Reorder the instructions in each cycle to fix and improve the 3688254f889dSBrendon Cahoon // generated code. 3689254f889dSBrendon Cahoon for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) { 3690254f889dSBrendon Cahoon std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle]; 3691f13bbf1dSKrzysztof Parzyszek std::deque<SUnit *> newOrderPhi; 3692254f889dSBrendon Cahoon for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { 3693254f889dSBrendon Cahoon SUnit *SU = cycleInstrs[i]; 3694f13bbf1dSKrzysztof Parzyszek if (SU->getInstr()->isPHI()) 3695f13bbf1dSKrzysztof Parzyszek newOrderPhi.push_back(SU); 3696254f889dSBrendon Cahoon } 3697254f889dSBrendon Cahoon std::deque<SUnit *> newOrderI; 3698254f889dSBrendon Cahoon for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) { 3699254f889dSBrendon Cahoon SUnit *SU = cycleInstrs[i]; 3700f13bbf1dSKrzysztof Parzyszek if (!SU->getInstr()->isPHI()) 3701254f889dSBrendon Cahoon orderDependence(SSD, SU, newOrderI); 3702254f889dSBrendon Cahoon } 3703254f889dSBrendon Cahoon // Replace the old order with the new order. 3704f13bbf1dSKrzysztof Parzyszek cycleInstrs.swap(newOrderPhi); 3705254f889dSBrendon Cahoon cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end()); 37068f174ddeSKrzysztof Parzyszek SSD->fixupRegisterOverlaps(cycleInstrs); 3707254f889dSBrendon Cahoon } 3708254f889dSBrendon Cahoon 3709d34e60caSNicola Zaghen LLVM_DEBUG(dump();); 3710254f889dSBrendon Cahoon } 3711254f889dSBrendon Cahoon 3712fa2e3583SAdrian Prantl void NodeSet::print(raw_ostream &os) const { 3713fa2e3583SAdrian Prantl os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV 3714fa2e3583SAdrian Prantl << " depth " << MaxDepth << " col " << Colocate << "\n"; 3715fa2e3583SAdrian Prantl for (const auto &I : Nodes) 3716fa2e3583SAdrian Prantl os << " SU(" << I->NodeNum << ") " << *(I->getInstr()); 3717fa2e3583SAdrian Prantl os << "\n"; 3718fa2e3583SAdrian Prantl } 3719fa2e3583SAdrian Prantl 3720615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3721254f889dSBrendon Cahoon /// Print the schedule information to the given output. 3722254f889dSBrendon Cahoon void SMSchedule::print(raw_ostream &os) const { 3723254f889dSBrendon Cahoon // Iterate over each cycle. 3724254f889dSBrendon Cahoon for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) { 3725254f889dSBrendon Cahoon // Iterate over each instruction in the cycle. 3726254f889dSBrendon Cahoon const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle); 3727254f889dSBrendon Cahoon for (SUnit *CI : cycleInstrs->second) { 3728254f889dSBrendon Cahoon os << "cycle " << cycle << " (" << stageScheduled(CI) << ") "; 3729254f889dSBrendon Cahoon os << "(" << CI->NodeNum << ") "; 3730254f889dSBrendon Cahoon CI->getInstr()->print(os); 3731254f889dSBrendon Cahoon os << "\n"; 3732254f889dSBrendon Cahoon } 3733254f889dSBrendon Cahoon } 3734254f889dSBrendon Cahoon } 3735254f889dSBrendon Cahoon 3736254f889dSBrendon Cahoon /// Utility function used for debugging to print the schedule. 37378c209aa8SMatthias Braun LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); } 3738fa2e3583SAdrian Prantl LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); } 3739fa2e3583SAdrian Prantl 37408c209aa8SMatthias Braun #endif 3741fa2e3583SAdrian Prantl 3742fa2e3583SAdrian Prantl 3743fa2e3583SAdrian Prantl 3744