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, RegUse &Defs, RegUse &Uses) const;
66   bool checkPressure(const MachineInstr &MI, GCNDownwardRPTracker &RPT);
67   void collectRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses) const;
68   bool processRegUses(const MachineInstr &MI, RegUse &Defs, RegUse &Uses,
69                       GCNDownwardRPTracker &RPT);
70 
71   const GCNSubtarget *ST;
72   const SIRegisterInfo *TRI;
73   const MachineRegisterInfo *MRI;
74   SIMachineFunctionInfo *MFI;
75 
76   unsigned LastRecordedOccupancy;
77   unsigned MaxVGPRs;
78   unsigned MaxSGPRs;
79 };
80 
81 } // End anonymous namespace.
82 
83 INITIALIZE_PASS_BEGIN(SIFormMemoryClauses, DEBUG_TYPE,
84                       "SI Form memory clauses", false, false)
85 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
86 INITIALIZE_PASS_END(SIFormMemoryClauses, DEBUG_TYPE,
87                     "SI Form memory clauses", false, false)
88 
89 
90 char SIFormMemoryClauses::ID = 0;
91 
92 char &llvm::SIFormMemoryClausesID = SIFormMemoryClauses::ID;
93 
94 FunctionPass *llvm::createSIFormMemoryClausesPass() {
95   return new SIFormMemoryClauses();
96 }
97 
98 static bool isVMEMClauseInst(const MachineInstr &MI) {
99   return SIInstrInfo::isFLAT(MI) || SIInstrInfo::isVMEM(MI);
100 }
101 
102 static bool isSMEMClauseInst(const MachineInstr &MI) {
103   return SIInstrInfo::isSMRD(MI);
104 }
105 
106 // There no sense to create store clauses, they do not define anything,
107 // thus there is nothing to set early-clobber.
108 static bool isValidClauseInst(const MachineInstr &MI, bool IsVMEMClause) {
109   if (MI.isDebugValue() || MI.isBundled())
110     return false;
111   if (!MI.mayLoad() || MI.mayStore())
112     return false;
113   if (AMDGPU::getAtomicNoRetOp(MI.getOpcode()) != -1 ||
114       AMDGPU::getAtomicRetOp(MI.getOpcode()) != -1)
115     return false;
116   if (IsVMEMClause && !isVMEMClauseInst(MI))
117     return false;
118   if (!IsVMEMClause && !isSMEMClauseInst(MI))
119     return false;
120   // If this is a load instruction where the result has been coalesced with an operand, then we cannot clause it.
121   for (const MachineOperand &ResMO : MI.defs()) {
122     Register ResReg = ResMO.getReg();
123     for (const MachineOperand &MO : MI.uses()) {
124       if (!MO.isReg() || MO.isDef())
125         continue;
126       if (MO.getReg() == ResReg)
127         return false;
128     }
129     break; // Only check the first def.
130   }
131   return true;
132 }
133 
134 static unsigned getMopState(const MachineOperand &MO) {
135   unsigned S = 0;
136   if (MO.isImplicit())
137     S |= RegState::Implicit;
138   if (MO.isDead())
139     S |= RegState::Dead;
140   if (MO.isUndef())
141     S |= RegState::Undef;
142   if (MO.isKill())
143     S |= RegState::Kill;
144   if (MO.isEarlyClobber())
145     S |= RegState::EarlyClobber;
146   if (MO.getReg().isPhysical() && MO.isRenamable())
147     S |= RegState::Renamable;
148   return S;
149 }
150 
151 template <typename Callable>
152 void SIFormMemoryClauses::forAllLanes(Register Reg, LaneBitmask LaneMask,
153                                       Callable Func) const {
154   if (LaneMask.all() || Reg.isPhysical() ||
155       LaneMask == MRI->getMaxLaneMaskForVReg(Reg)) {
156     Func(0);
157     return;
158   }
159 
160   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
161   unsigned E = TRI->getNumSubRegIndices();
162   SmallVector<unsigned, AMDGPU::NUM_TARGET_SUBREGS> CoveringSubregs;
163   for (unsigned Idx = 1; Idx < E; ++Idx) {
164     // Is this index even compatible with the given class?
165     if (TRI->getSubClassWithSubReg(RC, Idx) != RC)
166       continue;
167     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
168     // Early exit if we found a perfect match.
169     if (SubRegMask == LaneMask) {
170       Func(Idx);
171       return;
172     }
173 
174     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
175       continue;
176 
177     CoveringSubregs.push_back(Idx);
178   }
179 
180   llvm::sort(CoveringSubregs, [this](unsigned A, unsigned B) {
181     LaneBitmask MaskA = TRI->getSubRegIndexLaneMask(A);
182     LaneBitmask MaskB = TRI->getSubRegIndexLaneMask(B);
183     unsigned NA = MaskA.getNumLanes();
184     unsigned NB = MaskB.getNumLanes();
185     if (NA != NB)
186       return NA > NB;
187     return MaskA.getHighestLane() > MaskB.getHighestLane();
188   });
189 
190   for (unsigned Idx : CoveringSubregs) {
191     LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(Idx);
192     if ((SubRegMask & ~LaneMask).any() || (SubRegMask & LaneMask).none())
193       continue;
194 
195     Func(Idx);
196     LaneMask &= ~SubRegMask;
197     if (LaneMask.none())
198       return;
199   }
200 
201   llvm_unreachable("Failed to find all subregs to cover lane mask");
202 }
203 
204 // Returns false if there is a use of a def already in the map.
205 // In this case we must break the clause.
206 bool SIFormMemoryClauses::canBundle(const MachineInstr &MI,
207                                     RegUse &Defs, RegUse &Uses) const {
208   // Check interference with defs.
209   for (const MachineOperand &MO : MI.operands()) {
210     // TODO: Prologue/Epilogue Insertion pass does not process bundled
211     //       instructions.
212     if (MO.isFI())
213       return false;
214 
215     if (!MO.isReg())
216       continue;
217 
218     Register Reg = MO.getReg();
219 
220     // If it is tied we will need to write same register as we read.
221     if (MO.isTied())
222       return false;
223 
224     RegUse &Map = MO.isDef() ? Uses : Defs;
225     auto Conflict = Map.find(Reg);
226     if (Conflict == Map.end())
227       continue;
228 
229     if (Reg.isPhysical())
230       return false;
231 
232     LaneBitmask Mask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
233     if ((Conflict->second.second & Mask).any())
234       return false;
235   }
236 
237   return true;
238 }
239 
240 // Since all defs in the clause are early clobber we can run out of registers.
241 // Function returns false if pressure would hit the limit if instruction is
242 // bundled into a memory clause.
243 bool SIFormMemoryClauses::checkPressure(const MachineInstr &MI,
244                                         GCNDownwardRPTracker &RPT) {
245   // NB: skip advanceBeforeNext() call. Since all defs will be marked
246   // early-clobber they will all stay alive at least to the end of the
247   // clause. Therefor we should not decrease pressure even if load
248   // pointer becomes dead and could otherwise be reused for destination.
249   RPT.advanceToNext();
250   GCNRegPressure MaxPressure = RPT.moveMaxPressure();
251   unsigned Occupancy = MaxPressure.getOccupancy(*ST);
252   if (Occupancy >= MFI->getMinAllowedOccupancy() &&
253       MaxPressure.getVGPRNum() <= MaxVGPRs &&
254       MaxPressure.getSGPRNum() <= MaxSGPRs) {
255     LastRecordedOccupancy = Occupancy;
256     return true;
257   }
258   return false;
259 }
260 
261 // Collect register defs and uses along with their lane masks and states.
262 void SIFormMemoryClauses::collectRegUses(const MachineInstr &MI,
263                                          RegUse &Defs, RegUse &Uses) const {
264   for (const MachineOperand &MO : MI.operands()) {
265     if (!MO.isReg())
266       continue;
267     Register Reg = MO.getReg();
268     if (!Reg)
269       continue;
270 
271     LaneBitmask Mask = Reg.isVirtual()
272                            ? TRI->getSubRegIndexLaneMask(MO.getSubReg())
273                            : LaneBitmask::getAll();
274     RegUse &Map = MO.isDef() ? Defs : Uses;
275 
276     auto Loc = Map.find(Reg);
277     unsigned State = getMopState(MO);
278     if (Loc == Map.end()) {
279       Map[Reg] = std::make_pair(State, Mask);
280     } else {
281       Loc->second.first |= State;
282       Loc->second.second |= Mask;
283     }
284   }
285 }
286 
287 // Check register def/use conflicts, occupancy limits and collect def/use maps.
288 // Return true if instruction can be bundled with previous. It it cannot
289 // def/use maps are not updated.
290 bool SIFormMemoryClauses::processRegUses(const MachineInstr &MI,
291                                          RegUse &Defs, RegUse &Uses,
292                                          GCNDownwardRPTracker &RPT) {
293   if (!canBundle(MI, Defs, Uses))
294     return false;
295 
296   if (!checkPressure(MI, RPT))
297     return false;
298 
299   collectRegUses(MI, Defs, Uses);
300   return true;
301 }
302 
303 bool SIFormMemoryClauses::runOnMachineFunction(MachineFunction &MF) {
304   if (skipFunction(MF.getFunction()))
305     return false;
306 
307   ST = &MF.getSubtarget<GCNSubtarget>();
308   if (!ST->isXNACKEnabled())
309     return false;
310 
311   const SIInstrInfo *TII = ST->getInstrInfo();
312   TRI = ST->getRegisterInfo();
313   MRI = &MF.getRegInfo();
314   MFI = MF.getInfo<SIMachineFunctionInfo>();
315   LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
316   SlotIndexes *Ind = LIS->getSlotIndexes();
317   bool Changed = false;
318 
319   MaxVGPRs = TRI->getAllocatableSet(MF, &AMDGPU::VGPR_32RegClass).count();
320   MaxSGPRs = TRI->getAllocatableSet(MF, &AMDGPU::SGPR_32RegClass).count();
321   unsigned FuncMaxClause = AMDGPU::getIntegerAttribute(
322       MF.getFunction(), "amdgpu-max-memory-clause", MaxClause);
323 
324   for (MachineBasicBlock &MBB : MF) {
325     GCNDownwardRPTracker RPT(*LIS);
326     MachineBasicBlock::instr_iterator Next;
327     for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; I = Next) {
328       MachineInstr &MI = *I;
329       Next = std::next(I);
330 
331       bool IsVMEM = isVMEMClauseInst(MI);
332 
333       if (!isValidClauseInst(MI, IsVMEM))
334         continue;
335 
336       if (!RPT.getNext().isValid())
337         RPT.reset(MI);
338       else { // Advance the state to the current MI.
339         RPT.advance(MachineBasicBlock::const_iterator(MI));
340         RPT.advanceBeforeNext();
341       }
342 
343       const GCNRPTracker::LiveRegSet LiveRegsCopy(RPT.getLiveRegs());
344       RegUse Defs, Uses;
345       if (!processRegUses(MI, Defs, Uses, RPT)) {
346         RPT.reset(MI, &LiveRegsCopy);
347         continue;
348       }
349 
350       unsigned Length = 1;
351       for ( ; Next != E && Length < FuncMaxClause; ++Next) {
352         if (!isValidClauseInst(*Next, IsVMEM))
353           break;
354 
355         // A load from pointer which was loaded inside the same bundle is an
356         // impossible clause because we will need to write and read the same
357         // register inside. In this case processRegUses will return false.
358         if (!processRegUses(*Next, Defs, Uses, RPT))
359           break;
360 
361         ++Length;
362       }
363       if (Length < 2) {
364         RPT.reset(MI, &LiveRegsCopy);
365         continue;
366       }
367 
368       Changed = true;
369       MFI->limitOccupancy(LastRecordedOccupancy);
370 
371       auto B = BuildMI(MBB, I, DebugLoc(), TII->get(TargetOpcode::BUNDLE));
372       Ind->insertMachineInstrInMaps(*B);
373 
374       // Restore the state after processing the bundle.
375       RPT.reset(*B, &LiveRegsCopy);
376 
377       for (auto BI = I; BI != Next; ++BI) {
378         BI->bundleWithPred();
379         Ind->removeSingleMachineInstrFromMaps(*BI);
380 
381         for (MachineOperand &MO : BI->defs())
382           if (MO.readsReg())
383             MO.setIsInternalRead(true);
384       }
385 
386       for (auto &&R : Defs) {
387         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
388           unsigned S = R.second.first | RegState::EarlyClobber;
389           if (!SubReg)
390             S &= ~(RegState::Undef | RegState::Dead);
391           B.addDef(R.first, S, SubReg);
392         });
393       }
394 
395       for (auto &&R : Uses) {
396         forAllLanes(R.first, R.second.second, [&R, &B](unsigned SubReg) {
397           B.addUse(R.first, R.second.first & ~RegState::Kill, SubReg);
398         });
399       }
400 
401       for (auto &&R : Defs) {
402         Register Reg = R.first;
403         Uses.erase(Reg);
404         if (Reg.isPhysical())
405           continue;
406         LIS->removeInterval(Reg);
407         LIS->createAndComputeVirtRegInterval(Reg);
408       }
409 
410       for (auto &&R : Uses) {
411         Register Reg = R.first;
412         if (Reg.isPhysical())
413           continue;
414         LIS->removeInterval(Reg);
415         LIS->createAndComputeVirtRegInterval(Reg);
416       }
417     }
418   }
419 
420   return Changed;
421 }
422