xref: /llvm-project/llvm/lib/Target/AMDGPU/SIModeRegister.cpp (revision 35e27c0ee51f2822415c050c1cc4a73dfaa171d7)
1 //===-- SIModeRegister.cpp - Mode Register --------------------------------===//
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 /// \file
9 /// This pass inserts changes to the Mode register settings as required.
10 /// Note that currently it only deals with the Double Precision Floating Point
11 /// rounding mode setting, but is intended to be generic enough to be easily
12 /// expanded.
13 ///
14 //===----------------------------------------------------------------------===//
15 //
16 #include "AMDGPU.h"
17 #include "GCNSubtarget.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include <queue>
22 
23 #define DEBUG_TYPE "si-mode-register"
24 
25 STATISTIC(NumSetregInserted, "Number of setreg of mode register inserted.");
26 
27 using namespace llvm;
28 
29 struct Status {
30   // Mask is a bitmask where a '1' indicates the corresponding Mode bit has a
31   // known value
32   unsigned Mask = 0;
33   unsigned Mode = 0;
34 
35   Status() = default;
36 
37   Status(unsigned NewMask, unsigned NewMode) : Mask(NewMask), Mode(NewMode) {
38     Mode &= Mask;
39   };
40 
41   // merge two status values such that only values that don't conflict are
42   // preserved
43   Status merge(const Status &S) const {
44     return Status((Mask | S.Mask), ((Mode & ~S.Mask) | (S.Mode & S.Mask)));
45   }
46 
47   // merge an unknown value by using the unknown value's mask to remove bits
48   // from the result
49   Status mergeUnknown(unsigned newMask) {
50     return Status(Mask & ~newMask, Mode & ~newMask);
51   }
52 
53   // intersect two Status values to produce a mode and mask that is a subset
54   // of both values
55   Status intersect(const Status &S) const {
56     unsigned NewMask = (Mask & S.Mask) & (Mode ^ ~S.Mode);
57     unsigned NewMode = (Mode & NewMask);
58     return Status(NewMask, NewMode);
59   }
60 
61   // produce the delta required to change the Mode to the required Mode
62   Status delta(const Status &S) const {
63     return Status((S.Mask & (Mode ^ S.Mode)) | (~Mask & S.Mask), S.Mode);
64   }
65 
66   bool operator==(const Status &S) const {
67     return (Mask == S.Mask) && (Mode == S.Mode);
68   }
69 
70   bool operator!=(const Status &S) const { return !(*this == S); }
71 
72   bool isCompatible(Status &S) {
73     return ((Mask & S.Mask) == S.Mask) && ((Mode & S.Mask) == S.Mode);
74   }
75 
76   bool isCombinable(Status &S) { return !(Mask & S.Mask) || isCompatible(S); }
77 };
78 
79 class BlockData {
80 public:
81   // The Status that represents the mode register settings required by the
82   // FirstInsertionPoint (if any) in this block. Calculated in Phase 1.
83   Status Require;
84 
85   // The Status that represents the net changes to the Mode register made by
86   // this block, Calculated in Phase 1.
87   Status Change;
88 
89   // The Status that represents the mode register settings on exit from this
90   // block. Calculated in Phase 2.
91   Status Exit;
92 
93   // The Status that represents the intersection of exit Mode register settings
94   // from all predecessor blocks. Calculated in Phase 2, and used by Phase 3.
95   Status Pred;
96 
97   // In Phase 1 we record the first instruction that has a mode requirement,
98   // which is used in Phase 3 if we need to insert a mode change.
99   MachineInstr *FirstInsertionPoint = nullptr;
100 
101   // A flag to indicate whether an Exit value has been set (we can't tell by
102   // examining the Exit value itself as all values may be valid results).
103   bool ExitSet = false;
104 
105   BlockData() = default;
106 };
107 
108 namespace {
109 
110 class SIModeRegister : public MachineFunctionPass {
111 public:
112   static char ID;
113 
114   std::vector<std::unique_ptr<BlockData>> BlockInfo;
115   std::queue<MachineBasicBlock *> Phase2List;
116 
117   // The default mode register setting currently only caters for the floating
118   // point double precision rounding mode.
119   // We currently assume the default rounding mode is Round to Nearest
120   // NOTE: this should come from a per function rounding mode setting once such
121   // a setting exists.
122   unsigned DefaultMode = FP_ROUND_ROUND_TO_NEAREST;
123   Status DefaultStatus =
124       Status(FP_ROUND_MODE_DP(0x3), FP_ROUND_MODE_DP(DefaultMode));
125 
126   bool Changed = false;
127 
128 public:
129   SIModeRegister() : MachineFunctionPass(ID) {}
130 
131   bool runOnMachineFunction(MachineFunction &MF) override;
132 
133   void getAnalysisUsage(AnalysisUsage &AU) const override {
134     AU.setPreservesCFG();
135     MachineFunctionPass::getAnalysisUsage(AU);
136   }
137 
138   void processBlockPhase1(MachineBasicBlock &MBB, const SIInstrInfo *TII);
139 
140   void processBlockPhase2(MachineBasicBlock &MBB, const SIInstrInfo *TII);
141 
142   void processBlockPhase3(MachineBasicBlock &MBB, const SIInstrInfo *TII);
143 
144   Status getInstructionMode(MachineInstr &MI, const SIInstrInfo *TII);
145 
146   void insertSetreg(MachineBasicBlock &MBB, MachineInstr *I,
147                     const SIInstrInfo *TII, Status InstrMode);
148 };
149 } // End anonymous namespace.
150 
151 INITIALIZE_PASS(SIModeRegister, DEBUG_TYPE,
152                 "Insert required mode register values", false, false)
153 
154 char SIModeRegister::ID = 0;
155 
156 char &llvm::SIModeRegisterID = SIModeRegister::ID;
157 
158 FunctionPass *llvm::createSIModeRegisterPass() { return new SIModeRegister(); }
159 
160 // Determine the Mode register setting required for this instruction.
161 // Instructions which don't use the Mode register return a null Status.
162 // Note this currently only deals with instructions that use the floating point
163 // double precision setting.
164 Status SIModeRegister::getInstructionMode(MachineInstr &MI,
165                                           const SIInstrInfo *TII) {
166   unsigned Opcode = MI.getOpcode();
167   if (TII->usesFPDPRounding(MI) ||
168       Opcode == AMDGPU::FPTRUNC_ROUND_F16_F32_PSEUDO ||
169       Opcode == AMDGPU::FPTRUNC_ROUND_F32_F64_PSEUDO) {
170     switch (Opcode) {
171     case AMDGPU::V_INTERP_P1LL_F16:
172     case AMDGPU::V_INTERP_P1LV_F16:
173     case AMDGPU::V_INTERP_P2_F16:
174       // f16 interpolation instructions need double precision round to zero
175       return Status(FP_ROUND_MODE_DP(3),
176                     FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_ZERO));
177     case AMDGPU::FPTRUNC_ROUND_F16_F32_PSEUDO: {
178       unsigned Mode = MI.getOperand(2).getImm();
179       MI.removeOperand(2);
180       // Replacing the pseudo by a real instruction in place
181       if (TII->getSubtarget().hasTrue16BitInsts()) {
182         MachineBasicBlock &MBB = *MI.getParent();
183         MachineInstrBuilder B(*MBB.getParent(), MI);
184         MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_fake16_e64));
185         MachineOperand Src0 = MI.getOperand(1);
186         MI.removeOperand(1);
187         B.addImm(0); // src0_modifiers
188         B.add(Src0); // re-add src0 operand
189         B.addImm(0); // clamp
190         B.addImm(0); // omod
191       } else
192         MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_e32));
193       return Status(FP_ROUND_MODE_DP(3), FP_ROUND_MODE_DP(Mode));
194     }
195     case AMDGPU::FPTRUNC_ROUND_F32_F64_PSEUDO: {
196       unsigned Mode = MI.getOperand(2).getImm();
197       MI.removeOperand(2);
198       MI.setDesc(TII->get(AMDGPU::V_CVT_F32_F64_e32));
199       return Status(FP_ROUND_MODE_DP(3), FP_ROUND_MODE_DP(Mode));
200     }
201     default:
202       return DefaultStatus;
203     }
204   }
205   return Status();
206 }
207 
208 // Insert a setreg instruction to update the Mode register.
209 // It is possible (though unlikely) for an instruction to require a change to
210 // the value of disjoint parts of the Mode register when we don't know the
211 // value of the intervening bits. In that case we need to use more than one
212 // setreg instruction.
213 void SIModeRegister::insertSetreg(MachineBasicBlock &MBB, MachineInstr *MI,
214                                   const SIInstrInfo *TII, Status InstrMode) {
215   while (InstrMode.Mask) {
216     unsigned Offset = llvm::countr_zero<unsigned>(InstrMode.Mask);
217     unsigned Width = llvm::countr_one<unsigned>(InstrMode.Mask >> Offset);
218     unsigned Value = (InstrMode.Mode >> Offset) & ((1 << Width) - 1);
219     using namespace AMDGPU::Hwreg;
220     BuildMI(MBB, MI, nullptr, TII->get(AMDGPU::S_SETREG_IMM32_B32))
221         .addImm(Value)
222         .addImm(HwregEncoding::encode(ID_MODE, Offset, Width));
223     ++NumSetregInserted;
224     Changed = true;
225     InstrMode.Mask &= ~(((1 << Width) - 1) << Offset);
226   }
227 }
228 
229 // In Phase 1 we iterate through the instructions of the block and for each
230 // instruction we get its mode usage. If the instruction uses the Mode register
231 // we:
232 // - update the Change status, which tracks the changes to the Mode register
233 //   made by this block
234 // - if this instruction's requirements are compatible with the current setting
235 //   of the Mode register we merge the modes
236 // - if it isn't compatible and an InsertionPoint isn't set, then we set the
237 //   InsertionPoint to the current instruction, and we remember the current
238 //   mode
239 // - if it isn't compatible and InsertionPoint is set we insert a seteg before
240 //   that instruction (unless this instruction forms part of the block's
241 //   entry requirements in which case the insertion is deferred until Phase 3
242 //   when predecessor exit values are known), and move the insertion point to
243 //   this instruction
244 // - if this is a setreg instruction we treat it as an incompatible instruction.
245 //   This is sub-optimal but avoids some nasty corner cases, and is expected to
246 //   occur very rarely.
247 // - on exit we have set the Require, Change, and initial Exit modes.
248 void SIModeRegister::processBlockPhase1(MachineBasicBlock &MBB,
249                                         const SIInstrInfo *TII) {
250   auto NewInfo = std::make_unique<BlockData>();
251   MachineInstr *InsertionPoint = nullptr;
252   // RequirePending is used to indicate whether we are collecting the initial
253   // requirements for the block, and need to defer the first InsertionPoint to
254   // Phase 3. It is set to false once we have set FirstInsertionPoint, or when
255   // we discover an explicit setreg that means this block doesn't have any
256   // initial requirements.
257   bool RequirePending = true;
258   Status IPChange;
259   for (MachineInstr &MI : MBB) {
260     Status InstrMode = getInstructionMode(MI, TII);
261     if (MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
262         MI.getOpcode() == AMDGPU::S_SETREG_B32_mode ||
263         MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
264         MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
265       // We preserve any explicit mode register setreg instruction we encounter,
266       // as we assume it has been inserted by a higher authority (this is
267       // likely to be a very rare occurrence).
268       unsigned Dst = TII->getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
269       using namespace AMDGPU::Hwreg;
270       auto [Id, Offset, Width] = HwregEncoding::decode(Dst);
271       if (Id != ID_MODE)
272         continue;
273 
274       unsigned Mask = maskTrailingOnes<unsigned>(Width) << Offset;
275 
276       // If an InsertionPoint is set we will insert a setreg there.
277       if (InsertionPoint) {
278         insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
279         InsertionPoint = nullptr;
280       }
281       // If this is an immediate then we know the value being set, but if it is
282       // not an immediate then we treat the modified bits of the mode register
283       // as unknown.
284       if (MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
285           MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
286         unsigned Val = TII->getNamedOperand(MI, AMDGPU::OpName::imm)->getImm();
287         unsigned Mode = (Val << Offset) & Mask;
288         Status Setreg = Status(Mask, Mode);
289         // If we haven't already set the initial requirements for the block we
290         // don't need to as the requirements start from this explicit setreg.
291         RequirePending = false;
292         NewInfo->Change = NewInfo->Change.merge(Setreg);
293       } else {
294         NewInfo->Change = NewInfo->Change.mergeUnknown(Mask);
295       }
296     } else if (!NewInfo->Change.isCompatible(InstrMode)) {
297       // This instruction uses the Mode register and its requirements aren't
298       // compatible with the current mode.
299       if (InsertionPoint) {
300         // If the required mode change cannot be included in the current
301         // InsertionPoint changes, we need a setreg and start a new
302         // InsertionPoint.
303         if (!IPChange.delta(NewInfo->Change).isCombinable(InstrMode)) {
304           if (RequirePending) {
305             // This is the first insertionPoint in the block so we will defer
306             // the insertion of the setreg to Phase 3 where we know whether or
307             // not it is actually needed.
308             NewInfo->FirstInsertionPoint = InsertionPoint;
309             NewInfo->Require = NewInfo->Change;
310             RequirePending = false;
311           } else {
312             insertSetreg(MBB, InsertionPoint, TII,
313                          IPChange.delta(NewInfo->Change));
314             IPChange = NewInfo->Change;
315           }
316           // Set the new InsertionPoint
317           InsertionPoint = &MI;
318         }
319         NewInfo->Change = NewInfo->Change.merge(InstrMode);
320       } else {
321         // No InsertionPoint is currently set - this is either the first in
322         // the block or we have previously seen an explicit setreg.
323         InsertionPoint = &MI;
324         IPChange = NewInfo->Change;
325         NewInfo->Change = NewInfo->Change.merge(InstrMode);
326       }
327     }
328   }
329   if (RequirePending) {
330     // If we haven't yet set the initial requirements for the block we set them
331     // now.
332     NewInfo->FirstInsertionPoint = InsertionPoint;
333     NewInfo->Require = NewInfo->Change;
334   } else if (InsertionPoint) {
335     // We need to insert a setreg at the InsertionPoint
336     insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
337   }
338   NewInfo->Exit = NewInfo->Change;
339   BlockInfo[MBB.getNumber()] = std::move(NewInfo);
340 }
341 
342 // In Phase 2 we revisit each block and calculate the common Mode register
343 // value provided by all predecessor blocks. If the Exit value for the block
344 // is changed, then we add the successor blocks to the worklist so that the
345 // exit value is propagated.
346 void SIModeRegister::processBlockPhase2(MachineBasicBlock &MBB,
347                                         const SIInstrInfo *TII) {
348   bool RevisitRequired = false;
349   bool ExitSet = false;
350   unsigned ThisBlock = MBB.getNumber();
351   if (MBB.pred_empty()) {
352     // There are no predecessors, so use the default starting status.
353     BlockInfo[ThisBlock]->Pred = DefaultStatus;
354     ExitSet = true;
355   } else {
356     // Build a status that is common to all the predecessors by intersecting
357     // all the predecessor exit status values.
358     // Mask bits (which represent the Mode bits with a known value) can only be
359     // added by explicit SETREG instructions or the initial default value -
360     // the intersection process may remove Mask bits.
361     // If we find a predecessor that has not yet had an exit value determined
362     // (this can happen for example if a block is its own predecessor) we defer
363     // use of that value as the Mask will be all zero, and we will revisit this
364     // block again later (unless the only predecessor without an exit value is
365     // this block).
366     MachineBasicBlock::pred_iterator P = MBB.pred_begin(), E = MBB.pred_end();
367     MachineBasicBlock &PB = *(*P);
368     unsigned PredBlock = PB.getNumber();
369     if ((ThisBlock == PredBlock) && (std::next(P) == E)) {
370       BlockInfo[ThisBlock]->Pred = DefaultStatus;
371       ExitSet = true;
372     } else if (BlockInfo[PredBlock]->ExitSet) {
373       BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
374       ExitSet = true;
375     } else if (PredBlock != ThisBlock)
376       RevisitRequired = true;
377 
378     for (P = std::next(P); P != E; P = std::next(P)) {
379       MachineBasicBlock *Pred = *P;
380       unsigned PredBlock = Pred->getNumber();
381       if (BlockInfo[PredBlock]->ExitSet) {
382         if (BlockInfo[ThisBlock]->ExitSet) {
383           BlockInfo[ThisBlock]->Pred =
384               BlockInfo[ThisBlock]->Pred.intersect(BlockInfo[PredBlock]->Exit);
385         } else {
386           BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
387         }
388         ExitSet = true;
389       } else if (PredBlock != ThisBlock)
390         RevisitRequired = true;
391     }
392   }
393   Status TmpStatus =
394       BlockInfo[ThisBlock]->Pred.merge(BlockInfo[ThisBlock]->Change);
395   if (BlockInfo[ThisBlock]->Exit != TmpStatus) {
396     BlockInfo[ThisBlock]->Exit = TmpStatus;
397     // Add the successors to the work list so we can propagate the changed exit
398     // status.
399     for (MachineBasicBlock *Succ : MBB.successors())
400       Phase2List.push(Succ);
401   }
402   BlockInfo[ThisBlock]->ExitSet = ExitSet;
403   if (RevisitRequired)
404     Phase2List.push(&MBB);
405 }
406 
407 // In Phase 3 we revisit each block and if it has an insertion point defined we
408 // check whether the predecessor mode meets the block's entry requirements. If
409 // not we insert an appropriate setreg instruction to modify the Mode register.
410 void SIModeRegister::processBlockPhase3(MachineBasicBlock &MBB,
411                                         const SIInstrInfo *TII) {
412   unsigned ThisBlock = MBB.getNumber();
413   if (!BlockInfo[ThisBlock]->Pred.isCompatible(BlockInfo[ThisBlock]->Require)) {
414     Status Delta =
415         BlockInfo[ThisBlock]->Pred.delta(BlockInfo[ThisBlock]->Require);
416     if (BlockInfo[ThisBlock]->FirstInsertionPoint)
417       insertSetreg(MBB, BlockInfo[ThisBlock]->FirstInsertionPoint, TII, Delta);
418     else
419       insertSetreg(MBB, &MBB.instr_front(), TII, Delta);
420   }
421 }
422 
423 bool SIModeRegister::runOnMachineFunction(MachineFunction &MF) {
424   // Constrained FP intrinsics are used to support non-default rounding modes.
425   // strictfp attribute is required to mark functions with strict FP semantics
426   // having constrained FP intrinsics. This pass fixes up operations that uses
427   // a non-default rounding mode for non-strictfp functions. But it should not
428   // assume or modify any default rounding modes in case of strictfp functions.
429   const Function &F = MF.getFunction();
430   if (F.hasFnAttribute(llvm::Attribute::StrictFP))
431     return Changed;
432   BlockInfo.resize(MF.getNumBlockIDs());
433   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
434   const SIInstrInfo *TII = ST.getInstrInfo();
435 
436   // Processing is performed in a number of phases
437 
438   // Phase 1 - determine the initial mode required by each block, and add setreg
439   // instructions for intra block requirements.
440   for (MachineBasicBlock &BB : MF)
441     processBlockPhase1(BB, TII);
442 
443   // Phase 2 - determine the exit mode from each block. We add all blocks to the
444   // list here, but will also add any that need to be revisited during Phase 2
445   // processing.
446   for (MachineBasicBlock &BB : MF)
447     Phase2List.push(&BB);
448   while (!Phase2List.empty()) {
449     processBlockPhase2(*Phase2List.front(), TII);
450     Phase2List.pop();
451   }
452 
453   // Phase 3 - add an initial setreg to each block where the required entry mode
454   // is not satisfied by the exit mode of all its predecessors.
455   for (MachineBasicBlock &BB : MF)
456     processBlockPhase3(BB, TII);
457 
458   BlockInfo.clear();
459 
460   return Changed;
461 }
462