LLVM 20.0.0git
SIModeRegister.cpp
Go to the documentation of this file.
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"
19#include "llvm/ADT/Statistic.h"
21#include <queue>
22
23#define DEBUG_TYPE "si-mode-register"
24
25STATISTIC(NumSetregInserted, "Number of setreg of mode register inserted.");
26
27using namespace llvm;
28
29struct 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
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
79class BlockData {
80public:
81 // The Status that represents the mode register settings required by the
82 // FirstInsertionPoint (if any) in this block. Calculated in Phase 1.
84
85 // The Status that represents the net changes to the Mode register made by
86 // this block, Calculated in Phase 1.
88
89 // The Status that represents the mode register settings on exit from this
90 // block. Calculated in Phase 2.
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.
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.
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
108namespace {
109
110class SIModeRegister : public MachineFunctionPass {
111public:
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
128public:
129 SIModeRegister() : MachineFunctionPass(ID) {}
130
131 bool runOnMachineFunction(MachineFunction &MF) override;
132
133 void getAnalysisUsage(AnalysisUsage &AU) const override {
134 AU.setPreservesCFG();
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
151INITIALIZE_PASS(SIModeRegister, DEBUG_TYPE,
152 "Insert required mode register values", false, false)
153
154char SIModeRegister::ID = 0;
155
156char &llvm::SIModeRegisterID = SIModeRegister::ID;
157
158FunctionPass *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.
164Status 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 switch (Opcode) {
170 case AMDGPU::V_INTERP_P1LL_F16:
171 case AMDGPU::V_INTERP_P1LV_F16:
172 case AMDGPU::V_INTERP_P2_F16:
173 // f16 interpolation instructions need double precision round to zero
174 return Status(FP_ROUND_MODE_DP(3),
176 case AMDGPU::FPTRUNC_ROUND_F16_F32_PSEUDO: {
177 unsigned Mode = MI.getOperand(2).getImm();
178 MI.removeOperand(2);
179 // Replacing the pseudo by a real instruction in place
180 if (TII->getSubtarget().hasTrue16BitInsts()) {
181 MachineBasicBlock &MBB = *MI.getParent();
183 MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_t16_e64));
184 MachineOperand Src0 = MI.getOperand(1);
185 MI.removeOperand(1);
186 B.addImm(0); // src0_modifiers
187 B.add(Src0); // re-add src0 operand
188 B.addImm(0); // clamp
189 B.addImm(0); // omod
190 } else
191 MI.setDesc(TII->get(AMDGPU::V_CVT_F16_F32_e32));
192 return Status(FP_ROUND_MODE_DP(3),
193 FP_ROUND_MODE_DP(Mode));
194 }
195 default:
196 return DefaultStatus;
197 }
198 }
199 return Status();
200}
201
202// Insert a setreg instruction to update the Mode register.
203// It is possible (though unlikely) for an instruction to require a change to
204// the value of disjoint parts of the Mode register when we don't know the
205// value of the intervening bits. In that case we need to use more than one
206// setreg instruction.
207void SIModeRegister::insertSetreg(MachineBasicBlock &MBB, MachineInstr *MI,
208 const SIInstrInfo *TII, Status InstrMode) {
209 while (InstrMode.Mask) {
210 unsigned Offset = llvm::countr_zero<unsigned>(InstrMode.Mask);
211 unsigned Width = llvm::countr_one<unsigned>(InstrMode.Mask >> Offset);
212 unsigned Value = (InstrMode.Mode >> Offset) & ((1 << Width) - 1);
213 using namespace AMDGPU::Hwreg;
214 BuildMI(MBB, MI, nullptr, TII->get(AMDGPU::S_SETREG_IMM32_B32))
215 .addImm(Value)
216 .addImm(HwregEncoding::encode(ID_MODE, Offset, Width));
217 ++NumSetregInserted;
218 Changed = true;
219 InstrMode.Mask &= ~(((1 << Width) - 1) << Offset);
220 }
221}
222
223// In Phase 1 we iterate through the instructions of the block and for each
224// instruction we get its mode usage. If the instruction uses the Mode register
225// we:
226// - update the Change status, which tracks the changes to the Mode register
227// made by this block
228// - if this instruction's requirements are compatible with the current setting
229// of the Mode register we merge the modes
230// - if it isn't compatible and an InsertionPoint isn't set, then we set the
231// InsertionPoint to the current instruction, and we remember the current
232// mode
233// - if it isn't compatible and InsertionPoint is set we insert a seteg before
234// that instruction (unless this instruction forms part of the block's
235// entry requirements in which case the insertion is deferred until Phase 3
236// when predecessor exit values are known), and move the insertion point to
237// this instruction
238// - if this is a setreg instruction we treat it as an incompatible instruction.
239// This is sub-optimal but avoids some nasty corner cases, and is expected to
240// occur very rarely.
241// - on exit we have set the Require, Change, and initial Exit modes.
242void SIModeRegister::processBlockPhase1(MachineBasicBlock &MBB,
243 const SIInstrInfo *TII) {
244 auto NewInfo = std::make_unique<BlockData>();
245 MachineInstr *InsertionPoint = nullptr;
246 // RequirePending is used to indicate whether we are collecting the initial
247 // requirements for the block, and need to defer the first InsertionPoint to
248 // Phase 3. It is set to false once we have set FirstInsertionPoint, or when
249 // we discover an explicit setreg that means this block doesn't have any
250 // initial requirements.
251 bool RequirePending = true;
252 Status IPChange;
253 for (MachineInstr &MI : MBB) {
254 Status InstrMode = getInstructionMode(MI, TII);
255 if (MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
256 MI.getOpcode() == AMDGPU::S_SETREG_B32_mode ||
257 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
258 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
259 // We preserve any explicit mode register setreg instruction we encounter,
260 // as we assume it has been inserted by a higher authority (this is
261 // likely to be a very rare occurrence).
262 unsigned Dst = TII->getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
263 using namespace AMDGPU::Hwreg;
264 auto [Id, Offset, Width] = HwregEncoding::decode(Dst);
265 if (Id != ID_MODE)
266 continue;
267
268 unsigned Mask = maskTrailingOnes<unsigned>(Width) << Offset;
269
270 // If an InsertionPoint is set we will insert a setreg there.
271 if (InsertionPoint) {
272 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
273 InsertionPoint = nullptr;
274 }
275 // If this is an immediate then we know the value being set, but if it is
276 // not an immediate then we treat the modified bits of the mode register
277 // as unknown.
278 if (MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
279 MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32_mode) {
280 unsigned Val = TII->getNamedOperand(MI, AMDGPU::OpName::imm)->getImm();
281 unsigned Mode = (Val << Offset) & Mask;
282 Status Setreg = Status(Mask, Mode);
283 // If we haven't already set the initial requirements for the block we
284 // don't need to as the requirements start from this explicit setreg.
285 RequirePending = false;
286 NewInfo->Change = NewInfo->Change.merge(Setreg);
287 } else {
288 NewInfo->Change = NewInfo->Change.mergeUnknown(Mask);
289 }
290 } else if (!NewInfo->Change.isCompatible(InstrMode)) {
291 // This instruction uses the Mode register and its requirements aren't
292 // compatible with the current mode.
293 if (InsertionPoint) {
294 // If the required mode change cannot be included in the current
295 // InsertionPoint changes, we need a setreg and start a new
296 // InsertionPoint.
297 if (!IPChange.delta(NewInfo->Change).isCombinable(InstrMode)) {
298 if (RequirePending) {
299 // This is the first insertionPoint in the block so we will defer
300 // the insertion of the setreg to Phase 3 where we know whether or
301 // not it is actually needed.
302 NewInfo->FirstInsertionPoint = InsertionPoint;
303 NewInfo->Require = NewInfo->Change;
304 RequirePending = false;
305 } else {
306 insertSetreg(MBB, InsertionPoint, TII,
307 IPChange.delta(NewInfo->Change));
308 IPChange = NewInfo->Change;
309 }
310 // Set the new InsertionPoint
311 InsertionPoint = &MI;
312 }
313 NewInfo->Change = NewInfo->Change.merge(InstrMode);
314 } else {
315 // No InsertionPoint is currently set - this is either the first in
316 // the block or we have previously seen an explicit setreg.
317 InsertionPoint = &MI;
318 IPChange = NewInfo->Change;
319 NewInfo->Change = NewInfo->Change.merge(InstrMode);
320 }
321 }
322 }
323 if (RequirePending) {
324 // If we haven't yet set the initial requirements for the block we set them
325 // now.
326 NewInfo->FirstInsertionPoint = InsertionPoint;
327 NewInfo->Require = NewInfo->Change;
328 } else if (InsertionPoint) {
329 // We need to insert a setreg at the InsertionPoint
330 insertSetreg(MBB, InsertionPoint, TII, IPChange.delta(NewInfo->Change));
331 }
332 NewInfo->Exit = NewInfo->Change;
333 BlockInfo[MBB.getNumber()] = std::move(NewInfo);
334}
335
336// In Phase 2 we revisit each block and calculate the common Mode register
337// value provided by all predecessor blocks. If the Exit value for the block
338// is changed, then we add the successor blocks to the worklist so that the
339// exit value is propagated.
340void SIModeRegister::processBlockPhase2(MachineBasicBlock &MBB,
341 const SIInstrInfo *TII) {
342 bool RevisitRequired = false;
343 bool ExitSet = false;
344 unsigned ThisBlock = MBB.getNumber();
345 if (MBB.pred_empty()) {
346 // There are no predecessors, so use the default starting status.
347 BlockInfo[ThisBlock]->Pred = DefaultStatus;
348 ExitSet = true;
349 } else {
350 // Build a status that is common to all the predecessors by intersecting
351 // all the predecessor exit status values.
352 // Mask bits (which represent the Mode bits with a known value) can only be
353 // added by explicit SETREG instructions or the initial default value -
354 // the intersection process may remove Mask bits.
355 // If we find a predecessor that has not yet had an exit value determined
356 // (this can happen for example if a block is its own predecessor) we defer
357 // use of that value as the Mask will be all zero, and we will revisit this
358 // block again later (unless the only predecessor without an exit value is
359 // this block).
361 MachineBasicBlock &PB = *(*P);
362 unsigned PredBlock = PB.getNumber();
363 if ((ThisBlock == PredBlock) && (std::next(P) == E)) {
364 BlockInfo[ThisBlock]->Pred = DefaultStatus;
365 ExitSet = true;
366 } else if (BlockInfo[PredBlock]->ExitSet) {
367 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
368 ExitSet = true;
369 } else if (PredBlock != ThisBlock)
370 RevisitRequired = true;
371
372 for (P = std::next(P); P != E; P = std::next(P)) {
373 MachineBasicBlock *Pred = *P;
374 unsigned PredBlock = Pred->getNumber();
375 if (BlockInfo[PredBlock]->ExitSet) {
376 if (BlockInfo[ThisBlock]->ExitSet) {
377 BlockInfo[ThisBlock]->Pred =
378 BlockInfo[ThisBlock]->Pred.intersect(BlockInfo[PredBlock]->Exit);
379 } else {
380 BlockInfo[ThisBlock]->Pred = BlockInfo[PredBlock]->Exit;
381 }
382 ExitSet = true;
383 } else if (PredBlock != ThisBlock)
384 RevisitRequired = true;
385 }
386 }
387 Status TmpStatus =
388 BlockInfo[ThisBlock]->Pred.merge(BlockInfo[ThisBlock]->Change);
389 if (BlockInfo[ThisBlock]->Exit != TmpStatus) {
390 BlockInfo[ThisBlock]->Exit = TmpStatus;
391 // Add the successors to the work list so we can propagate the changed exit
392 // status.
393 for (MachineBasicBlock *Succ : MBB.successors())
394 Phase2List.push(Succ);
395 }
396 BlockInfo[ThisBlock]->ExitSet = ExitSet;
397 if (RevisitRequired)
398 Phase2List.push(&MBB);
399}
400
401// In Phase 3 we revisit each block and if it has an insertion point defined we
402// check whether the predecessor mode meets the block's entry requirements. If
403// not we insert an appropriate setreg instruction to modify the Mode register.
404void SIModeRegister::processBlockPhase3(MachineBasicBlock &MBB,
405 const SIInstrInfo *TII) {
406 unsigned ThisBlock = MBB.getNumber();
407 if (!BlockInfo[ThisBlock]->Pred.isCompatible(BlockInfo[ThisBlock]->Require)) {
408 Status Delta =
409 BlockInfo[ThisBlock]->Pred.delta(BlockInfo[ThisBlock]->Require);
410 if (BlockInfo[ThisBlock]->FirstInsertionPoint)
411 insertSetreg(MBB, BlockInfo[ThisBlock]->FirstInsertionPoint, TII, Delta);
412 else
413 insertSetreg(MBB, &MBB.instr_front(), TII, Delta);
414 }
415}
416
417bool SIModeRegister::runOnMachineFunction(MachineFunction &MF) {
418 // Constrained FP intrinsics are used to support non-default rounding modes.
419 // strictfp attribute is required to mark functions with strict FP semantics
420 // having constrained FP intrinsics. This pass fixes up operations that uses
421 // a non-default rounding mode for non-strictfp functions. But it should not
422 // assume or modify any default rounding modes in case of strictfp functions.
423 const Function &F = MF.getFunction();
424 if (F.hasFnAttribute(llvm::Attribute::StrictFP))
425 return Changed;
426 BlockInfo.resize(MF.getNumBlockIDs());
428 const SIInstrInfo *TII = ST.getInstrInfo();
429
430 // Processing is performed in a number of phases
431
432 // Phase 1 - determine the initial mode required by each block, and add setreg
433 // instructions for intra block requirements.
434 for (MachineBasicBlock &BB : MF)
435 processBlockPhase1(BB, TII);
436
437 // Phase 2 - determine the exit mode from each block. We add all blocks to the
438 // list here, but will also add any that need to be revisited during Phase 2
439 // processing.
440 for (MachineBasicBlock &BB : MF)
441 Phase2List.push(&BB);
442 while (!Phase2List.empty()) {
443 processBlockPhase2(*Phase2List.front(), TII);
444 Phase2List.pop();
445 }
446
447 // Phase 3 - add an initial setreg to each block where the required entry mode
448 // is not satisfied by the exit mode of all its predecessors.
449 for (MachineBasicBlock &BB : MF)
450 processBlockPhase3(BB, TII);
451
452 BlockInfo.clear();
453
454 return Changed;
455}
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
#define FP_ROUND_MODE_DP(x)
Definition: SIDefines.h:1167
#define FP_ROUND_ROUND_TO_NEAREST
Definition: SIDefines.h:1159
#define FP_ROUND_ROUND_TO_ZERO
Definition: SIDefines.h:1162
#define DEBUG_TYPE
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
BlockData()=default
MachineInstr * FirstInsertionPoint
Status Require
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
MachineInstr & instr_front()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineOperand class - Representation of each machine instruction operand.
LLVM Value Representation.
Definition: Value.h:74
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createSIModeRegisterPass()
char & SIModeRegisterID
Status delta(const Status &S) const
Status(unsigned NewMask, unsigned NewMode)
bool isCombinable(Status &S)
bool operator==(const Status &S) const
Status()=default
bool isCompatible(Status &S)
Status merge(const Status &S) const
Status intersect(const Status &S) const
bool operator!=(const Status &S) const
unsigned Mask
unsigned Mode
Status mergeUnknown(unsigned newMask)