xref: /llvm-project/llvm/lib/Target/AMDGPU/SIFormMemoryClauses.cpp (revision 477e3fe4f874b1c4d5896f3bfaf7b3b8a6d38103)
1 //===-- SIFormMemoryClauses.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This pass creates bundles of SMEM and VMEM instructions forming memory
11 /// clauses if XNACK is enabled. Def operands of clauses are marked as early
12 /// clobber to make sure we will not override any source within a clause.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPU.h"
17 #include "GCNRegPressure.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "llvm/InitializePasses.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "si-form-memory-clauses"
24 
25 // Clauses longer then 15 instructions would overflow one of the counters
26 // and stall. They can stall even earlier if there are outstanding counters.
27 static cl::opt<unsigned>
28 MaxClause("amdgpu-max-memory-clause", cl::Hidden, cl::init(15),
29           cl::desc("Maximum length of a memory clause, instructions"));
30 
31 namespace {
32 
33 class SIFormMemoryClauses : public MachineFunctionPass {
34   typedef DenseMap<unsigned, std::pair<unsigned, LaneBitmask>> RegUse;
35 
36 public:
37   static char ID;
38 
39 public:
40   SIFormMemoryClauses() : MachineFunctionPass(ID) {
41     initializeSIFormMemoryClausesPass(*PassRegistry::getPassRegistry());
42   }
43 
44   bool runOnMachineFunction(MachineFunction &MF) override;
45 
46   StringRef getPassName() const override {
47     return "SI Form memory clauses";
48   }
49 
50   void getAnalysisUsage(AnalysisUsage &AU) const override {
51     AU.addRequired<LiveIntervals>();
52     AU.setPreservesAll();
53     MachineFunctionPass::getAnalysisUsage(AU);
54   }
55 
56   MachineFunctionProperties getClearedProperties() const override {
57     return MachineFunctionProperties().set(
58         MachineFunctionProperties::Property::IsSSA);
59   }
60 
61 private:
62   template <typename Callable>
63   void forAllLanes(Register Reg, LaneBitmask LaneMask, Callable Func) const;
64 
65   bool canBundle(const MachineInstr &MI, const RegUse &Defs,
66                  const RegUse &Uses) const;
67   bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT);
68   void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const;
69   bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses,
70                       GCNDownwardRPTracker &RPT);
71 
72   const GCNSubtarget *ST;
73   const SIRegisterInfo *TRI;
74   const MachineRegisterInfo *MRI;
75   SIMachineFunctionInfo *MFI;
76 
77   unsigned LastRecordedOccupancy;
78   unsigned MaxVGPRs;
79   unsigned MaxSGPRs;
80 };
81 
82 } // End anonymous namespace.
83 
84 INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE,
85                       "SI Form memory clauses", false, false)
86 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
87 INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE,
88                     "SI Form memory clauses", false, false)
89 
90 
91 char SIFormMemoryClauses::ID = 0;
92 
93 char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID;
94 
95 FunctionPass *llvm::createSIFormMemoryClausesPass() {
96   return new SIFormMemoryClauses();
97 }
98 
99 static bool isVMEMClauseInst(const MachineInstr &MI) {
100   return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI);
101 }
102 
103 static bool isSMEMClauseInst(const MachineInstr &MI) {
104   return SIInstrInfo::isSMRD(MI);
105 }
106 
107 // There no sense to create store clauses, they do not define anything,
108 // thus there is nothing to set early-clobber.
109 static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) {
110   assert(!MI.isDebugInstr() && "debug instructions should not reach here");
111   if (MI.isBundled())
112     return false;
113   if (!MI.mayLoad() || MI.mayStore())
114     return false;
115   if (AMDGPU::getAtomicNoRetOp(MI.getOpcode()) != -1 ||
116       AMDGPU::getAtomicRetOp(MI.getOpcode()) != -1)
117     return false;
118   if (IsVMEMClause && !isVMEMClauseInst(MI))
119     return false;
120   if (!IsVMEMClause && !isSMEMClauseInst(MI))
121     return false;
122   // If this is a load instruction where the result has been coalesced with an operand, then we cannot clause it.
123   for (const MachineOperand &ResMO : MI.defs()) {
124     Register ResReg = ResMO.getReg();
125     for (const MachineOperand &MO : MI.uses()) {
126       if (!MO.isReg() || MO.isDef())
127         continue;
128       if (MO.getReg() == ResReg)
129         return false;
130     }
131     break; // Only check the first def.
132   }
133   return true;
134 }
135 
136 static unsigned getMopState(const MachineOperand &MO) {
137   unsigned S = 0;
138   if (MO.isImplicit())
139     S |= RegState::Implicit;
140   if (MO.isDead())
141     S |= RegState::Dead;
142   if (MO.isUndef())
143     S |= RegState::Undef;
144   if (MO.isKill())
145     S |= RegState::Kill;
146   if (MO.isEarlyClobber())
147     S |= RegState::EarlyClobber;
148   if (MO.getReg().isPhysical() && MO.isRenamable())
149     S |= RegState::Renamable;
150   return S;
151 }
152 
153 template <typename Callable>
154 void SIFormMemoryClauses::forAllLanes(Register Reg, LaneBitmask LaneMask,
155                                       Callable Func) const {
156   if (LaneMask.all() || Reg.isPhysical() ||
157       LaneMask == MRI->getMaxLaneMaskForVReg(Reg)) {
158     Func(0);
159     return;
160   }
161 
162   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
163   unsigned E = TRI->getNumSubRegIndices();
164   SmallVector<unsigned, AMDGPU::NUM_TARGET_SUBREGS> CoveringSubregs;
165   for (unsigned Idx = 1; Idx < E; ++Idx) {
166     // Is this index even compatible with the given class?
167     if (TRI->getSubClassWithSubReg(RC, Idx) != RC)
168       continue;
169     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
170     // Early exit if we found a perfect match.
171     if (SubRegMask == LaneMask) {
172       Func(Idx);
173       return;
174     }
175 
176     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
177       continue;
178 
179     CoveringSubregs.push_back(Idx);
180   }
181 
182   llvm::sort(CoveringSubregs, [this](unsigned A, unsigned B) {
183     LaneBitmask MaskA = TRI->getSubRegIndexLaneMask(A);
184     LaneBitmask MaskB = TRI->getSubRegIndexLaneMask(B);
185     unsigned NA = MaskA.getNumLanes();
186     unsigned NB = MaskB.getNumLanes();
187     if (NA != NB)
188       return NA > NB;
189     return MaskA.getHighestLane() > MaskB.getHighestLane();
190   });
191 
192   for (unsigned Idx : CoveringSubregs) {
193     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
194     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
195       continue;
196 
197     Func(Idx);
198     LaneMask &= ~SubRegMask;
199     if (LaneMask.none())
200       return;
201   }
202 
203   llvm_unreachable("Failed to find all subregs to cover lane mask");
204 }
205 
206 // Returns false if there is a use of a def already in the map.
207 // In this case we must break the clause.
208 bool SIFormMemoryClauses::canBundle(const MachineInstr &MI, const RegUse &Defs,
209                                     const RegUse &Uses) const {
210   // Check interference with defs.
211   for (const MachineOperand &MO : MI.operands()) {
212     // TODO: Prologue/Epilogue Insertion pass does not process bundled
213     //       instructions.
214     if (MO.isFI())
215       return false;
216 
217     if (!MO.isReg())
218       continue;
219 
220     Register Reg = MO.getReg();
221 
222     // If it is tied we will need to write same register as we read.
223     if (MO.isTied())
224       return false;
225 
226     const RegUse &Map = MO.isDef() ? Uses : Defs;
227     auto Conflict = Map.find(Reg);
228     if (Conflict == Map.end())
229       continue;
230 
231     if (Reg.isPhysical())
232       return false;
233 
234     LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
235     if ((Conflict->second.second & Mask).any())
236       return false;
237   }
238 
239   return true;
240 }
241 
242 // Since all defs in the clause are early clobber we can run out of registers.
243 // Function returns false if pressure would hit the limit if instruction is
244 // bundled into a memory clause.
245 bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI,
246                                         GCNDownwardRPTracker &RPT) {
247   // NB: skip advanceBeforeNext() call. Since all defs will be marked
248   // early-clobber they will all stay alive at least to the end of the
249   // clause. Therefor we should not decrease pressure even if load
250   // pointer becomes dead and could otherwise be reused for destination.
251   RPT.advanceToNext();
252   GCNRegPressure MaxPressure = RPT.moveMaxPressure();
253   unsigned Occupancy = MaxPressure.getOccupancy(*ST);
254   if (Occupancy >= MFI->getMinAllowedOccupancy() &&
255       MaxPressure.getVGPRNum() <= MaxVGPRs &&
256       MaxPressure.getSGPRNum() <= MaxSGPRs) {
257     LastRecordedOccupancy = Occupancy;
258     return true;
259   }
260   return false;
261 }
262 
263 // Collect register defs and uses along with their lane masks and states.
264 void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI,
265                                          RegUse &Defs, RegUse &Uses) const {
266   for (const MachineOperand &MO : MI.operands()) {
267     if (!MO.isReg())
268       continue;
269     Register Reg = MO.getReg();
270     if (!Reg)
271       continue;
272 
273     LaneBitmask Mask = Reg.isVirtual()
274                            ? TRI->getSubRegIndexLaneMask(MO.getSubReg())
275                            : LaneBitmask::getAll();
276     RegUse &Map = MO.isDef() ? Defs : Uses;
277 
278     auto Loc = Map.find(Reg);
279     unsigned State = getMopState(MO);
280     if (Loc == Map.end()) {
281       Map[Reg] = std::make_pair(State, Mask);
282     } else {
283       Loc->second.first |= State;
284       Loc->second.second |= Mask;
285     }
286   }
287 }
288 
289 // Check register def/use conflicts, occupancy limits and collect def/use maps.
290 // Return true if instruction can be bundled with previous. It it cannot
291 // def/use maps are not updated.
292 bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI,
293                                          RegUse &Defs, RegUse &Uses,
294                                          GCNDownwardRPTracker &RPT) {
295   if (!canBundle(MI, Defs, Uses))
296     return false;
297 
298   if (!checkPressure(MI, RPT))
299     return false;
300 
301   collectRegUses(MI, Defs, Uses);
302   return true;
303 }
304 
305 bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) {
306   if (skipFunction(MF.getFunction()))
307     return false;
308 
309   ST = &MF.getSubtarget<GCNSubtarget>();
310   if (!ST->isXNACKEnabled())
311     return false;
312 
313   const SIInstrInfo *TII = ST->getInstrInfo();
314   TRI = ST->getRegisterInfo();
315   MRI = &MF.getRegInfo();
316   MFI = MF.getInfo<SIMachineFunctionInfo>();
317   LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
318   SlotIndexes *Ind = LIS->getSlotIndexes();
319   bool Changed = false;
320 
321   MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count();
322   MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count();
323   unsigned FuncMaxClause = AMDGPU::getIntegerAttribute(
324       MF.getFunction(), "amdgpu-max-memory-clause", MaxClause);
325 
326   SmallVector<MachineInstr *> DbgInstrs;
327 
328   for (MachineBasicBlock &MBB : MF) {
329     GCNDownwardRPTracker RPT(*LIS);
330     MachineBasicBlock::instr_iterator Next;
331     for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) {
332       MachineInstr &MI = *I;
333       Next = std::next(I);
334 
335       if (MI.isDebugInstr())
336         continue;
337 
338       bool IsVMEM = isVMEMClauseInst(MI);
339 
340       if (!isValidClauseInst(MI, IsVMEM))
341         continue;
342 
343       if (!RPT.getNext().isValid())
344         RPT.reset(MI);
345       else { // Advance the state to the current MI.
346         RPT.advance(MachineBasicBlock::const_iterator(MI));
347         RPT.advanceBeforeNext();
348       }
349 
350       const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs());
351       RegUse Defs, Uses;
352       if (!processRegUses(MI, Defs, Uses, RPT)) {
353         RPT.reset(MI, &LiveRegsCopy);
354         continue;
355       }
356 
357       unsigned Length = 1;
358       for ( ; Next != E && Length < FuncMaxClause; ++Next) {
359         // Debug instructions should not change the bundling. We need to move
360         // these after the bundle
361         if (Next->isDebugInstr())
362           continue;
363 
364         if (!isValidClauseInst(*Next, IsVMEM))
365           break;
366 
367         // A load from pointer which was loaded inside the same bundle is an
368         // impossible clause because we will need to write and read the same
369         // register inside. In this case processRegUses will return false.
370         if (!processRegUses(*Next, Defs, Uses, RPT))
371           break;
372 
373         ++Length;
374       }
375       if (Length < 2) {
376         RPT.reset(MI, &LiveRegsCopy);
377         continue;
378       }
379 
380       Changed = true;
381       MFI->limitOccupancy(LastRecordedOccupancy);
382 
383       auto B = BuildMI(MBB, I, DebugLoc(), TII->get(TargetOpcode::BUNDLE));
384       Ind->insertMachineInstrInMaps(*B);
385 
386       // Restore the state after processing the bundle.
387       RPT.reset(*B, &LiveRegsCopy);
388       DbgInstrs.clear();
389 
390       auto BundleNext = I;
391       for (auto BI = I; BI != Next; BI = BundleNext) {
392         BundleNext = std::next(BI);
393 
394         if (BI->isDebugValue()) {
395           DbgInstrs.push_back(BI->removeFromParent());
396           continue;
397         }
398 
399         BI->bundleWithPred();
400         Ind->removeSingleMachineInstrFromMaps(*BI);
401 
402         for (MachineOperand &MO : BI->defs())
403           if (MO.readsReg())
404             MO.setIsInternalRead(true);
405       }
406 
407       // Replace any debug instructions after the new bundle.
408       for (MachineInstr *DbgInst : DbgInstrs)
409         MBB.insert(Next, DbgInst);
410 
411       for (auto &&R : Defs) {
412         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
413           unsigned S = R.second.first | RegState::EarlyClobber;
414           if (!SubReg)
415             S &= ~(RegState::Undef | RegState::Dead);
416           B.addDef(R.first, S, SubReg);
417         });
418       }
419 
420       for (auto &&R : Uses) {
421         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
422           B.addUse(R.first, R.second.first & ~RegState::Kill, SubReg);
423         });
424       }
425 
426       for (auto &&R : Defs) {
427         Register Reg = R.first;
428         Uses.erase(Reg);
429         if (Reg.isPhysical())
430           continue;
431         LIS->removeInterval(Reg);
432         LIS->createAndComputeVirtRegInterval(Reg);
433       }
434 
435       for (auto &&R : Uses) {
436         Register Reg = R.first;
437         if (Reg.isPhysical())
438           continue;
439         LIS->removeInterval(Reg);
440         LIS->createAndComputeVirtRegInterval(Reg);
441       }
442     }
443   }
444 
445   return Changed;
446 }
447