LLVM 24.0.0git
SIWholeQuadMode.cpp
Go to the documentation of this file.
1//===-- SIWholeQuadMode.cpp - enter and suspend whole quad mode -----------===//
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 adds instructions to enable whole quad mode (strict or non-strict)
11/// for pixel shaders, and strict whole wavefront mode for all programs.
12///
13/// The "strict" prefix indicates that inactive lanes do not take part in
14/// control flow, specifically an inactive lane enabled by a strict WQM/WWM will
15/// always be enabled irrespective of control flow decisions. Conversely in
16/// non-strict WQM inactive lanes may control flow decisions.
17///
18/// Whole quad mode is required for derivative computations, but it interferes
19/// with shader side effects (stores and atomics). It ensures that WQM is
20/// enabled when necessary, but disabled around stores and atomics.
21///
22/// When necessary, this pass creates a function prolog
23///
24/// S_MOV_B64 LiveMask, EXEC
25/// S_WQM_B64 EXEC, EXEC
26///
27/// to enter WQM at the top of the function and surrounds blocks of Exact
28/// instructions by
29///
30/// S_AND_SAVEEXEC_B64 Tmp, LiveMask
31/// ...
32/// S_MOV_B64 EXEC, Tmp
33///
34/// We also compute when a sequence of instructions requires strict whole
35/// wavefront mode (StrictWWM) and insert instructions to save and restore it:
36///
37/// S_OR_SAVEEXEC_B64 Tmp, -1
38/// ...
39/// S_MOV_B64 EXEC, Tmp
40///
41/// When a sequence of instructions requires strict whole quad mode (StrictWQM)
42/// we use a similar save and restore mechanism and force whole quad mode for
43/// those instructions:
44///
45/// S_MOV_B64 Tmp, EXEC
46/// S_WQM_B64 EXEC, EXEC
47/// ...
48/// S_MOV_B64 EXEC, Tmp
49///
50/// In order to avoid excessive switching during sequences of Exact
51/// instructions, the pass first analyzes which instructions must be run in WQM
52/// (aka which instructions produce values that lead to derivative
53/// computations).
54///
55/// Basic blocks are always exited in WQM as long as some successor needs WQM.
56///
57/// There is room for improvement given better control flow analysis:
58///
59/// (1) at the top level (outside of control flow statements, and as long as
60/// kill hasn't been used), one SGPR can be saved by recovering WQM from
61/// the LiveMask (this is implemented for the entry block).
62///
63/// (2) when entire regions (e.g. if-else blocks or entire loops) only
64/// consist of exact and don't-care instructions, the switch only has to
65/// be done at the entry and exit points rather than potentially in each
66/// block of the region.
67///
68//===----------------------------------------------------------------------===//
69
70#include "SIWholeQuadMode.h"
71#include "AMDGPU.h"
72#include "AMDGPULaneMaskUtils.h"
73#include "GCNSubtarget.h"
81#include "llvm/IR/CallingConv.h"
84
85using namespace llvm;
86
87#define DEBUG_TYPE "si-wqm"
88
89namespace {
90
91enum {
92 StateWQM = 0x1,
93 StateStrictWWM = 0x2,
94 StateStrictWQM = 0x4,
95 StateExact = 0x8,
96 StateStrict = StateStrictWWM | StateStrictWQM,
97};
98
99struct PrintState {
100public:
101 int State;
102
103 explicit PrintState(int State) : State(State) {}
104};
105
106#ifndef NDEBUG
107static raw_ostream &operator<<(raw_ostream &OS, const PrintState &PS) {
108
109 static const std::pair<char, const char *> Mapping[] = {
110 std::pair(StateWQM, "WQM"), std::pair(StateStrictWWM, "StrictWWM"),
111 std::pair(StateStrictWQM, "StrictWQM"), std::pair(StateExact, "Exact")};
112 char State = PS.State;
113 for (auto M : Mapping) {
114 if (State & M.first) {
115 OS << M.second;
116 State &= ~M.first;
117
118 if (State)
119 OS << '|';
120 }
121 }
122 assert(State == 0);
123 return OS;
124}
125#endif
126
127struct InstrInfo {
128 char Needs = 0;
129 char Disabled = 0;
130 char OutNeeds = 0;
131 char MarkedStates = 0;
132};
133
134struct BlockInfo {
135 char Needs = 0;
136 char InNeeds = 0;
137 char OutNeeds = 0;
138 char InitialState = 0;
139 bool NeedsLowering = false;
140};
141
142struct WorkItem {
143 MachineBasicBlock *MBB = nullptr;
144 MachineInstr *MI = nullptr;
145
146 WorkItem() = default;
149};
150
151class SIWholeQuadMode {
152public:
153 SIWholeQuadMode(MachineFunction &MF, LiveIntervals *LIS,
155 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
156 TRI(&TII->getRegisterInfo()), MRI(&MF.getRegInfo()), LIS(LIS), MDT(MDT),
157 PDT(PDT), LMC(AMDGPU::LaneMaskConstants::get(*ST)) {}
158 bool run(MachineFunction &MF);
159
160private:
161 const GCNSubtarget *ST;
162 const SIInstrInfo *TII;
163 const SIRegisterInfo *TRI;
165 LiveIntervals *LIS;
168 const AMDGPU::LaneMaskConstants &LMC;
169
170 Register LiveMaskReg;
171
174
175 // Tracks state (WQM/StrictWWM/StrictWQM/Exact) after a given instruction
177
178 SmallVector<MachineInstr *, 2> LiveMaskQueries;
179 SmallVector<MachineInstr *, 4> LowerToMovInstrs;
180 SmallSetVector<MachineInstr *, 4> LowerToCopyInstrs;
182 SmallVector<MachineInstr *, 4> InitExecInstrs;
183 SmallVector<MachineInstr *, 4> SetInactiveInstrs;
184
185 void printInfo();
186
187 void markInstruction(MachineInstr &MI, char Flag,
188 std::vector<WorkItem> &Worklist);
189 void markDefs(const MachineInstr &UseMI, LiveRange &LR,
190 VirtRegOrUnit VRegOrUnit, unsigned SubReg, char Flag,
191 std::vector<WorkItem> &Worklist);
192 void markOperand(const MachineInstr &MI, const MachineOperand &Op, char Flag,
193 std::vector<WorkItem> &Worklist);
194 void markInstructionUses(const MachineInstr &MI, char Flag,
195 std::vector<WorkItem> &Worklist);
196 char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist,
197 SmallVector<MachineInstr *> &ExeczSideEffectInstrs);
198 void propagateInstruction(MachineInstr &MI, std::vector<WorkItem> &Worklist);
199 void propagateBlock(MachineBasicBlock &MBB, std::vector<WorkItem> &Worklist);
201
206 MachineBasicBlock::iterator Last, bool PreferLast,
207 bool SaveSCC);
209 Register SaveWQM);
211 Register SavedWQM);
212 void toStrictMode(MachineBasicBlock &MBB, MachineBasicBlock::iterator Before,
213 Register SaveOrig, char StrictStateNeeded);
214 void fromStrictMode(MachineBasicBlock &MBB,
215 MachineBasicBlock::iterator Before, Register SavedOrig,
216 char NonStrictState, char CurrentStrictState);
217
218 void splitBlock(MachineInstr *TermMI);
219 MachineInstr *lowerKillI1(MachineInstr &MI, bool IsWQM);
220 MachineInstr *lowerKillF32(MachineInstr &MI);
221
222 void lowerBlock(MachineBasicBlock &MBB, BlockInfo &BI);
223 void processBlock(MachineBasicBlock &MBB, BlockInfo &BI, bool IsEntry);
224
225 bool lowerLiveMaskQueries();
226 bool lowerCopyInstrs();
227 bool lowerKillInstrs(bool IsWQM);
228 void lowerInitExec(MachineInstr &MI);
229 MachineBasicBlock::iterator lowerInitExecInstrs(MachineBasicBlock &Entry,
230 bool &Changed);
231};
232
233class SIWholeQuadModeLegacy : public MachineFunctionPass {
234public:
235 static char ID;
236
237 SIWholeQuadModeLegacy() : MachineFunctionPass(ID) {}
238
239 bool runOnMachineFunction(MachineFunction &MF) override;
240
241 StringRef getPassName() const override { return "SI Whole Quad Mode"; }
242
243 void getAnalysisUsage(AnalysisUsage &AU) const override {
250 }
251
252 MachineFunctionProperties getClearedProperties() const override {
253 return MachineFunctionProperties().setIsSSA();
254 }
255};
256} // end anonymous namespace
257
258char SIWholeQuadModeLegacy::ID = 0;
259
260INITIALIZE_PASS_BEGIN(SIWholeQuadModeLegacy, DEBUG_TYPE, "SI Whole Quad Mode",
261 false, false)
265INITIALIZE_PASS_END(SIWholeQuadModeLegacy, DEBUG_TYPE, "SI Whole Quad Mode",
267
268char &llvm::SIWholeQuadModeID = SIWholeQuadModeLegacy::ID;
269
271 return new SIWholeQuadModeLegacy;
272}
273
274#ifndef NDEBUG
275LLVM_DUMP_METHOD void SIWholeQuadMode::printInfo() {
276 for (const auto &BII : Blocks) {
277 dbgs() << "\n"
278 << printMBBReference(*BII.first) << ":\n"
279 << " InNeeds = " << PrintState(BII.second.InNeeds)
280 << ", Needs = " << PrintState(BII.second.Needs)
281 << ", OutNeeds = " << PrintState(BII.second.OutNeeds) << "\n\n";
282
283 for (const MachineInstr &MI : *BII.first) {
284 auto III = Instructions.find(&MI);
285 if (III != Instructions.end()) {
286 dbgs() << " " << MI << " Needs = " << PrintState(III->second.Needs)
287 << ", OutNeeds = " << PrintState(III->second.OutNeeds) << '\n';
288 }
289 }
290 }
291}
292#endif
293
294void SIWholeQuadMode::markInstruction(MachineInstr &MI, char Flag,
295 std::vector<WorkItem> &Worklist) {
296 InstrInfo &II = Instructions[&MI];
297
298 assert(!(Flag & StateExact) && Flag != 0);
299
300 // Capture all states requested in marking including disabled ones.
301 II.MarkedStates |= Flag;
302
303 // Remove any disabled states from the flag. The user that required it gets
304 // an undefined value in the helper lanes. For example, this can happen if
305 // the result of an atomic is used by instruction that requires WQM, where
306 // ignoring the request for WQM is correct as per the relevant specs.
307 Flag &= ~II.Disabled;
308
309 // Ignore if the flag is already encompassed by the existing needs, or we
310 // just disabled everything.
311 if ((II.Needs & Flag) == Flag)
312 return;
313
314 LLVM_DEBUG(dbgs() << "markInstruction " << PrintState(Flag) << ": " << MI);
315 II.Needs |= Flag;
316 Worklist.emplace_back(&MI);
317}
318
319/// Mark all relevant definitions of register \p Reg in usage \p UseMI.
320void SIWholeQuadMode::markDefs(const MachineInstr &UseMI, LiveRange &LR,
321 VirtRegOrUnit VRegOrUnit, unsigned SubReg,
322 char Flag, std::vector<WorkItem> &Worklist) {
323 LLVM_DEBUG(dbgs() << "markDefs " << PrintState(Flag) << ": " << UseMI);
324
325 LiveQueryResult UseLRQ = LR.Query(LIS->getInstructionIndex(UseMI));
326 const VNInfo *Value = UseLRQ.valueIn();
327 if (!Value)
328 return;
329
330 // Note: this code assumes that lane masks on AMDGPU completely
331 // cover registers.
332 const LaneBitmask UseLanes =
333 SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
334 : (VRegOrUnit.isVirtualReg()
335 ? MRI->getMaxLaneMaskForVReg(VRegOrUnit.asVirtualReg())
337
338 // Perform a depth-first iteration of the LiveRange graph marking defs.
339 // Stop processing of a given branch when all use lanes have been defined.
340 // The first definition stops processing for a physical register.
341 struct PhiEntry {
342 const VNInfo *Phi;
343 unsigned PredIdx;
344 LaneBitmask DefinedLanes;
345
346 PhiEntry(const VNInfo *Phi, unsigned PredIdx, LaneBitmask DefinedLanes)
347 : Phi(Phi), PredIdx(PredIdx), DefinedLanes(DefinedLanes) {}
348 };
349 using VisitKey = std::pair<const VNInfo *, LaneBitmask>;
351 SmallSet<VisitKey, 4> Visited;
352 LaneBitmask DefinedLanes;
353 unsigned NextPredIdx = 0; // Only used for processing phi nodes
354 do {
355 const VNInfo *NextValue = nullptr;
356 const VisitKey Key(Value, DefinedLanes);
357
358 if (Visited.insert(Key).second) {
359 // On first visit to a phi then start processing first predecessor
360 NextPredIdx = 0;
361 }
362
363 if (Value->isPHIDef()) {
364 // Each predecessor node in the phi must be processed as a subgraph
365 const MachineBasicBlock *MBB = LIS->getMBBFromIndex(Value->def);
366 assert(MBB && "Phi-def has no defining MBB");
367
368 // Find next predecessor to process
369 unsigned Idx = NextPredIdx;
370 const auto *PI = MBB->pred_begin() + Idx;
371 const auto *PE = MBB->pred_end();
372 for (; PI != PE && !NextValue; ++PI, ++Idx) {
373 if (const VNInfo *VN = LR.getVNInfoBefore(LIS->getMBBEndIdx(*PI))) {
374 if (!Visited.count(VisitKey(VN, DefinedLanes)))
375 NextValue = VN;
376 }
377 }
378
379 // If there are more predecessors to process; add phi to stack
380 if (PI != PE)
381 PhiStack.emplace_back(Value, Idx, DefinedLanes);
382 } else {
383 MachineInstr *MI = LIS->getInstructionFromIndex(Value->def);
384 assert(MI && "Def has no defining instruction");
385
386 if (VRegOrUnit.isVirtualReg()) {
387 // Iterate over all operands to find relevant definitions
388 bool HasDef = false;
389 for (const MachineOperand &Op : MI->all_defs()) {
390 if (Op.getReg() != VRegOrUnit.asVirtualReg())
391 continue;
392
393 // Compute lanes defined and overlap with use
394 LaneBitmask OpLanes =
395 Op.isUndef() ? LaneBitmask::getAll()
396 : TRI->getSubRegIndexLaneMask(Op.getSubReg());
397 LaneBitmask Overlap = (UseLanes & OpLanes);
398
399 // Record if this instruction defined any of use
400 HasDef |= Overlap.any();
401
402 // Mark any lanes defined
403 DefinedLanes |= OpLanes;
404 }
405
406 // Check if all lanes of use have been defined
407 if ((DefinedLanes & UseLanes) != UseLanes) {
408 // Definition not complete; need to process input value
409 LiveQueryResult LRQ = LR.Query(LIS->getInstructionIndex(*MI));
410 if (const VNInfo *VN = LRQ.valueIn()) {
411 if (!Visited.count(VisitKey(VN, DefinedLanes)))
412 NextValue = VN;
413 }
414 }
415
416 // Only mark the instruction if it defines some part of the use
417 if (HasDef)
418 markInstruction(*MI, Flag, Worklist);
419 } else {
420 // For physical registers simply mark the defining instruction
421 markInstruction(*MI, Flag, Worklist);
422 }
423 }
424
425 if (!NextValue && !PhiStack.empty()) {
426 // Reach end of chain; revert to processing last phi
427 PhiEntry &Entry = PhiStack.back();
428 NextValue = Entry.Phi;
429 NextPredIdx = Entry.PredIdx;
430 DefinedLanes = Entry.DefinedLanes;
431 PhiStack.pop_back();
432 }
433
434 Value = NextValue;
435 } while (Value);
436}
437
438void SIWholeQuadMode::markOperand(const MachineInstr &MI,
439 const MachineOperand &Op, char Flag,
440 std::vector<WorkItem> &Worklist) {
441 assert(Op.isReg());
442 Register Reg = Op.getReg();
443
444 // Ignore some hardware registers
445 switch (Reg) {
446 case AMDGPU::EXEC:
447 case AMDGPU::EXEC_LO:
448 return;
449 default:
450 break;
451 }
452
453 LLVM_DEBUG(dbgs() << "markOperand " << PrintState(Flag) << ": " << Op
454 << " for " << MI);
455 if (Reg.isVirtual()) {
456 LiveRange &LR = LIS->getInterval(Reg);
457 markDefs(MI, LR, VirtRegOrUnit(Reg), Op.getSubReg(), Flag, Worklist);
458 } else {
459 // Handle physical registers that we need to track; this is mostly relevant
460 // for VCC, which can appear as the (implicit) input of a uniform branch,
461 // e.g. when a loop counter is stored in a VGPR.
462 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
463 LiveRange &LR = LIS->getRegUnit(Unit);
464 const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
465 if (Value)
466 markDefs(MI, LR, VirtRegOrUnit(Unit), AMDGPU::NoSubRegister, Flag,
467 Worklist);
468 }
469 }
470}
471
472/// Mark all instructions defining the uses in \p MI with \p Flag.
473void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
474 std::vector<WorkItem> &Worklist) {
475 LLVM_DEBUG(dbgs() << "markInstructionUses " << PrintState(Flag) << ": "
476 << MI);
477
478 for (const MachineOperand &Use : MI.all_uses())
479 markOperand(MI, Use, Flag, Worklist);
480}
481
482// Scan instructions to determine which ones require an Exact execmask and
483// which ones seed WQM requirements.
484char SIWholeQuadMode::scanInstructions(
485 MachineFunction &MF, std::vector<WorkItem> &Worklist,
486 SmallVector<MachineInstr *> &ExeczSideEffectInstrs) {
487 char GlobalFlags = 0;
488 bool WQMOutputs = MF.getFunction().hasFnAttribute("amdgpu-ps-wqm-outputs");
489 SmallVector<MachineInstr *, 4> SoftWQMInstrs;
490 bool HasImplicitDerivatives =
491 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
492
493 // We need to visit the basic blocks in reverse post-order so that we visit
494 // defs before uses, in particular so that we don't accidentally mark an
495 // instruction as needing e.g. WQM before visiting it and realizing it needs
496 // WQM disabled.
497 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
498 for (MachineBasicBlock *MBB : RPOT) {
499 BlockInfo &BBI = Blocks[MBB];
500
501 for (MachineInstr &MI : *MBB) {
502 InstrInfo &III = Instructions[&MI];
503 unsigned Opcode = MI.getOpcode();
504 char Flags = 0;
505
506 if (TII->isWQM(Opcode)) {
507 // If LOD is not supported WQM is not needed.
508 // Only generate implicit WQM if implicit derivatives are required.
509 // This avoids inserting unintended WQM if a shader type without
510 // implicit derivatives uses an image sampling instruction.
511 if (ST->hasExtendedImageInsts() && HasImplicitDerivatives) {
512 // Sampling instructions don't need to produce results for all pixels
513 // in a quad, they just require all inputs of a quad to have been
514 // computed for derivatives.
515 markInstructionUses(MI, StateWQM, Worklist);
516 GlobalFlags |= StateWQM;
517 }
518 } else if (Opcode == AMDGPU::WQM) {
519 // The WQM intrinsic requires its output to have all the helper lanes
520 // correct, so we need it to be in WQM.
521 Flags = StateWQM;
522 LowerToCopyInstrs.insert(&MI);
523 } else if (Opcode == AMDGPU::SOFT_WQM) {
524 LowerToCopyInstrs.insert(&MI);
525 SoftWQMInstrs.push_back(&MI);
526 } else if (Opcode == AMDGPU::STRICT_WWM) {
527 // The STRICT_WWM intrinsic doesn't make the same guarantee, and plus
528 // it needs to be executed in WQM or Exact so that its copy doesn't
529 // clobber inactive lanes.
530 markInstructionUses(MI, StateStrictWWM, Worklist);
531 GlobalFlags |= StateStrictWWM;
532 LowerToMovInstrs.push_back(&MI);
533 } else if (Opcode == AMDGPU::STRICT_WQM ||
534 TII->isDualSourceBlendEXP(MI)) {
535 // STRICT_WQM is similar to STRICTWWM, but instead of enabling all
536 // threads of the wave like STRICTWWM, STRICT_WQM enables all threads in
537 // quads that have at least one active thread.
538 markInstructionUses(MI, StateStrictWQM, Worklist);
539 GlobalFlags |= StateStrictWQM;
540
541 if (Opcode == AMDGPU::STRICT_WQM) {
542 LowerToMovInstrs.push_back(&MI);
543 } else {
544 // Dual source blend export acts as implicit strict-wqm, its sources
545 // need to be shuffled in strict wqm, but the export itself needs to
546 // run in exact mode.
547 BBI.Needs |= StateExact;
548 if (!(BBI.InNeeds & StateExact)) {
549 BBI.InNeeds |= StateExact;
550 Worklist.emplace_back(MBB);
551 }
552 GlobalFlags |= StateExact;
553 III.Disabled = StateWQM | StateStrict;
554 }
555 } else if (Opcode == AMDGPU::LDS_PARAM_LOAD ||
556 Opcode == AMDGPU::DS_PARAM_LOAD ||
557 Opcode == AMDGPU::LDS_DIRECT_LOAD ||
558 Opcode == AMDGPU::DS_DIRECT_LOAD) {
559 // Mark these STRICTWQM, but only for the instruction, not its operands.
560 // This avoid unnecessarily marking M0 as requiring WQM.
561 III.Needs |= StateStrictWQM;
562 GlobalFlags |= StateStrictWQM;
563 } else if (Opcode == AMDGPU::V_SET_INACTIVE_B32) {
564 // Disable strict states; StrictWQM will be added as required later.
565 III.Disabled = StateStrict;
566 MachineOperand &Inactive = MI.getOperand(4);
567 if (Inactive.isReg()) {
568 if (Inactive.isUndef() && MI.getOperand(3).getImm() == 0)
569 LowerToCopyInstrs.insert(&MI);
570 else
571 markOperand(MI, Inactive, StateStrictWWM, Worklist);
572 }
573 SetInactiveInstrs.push_back(&MI);
574 BBI.NeedsLowering = true;
575 } else if (TII->isDisableWQM(MI)) {
576 BBI.Needs |= StateExact;
577 if (!(BBI.InNeeds & StateExact)) {
578 BBI.InNeeds |= StateExact;
579 Worklist.emplace_back(MBB);
580 }
581 GlobalFlags |= StateExact;
582 III.Disabled = StateWQM | StateStrict;
583 } else if (Opcode == AMDGPU::SI_PS_LIVE ||
584 Opcode == AMDGPU::SI_LIVE_MASK) {
585 LiveMaskQueries.push_back(&MI);
586 } else if (Opcode == AMDGPU::SI_KILL_I1_TERMINATOR ||
587 Opcode == AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR ||
588 Opcode == AMDGPU::SI_DEMOTE_I1) {
589 KillInstrs.push_back(&MI);
590 BBI.NeedsLowering = true;
591 } else if (Opcode == AMDGPU::SI_INIT_EXEC ||
592 Opcode == AMDGPU::SI_INIT_EXEC_FROM_INPUT ||
593 Opcode == AMDGPU::SI_INIT_WHOLE_WAVE) {
594 InitExecInstrs.push_back(&MI);
595 } else if (WQMOutputs) {
596 // The function is in machine SSA form, which means that physical
597 // VGPRs correspond to shader inputs and outputs. Inputs are
598 // only used, outputs are only defined.
599 // FIXME: is this still valid?
600 for (const MachineOperand &MO : MI.defs()) {
601 Register Reg = MO.getReg();
602 if (Reg.isPhysical() &&
603 TRI->hasVectorRegisters(TRI->getPhysRegBaseClass(Reg))) {
604 Flags = StateWQM;
605 break;
606 }
607 }
608 }
609
610 if (TII->hasUnwantedEffectsWhenEXECEmpty(MI)) {
611 for (auto &Op : MI.uses()) {
612 if (!Op.isReg())
613 continue;
614 if (!TRI->isVectorRegister(*MRI, Op.getReg()))
615 continue;
616
617 ExeczSideEffectInstrs.push_back(&MI);
618 break;
619 }
620 }
621
622 if (Flags) {
623 markInstruction(MI, Flags, Worklist);
624 GlobalFlags |= Flags;
625 }
626 }
627 }
628
629 // Mark sure that any SET_INACTIVE instructions are computed in WQM if WQM is
630 // ever used anywhere in the function. This implements the corresponding
631 // semantics of @llvm.amdgcn.set.inactive.
632 // Similarly for SOFT_WQM instructions, implementing @llvm.amdgcn.softwqm.
633 if (GlobalFlags & StateWQM) {
634 for (MachineInstr *MI : SetInactiveInstrs)
635 markInstruction(*MI, StateWQM, Worklist);
636 for (MachineInstr *MI : SoftWQMInstrs)
637 markInstruction(*MI, StateWQM, Worklist);
638 }
639
640 return GlobalFlags;
641}
642
643void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
644 std::vector<WorkItem>& Worklist) {
645 MachineBasicBlock *MBB = MI.getParent();
646 InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
647 BlockInfo &BI = Blocks[MBB];
648
649 // Control flow-type instructions and stores to temporary memory that are
650 // followed by WQM computations must themselves be in WQM.
651 if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
652 (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
653 Instructions[&MI].Needs = StateWQM;
654 II.Needs = StateWQM;
655 }
656
657 // Propagate to block level
658 if (II.Needs & StateWQM) {
659 BI.Needs |= StateWQM;
660 if (!(BI.InNeeds & StateWQM)) {
661 BI.InNeeds |= StateWQM;
662 Worklist.emplace_back(MBB);
663 }
664 }
665
666 // Propagate backwards within block
667 if (MachineInstr *PrevMI = MI.getPrevNode()) {
668 char InNeeds = (II.Needs & ~StateStrict) | II.OutNeeds;
669 if (!PrevMI->isPHI()) {
670 InstrInfo &PrevII = Instructions[PrevMI];
671 if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
672 PrevII.OutNeeds |= InNeeds;
673 Worklist.emplace_back(PrevMI);
674 }
675 }
676 }
677
678 // Propagate WQM flag to instruction inputs
679 assert(!(II.Needs & StateExact));
680
681 if (II.Needs != 0)
682 markInstructionUses(MI, II.Needs, Worklist);
683
684 // Ensure we process a block containing StrictWWM/StrictWQM, even if it does
685 // not require any WQM transitions.
686 if (II.Needs & StateStrictWWM)
687 BI.Needs |= StateStrictWWM;
688 if (II.Needs & StateStrictWQM)
689 BI.Needs |= StateStrictWQM;
690}
691
692void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
693 std::vector<WorkItem>& Worklist) {
694 BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
695
696 // Propagate through instructions
697 if (!MBB.empty()) {
698 MachineInstr *LastMI = &*MBB.rbegin();
699 InstrInfo &LastII = Instructions[LastMI];
700 if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
701 LastII.OutNeeds |= BI.OutNeeds;
702 Worklist.emplace_back(LastMI);
703 }
704 }
705
706 // Predecessor blocks must provide for our WQM/Exact needs.
707 for (MachineBasicBlock *Pred : MBB.predecessors()) {
708 BlockInfo &PredBI = Blocks[Pred];
709 if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
710 continue;
711
712 PredBI.OutNeeds |= BI.InNeeds;
713 PredBI.InNeeds |= BI.InNeeds;
714 Worklist.emplace_back(Pred);
715 }
716
717 // All successors must be prepared to accept the same set of WQM/Exact data.
718 for (MachineBasicBlock *Succ : MBB.successors()) {
719 BlockInfo &SuccBI = Blocks[Succ];
720 if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
721 continue;
722
723 SuccBI.InNeeds |= BI.OutNeeds;
724 Worklist.emplace_back(Succ);
725 }
726}
727
728char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
729 std::vector<WorkItem> Worklist;
730 SmallVector<MachineInstr *> ExeczSideEffectInstrs;
731 char GlobalFlags = scanInstructions(MF, Worklist, ExeczSideEffectInstrs);
732
733 while (!Worklist.empty()) {
734 WorkItem WI = Worklist.back();
735 Worklist.pop_back();
736
737 if (WI.MI)
738 propagateInstruction(*WI.MI, Worklist);
739 else
740 propagateBlock(*WI.MBB, Worklist);
741
742 if (Worklist.empty()) {
743 // Currently we let the instructions having sideeffect when execz to run
744 // under wqm, this avoids unwanted side-effect with exact mode if only
745 // helper lanes execute the parent block. At the same time, the wqm
746 // property should be back-propagated along the data-flow of their sources
747 // to ensure their sources have correct data for helper lanes.
748 for (auto *MI : ExeczSideEffectInstrs) {
749 InstrInfo II = Instructions[MI];
750 if (II.OutNeeds & StateWQM)
751 markInstructionUses(*MI, StateWQM, Worklist);
752 }
753 // The side-effect backward propagation should not expand the wqm-region.
754 // So we only need to run the propagation once.
755 ExeczSideEffectInstrs.clear();
756 }
757 }
758
759 return GlobalFlags;
760}
761
763SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
765 Register SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
766
767 MachineInstr *Save =
768 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
769 .addReg(AMDGPU::SCC);
770 MachineInstr *Restore =
771 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
772 .addReg(SaveReg);
773
774 LIS->InsertMachineInstrInMaps(*Save);
775 LIS->InsertMachineInstrInMaps(*Restore);
777
778 return Restore;
779}
780
781void SIWholeQuadMode::splitBlock(MachineInstr *TermMI) {
782 MachineBasicBlock *BB = TermMI->getParent();
783 LLVM_DEBUG(dbgs() << "Split block " << printMBBReference(*BB) << " @ "
784 << *TermMI << "\n");
785
786 MachineBasicBlock *SplitBB =
787 BB->splitAt(*TermMI, /*UpdateLiveIns*/ true, LIS);
788
789 // Convert last instruction in block to a terminator.
790 // Note: this only covers the expected patterns
791 unsigned NewOpcode = 0;
792 switch (TermMI->getOpcode()) {
793 case AMDGPU::S_AND_B32:
794 NewOpcode = AMDGPU::S_AND_B32_term;
795 break;
796 case AMDGPU::S_AND_B64:
797 NewOpcode = AMDGPU::S_AND_B64_term;
798 break;
799 case AMDGPU::S_MOV_B32:
800 NewOpcode = AMDGPU::S_MOV_B32_term;
801 break;
802 case AMDGPU::S_MOV_B64:
803 NewOpcode = AMDGPU::S_MOV_B64_term;
804 break;
805 case AMDGPU::S_ANDN2_B32:
806 NewOpcode = AMDGPU::S_ANDN2_B32_term;
807 break;
808 case AMDGPU::S_ANDN2_B64:
809 NewOpcode = AMDGPU::S_ANDN2_B64_term;
810 break;
811 default:
812 llvm_unreachable("Unexpected instruction");
813 }
814
815 // These terminators fallthrough to the next block, no need to add an
816 // unconditional branch to the next block (SplitBB).
817 TermMI->setDesc(TII->get(NewOpcode));
818
819 if (SplitBB != BB) {
820 // Update dominator trees
821 using DomTreeT = DomTreeBase<MachineBasicBlock>;
823 for (MachineBasicBlock *Succ : SplitBB->successors()) {
824 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
825 DTUpdates.push_back({DomTreeT::Delete, BB, Succ});
826 }
827 DTUpdates.push_back({DomTreeT::Insert, BB, SplitBB});
828 if (MDT)
829 MDT->applyUpdates(DTUpdates);
830 if (PDT)
831 PDT->applyUpdates(DTUpdates);
832 }
833}
834
835MachineInstr *SIWholeQuadMode::lowerKillF32(MachineInstr &MI) {
836 assert(LiveMaskReg.isVirtual());
837
838 const DebugLoc &DL = MI.getDebugLoc();
839 unsigned Opcode = 0;
840
841 assert(MI.getOperand(0).isReg());
842
843 // Comparison is for live lanes; however here we compute the inverse
844 // (killed lanes). This is because VCMP will always generate 0 bits
845 // for inactive lanes so a mask of live lanes would not be correct
846 // inside control flow.
847 // Invert the comparison by swapping the operands and adjusting
848 // the comparison codes.
849
850 switch (MI.getOperand(2).getImm()) {
851 case ISD::SETUEQ:
852 Opcode = AMDGPU::V_CMP_LG_F32_e64;
853 break;
854 case ISD::SETUGT:
855 Opcode = AMDGPU::V_CMP_GE_F32_e64;
856 break;
857 case ISD::SETUGE:
858 Opcode = AMDGPU::V_CMP_GT_F32_e64;
859 break;
860 case ISD::SETULT:
861 Opcode = AMDGPU::V_CMP_LE_F32_e64;
862 break;
863 case ISD::SETULE:
864 Opcode = AMDGPU::V_CMP_LT_F32_e64;
865 break;
866 case ISD::SETUNE:
867 Opcode = AMDGPU::V_CMP_EQ_F32_e64;
868 break;
869 case ISD::SETO:
870 Opcode = AMDGPU::V_CMP_O_F32_e64;
871 break;
872 case ISD::SETUO:
873 Opcode = AMDGPU::V_CMP_U_F32_e64;
874 break;
875 case ISD::SETOEQ:
876 case ISD::SETEQ:
877 Opcode = AMDGPU::V_CMP_NEQ_F32_e64;
878 break;
879 case ISD::SETOGT:
880 case ISD::SETGT:
881 Opcode = AMDGPU::V_CMP_NLT_F32_e64;
882 break;
883 case ISD::SETOGE:
884 case ISD::SETGE:
885 Opcode = AMDGPU::V_CMP_NLE_F32_e64;
886 break;
887 case ISD::SETOLT:
888 case ISD::SETLT:
889 Opcode = AMDGPU::V_CMP_NGT_F32_e64;
890 break;
891 case ISD::SETOLE:
892 case ISD::SETLE:
893 Opcode = AMDGPU::V_CMP_NGE_F32_e64;
894 break;
895 case ISD::SETONE:
896 case ISD::SETNE:
897 Opcode = AMDGPU::V_CMP_NLG_F32_e64;
898 break;
899 default:
900 llvm_unreachable("invalid ISD:SET cond code");
901 }
902
903 MachineBasicBlock &MBB = *MI.getParent();
904
905 // Pick opcode based on comparison type.
906 MachineInstr *VcmpMI;
907 const MachineOperand &Op0 = MI.getOperand(0);
908 const MachineOperand &Op1 = MI.getOperand(1);
909
910 // VCC represents lanes killed.
911 if (TRI->isVGPR(*MRI, Op0.getReg())) {
912 Opcode = AMDGPU::getVOPe32(Opcode);
913 VcmpMI = BuildMI(MBB, &MI, DL, TII->get(Opcode)).add(Op1).add(Op0);
914 } else {
915 VcmpMI = BuildMI(MBB, &MI, DL, TII->get(Opcode))
916 .addReg(LMC.VccReg, RegState::Define)
917 .addImm(0) // src0 modifiers
918 .add(Op1)
919 .addImm(0) // src1 modifiers
920 .add(Op0)
921 .addImm(0); // omod
922 }
923
924 MachineInstr *MaskUpdateMI =
925 BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
926 .addReg(LiveMaskReg)
927 .addReg(LMC.VccReg);
928
929 // State of SCC represents whether any lanes are live in mask,
930 // if SCC is 0 then no lanes will be alive anymore.
931 MachineInstr *EarlyTermMI =
932 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_EARLY_TERMINATE_SCC0));
933
934 MachineInstr *ExecMaskMI =
935 BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LMC.ExecReg)
936 .addReg(LMC.ExecReg)
937 .addReg(LMC.VccReg)
938 .setOperandDead(3);
939
940 assert(MBB.succ_size() == 1);
941
942 // Update live intervals
944
945 LIS->ReplaceMachineInstrInMaps(MI, *VcmpMI);
946 MBB.remove(&MI);
947
948 LIS->InsertMachineInstrInMaps(*MaskUpdateMI);
949 LIS->InsertMachineInstrInMaps(*EarlyTermMI);
950 LIS->InsertMachineInstrInMaps(*ExecMaskMI);
951
952 return ExecMaskMI;
953}
954
955MachineInstr *SIWholeQuadMode::lowerKillI1(MachineInstr &MI, bool IsWQM) {
956 assert(LiveMaskReg.isVirtual());
957
958 MachineBasicBlock &MBB = *MI.getParent();
959
960 const DebugLoc &DL = MI.getDebugLoc();
961 MachineInstr *MaskUpdateMI = nullptr;
962
963 const bool IsDemote = IsWQM && (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1);
964 const MachineOperand &Op = MI.getOperand(0);
965 int64_t KillVal = MI.getOperand(1).getImm();
966 MachineInstr *ComputeKilledMaskMI = nullptr;
967 Register CndReg = !Op.isImm() ? Op.getReg() : Register();
968 Register TmpReg;
969
970 // Is this a static or dynamic kill?
971 if (Op.isImm()) {
972 if (Op.getImm() == KillVal) {
973 // Static: all active lanes are killed
974 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
975 .addReg(LiveMaskReg)
976 .addReg(LMC.ExecReg);
977 } else {
978 // Static: kill does nothing
979 bool IsLastTerminator = std::next(MI.getIterator()) == MBB.end();
980 if (!IsLastTerminator) {
982 } else {
983 assert(MBB.succ_size() == 1);
984 MachineInstr *NewTerm = BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_BRANCH))
985 .addMBB(*MBB.succ_begin());
986 LIS->ReplaceMachineInstrInMaps(MI, *NewTerm);
987 }
988 MBB.remove(&MI);
989 return nullptr;
990 }
991 } else {
992 if (!KillVal) {
993 // Op represents live lanes after kill,
994 // so exec mask needs to be factored in.
995 TmpReg = MRI->createVirtualRegister(TRI->getBoolRC());
996 ComputeKilledMaskMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), TmpReg)
997 .addReg(LMC.ExecReg)
998 .add(Op)
999 .setOperandDead(3);
1000 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
1001 .addReg(LiveMaskReg)
1002 .addReg(TmpReg);
1003 } else {
1004 // Op represents lanes to kill
1005 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
1006 .addReg(LiveMaskReg)
1007 .add(Op);
1008 }
1009 }
1010
1011 // State of SCC represents whether any lanes are live in mask,
1012 // if SCC is 0 then no lanes will be alive anymore.
1013 MachineInstr *EarlyTermMI =
1014 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_EARLY_TERMINATE_SCC0));
1015
1016 // In the case we got this far some lanes are still live,
1017 // update EXEC to deactivate lanes as appropriate.
1018 MachineInstr *NewTerm;
1019 MachineInstr *WQMMaskMI = nullptr;
1020 Register LiveMaskWQM;
1021 if (IsDemote) {
1022 // Demote - deactivate quads with only helper lanes
1023 LiveMaskWQM = MRI->createVirtualRegister(TRI->getBoolRC());
1024 WQMMaskMI = BuildMI(MBB, MI, DL, TII->get(LMC.WQMOpc), LiveMaskWQM)
1025 .addReg(LiveMaskReg)
1026 .setOperandDead(2);
1027 NewTerm = BuildMI(MBB, MI, DL, TII->get(LMC.AndOpc), LMC.ExecReg)
1028 .addReg(LMC.ExecReg)
1029 .addReg(LiveMaskWQM)
1030 .setOperandDead(3);
1031 } else {
1032 // Kill - deactivate lanes no longer in live mask
1033 if (Op.isImm()) {
1034 NewTerm =
1035 BuildMI(MBB, &MI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(0);
1036 } else if (!IsWQM) {
1037 NewTerm = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), LMC.ExecReg)
1038 .addReg(LMC.ExecReg)
1039 .addReg(LiveMaskReg)
1040 .setOperandDead(3);
1041 } else {
1042 unsigned Opcode = KillVal ? LMC.AndN2Opc : LMC.AndOpc;
1043 NewTerm = BuildMI(MBB, &MI, DL, TII->get(Opcode), LMC.ExecReg)
1044 .addReg(LMC.ExecReg)
1045 .add(Op)
1046 .setOperandDead(3);
1047 }
1048 }
1049
1050 // Update live intervals
1052 MBB.remove(&MI);
1053 assert(EarlyTermMI);
1054 assert(MaskUpdateMI);
1055 assert(NewTerm);
1056 if (ComputeKilledMaskMI)
1057 LIS->InsertMachineInstrInMaps(*ComputeKilledMaskMI);
1058 LIS->InsertMachineInstrInMaps(*MaskUpdateMI);
1059 LIS->InsertMachineInstrInMaps(*EarlyTermMI);
1060 if (WQMMaskMI)
1061 LIS->InsertMachineInstrInMaps(*WQMMaskMI);
1062 LIS->InsertMachineInstrInMaps(*NewTerm);
1063
1064 if (CndReg) {
1065 LIS->removeInterval(CndReg);
1067 }
1068 if (TmpReg)
1070 if (LiveMaskWQM)
1071 LIS->createAndComputeVirtRegInterval(LiveMaskWQM);
1072
1073 return NewTerm;
1074}
1075
1076// Replace (or supplement) instructions accessing live mask.
1077// This can only happen once all the live mask registers have been created
1078// and the execute state (WQM/StrictWWM/Exact) of instructions is known.
1079void SIWholeQuadMode::lowerBlock(MachineBasicBlock &MBB, BlockInfo &BI) {
1080 if (!BI.NeedsLowering)
1081 return;
1082
1083 LLVM_DEBUG(dbgs() << "\nLowering block " << printMBBReference(MBB) << ":\n");
1084
1085 SmallVector<MachineInstr *, 4> SplitPoints;
1086 Register ActiveLanesReg = 0;
1087 char State = BI.InitialState;
1088
1089 for (MachineInstr &MI : llvm::make_early_inc_range(
1091 auto MIState = StateTransition.find(&MI);
1092 if (MIState != StateTransition.end())
1093 State = MIState->second;
1094
1095 MachineInstr *SplitPoint = nullptr;
1096 switch (MI.getOpcode()) {
1097 case AMDGPU::SI_DEMOTE_I1:
1098 case AMDGPU::SI_KILL_I1_TERMINATOR:
1099 SplitPoint = lowerKillI1(MI, State == StateWQM);
1100 break;
1101 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1102 SplitPoint = lowerKillF32(MI);
1103 break;
1104 case AMDGPU::ENTER_STRICT_WWM:
1105 ActiveLanesReg = MI.getOperand(0).getReg();
1106 break;
1107 case AMDGPU::EXIT_STRICT_WWM:
1108 ActiveLanesReg = 0;
1109 break;
1110 case AMDGPU::V_SET_INACTIVE_B32:
1111 if (ActiveLanesReg) {
1112 LiveInterval &LI = LIS->getInterval(MI.getOperand(5).getReg());
1113 MRI->constrainRegClass(ActiveLanesReg, TRI->getWaveMaskRegClass());
1114 MI.getOperand(5).setReg(ActiveLanesReg);
1115 LIS->shrinkToUses(&LI);
1116 } else {
1117 assert(State == StateExact || State == StateWQM);
1118 }
1119 break;
1120 default:
1121 break;
1122 }
1123 if (SplitPoint)
1124 SplitPoints.push_back(SplitPoint);
1125 }
1126
1127 // Perform splitting after instruction scan to simplify iteration.
1128 for (MachineInstr *MI : SplitPoints)
1129 splitBlock(MI);
1130}
1131
1132// Return an iterator in the (inclusive) range [First, Last] at which
1133// instructions can be safely inserted, keeping in mind that some of the
1134// instructions we want to add necessarily clobber SCC.
1135MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
1136 MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
1137 MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
1138 if (!SaveSCC)
1139 return PreferLast ? Last : First;
1140
1141 LiveRange &LR =
1142 LIS->getRegUnit(*TRI->regunits(MCRegister::from(AMDGPU::SCC)).begin());
1143 auto MBBE = MBB.end();
1144 // Skip debug instructions when getting slot indices, as they don't have
1145 // entries in the slot index map.
1146 auto FirstNonDbg = skipDebugInstructionsForward(First, MBBE);
1147 auto LastNonDbg = skipDebugInstructionsForward(Last, MBBE);
1148 SlotIndex FirstIdx = FirstNonDbg != MBBE
1149 ? LIS->getInstructionIndex(*FirstNonDbg)
1150 : LIS->getMBBEndIdx(&MBB);
1151 SlotIndex LastIdx = LastNonDbg != MBBE ? LIS->getInstructionIndex(*LastNonDbg)
1152 : LIS->getMBBEndIdx(&MBB);
1153 SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
1154 const LiveRange::Segment *S;
1155
1156 for (;;) {
1157 S = LR.getSegmentContaining(Idx);
1158 if (!S)
1159 break;
1160
1161 if (PreferLast) {
1162 SlotIndex Next = S->start.getBaseIndex();
1163 if (Next < FirstIdx)
1164 break;
1165 Idx = Next;
1166 } else {
1167 MachineInstr *EndMI = LIS->getInstructionFromIndex(S->end.getBaseIndex());
1168 assert(EndMI && "Segment does not end on valid instruction");
1169 auto NextI = next_nodbg(EndMI->getIterator(), MBB.instr_end());
1170 if (NextI == MBB.instr_end())
1171 break;
1172 SlotIndex Next = LIS->getInstructionIndex(*NextI);
1173 if (Next > LastIdx)
1174 break;
1175 Idx = Next;
1176 }
1177 }
1178
1180
1181 if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
1182 MBBI = MI;
1183 else {
1184 assert(Idx == LIS->getMBBEndIdx(&MBB));
1185 MBBI = MBB.end();
1186 }
1187
1188 // Move insertion point past any operations modifying EXEC.
1189 // This assumes that the value of SCC defined by any of these operations
1190 // does not need to be preserved.
1191 while (MBBI != Last) {
1192 bool IsExecDef = false;
1193 for (const MachineOperand &MO : MBBI->all_defs()) {
1194 IsExecDef |=
1195 MO.getReg() == AMDGPU::EXEC_LO || MO.getReg() == AMDGPU::EXEC;
1196 }
1197 if (!IsExecDef)
1198 break;
1199 MBBI++;
1200 S = nullptr;
1201 }
1202
1203 if (S)
1204 MBBI = saveSCC(MBB, MBBI);
1205
1206 return MBBI;
1207}
1208
1209void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
1211 Register SaveWQM) {
1212 assert(LiveMaskReg.isVirtual());
1213
1214 bool IsTerminator = Before == MBB.end();
1215 if (!IsTerminator) {
1216 auto FirstTerm = MBB.getFirstTerminator();
1217 if (FirstTerm != MBB.end()) {
1218 SlotIndex FirstTermIdx = LIS->getInstructionIndex(*FirstTerm);
1219 SlotIndex BeforeIdx = LIS->getInstructionIndex(*Before);
1220 IsTerminator = BeforeIdx > FirstTermIdx;
1221 }
1222 }
1223
1224 const DebugLoc &DL = MBB.findDebugLoc(Before);
1225 MachineInstr *MI;
1226
1227 if (SaveWQM) {
1228 unsigned Opcode =
1229 IsTerminator ? LMC.AndSaveExecTermOpc : LMC.AndSaveExecOpc;
1230 MI = BuildMI(MBB, Before, DL, TII->get(Opcode), SaveWQM)
1231 .addReg(LiveMaskReg)
1232 .setOperandDead(3);
1233 } else {
1234 unsigned Opcode = IsTerminator ? LMC.AndTermOpc : LMC.AndOpc;
1235 MI = BuildMI(MBB, Before, DL, TII->get(Opcode), LMC.ExecReg)
1236 .addReg(LMC.ExecReg)
1237 .addReg(LiveMaskReg)
1238 .setOperandDead(3);
1239 }
1240
1242 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
1243 StateTransition[MI] = StateExact;
1244}
1245
1246void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
1248 Register SavedWQM) {
1249 const DebugLoc &DL = MBB.findDebugLoc(Before);
1250 MachineInstr *MI;
1251
1252 if (SavedWQM) {
1253 MI = BuildMI(MBB, Before, DL, TII->get(AMDGPU::COPY), LMC.ExecReg)
1254 .addReg(SavedWQM);
1255 } else {
1256 MI = BuildMI(MBB, Before, DL, TII->get(LMC.WQMOpc), LMC.ExecReg)
1257 .addReg(LMC.ExecReg)
1258 .setOperandDead(2);
1259 }
1260
1262 StateTransition[MI] = StateWQM;
1263}
1264
1265void SIWholeQuadMode::toStrictMode(MachineBasicBlock &MBB,
1267 Register SaveOrig, char StrictStateNeeded) {
1268 MachineInstr *MI;
1269 assert(SaveOrig);
1270 assert(StrictStateNeeded == StateStrictWWM ||
1271 StrictStateNeeded == StateStrictWQM);
1272
1273 const DebugLoc &DL = MBB.findDebugLoc(Before);
1274
1275 if (StrictStateNeeded == StateStrictWWM) {
1276 MI = BuildMI(MBB, Before, DL, TII->get(AMDGPU::ENTER_STRICT_WWM), SaveOrig)
1277 .addImm(-1)
1278 .setOperandDead(3);
1279 } else {
1280 MI = BuildMI(MBB, Before, DL, TII->get(AMDGPU::ENTER_STRICT_WQM), SaveOrig)
1281 .addImm(-1)
1282 .setOperandDead(3);
1283 }
1285 StateTransition[MI] = StrictStateNeeded;
1286}
1287
1288void SIWholeQuadMode::fromStrictMode(MachineBasicBlock &MBB,
1290 Register SavedOrig, char NonStrictState,
1291 char CurrentStrictState) {
1292 MachineInstr *MI;
1293
1294 assert(SavedOrig);
1295 assert(CurrentStrictState == StateStrictWWM ||
1296 CurrentStrictState == StateStrictWQM);
1297
1298 const DebugLoc &DL = MBB.findDebugLoc(Before);
1299
1300 if (CurrentStrictState == StateStrictWWM) {
1301 MI =
1302 BuildMI(MBB, Before, DL, TII->get(AMDGPU::EXIT_STRICT_WWM), LMC.ExecReg)
1303 .addReg(SavedOrig);
1304 } else {
1305 MI =
1306 BuildMI(MBB, Before, DL, TII->get(AMDGPU::EXIT_STRICT_WQM), LMC.ExecReg)
1307 .addReg(SavedOrig);
1308 }
1310 StateTransition[MI] = NonStrictState;
1311}
1312
1313void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, BlockInfo &BI,
1314 bool IsEntry) {
1315 // This is a non-entry block that is WQM throughout, so no need to do
1316 // anything.
1317 if (!IsEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact) {
1318 BI.InitialState = StateWQM;
1319 return;
1320 }
1321
1322 LLVM_DEBUG(dbgs() << "\nProcessing block " << printMBBReference(MBB)
1323 << ":\n");
1324
1325 Register SavedWQMReg;
1326 Register SavedNonStrictReg;
1327 bool WQMFromExec = IsEntry;
1328 char State = (IsEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
1329 char NonStrictState = 0;
1330 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
1331
1332 auto II = MBB.getFirstNonPHI(), IE = MBB.end();
1333 if (IsEntry) {
1334 // Skip the instruction that saves LiveMask
1335 if (II != IE && II->getOpcode() == AMDGPU::COPY &&
1336 II->getOperand(1).getReg() == LMC.ExecReg)
1337 ++II;
1338 }
1339
1340 // This stores the first instruction where it's safe to switch from WQM to
1341 // Exact or vice versa.
1343
1344 // This stores the first instruction where it's safe to switch from Strict
1345 // mode to Exact/WQM or to switch to Strict mode. It must always be the same
1346 // as, or after, FirstWQM since if it's safe to switch to/from Strict, it must
1347 // be safe to switch to/from WQM as well.
1348 MachineBasicBlock::iterator FirstStrict = IE;
1349
1350 // Record initial state is block information.
1351 BI.InitialState = State;
1352
1353 for (unsigned Idx = 0;; ++Idx) {
1355 char Needs = StateExact | StateWQM; // Strict mode is disabled by default.
1356 char OutNeeds = 0;
1357
1358 if (FirstWQM == IE)
1359 FirstWQM = II;
1360
1361 if (FirstStrict == IE)
1362 FirstStrict = II;
1363
1364 // Adjust needs if this is first instruction of WQM requiring shader.
1365 if (IsEntry && Idx == 0 && (BI.InNeeds & StateWQM))
1366 Needs = StateWQM;
1367
1368 // First, figure out the allowed states (Needs) based on the propagated
1369 // flags.
1370 if (II != IE) {
1371 MachineInstr &MI = *II;
1372
1373 if (MI.isTerminator() || TII->mayReadEXEC(*MRI, MI)) {
1374 auto III = Instructions.find(&MI);
1375 if (III != Instructions.end()) {
1376 if (III->second.Needs & StateStrictWWM)
1377 Needs = StateStrictWWM;
1378 else if (III->second.Needs & StateStrictWQM)
1379 Needs = StateStrictWQM;
1380 else if (III->second.Needs & StateWQM)
1381 Needs = StateWQM;
1382 else
1383 Needs &= ~III->second.Disabled;
1384 OutNeeds = III->second.OutNeeds;
1385 }
1386 } else {
1387 // If the instruction doesn't actually need a correct EXEC, then we can
1388 // safely leave Strict mode enabled.
1389 Needs = StateExact | StateWQM | StateStrict;
1390 }
1391
1392 // Exact mode exit can occur in terminators, but must be before branches.
1393 if (MI.isBranch() && OutNeeds == StateExact)
1394 Needs = StateExact;
1395
1396 ++Next;
1397 } else {
1398 // End of basic block
1399 if (BI.OutNeeds & StateWQM)
1400 Needs = StateWQM;
1401 else if (BI.OutNeeds == StateExact)
1402 Needs = StateExact;
1403 else
1404 Needs = StateWQM | StateExact;
1405 }
1406
1407 // Now, transition if necessary.
1408 if (!(Needs & State)) {
1410 if (State == StateStrictWWM || Needs == StateStrictWWM ||
1411 State == StateStrictWQM || Needs == StateStrictWQM) {
1412 // We must switch to or from Strict mode.
1413 First = FirstStrict;
1414 } else {
1415 // We only need to switch to/from WQM, so we can use FirstWQM.
1416 First = FirstWQM;
1417 }
1418
1419 // Whether we need to save SCC depends on start and end states.
1420 bool SaveSCC = false;
1421 switch (State) {
1422 case StateExact:
1423 case StateStrictWWM:
1424 case StateStrictWQM:
1425 // Exact/Strict -> Strict: save SCC
1426 // Exact/Strict -> WQM: save SCC if WQM mask is generated from exec
1427 // Exact/Strict -> Exact: no save
1428 SaveSCC = (Needs & StateStrict) || ((Needs & StateWQM) && WQMFromExec);
1429 break;
1430 case StateWQM:
1431 // WQM -> Exact/Strict: save SCC
1432 SaveSCC = !(Needs & StateWQM);
1433 break;
1434 default:
1435 llvm_unreachable("Unknown state");
1436 break;
1437 }
1438 char StartState = State & StateStrict ? NonStrictState : State;
1439 bool WQMToExact =
1440 StartState == StateWQM && (Needs & StateExact) && !(Needs & StateWQM);
1441 bool ExactToWQM = StartState == StateExact && (Needs & StateWQM) &&
1442 !(Needs & StateExact);
1443 bool PreferLast = Needs == StateWQM;
1444 // Exact regions in divergent control flow may run at EXEC=0, so try to
1445 // exclude instructions with unexpected effects from them.
1446 // FIXME: ideally we would branch over these when EXEC=0,
1447 // but this requires updating implicit values, live intervals and CFG.
1448 if ((WQMToExact && (OutNeeds & StateWQM)) || ExactToWQM) {
1449 for (MachineBasicBlock::iterator I = First; I != II; ++I) {
1450 if (TII->hasUnwantedEffectsWhenEXECEmpty(*I)) {
1451 PreferLast = WQMToExact;
1452 break;
1453 }
1454 }
1455 }
1457 prepareInsertion(MBB, First, II, PreferLast, SaveSCC);
1458
1459 if (State & StateStrict) {
1460 assert(State == StateStrictWWM || State == StateStrictWQM);
1461 assert(SavedNonStrictReg);
1462 fromStrictMode(MBB, Before, SavedNonStrictReg, NonStrictState, State);
1463
1464 LIS->createAndComputeVirtRegInterval(SavedNonStrictReg);
1465 SavedNonStrictReg = 0;
1466 State = NonStrictState;
1467 }
1468
1469 if (Needs & StateStrict) {
1470 NonStrictState = State;
1471 assert(Needs == StateStrictWWM || Needs == StateStrictWQM);
1472 assert(!SavedNonStrictReg);
1473 SavedNonStrictReg = MRI->createVirtualRegister(BoolRC);
1474
1475 toStrictMode(MBB, Before, SavedNonStrictReg, Needs);
1476 State = Needs;
1477 } else {
1478 if (WQMToExact) {
1479 if (!WQMFromExec && (OutNeeds & StateWQM)) {
1480 assert(!SavedWQMReg);
1481 SavedWQMReg = MRI->createVirtualRegister(BoolRC);
1482 }
1483 Before = skipDebugInstructionsForward(Before, MBB.end());
1484 toExact(MBB, Before, SavedWQMReg);
1485 State = StateExact;
1486 } else if (ExactToWQM) {
1487 assert(WQMFromExec == (SavedWQMReg == 0));
1488
1489 toWQM(MBB, Before, SavedWQMReg);
1490
1491 if (SavedWQMReg) {
1492 LIS->createAndComputeVirtRegInterval(SavedWQMReg);
1493 SavedWQMReg = 0;
1494 }
1495 State = StateWQM;
1496 } else {
1497 // We can get here if we transitioned from StrictWWM to a
1498 // non-StrictWWM state that already matches our needs, but we
1499 // shouldn't need to do anything.
1500 assert(Needs & State);
1501 }
1502 }
1503 }
1504
1505 if (Needs != (StateExact | StateWQM | StateStrict)) {
1506 if (Needs != (StateExact | StateWQM))
1507 FirstWQM = IE;
1508 FirstStrict = IE;
1509 }
1510
1511 if (II == IE)
1512 break;
1513
1514 II = Next;
1515 }
1516 assert(!SavedWQMReg);
1517 assert(!SavedNonStrictReg);
1518}
1519
1520bool SIWholeQuadMode::lowerLiveMaskQueries() {
1521 for (MachineInstr *MI : LiveMaskQueries) {
1522 const DebugLoc &DL = MI->getDebugLoc();
1523 Register Dest = MI->getOperand(0).getReg();
1524
1525 MachineInstr *Copy =
1526 BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
1527 .addReg(LiveMaskReg);
1528
1529 LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
1530 MI->eraseFromParent();
1531 }
1532 return !LiveMaskQueries.empty();
1533}
1534
1535bool SIWholeQuadMode::lowerCopyInstrs() {
1536 for (MachineInstr *MI : LowerToMovInstrs) {
1537 assert(MI->getNumExplicitOperands() == 2);
1538
1539 const Register Reg = MI->getOperand(0).getReg();
1540
1541 const TargetRegisterClass *regClass =
1542 TRI->getRegClassForOperandReg(*MRI, MI->getOperand(0));
1543 if (TRI->isVGPRClass(regClass)) {
1544 const unsigned MovOp = TII->getMovOpcode(regClass);
1545 MI->setDesc(TII->get(MovOp));
1546
1547 // Check that it already implicitly depends on exec (like all VALU movs
1548 // should do).
1549 assert(any_of(MI->implicit_operands(), [](const MachineOperand &MO) {
1550 return MO.isUse() && MO.getReg() == AMDGPU::EXEC;
1551 }));
1552 } else {
1553 // Remove early-clobber and exec dependency from simple SGPR copies.
1554 // This allows some to be eliminated during/post RA.
1555 LLVM_DEBUG(dbgs() << "simplify SGPR copy: " << *MI);
1556 if (MI->getOperand(0).isEarlyClobber()) {
1557 LIS->removeInterval(Reg);
1558 MI->getOperand(0).setIsEarlyClobber(false);
1560 }
1561 int Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC, /*TRI=*/nullptr);
1562 while (Index >= 0) {
1563 MI->removeOperand(Index);
1564 Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC, /*TRI=*/nullptr);
1565 }
1566 MI->setDesc(TII->get(AMDGPU::COPY));
1567 LLVM_DEBUG(dbgs() << " -> " << *MI);
1568 }
1569 }
1570 for (MachineInstr *MI : LowerToCopyInstrs) {
1571 LLVM_DEBUG(dbgs() << "simplify: " << *MI);
1572
1573 if (MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32) {
1574 assert(MI->getNumExplicitOperands() == 6);
1575
1576 LiveInterval *RecomputeLI = nullptr;
1577 if (MI->getOperand(4).isReg())
1578 RecomputeLI = &LIS->getInterval(MI->getOperand(4).getReg());
1579
1580 MI->removeOperand(5);
1581 MI->removeOperand(4);
1582 MI->removeOperand(3);
1583 MI->removeOperand(1);
1584
1585 if (RecomputeLI)
1586 LIS->shrinkToUses(RecomputeLI);
1587 } else {
1588 assert(MI->getNumExplicitOperands() == 2);
1589 }
1590
1591 unsigned CopyOp = MI->getOperand(1).isReg()
1592 ? (unsigned)AMDGPU::COPY
1593 : TII->getMovOpcode(TRI->getRegClassForOperandReg(
1594 *MRI, MI->getOperand(0)));
1595 MI->setDesc(TII->get(CopyOp));
1596 LLVM_DEBUG(dbgs() << " -> " << *MI);
1597 }
1598 return !LowerToCopyInstrs.empty() || !LowerToMovInstrs.empty();
1599}
1600
1601bool SIWholeQuadMode::lowerKillInstrs(bool IsWQM) {
1602 for (MachineInstr *MI : KillInstrs) {
1603 MachineInstr *SplitPoint = nullptr;
1604 switch (MI->getOpcode()) {
1605 case AMDGPU::SI_DEMOTE_I1:
1606 case AMDGPU::SI_KILL_I1_TERMINATOR:
1607 SplitPoint = lowerKillI1(*MI, IsWQM);
1608 break;
1609 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1610 SplitPoint = lowerKillF32(*MI);
1611 break;
1612 }
1613 if (SplitPoint)
1614 splitBlock(SplitPoint);
1615 }
1616 return !KillInstrs.empty();
1617}
1618
1619void SIWholeQuadMode::lowerInitExec(MachineInstr &MI) {
1620 MachineBasicBlock *MBB = MI.getParent();
1621
1622 if (MI.getOpcode() == AMDGPU::SI_INIT_WHOLE_WAVE) {
1623 assert(MBB == &MBB->getParent()->front() &&
1624 "init whole wave not in entry block");
1625 Register EntryExec = MRI->createVirtualRegister(TRI->getBoolRC());
1626 MachineInstr *SaveExec = BuildMI(*MBB, MBB->begin(), MI.getDebugLoc(),
1627 TII->get(LMC.OrSaveExecOpc), EntryExec)
1628 .addImm(-1)
1629 .setOperandDead(3);
1630
1631 // Replace all uses of MI's destination reg with EntryExec.
1632 MRI->replaceRegWith(MI.getOperand(0).getReg(), EntryExec);
1633
1634 if (LIS) {
1636 }
1637
1638 MI.eraseFromParent();
1639
1640 if (LIS) {
1641 LIS->InsertMachineInstrInMaps(*SaveExec);
1642 LIS->createAndComputeVirtRegInterval(EntryExec);
1643 }
1644 return;
1645 }
1646
1647 if (MI.getOpcode() == AMDGPU::SI_INIT_EXEC) {
1648 // This should be before all vector instructions.
1649 MachineInstr *InitMI = BuildMI(*MBB, MBB->begin(), MI.getDebugLoc(),
1650 TII->get(LMC.MovOpc), LMC.ExecReg)
1651 .addImm(MI.getOperand(0).getImm());
1652 if (LIS) {
1654 LIS->InsertMachineInstrInMaps(*InitMI);
1655 }
1656 MI.eraseFromParent();
1657 return;
1658 }
1659
1660 // Extract the thread count from an SGPR input and set EXEC accordingly.
1661 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
1662 //
1663 // S_BFE_U32 count, input, {shift, 7}
1664 // S_BFM_B64 exec, count, 0
1665 // S_CMP_EQ_U32 count, 64
1666 // S_CMOV_B64 exec, -1
1667 Register InputReg = MI.getOperand(0).getReg();
1668 MachineInstr *FirstMI = &*MBB->begin();
1669 if (InputReg.isVirtual()) {
1670 MachineInstr *DefInstr = MRI->getVRegDef(InputReg);
1671 assert(DefInstr && DefInstr->isCopy());
1672 if (DefInstr->getParent() == MBB) {
1673 if (DefInstr != FirstMI) {
1674 // If the `InputReg` is defined in current block, we also need to
1675 // move that instruction to the beginning of the block.
1676 DefInstr->removeFromParent();
1677 MBB->insert(FirstMI, DefInstr);
1678 if (LIS)
1679 LIS->handleMove(*DefInstr);
1680 } else {
1681 // If first instruction is definition then move pointer after it.
1682 FirstMI = &*std::next(FirstMI->getIterator());
1683 }
1684 }
1685 }
1686
1687 // Insert instruction sequence at block beginning (before vector operations).
1688 const DebugLoc &DL = MI.getDebugLoc();
1689 const unsigned WavefrontSize = ST->getWavefrontSize();
1690 const unsigned Mask = (WavefrontSize << 1) - 1;
1691 Register CountReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1692 auto BfeMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_BFE_U32), CountReg)
1693 .addReg(InputReg)
1694 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000)
1695 .setOperandDead(3);
1696 auto BfmMI = BuildMI(*MBB, FirstMI, DL, TII->get(LMC.BfmOpc), LMC.ExecReg)
1697 .addReg(CountReg)
1698 .addImm(0);
1699 auto CmpMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
1700 .addReg(CountReg, RegState::Kill)
1701 .addImm(WavefrontSize);
1702 auto CmovMI =
1703 BuildMI(*MBB, FirstMI, DL, TII->get(LMC.CMovOpc), LMC.ExecReg).addImm(-1);
1704
1705 if (!LIS) {
1706 MI.eraseFromParent();
1707 return;
1708 }
1709
1711 MI.eraseFromParent();
1712
1713 LIS->InsertMachineInstrInMaps(*BfeMI);
1714 LIS->InsertMachineInstrInMaps(*BfmMI);
1715 LIS->InsertMachineInstrInMaps(*CmpMI);
1716 LIS->InsertMachineInstrInMaps(*CmovMI);
1717
1718 LIS->removeInterval(InputReg);
1719 LIS->createAndComputeVirtRegInterval(InputReg);
1720 LIS->createAndComputeVirtRegInterval(CountReg);
1721}
1722
1723/// Lower INIT_EXEC instructions. Return a suitable insert point in \p Entry
1724/// for instructions that depend on EXEC.
1726SIWholeQuadMode::lowerInitExecInstrs(MachineBasicBlock &Entry, bool &Changed) {
1727 MachineBasicBlock::iterator InsertPt = Entry.getFirstNonPHI();
1728
1729 for (MachineInstr *MI : InitExecInstrs) {
1730 // Try to handle undefined cases gracefully:
1731 // - multiple INIT_EXEC instructions
1732 // - INIT_EXEC instructions not in the entry block
1733 if (MI->getParent() == &Entry)
1734 InsertPt = std::next(MI->getIterator());
1735
1736 lowerInitExec(*MI);
1737 Changed = true;
1738 }
1739
1740 return InsertPt;
1741}
1742
1743bool SIWholeQuadMode::run(MachineFunction &MF) {
1744 LLVM_DEBUG(dbgs() << "SI Whole Quad Mode on " << MF.getName()
1745 << " ------------- \n");
1746 LLVM_DEBUG(MF.dump(););
1747
1748 Instructions.clear();
1749 Blocks.clear();
1750 LiveMaskQueries.clear();
1751 LowerToCopyInstrs.clear();
1752 LowerToMovInstrs.clear();
1753 KillInstrs.clear();
1754 InitExecInstrs.clear();
1755 SetInactiveInstrs.clear();
1756 StateTransition.clear();
1757
1758 const char GlobalFlags = analyzeFunction(MF);
1759 bool Changed = false;
1760
1761 LiveMaskReg = LMC.ExecReg;
1762
1763 MachineBasicBlock &Entry = MF.front();
1764 MachineBasicBlock::iterator EntryMI = lowerInitExecInstrs(Entry, Changed);
1765
1766 // Store a copy of the original live mask when required
1767 const bool HasLiveMaskQueries = !LiveMaskQueries.empty();
1768 const bool HasWaveModes = GlobalFlags & ~StateExact;
1769 const bool HasKills = !KillInstrs.empty();
1770 const bool UsesWQM = GlobalFlags & StateWQM;
1771 if (HasKills || UsesWQM || (HasWaveModes && HasLiveMaskQueries)) {
1772 LiveMaskReg = MRI->createVirtualRegister(TRI->getBoolRC());
1773 MachineInstr *MI =
1774 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::COPY), LiveMaskReg)
1775 .addReg(LMC.ExecReg);
1777 Changed = true;
1778 }
1779
1780 // Check if V_SET_INACTIVE was touched by a strict state mode.
1781 // If so, promote to WWM; otherwise lower to COPY.
1782 for (MachineInstr *MI : SetInactiveInstrs) {
1783 if (LowerToCopyInstrs.contains(MI))
1784 continue;
1785 auto &Info = Instructions[MI];
1786 if (Info.MarkedStates & StateStrict) {
1787 Info.Needs |= StateStrictWWM;
1788 Info.Disabled &= ~StateStrictWWM;
1789 Blocks[MI->getParent()].Needs |= StateStrictWWM;
1790 } else {
1791 LLVM_DEBUG(dbgs() << "Has no WWM marking: " << *MI);
1792 LowerToCopyInstrs.insert(MI);
1793 }
1794 }
1795
1796 LLVM_DEBUG(printInfo());
1797
1798 Changed |= lowerLiveMaskQueries();
1799 Changed |= lowerCopyInstrs();
1800
1801 if (!HasWaveModes) {
1802 // No wave mode execution
1803 Changed |= lowerKillInstrs(false);
1804 } else if (GlobalFlags == StateWQM) {
1805 // Shader only needs WQM
1806 auto MI =
1807 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(LMC.WQMOpc), LMC.ExecReg)
1808 .addReg(LMC.ExecReg)
1809 .setOperandDead(2);
1811 lowerKillInstrs(true);
1812 Changed = true;
1813 } else {
1814 // Mark entry for WQM if required.
1815 if (GlobalFlags & StateWQM)
1816 Blocks[&Entry].InNeeds |= StateWQM;
1817 // Wave mode switching requires full lowering pass.
1818 for (auto &BII : Blocks)
1819 processBlock(*BII.first, BII.second, BII.first == &Entry);
1820 // Lowering blocks causes block splitting so perform as a second pass.
1821 for (auto &BII : Blocks)
1822 lowerBlock(*BII.first, BII.second);
1823 Changed = true;
1824 }
1825
1826 // Compute live range for live mask
1827 if (LiveMaskReg != LMC.ExecReg)
1828 LIS->createAndComputeVirtRegInterval(LiveMaskReg);
1829
1830 // Physical registers like SCC aren't tracked by default anyway, so just
1831 // removing the ranges we computed is the simplest option for maintaining
1832 // the analysis results.
1833 LIS->removeAllRegUnitsForPhysReg(AMDGPU::SCC);
1834
1835 // If we performed any kills then recompute EXEC
1836 if (!KillInstrs.empty() || !InitExecInstrs.empty())
1837 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
1838
1839 return Changed;
1840}
1841
1842bool SIWholeQuadModeLegacy::runOnMachineFunction(MachineFunction &MF) {
1843 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1844 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
1845 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
1846 auto *PDTWrapper =
1847 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
1848 MachinePostDominatorTree *PDT =
1849 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
1850 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
1851 return Impl.run(MF);
1852}
1853
1854PreservedAnalyses
1857 MFPropsModifier _(*this, MF);
1858
1864 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
1865 bool Changed = Impl.run(MF);
1866 if (!Changed)
1867 return PreservedAnalyses::all();
1868
1874 return PA;
1875}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void analyzeFunction(Function &Fn, const DataLayout &Layout, FunctionVarLocsBuilder *FnVarLocs)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static void splitBlock(MachineBasicBlock &MBB, MachineInstr &MI, MachineDominatorTree *MDT, MachineLoopInfo *MLI)
SI Optimize VGPR LiveRange
#define LLVM_DEBUG(...)
Definition Debug.h:119
unsigned getWavefrontSize() const
static const LaneMaskConstants & get(const GCNSubtarget &ST)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
This class represents the liveness of a register, stack slot, etc.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
static MCRegister from(unsigned Val)
Check the provided unsigned value is a valid MCRegister.
Definition MCRegister.h:77
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI MachineBasicBlock * splitAt(MachineInstr &SplitInst, bool UpdateLiveIns=true, LiveIntervals *LIS=nullptr)
Split a basic block into 2 pieces at SplitPoint.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
LLVM_ABI MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it.
const MachineBasicBlock * getParent() const
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Wrapper class representing a virtual register or register unit.
Definition Register.h:175
constexpr bool isVirtualReg() const
Definition Register.h:191
constexpr Register asVirtualReg() const
Definition Register.h:200
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char WavefrontSize[]
Key for Kernel::CodeProps::Metadata::mWavefrontSize.
LLVM_READONLY int32_t getVOPe32(uint32_t Opcode)
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.
@ Entry
Definition COFF.h:862
Flag
These should be considered private to the implementation of the MCInstrDesc class.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
FunctionPass * createSIWholeQuadModeLegacyPass()
char & SIWholeQuadModeID
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:30
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
WorkItem(const BasicBlock *BB, int St)
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81