LLVM 22.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"
75#include "llvm/ADT/MapVector.h"
83#include "llvm/IR/CallingConv.h"
86
87using namespace llvm;
88
89#define DEBUG_TYPE "si-wqm"
90
91namespace {
92
93enum {
94 StateWQM = 0x1,
95 StateStrictWWM = 0x2,
96 StateStrictWQM = 0x4,
97 StateExact = 0x8,
98 StateStrict = StateStrictWWM | StateStrictWQM,
99};
100
101struct PrintState {
102public:
103 int State;
104
105 explicit PrintState(int State) : State(State) {}
106};
107
108#ifndef NDEBUG
109static raw_ostream &operator<<(raw_ostream &OS, const PrintState &PS) {
110
111 static const std::pair<char, const char *> Mapping[] = {
112 std::pair(StateWQM, "WQM"), std::pair(StateStrictWWM, "StrictWWM"),
113 std::pair(StateStrictWQM, "StrictWQM"), std::pair(StateExact, "Exact")};
114 char State = PS.State;
115 for (auto M : Mapping) {
116 if (State & M.first) {
117 OS << M.second;
118 State &= ~M.first;
119
120 if (State)
121 OS << '|';
122 }
123 }
124 assert(State == 0);
125 return OS;
126}
127#endif
128
129struct InstrInfo {
130 char Needs = 0;
131 char Disabled = 0;
132 char OutNeeds = 0;
133 char MarkedStates = 0;
134};
135
136struct BlockInfo {
137 char Needs = 0;
138 char InNeeds = 0;
139 char OutNeeds = 0;
140 char InitialState = 0;
141 bool NeedsLowering = false;
142};
143
144struct WorkItem {
145 MachineBasicBlock *MBB = nullptr;
146 MachineInstr *MI = nullptr;
147
148 WorkItem() = default;
151};
152
153class SIWholeQuadMode {
154public:
155 SIWholeQuadMode(MachineFunction &MF, LiveIntervals *LIS,
157 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
158 TRI(&TII->getRegisterInfo()), MRI(&MF.getRegInfo()), LIS(LIS), MDT(MDT),
159 PDT(PDT), LMC(AMDGPU::LaneMaskConstants::get(*ST)) {}
160 bool run(MachineFunction &MF);
161
162private:
163 const GCNSubtarget *ST;
164 const SIInstrInfo *TII;
165 const SIRegisterInfo *TRI;
167 LiveIntervals *LIS;
170 const AMDGPU::LaneMaskConstants &LMC;
171
172 Register LiveMaskReg;
173
176
177 // Tracks state (WQM/StrictWWM/StrictWQM/Exact) after a given instruction
179
180 SmallVector<MachineInstr *, 2> LiveMaskQueries;
181 SmallVector<MachineInstr *, 4> LowerToMovInstrs;
182 SmallSetVector<MachineInstr *, 4> LowerToCopyInstrs;
184 SmallVector<MachineInstr *, 4> InitExecInstrs;
185 SmallVector<MachineInstr *, 4> SetInactiveInstrs;
186
187 void printInfo();
188
189 void markInstruction(MachineInstr &MI, char Flag,
190 std::vector<WorkItem> &Worklist);
191 void markDefs(const MachineInstr &UseMI, LiveRange &LR, Register Reg,
192 unsigned SubReg, char Flag, std::vector<WorkItem> &Worklist);
193 void markOperand(const MachineInstr &MI, const MachineOperand &Op, char Flag,
194 std::vector<WorkItem> &Worklist);
195 void markInstructionUses(const MachineInstr &MI, char Flag,
196 std::vector<WorkItem> &Worklist);
197 char scanInstructions(MachineFunction &MF, std::vector<WorkItem> &Worklist);
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 Register Reg, unsigned SubReg, char Flag,
322 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 : (Reg.isVirtual() ? MRI->getMaxLaneMaskForVReg(Reg)
336
337 // Perform a depth-first iteration of the LiveRange graph marking defs.
338 // Stop processing of a given branch when all use lanes have been defined.
339 // The first definition stops processing for a physical register.
340 struct PhiEntry {
341 const VNInfo *Phi;
342 unsigned PredIdx;
343 LaneBitmask DefinedLanes;
344
345 PhiEntry(const VNInfo *Phi, unsigned PredIdx, LaneBitmask DefinedLanes)
346 : Phi(Phi), PredIdx(PredIdx), DefinedLanes(DefinedLanes) {}
347 };
348 using VisitKey = std::pair<const VNInfo *, LaneBitmask>;
350 SmallSet<VisitKey, 4> Visited;
351 LaneBitmask DefinedLanes;
352 unsigned NextPredIdx = 0; // Only used for processing phi nodes
353 do {
354 const VNInfo *NextValue = nullptr;
355 const VisitKey Key(Value, DefinedLanes);
356
357 if (Visited.insert(Key).second) {
358 // On first visit to a phi then start processing first predecessor
359 NextPredIdx = 0;
360 }
361
362 if (Value->isPHIDef()) {
363 // Each predecessor node in the phi must be processed as a subgraph
364 const MachineBasicBlock *MBB = LIS->getMBBFromIndex(Value->def);
365 assert(MBB && "Phi-def has no defining MBB");
366
367 // Find next predecessor to process
368 unsigned Idx = NextPredIdx;
369 const auto *PI = MBB->pred_begin() + Idx;
370 const auto *PE = MBB->pred_end();
371 for (; PI != PE && !NextValue; ++PI, ++Idx) {
372 if (const VNInfo *VN = LR.getVNInfoBefore(LIS->getMBBEndIdx(*PI))) {
373 if (!Visited.count(VisitKey(VN, DefinedLanes)))
374 NextValue = VN;
375 }
376 }
377
378 // If there are more predecessors to process; add phi to stack
379 if (PI != PE)
380 PhiStack.emplace_back(Value, Idx, DefinedLanes);
381 } else {
382 MachineInstr *MI = LIS->getInstructionFromIndex(Value->def);
383 assert(MI && "Def has no defining instruction");
384
385 if (Reg.isVirtual()) {
386 // Iterate over all operands to find relevant definitions
387 bool HasDef = false;
388 for (const MachineOperand &Op : MI->all_defs()) {
389 if (Op.getReg() != Reg)
390 continue;
391
392 // Compute lanes defined and overlap with use
393 LaneBitmask OpLanes =
394 Op.isUndef() ? LaneBitmask::getAll()
395 : TRI->getSubRegIndexLaneMask(Op.getSubReg());
396 LaneBitmask Overlap = (UseLanes & OpLanes);
397
398 // Record if this instruction defined any of use
399 HasDef |= Overlap.any();
400
401 // Mark any lanes defined
402 DefinedLanes |= OpLanes;
403 }
404
405 // Check if all lanes of use have been defined
406 if ((DefinedLanes & UseLanes) != UseLanes) {
407 // Definition not complete; need to process input value
408 LiveQueryResult LRQ = LR.Query(LIS->getInstructionIndex(*MI));
409 if (const VNInfo *VN = LRQ.valueIn()) {
410 if (!Visited.count(VisitKey(VN, DefinedLanes)))
411 NextValue = VN;
412 }
413 }
414
415 // Only mark the instruction if it defines some part of the use
416 if (HasDef)
417 markInstruction(*MI, Flag, Worklist);
418 } else {
419 // For physical registers simply mark the defining instruction
420 markInstruction(*MI, Flag, Worklist);
421 }
422 }
423
424 if (!NextValue && !PhiStack.empty()) {
425 // Reach end of chain; revert to processing last phi
426 PhiEntry &Entry = PhiStack.back();
427 NextValue = Entry.Phi;
428 NextPredIdx = Entry.PredIdx;
429 DefinedLanes = Entry.DefinedLanes;
430 PhiStack.pop_back();
431 }
432
433 Value = NextValue;
434 } while (Value);
435}
436
437void SIWholeQuadMode::markOperand(const MachineInstr &MI,
438 const MachineOperand &Op, char Flag,
439 std::vector<WorkItem> &Worklist) {
440 assert(Op.isReg());
441 Register Reg = Op.getReg();
442
443 // Ignore some hardware registers
444 switch (Reg) {
445 case AMDGPU::EXEC:
446 case AMDGPU::EXEC_LO:
447 return;
448 default:
449 break;
450 }
451
452 LLVM_DEBUG(dbgs() << "markOperand " << PrintState(Flag) << ": " << Op
453 << " for " << MI);
454 if (Reg.isVirtual()) {
455 LiveRange &LR = LIS->getInterval(Reg);
456 markDefs(MI, LR, Reg, Op.getSubReg(), Flag, Worklist);
457 } else {
458 // Handle physical registers that we need to track; this is mostly relevant
459 // for VCC, which can appear as the (implicit) input of a uniform branch,
460 // e.g. when a loop counter is stored in a VGPR.
461 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
462 LiveRange &LR = LIS->getRegUnit(Unit);
463 const VNInfo *Value = LR.Query(LIS->getInstructionIndex(MI)).valueIn();
464 if (Value)
465 markDefs(MI, LR, Unit, AMDGPU::NoSubRegister, Flag, Worklist);
466 }
467 }
468}
469
470/// Mark all instructions defining the uses in \p MI with \p Flag.
471void SIWholeQuadMode::markInstructionUses(const MachineInstr &MI, char Flag,
472 std::vector<WorkItem> &Worklist) {
473 LLVM_DEBUG(dbgs() << "markInstructionUses " << PrintState(Flag) << ": "
474 << MI);
475
476 for (const MachineOperand &Use : MI.all_uses())
477 markOperand(MI, Use, Flag, Worklist);
478}
479
480// Scan instructions to determine which ones require an Exact execmask and
481// which ones seed WQM requirements.
482char SIWholeQuadMode::scanInstructions(MachineFunction &MF,
483 std::vector<WorkItem> &Worklist) {
484 char GlobalFlags = 0;
485 bool WQMOutputs = MF.getFunction().hasFnAttribute("amdgpu-ps-wqm-outputs");
486 SmallVector<MachineInstr *, 4> SoftWQMInstrs;
487 bool HasImplicitDerivatives =
488 MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS;
489
490 // We need to visit the basic blocks in reverse post-order so that we visit
491 // defs before uses, in particular so that we don't accidentally mark an
492 // instruction as needing e.g. WQM before visiting it and realizing it needs
493 // WQM disabled.
494 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
495 for (MachineBasicBlock *MBB : RPOT) {
496 BlockInfo &BBI = Blocks[MBB];
497
498 for (MachineInstr &MI : *MBB) {
499 InstrInfo &III = Instructions[&MI];
500 unsigned Opcode = MI.getOpcode();
501 char Flags = 0;
502
503 if (TII->isWQM(Opcode)) {
504 // If LOD is not supported WQM is not needed.
505 // Only generate implicit WQM if implicit derivatives are required.
506 // This avoids inserting unintended WQM if a shader type without
507 // implicit derivatives uses an image sampling instruction.
508 if (ST->hasExtendedImageInsts() && HasImplicitDerivatives) {
509 // Sampling instructions don't need to produce results for all pixels
510 // in a quad, they just require all inputs of a quad to have been
511 // computed for derivatives.
512 markInstructionUses(MI, StateWQM, Worklist);
513 GlobalFlags |= StateWQM;
514 }
515 } else if (Opcode == AMDGPU::WQM) {
516 // The WQM intrinsic requires its output to have all the helper lanes
517 // correct, so we need it to be in WQM.
518 Flags = StateWQM;
519 LowerToCopyInstrs.insert(&MI);
520 } else if (Opcode == AMDGPU::SOFT_WQM) {
521 LowerToCopyInstrs.insert(&MI);
522 SoftWQMInstrs.push_back(&MI);
523 } else if (Opcode == AMDGPU::STRICT_WWM) {
524 // The STRICT_WWM intrinsic doesn't make the same guarantee, and plus
525 // it needs to be executed in WQM or Exact so that its copy doesn't
526 // clobber inactive lanes.
527 markInstructionUses(MI, StateStrictWWM, Worklist);
528 GlobalFlags |= StateStrictWWM;
529 LowerToMovInstrs.push_back(&MI);
530 } else if (Opcode == AMDGPU::STRICT_WQM ||
531 TII->isDualSourceBlendEXP(MI)) {
532 // STRICT_WQM is similar to STRICTWWM, but instead of enabling all
533 // threads of the wave like STRICTWWM, STRICT_WQM enables all threads in
534 // quads that have at least one active thread.
535 markInstructionUses(MI, StateStrictWQM, Worklist);
536 GlobalFlags |= StateStrictWQM;
537
538 if (Opcode == AMDGPU::STRICT_WQM) {
539 LowerToMovInstrs.push_back(&MI);
540 } else {
541 // Dual source blend export acts as implicit strict-wqm, its sources
542 // need to be shuffled in strict wqm, but the export itself needs to
543 // run in exact mode.
544 BBI.Needs |= StateExact;
545 if (!(BBI.InNeeds & StateExact)) {
546 BBI.InNeeds |= StateExact;
547 Worklist.emplace_back(MBB);
548 }
549 GlobalFlags |= StateExact;
550 III.Disabled = StateWQM | StateStrict;
551 }
552 } else if (Opcode == AMDGPU::LDS_PARAM_LOAD ||
553 Opcode == AMDGPU::DS_PARAM_LOAD ||
554 Opcode == AMDGPU::LDS_DIRECT_LOAD ||
555 Opcode == AMDGPU::DS_DIRECT_LOAD) {
556 // Mark these STRICTWQM, but only for the instruction, not its operands.
557 // This avoid unnecessarily marking M0 as requiring WQM.
558 III.Needs |= StateStrictWQM;
559 GlobalFlags |= StateStrictWQM;
560 } else if (Opcode == AMDGPU::V_SET_INACTIVE_B32) {
561 // Disable strict states; StrictWQM will be added as required later.
562 III.Disabled = StateStrict;
563 MachineOperand &Inactive = MI.getOperand(4);
564 if (Inactive.isReg()) {
565 if (Inactive.isUndef() && MI.getOperand(3).getImm() == 0)
566 LowerToCopyInstrs.insert(&MI);
567 else
568 markOperand(MI, Inactive, StateStrictWWM, Worklist);
569 }
570 SetInactiveInstrs.push_back(&MI);
571 BBI.NeedsLowering = true;
572 } else if (TII->isDisableWQM(MI)) {
573 BBI.Needs |= StateExact;
574 if (!(BBI.InNeeds & StateExact)) {
575 BBI.InNeeds |= StateExact;
576 Worklist.emplace_back(MBB);
577 }
578 GlobalFlags |= StateExact;
579 III.Disabled = StateWQM | StateStrict;
580 } else if (Opcode == AMDGPU::SI_PS_LIVE ||
581 Opcode == AMDGPU::SI_LIVE_MASK) {
582 LiveMaskQueries.push_back(&MI);
583 } else if (Opcode == AMDGPU::SI_KILL_I1_TERMINATOR ||
584 Opcode == AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR ||
585 Opcode == AMDGPU::SI_DEMOTE_I1) {
586 KillInstrs.push_back(&MI);
587 BBI.NeedsLowering = true;
588 } else if (Opcode == AMDGPU::SI_INIT_EXEC ||
589 Opcode == AMDGPU::SI_INIT_EXEC_FROM_INPUT ||
590 Opcode == AMDGPU::SI_INIT_WHOLE_WAVE) {
591 InitExecInstrs.push_back(&MI);
592 } else if (WQMOutputs) {
593 // The function is in machine SSA form, which means that physical
594 // VGPRs correspond to shader inputs and outputs. Inputs are
595 // only used, outputs are only defined.
596 // FIXME: is this still valid?
597 for (const MachineOperand &MO : MI.defs()) {
598 Register Reg = MO.getReg();
599 if (Reg.isPhysical() &&
600 TRI->hasVectorRegisters(TRI->getPhysRegBaseClass(Reg))) {
601 Flags = StateWQM;
602 break;
603 }
604 }
605 }
606
607 if (Flags) {
608 markInstruction(MI, Flags, Worklist);
609 GlobalFlags |= Flags;
610 }
611 }
612 }
613
614 // Mark sure that any SET_INACTIVE instructions are computed in WQM if WQM is
615 // ever used anywhere in the function. This implements the corresponding
616 // semantics of @llvm.amdgcn.set.inactive.
617 // Similarly for SOFT_WQM instructions, implementing @llvm.amdgcn.softwqm.
618 if (GlobalFlags & StateWQM) {
619 for (MachineInstr *MI : SetInactiveInstrs)
620 markInstruction(*MI, StateWQM, Worklist);
621 for (MachineInstr *MI : SoftWQMInstrs)
622 markInstruction(*MI, StateWQM, Worklist);
623 }
624
625 return GlobalFlags;
626}
627
628void SIWholeQuadMode::propagateInstruction(MachineInstr &MI,
629 std::vector<WorkItem>& Worklist) {
630 MachineBasicBlock *MBB = MI.getParent();
631 InstrInfo II = Instructions[&MI]; // take a copy to prevent dangling references
632 BlockInfo &BI = Blocks[MBB];
633
634 // Control flow-type instructions and stores to temporary memory that are
635 // followed by WQM computations must themselves be in WQM.
636 if ((II.OutNeeds & StateWQM) && !(II.Disabled & StateWQM) &&
637 (MI.isTerminator() || (TII->usesVM_CNT(MI) && MI.mayStore()))) {
638 Instructions[&MI].Needs = StateWQM;
639 II.Needs = StateWQM;
640 }
641
642 // Propagate to block level
643 if (II.Needs & StateWQM) {
644 BI.Needs |= StateWQM;
645 if (!(BI.InNeeds & StateWQM)) {
646 BI.InNeeds |= StateWQM;
647 Worklist.emplace_back(MBB);
648 }
649 }
650
651 // Propagate backwards within block
652 if (MachineInstr *PrevMI = MI.getPrevNode()) {
653 char InNeeds = (II.Needs & ~StateStrict) | II.OutNeeds;
654 if (!PrevMI->isPHI()) {
655 InstrInfo &PrevII = Instructions[PrevMI];
656 if ((PrevII.OutNeeds | InNeeds) != PrevII.OutNeeds) {
657 PrevII.OutNeeds |= InNeeds;
658 Worklist.emplace_back(PrevMI);
659 }
660 }
661 }
662
663 // Propagate WQM flag to instruction inputs
664 assert(!(II.Needs & StateExact));
665
666 if (II.Needs != 0)
667 markInstructionUses(MI, II.Needs, Worklist);
668
669 // Ensure we process a block containing StrictWWM/StrictWQM, even if it does
670 // not require any WQM transitions.
671 if (II.Needs & StateStrictWWM)
672 BI.Needs |= StateStrictWWM;
673 if (II.Needs & StateStrictWQM)
674 BI.Needs |= StateStrictWQM;
675}
676
677void SIWholeQuadMode::propagateBlock(MachineBasicBlock &MBB,
678 std::vector<WorkItem>& Worklist) {
679 BlockInfo BI = Blocks[&MBB]; // Make a copy to prevent dangling references.
680
681 // Propagate through instructions
682 if (!MBB.empty()) {
683 MachineInstr *LastMI = &*MBB.rbegin();
684 InstrInfo &LastII = Instructions[LastMI];
685 if ((LastII.OutNeeds | BI.OutNeeds) != LastII.OutNeeds) {
686 LastII.OutNeeds |= BI.OutNeeds;
687 Worklist.emplace_back(LastMI);
688 }
689 }
690
691 // Predecessor blocks must provide for our WQM/Exact needs.
692 for (MachineBasicBlock *Pred : MBB.predecessors()) {
693 BlockInfo &PredBI = Blocks[Pred];
694 if ((PredBI.OutNeeds | BI.InNeeds) == PredBI.OutNeeds)
695 continue;
696
697 PredBI.OutNeeds |= BI.InNeeds;
698 PredBI.InNeeds |= BI.InNeeds;
699 Worklist.emplace_back(Pred);
700 }
701
702 // All successors must be prepared to accept the same set of WQM/Exact data.
703 for (MachineBasicBlock *Succ : MBB.successors()) {
704 BlockInfo &SuccBI = Blocks[Succ];
705 if ((SuccBI.InNeeds | BI.OutNeeds) == SuccBI.InNeeds)
706 continue;
707
708 SuccBI.InNeeds |= BI.OutNeeds;
709 Worklist.emplace_back(Succ);
710 }
711}
712
713char SIWholeQuadMode::analyzeFunction(MachineFunction &MF) {
714 std::vector<WorkItem> Worklist;
715 char GlobalFlags = scanInstructions(MF, Worklist);
716
717 while (!Worklist.empty()) {
718 WorkItem WI = Worklist.back();
719 Worklist.pop_back();
720
721 if (WI.MI)
722 propagateInstruction(*WI.MI, Worklist);
723 else
724 propagateBlock(*WI.MBB, Worklist);
725 }
726
727 return GlobalFlags;
728}
729
731SIWholeQuadMode::saveSCC(MachineBasicBlock &MBB,
733 Register SaveReg = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
734
735 MachineInstr *Save =
736 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), SaveReg)
737 .addReg(AMDGPU::SCC);
738 MachineInstr *Restore =
739 BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), AMDGPU::SCC)
740 .addReg(SaveReg);
741
742 LIS->InsertMachineInstrInMaps(*Save);
743 LIS->InsertMachineInstrInMaps(*Restore);
745
746 return Restore;
747}
748
749void SIWholeQuadMode::splitBlock(MachineInstr *TermMI) {
750 MachineBasicBlock *BB = TermMI->getParent();
751 LLVM_DEBUG(dbgs() << "Split block " << printMBBReference(*BB) << " @ "
752 << *TermMI << "\n");
753
754 MachineBasicBlock *SplitBB =
755 BB->splitAt(*TermMI, /*UpdateLiveIns*/ true, LIS);
756
757 // Convert last instruction in block to a terminator.
758 // Note: this only covers the expected patterns
759 unsigned NewOpcode = 0;
760 switch (TermMI->getOpcode()) {
761 case AMDGPU::S_AND_B32:
762 NewOpcode = AMDGPU::S_AND_B32_term;
763 break;
764 case AMDGPU::S_AND_B64:
765 NewOpcode = AMDGPU::S_AND_B64_term;
766 break;
767 case AMDGPU::S_MOV_B32:
768 NewOpcode = AMDGPU::S_MOV_B32_term;
769 break;
770 case AMDGPU::S_MOV_B64:
771 NewOpcode = AMDGPU::S_MOV_B64_term;
772 break;
773 case AMDGPU::S_ANDN2_B32:
774 NewOpcode = AMDGPU::S_ANDN2_B32_term;
775 break;
776 case AMDGPU::S_ANDN2_B64:
777 NewOpcode = AMDGPU::S_ANDN2_B64_term;
778 break;
779 default:
780 llvm_unreachable("Unexpected instruction");
781 }
782
783 // These terminators fallthrough to the next block, no need to add an
784 // unconditional branch to the next block (SplitBB).
785 TermMI->setDesc(TII->get(NewOpcode));
786
787 if (SplitBB != BB) {
788 // Update dominator trees
789 using DomTreeT = DomTreeBase<MachineBasicBlock>;
791 for (MachineBasicBlock *Succ : SplitBB->successors()) {
792 DTUpdates.push_back({DomTreeT::Insert, SplitBB, Succ});
793 DTUpdates.push_back({DomTreeT::Delete, BB, Succ});
794 }
795 DTUpdates.push_back({DomTreeT::Insert, BB, SplitBB});
796 if (MDT)
797 MDT->applyUpdates(DTUpdates);
798 if (PDT)
799 PDT->applyUpdates(DTUpdates);
800 }
801}
802
803MachineInstr *SIWholeQuadMode::lowerKillF32(MachineInstr &MI) {
804 assert(LiveMaskReg.isVirtual());
805
806 const DebugLoc &DL = MI.getDebugLoc();
807 unsigned Opcode = 0;
808
809 assert(MI.getOperand(0).isReg());
810
811 // Comparison is for live lanes; however here we compute the inverse
812 // (killed lanes). This is because VCMP will always generate 0 bits
813 // for inactive lanes so a mask of live lanes would not be correct
814 // inside control flow.
815 // Invert the comparison by swapping the operands and adjusting
816 // the comparison codes.
817
818 switch (MI.getOperand(2).getImm()) {
819 case ISD::SETUEQ:
820 Opcode = AMDGPU::V_CMP_LG_F32_e64;
821 break;
822 case ISD::SETUGT:
823 Opcode = AMDGPU::V_CMP_GE_F32_e64;
824 break;
825 case ISD::SETUGE:
826 Opcode = AMDGPU::V_CMP_GT_F32_e64;
827 break;
828 case ISD::SETULT:
829 Opcode = AMDGPU::V_CMP_LE_F32_e64;
830 break;
831 case ISD::SETULE:
832 Opcode = AMDGPU::V_CMP_LT_F32_e64;
833 break;
834 case ISD::SETUNE:
835 Opcode = AMDGPU::V_CMP_EQ_F32_e64;
836 break;
837 case ISD::SETO:
838 Opcode = AMDGPU::V_CMP_O_F32_e64;
839 break;
840 case ISD::SETUO:
841 Opcode = AMDGPU::V_CMP_U_F32_e64;
842 break;
843 case ISD::SETOEQ:
844 case ISD::SETEQ:
845 Opcode = AMDGPU::V_CMP_NEQ_F32_e64;
846 break;
847 case ISD::SETOGT:
848 case ISD::SETGT:
849 Opcode = AMDGPU::V_CMP_NLT_F32_e64;
850 break;
851 case ISD::SETOGE:
852 case ISD::SETGE:
853 Opcode = AMDGPU::V_CMP_NLE_F32_e64;
854 break;
855 case ISD::SETOLT:
856 case ISD::SETLT:
857 Opcode = AMDGPU::V_CMP_NGT_F32_e64;
858 break;
859 case ISD::SETOLE:
860 case ISD::SETLE:
861 Opcode = AMDGPU::V_CMP_NGE_F32_e64;
862 break;
863 case ISD::SETONE:
864 case ISD::SETNE:
865 Opcode = AMDGPU::V_CMP_NLG_F32_e64;
866 break;
867 default:
868 llvm_unreachable("invalid ISD:SET cond code");
869 }
870
871 MachineBasicBlock &MBB = *MI.getParent();
872
873 // Pick opcode based on comparison type.
874 MachineInstr *VcmpMI;
875 const MachineOperand &Op0 = MI.getOperand(0);
876 const MachineOperand &Op1 = MI.getOperand(1);
877
878 // VCC represents lanes killed.
879 if (TRI->isVGPR(*MRI, Op0.getReg())) {
880 Opcode = AMDGPU::getVOPe32(Opcode);
881 VcmpMI = BuildMI(MBB, &MI, DL, TII->get(Opcode)).add(Op1).add(Op0);
882 } else {
883 VcmpMI = BuildMI(MBB, &MI, DL, TII->get(Opcode))
885 .addImm(0) // src0 modifiers
886 .add(Op1)
887 .addImm(0) // src1 modifiers
888 .add(Op0)
889 .addImm(0); // omod
890 }
891
892 MachineInstr *MaskUpdateMI =
893 BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
894 .addReg(LiveMaskReg)
895 .addReg(LMC.VccReg);
896
897 // State of SCC represents whether any lanes are live in mask,
898 // if SCC is 0 then no lanes will be alive anymore.
899 MachineInstr *EarlyTermMI =
900 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_EARLY_TERMINATE_SCC0));
901
902 MachineInstr *ExecMaskMI =
903 BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LMC.ExecReg)
904 .addReg(LMC.ExecReg)
905 .addReg(LMC.VccReg);
906
907 assert(MBB.succ_size() == 1);
908
909 // Update live intervals
910 LIS->ReplaceMachineInstrInMaps(MI, *VcmpMI);
911 MBB.remove(&MI);
912
913 LIS->InsertMachineInstrInMaps(*MaskUpdateMI);
914 LIS->InsertMachineInstrInMaps(*EarlyTermMI);
915 LIS->InsertMachineInstrInMaps(*ExecMaskMI);
916
917 return ExecMaskMI;
918}
919
920MachineInstr *SIWholeQuadMode::lowerKillI1(MachineInstr &MI, bool IsWQM) {
921 assert(LiveMaskReg.isVirtual());
922
923 MachineBasicBlock &MBB = *MI.getParent();
924
925 const DebugLoc &DL = MI.getDebugLoc();
926 MachineInstr *MaskUpdateMI = nullptr;
927
928 const bool IsDemote = IsWQM && (MI.getOpcode() == AMDGPU::SI_DEMOTE_I1);
929 const MachineOperand &Op = MI.getOperand(0);
930 int64_t KillVal = MI.getOperand(1).getImm();
931 MachineInstr *ComputeKilledMaskMI = nullptr;
932 Register CndReg = !Op.isImm() ? Op.getReg() : Register();
933 Register TmpReg;
934
935 // Is this a static or dynamic kill?
936 if (Op.isImm()) {
937 if (Op.getImm() == KillVal) {
938 // Static: all active lanes are killed
939 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
940 .addReg(LiveMaskReg)
941 .addReg(LMC.ExecReg);
942 } else {
943 // Static: kill does nothing
944 bool IsLastTerminator = std::next(MI.getIterator()) == MBB.end();
945 if (!IsLastTerminator) {
947 } else {
948 assert(MBB.succ_size() == 1 && MI.getOpcode() != AMDGPU::SI_DEMOTE_I1);
949 MachineInstr *NewTerm = BuildMI(MBB, MI, DL, TII->get(AMDGPU::S_BRANCH))
950 .addMBB(*MBB.succ_begin());
951 LIS->ReplaceMachineInstrInMaps(MI, *NewTerm);
952 }
953 MBB.remove(&MI);
954 return nullptr;
955 }
956 } else {
957 if (!KillVal) {
958 // Op represents live lanes after kill,
959 // so exec mask needs to be factored in.
960 TmpReg = MRI->createVirtualRegister(TRI->getBoolRC());
961 ComputeKilledMaskMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), TmpReg)
962 .addReg(LMC.ExecReg)
963 .add(Op);
964 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
965 .addReg(LiveMaskReg)
966 .addReg(TmpReg);
967 } else {
968 // Op represents lanes to kill
969 MaskUpdateMI = BuildMI(MBB, MI, DL, TII->get(LMC.AndN2Opc), LiveMaskReg)
970 .addReg(LiveMaskReg)
971 .add(Op);
972 }
973 }
974
975 // State of SCC represents whether any lanes are live in mask,
976 // if SCC is 0 then no lanes will be alive anymore.
977 MachineInstr *EarlyTermMI =
978 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_EARLY_TERMINATE_SCC0));
979
980 // In the case we got this far some lanes are still live,
981 // update EXEC to deactivate lanes as appropriate.
982 MachineInstr *NewTerm;
983 MachineInstr *WQMMaskMI = nullptr;
984 Register LiveMaskWQM;
985 if (IsDemote) {
986 // Demote - deactivate quads with only helper lanes
987 LiveMaskWQM = MRI->createVirtualRegister(TRI->getBoolRC());
988 WQMMaskMI = BuildMI(MBB, MI, DL, TII->get(LMC.WQMOpc), LiveMaskWQM)
989 .addReg(LiveMaskReg);
990 NewTerm = BuildMI(MBB, MI, DL, TII->get(LMC.AndOpc), LMC.ExecReg)
991 .addReg(LMC.ExecReg)
992 .addReg(LiveMaskWQM);
993 } else {
994 // Kill - deactivate lanes no longer in live mask
995 if (Op.isImm()) {
996 NewTerm =
997 BuildMI(MBB, &MI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(0);
998 } else if (!IsWQM) {
999 NewTerm = BuildMI(MBB, &MI, DL, TII->get(LMC.AndOpc), LMC.ExecReg)
1000 .addReg(LMC.ExecReg)
1001 .addReg(LiveMaskReg);
1002 } else {
1003 unsigned Opcode = KillVal ? LMC.AndN2Opc : LMC.AndOpc;
1004 NewTerm = BuildMI(MBB, &MI, DL, TII->get(Opcode), LMC.ExecReg)
1005 .addReg(LMC.ExecReg)
1006 .add(Op);
1007 }
1008 }
1009
1010 // Update live intervals
1012 MBB.remove(&MI);
1013 assert(EarlyTermMI);
1014 assert(MaskUpdateMI);
1015 assert(NewTerm);
1016 if (ComputeKilledMaskMI)
1017 LIS->InsertMachineInstrInMaps(*ComputeKilledMaskMI);
1018 LIS->InsertMachineInstrInMaps(*MaskUpdateMI);
1019 LIS->InsertMachineInstrInMaps(*EarlyTermMI);
1020 if (WQMMaskMI)
1021 LIS->InsertMachineInstrInMaps(*WQMMaskMI);
1022 LIS->InsertMachineInstrInMaps(*NewTerm);
1023
1024 if (CndReg) {
1025 LIS->removeInterval(CndReg);
1027 }
1028 if (TmpReg)
1030 if (LiveMaskWQM)
1031 LIS->createAndComputeVirtRegInterval(LiveMaskWQM);
1032
1033 return NewTerm;
1034}
1035
1036// Replace (or supplement) instructions accessing live mask.
1037// This can only happen once all the live mask registers have been created
1038// and the execute state (WQM/StrictWWM/Exact) of instructions is known.
1039void SIWholeQuadMode::lowerBlock(MachineBasicBlock &MBB, BlockInfo &BI) {
1040 if (!BI.NeedsLowering)
1041 return;
1042
1043 LLVM_DEBUG(dbgs() << "\nLowering block " << printMBBReference(MBB) << ":\n");
1044
1045 SmallVector<MachineInstr *, 4> SplitPoints;
1046 Register ActiveLanesReg = 0;
1047 char State = BI.InitialState;
1048
1049 for (MachineInstr &MI : llvm::make_early_inc_range(
1051 auto MIState = StateTransition.find(&MI);
1052 if (MIState != StateTransition.end())
1053 State = MIState->second;
1054
1055 MachineInstr *SplitPoint = nullptr;
1056 switch (MI.getOpcode()) {
1057 case AMDGPU::SI_DEMOTE_I1:
1058 case AMDGPU::SI_KILL_I1_TERMINATOR:
1059 SplitPoint = lowerKillI1(MI, State == StateWQM);
1060 break;
1061 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1062 SplitPoint = lowerKillF32(MI);
1063 break;
1064 case AMDGPU::ENTER_STRICT_WWM:
1065 ActiveLanesReg = MI.getOperand(0).getReg();
1066 break;
1067 case AMDGPU::EXIT_STRICT_WWM:
1068 ActiveLanesReg = 0;
1069 break;
1070 case AMDGPU::V_SET_INACTIVE_B32:
1071 if (ActiveLanesReg) {
1072 LiveInterval &LI = LIS->getInterval(MI.getOperand(5).getReg());
1073 MRI->constrainRegClass(ActiveLanesReg, TRI->getWaveMaskRegClass());
1074 MI.getOperand(5).setReg(ActiveLanesReg);
1075 LIS->shrinkToUses(&LI);
1076 } else {
1077 assert(State == StateExact || State == StateWQM);
1078 }
1079 break;
1080 default:
1081 break;
1082 }
1083 if (SplitPoint)
1084 SplitPoints.push_back(SplitPoint);
1085 }
1086
1087 // Perform splitting after instruction scan to simplify iteration.
1088 for (MachineInstr *MI : SplitPoints)
1089 splitBlock(MI);
1090}
1091
1092// Return an iterator in the (inclusive) range [First, Last] at which
1093// instructions can be safely inserted, keeping in mind that some of the
1094// instructions we want to add necessarily clobber SCC.
1095MachineBasicBlock::iterator SIWholeQuadMode::prepareInsertion(
1096 MachineBasicBlock &MBB, MachineBasicBlock::iterator First,
1097 MachineBasicBlock::iterator Last, bool PreferLast, bool SaveSCC) {
1098 if (!SaveSCC)
1099 return PreferLast ? Last : First;
1100
1101 LiveRange &LR =
1102 LIS->getRegUnit(*TRI->regunits(MCRegister::from(AMDGPU::SCC)).begin());
1103 auto MBBE = MBB.end();
1104 SlotIndex FirstIdx = First != MBBE ? LIS->getInstructionIndex(*First)
1105 : LIS->getMBBEndIdx(&MBB);
1106 SlotIndex LastIdx =
1107 Last != MBBE ? LIS->getInstructionIndex(*Last) : LIS->getMBBEndIdx(&MBB);
1108 SlotIndex Idx = PreferLast ? LastIdx : FirstIdx;
1109 const LiveRange::Segment *S;
1110
1111 for (;;) {
1112 S = LR.getSegmentContaining(Idx);
1113 if (!S)
1114 break;
1115
1116 if (PreferLast) {
1117 SlotIndex Next = S->start.getBaseIndex();
1118 if (Next < FirstIdx)
1119 break;
1120 Idx = Next;
1121 } else {
1122 MachineInstr *EndMI = LIS->getInstructionFromIndex(S->end.getBaseIndex());
1123 assert(EndMI && "Segment does not end on valid instruction");
1124 auto NextI = std::next(EndMI->getIterator());
1125 if (NextI == MBB.end())
1126 break;
1127 SlotIndex Next = LIS->getInstructionIndex(*NextI);
1128 if (Next > LastIdx)
1129 break;
1130 Idx = Next;
1131 }
1132 }
1133
1135
1136 if (MachineInstr *MI = LIS->getInstructionFromIndex(Idx))
1137 MBBI = MI;
1138 else {
1139 assert(Idx == LIS->getMBBEndIdx(&MBB));
1140 MBBI = MBB.end();
1141 }
1142
1143 // Move insertion point past any operations modifying EXEC.
1144 // This assumes that the value of SCC defined by any of these operations
1145 // does not need to be preserved.
1146 while (MBBI != Last) {
1147 bool IsExecDef = false;
1148 for (const MachineOperand &MO : MBBI->all_defs()) {
1149 IsExecDef |=
1150 MO.getReg() == AMDGPU::EXEC_LO || MO.getReg() == AMDGPU::EXEC;
1151 }
1152 if (!IsExecDef)
1153 break;
1154 MBBI++;
1155 S = nullptr;
1156 }
1157
1158 if (S)
1159 MBBI = saveSCC(MBB, MBBI);
1160
1161 return MBBI;
1162}
1163
1164void SIWholeQuadMode::toExact(MachineBasicBlock &MBB,
1166 Register SaveWQM) {
1167 assert(LiveMaskReg.isVirtual());
1168
1169 bool IsTerminator = Before == MBB.end();
1170 if (!IsTerminator) {
1171 auto FirstTerm = MBB.getFirstTerminator();
1172 if (FirstTerm != MBB.end()) {
1173 SlotIndex FirstTermIdx = LIS->getInstructionIndex(*FirstTerm);
1174 SlotIndex BeforeIdx = LIS->getInstructionIndex(*Before);
1175 IsTerminator = BeforeIdx > FirstTermIdx;
1176 }
1177 }
1178
1179 MachineInstr *MI;
1180
1181 if (SaveWQM) {
1182 unsigned Opcode =
1183 IsTerminator ? LMC.AndSaveExecTermOpc : LMC.AndSaveExecOpc;
1184 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(Opcode), SaveWQM)
1185 .addReg(LiveMaskReg);
1186 } else {
1187 unsigned Opcode = IsTerminator ? LMC.AndTermOpc : LMC.AndOpc;
1188 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(Opcode), LMC.ExecReg)
1189 .addReg(LMC.ExecReg)
1190 .addReg(LiveMaskReg);
1191 }
1192
1194 StateTransition[MI] = StateExact;
1195}
1196
1197void SIWholeQuadMode::toWQM(MachineBasicBlock &MBB,
1199 Register SavedWQM) {
1200 MachineInstr *MI;
1201
1202 if (SavedWQM) {
1203 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::COPY), LMC.ExecReg)
1204 .addReg(SavedWQM);
1205 } else {
1206 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(LMC.WQMOpc), LMC.ExecReg)
1207 .addReg(LMC.ExecReg);
1208 }
1209
1211 StateTransition[MI] = StateWQM;
1212}
1213
1214void SIWholeQuadMode::toStrictMode(MachineBasicBlock &MBB,
1216 Register SaveOrig, char StrictStateNeeded) {
1217 MachineInstr *MI;
1218 assert(SaveOrig);
1219 assert(StrictStateNeeded == StateStrictWWM ||
1220 StrictStateNeeded == StateStrictWQM);
1221
1222 if (StrictStateNeeded == StateStrictWWM) {
1223 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::ENTER_STRICT_WWM),
1224 SaveOrig)
1225 .addImm(-1);
1226 } else {
1227 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::ENTER_STRICT_WQM),
1228 SaveOrig)
1229 .addImm(-1);
1230 }
1232 StateTransition[MI] = StrictStateNeeded;
1233}
1234
1235void SIWholeQuadMode::fromStrictMode(MachineBasicBlock &MBB,
1237 Register SavedOrig, char NonStrictState,
1238 char CurrentStrictState) {
1239 MachineInstr *MI;
1240
1241 assert(SavedOrig);
1242 assert(CurrentStrictState == StateStrictWWM ||
1243 CurrentStrictState == StateStrictWQM);
1244
1245 if (CurrentStrictState == StateStrictWWM) {
1246 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_STRICT_WWM),
1247 LMC.ExecReg)
1248 .addReg(SavedOrig);
1249 } else {
1250 MI = BuildMI(MBB, Before, DebugLoc(), TII->get(AMDGPU::EXIT_STRICT_WQM),
1251 LMC.ExecReg)
1252 .addReg(SavedOrig);
1253 }
1255 StateTransition[MI] = NonStrictState;
1256}
1257
1258void SIWholeQuadMode::processBlock(MachineBasicBlock &MBB, BlockInfo &BI,
1259 bool IsEntry) {
1260 // This is a non-entry block that is WQM throughout, so no need to do
1261 // anything.
1262 if (!IsEntry && BI.Needs == StateWQM && BI.OutNeeds != StateExact) {
1263 BI.InitialState = StateWQM;
1264 return;
1265 }
1266
1267 LLVM_DEBUG(dbgs() << "\nProcessing block " << printMBBReference(MBB)
1268 << ":\n");
1269
1270 Register SavedWQMReg;
1271 Register SavedNonStrictReg;
1272 bool WQMFromExec = IsEntry;
1273 char State = (IsEntry || !(BI.InNeeds & StateWQM)) ? StateExact : StateWQM;
1274 char NonStrictState = 0;
1275 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
1276
1277 auto II = MBB.getFirstNonPHI(), IE = MBB.end();
1278 if (IsEntry) {
1279 // Skip the instruction that saves LiveMask
1280 if (II != IE && II->getOpcode() == AMDGPU::COPY &&
1281 II->getOperand(1).getReg() == LMC.ExecReg)
1282 ++II;
1283 }
1284
1285 // This stores the first instruction where it's safe to switch from WQM to
1286 // Exact or vice versa.
1288
1289 // This stores the first instruction where it's safe to switch from Strict
1290 // mode to Exact/WQM or to switch to Strict mode. It must always be the same
1291 // as, or after, FirstWQM since if it's safe to switch to/from Strict, it must
1292 // be safe to switch to/from WQM as well.
1293 MachineBasicBlock::iterator FirstStrict = IE;
1294
1295 // Record initial state is block information.
1296 BI.InitialState = State;
1297
1298 for (unsigned Idx = 0;; ++Idx) {
1300 char Needs = StateExact | StateWQM; // Strict mode is disabled by default.
1301 char OutNeeds = 0;
1302
1303 if (FirstWQM == IE)
1304 FirstWQM = II;
1305
1306 if (FirstStrict == IE)
1307 FirstStrict = II;
1308
1309 // Adjust needs if this is first instruction of WQM requiring shader.
1310 if (IsEntry && Idx == 0 && (BI.InNeeds & StateWQM))
1311 Needs = StateWQM;
1312
1313 // First, figure out the allowed states (Needs) based on the propagated
1314 // flags.
1315 if (II != IE) {
1316 MachineInstr &MI = *II;
1317
1318 if (MI.isTerminator() || TII->mayReadEXEC(*MRI, MI)) {
1319 auto III = Instructions.find(&MI);
1320 if (III != Instructions.end()) {
1321 if (III->second.Needs & StateStrictWWM)
1322 Needs = StateStrictWWM;
1323 else if (III->second.Needs & StateStrictWQM)
1324 Needs = StateStrictWQM;
1325 else if (III->second.Needs & StateWQM)
1326 Needs = StateWQM;
1327 else
1328 Needs &= ~III->second.Disabled;
1329 OutNeeds = III->second.OutNeeds;
1330 }
1331 } else {
1332 // If the instruction doesn't actually need a correct EXEC, then we can
1333 // safely leave Strict mode enabled.
1334 Needs = StateExact | StateWQM | StateStrict;
1335 }
1336
1337 // Exact mode exit can occur in terminators, but must be before branches.
1338 if (MI.isBranch() && OutNeeds == StateExact)
1339 Needs = StateExact;
1340
1341 ++Next;
1342 } else {
1343 // End of basic block
1344 if (BI.OutNeeds & StateWQM)
1345 Needs = StateWQM;
1346 else if (BI.OutNeeds == StateExact)
1347 Needs = StateExact;
1348 else
1349 Needs = StateWQM | StateExact;
1350 }
1351
1352 // Now, transition if necessary.
1353 if (!(Needs & State)) {
1355 if (State == StateStrictWWM || Needs == StateStrictWWM ||
1356 State == StateStrictWQM || Needs == StateStrictWQM) {
1357 // We must switch to or from Strict mode.
1358 First = FirstStrict;
1359 } else {
1360 // We only need to switch to/from WQM, so we can use FirstWQM.
1361 First = FirstWQM;
1362 }
1363
1364 // Whether we need to save SCC depends on start and end states.
1365 bool SaveSCC = false;
1366 switch (State) {
1367 case StateExact:
1368 case StateStrictWWM:
1369 case StateStrictWQM:
1370 // Exact/Strict -> Strict: save SCC
1371 // Exact/Strict -> WQM: save SCC if WQM mask is generated from exec
1372 // Exact/Strict -> Exact: no save
1373 SaveSCC = (Needs & StateStrict) || ((Needs & StateWQM) && WQMFromExec);
1374 break;
1375 case StateWQM:
1376 // WQM -> Exact/Strict: save SCC
1377 SaveSCC = !(Needs & StateWQM);
1378 break;
1379 default:
1380 llvm_unreachable("Unknown state");
1381 break;
1382 }
1383 char StartState = State & StateStrict ? NonStrictState : State;
1384 bool WQMToExact =
1385 StartState == StateWQM && (Needs & StateExact) && !(Needs & StateWQM);
1386 bool ExactToWQM = StartState == StateExact && (Needs & StateWQM) &&
1387 !(Needs & StateExact);
1388 bool PreferLast = Needs == StateWQM;
1389 // Exact regions in divergent control flow may run at EXEC=0, so try to
1390 // exclude instructions with unexpected effects from them.
1391 // FIXME: ideally we would branch over these when EXEC=0,
1392 // but this requires updating implicit values, live intervals and CFG.
1393 if ((WQMToExact && (OutNeeds & StateWQM)) || ExactToWQM) {
1394 for (MachineBasicBlock::iterator I = First; I != II; ++I) {
1395 if (TII->hasUnwantedEffectsWhenEXECEmpty(*I)) {
1396 PreferLast = WQMToExact;
1397 break;
1398 }
1399 }
1400 }
1402 prepareInsertion(MBB, First, II, PreferLast, SaveSCC);
1403
1404 if (State & StateStrict) {
1405 assert(State == StateStrictWWM || State == StateStrictWQM);
1406 assert(SavedNonStrictReg);
1407 fromStrictMode(MBB, Before, SavedNonStrictReg, NonStrictState, State);
1408
1409 LIS->createAndComputeVirtRegInterval(SavedNonStrictReg);
1410 SavedNonStrictReg = 0;
1411 State = NonStrictState;
1412 }
1413
1414 if (Needs & StateStrict) {
1415 NonStrictState = State;
1416 assert(Needs == StateStrictWWM || Needs == StateStrictWQM);
1417 assert(!SavedNonStrictReg);
1418 SavedNonStrictReg = MRI->createVirtualRegister(BoolRC);
1419
1420 toStrictMode(MBB, Before, SavedNonStrictReg, Needs);
1421 State = Needs;
1422 } else {
1423 if (WQMToExact) {
1424 if (!WQMFromExec && (OutNeeds & StateWQM)) {
1425 assert(!SavedWQMReg);
1426 SavedWQMReg = MRI->createVirtualRegister(BoolRC);
1427 }
1428
1429 toExact(MBB, Before, SavedWQMReg);
1430 State = StateExact;
1431 } else if (ExactToWQM) {
1432 assert(WQMFromExec == (SavedWQMReg == 0));
1433
1434 toWQM(MBB, Before, SavedWQMReg);
1435
1436 if (SavedWQMReg) {
1437 LIS->createAndComputeVirtRegInterval(SavedWQMReg);
1438 SavedWQMReg = 0;
1439 }
1440 State = StateWQM;
1441 } else {
1442 // We can get here if we transitioned from StrictWWM to a
1443 // non-StrictWWM state that already matches our needs, but we
1444 // shouldn't need to do anything.
1445 assert(Needs & State);
1446 }
1447 }
1448 }
1449
1450 if (Needs != (StateExact | StateWQM | StateStrict)) {
1451 if (Needs != (StateExact | StateWQM))
1452 FirstWQM = IE;
1453 FirstStrict = IE;
1454 }
1455
1456 if (II == IE)
1457 break;
1458
1459 II = Next;
1460 }
1461 assert(!SavedWQMReg);
1462 assert(!SavedNonStrictReg);
1463}
1464
1465bool SIWholeQuadMode::lowerLiveMaskQueries() {
1466 for (MachineInstr *MI : LiveMaskQueries) {
1467 const DebugLoc &DL = MI->getDebugLoc();
1468 Register Dest = MI->getOperand(0).getReg();
1469
1470 MachineInstr *Copy =
1471 BuildMI(*MI->getParent(), MI, DL, TII->get(AMDGPU::COPY), Dest)
1472 .addReg(LiveMaskReg);
1473
1474 LIS->ReplaceMachineInstrInMaps(*MI, *Copy);
1475 MI->eraseFromParent();
1476 }
1477 return !LiveMaskQueries.empty();
1478}
1479
1480bool SIWholeQuadMode::lowerCopyInstrs() {
1481 for (MachineInstr *MI : LowerToMovInstrs) {
1482 assert(MI->getNumExplicitOperands() == 2);
1483
1484 const Register Reg = MI->getOperand(0).getReg();
1485
1486 const TargetRegisterClass *regClass =
1487 TRI->getRegClassForOperandReg(*MRI, MI->getOperand(0));
1488 if (TRI->isVGPRClass(regClass)) {
1489 const unsigned MovOp = TII->getMovOpcode(regClass);
1490 MI->setDesc(TII->get(MovOp));
1491
1492 // Check that it already implicitly depends on exec (like all VALU movs
1493 // should do).
1494 assert(any_of(MI->implicit_operands(), [](const MachineOperand &MO) {
1495 return MO.isUse() && MO.getReg() == AMDGPU::EXEC;
1496 }));
1497 } else {
1498 // Remove early-clobber and exec dependency from simple SGPR copies.
1499 // This allows some to be eliminated during/post RA.
1500 LLVM_DEBUG(dbgs() << "simplify SGPR copy: " << *MI);
1501 if (MI->getOperand(0).isEarlyClobber()) {
1502 LIS->removeInterval(Reg);
1503 MI->getOperand(0).setIsEarlyClobber(false);
1505 }
1506 int Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC, /*TRI=*/nullptr);
1507 while (Index >= 0) {
1508 MI->removeOperand(Index);
1509 Index = MI->findRegisterUseOperandIdx(AMDGPU::EXEC, /*TRI=*/nullptr);
1510 }
1511 MI->setDesc(TII->get(AMDGPU::COPY));
1512 LLVM_DEBUG(dbgs() << " -> " << *MI);
1513 }
1514 }
1515 for (MachineInstr *MI : LowerToCopyInstrs) {
1516 LLVM_DEBUG(dbgs() << "simplify: " << *MI);
1517
1518 if (MI->getOpcode() == AMDGPU::V_SET_INACTIVE_B32) {
1519 assert(MI->getNumExplicitOperands() == 6);
1520
1521 LiveInterval *RecomputeLI = nullptr;
1522 if (MI->getOperand(4).isReg())
1523 RecomputeLI = &LIS->getInterval(MI->getOperand(4).getReg());
1524
1525 MI->removeOperand(5);
1526 MI->removeOperand(4);
1527 MI->removeOperand(3);
1528 MI->removeOperand(1);
1529
1530 if (RecomputeLI)
1531 LIS->shrinkToUses(RecomputeLI);
1532 } else {
1533 assert(MI->getNumExplicitOperands() == 2);
1534 }
1535
1536 unsigned CopyOp = MI->getOperand(1).isReg()
1537 ? (unsigned)AMDGPU::COPY
1538 : TII->getMovOpcode(TRI->getRegClassForOperandReg(
1539 *MRI, MI->getOperand(0)));
1540 MI->setDesc(TII->get(CopyOp));
1541 LLVM_DEBUG(dbgs() << " -> " << *MI);
1542 }
1543 return !LowerToCopyInstrs.empty() || !LowerToMovInstrs.empty();
1544}
1545
1546bool SIWholeQuadMode::lowerKillInstrs(bool IsWQM) {
1547 for (MachineInstr *MI : KillInstrs) {
1548 MachineInstr *SplitPoint = nullptr;
1549 switch (MI->getOpcode()) {
1550 case AMDGPU::SI_DEMOTE_I1:
1551 case AMDGPU::SI_KILL_I1_TERMINATOR:
1552 SplitPoint = lowerKillI1(*MI, IsWQM);
1553 break;
1554 case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1555 SplitPoint = lowerKillF32(*MI);
1556 break;
1557 }
1558 if (SplitPoint)
1559 splitBlock(SplitPoint);
1560 }
1561 return !KillInstrs.empty();
1562}
1563
1564void SIWholeQuadMode::lowerInitExec(MachineInstr &MI) {
1565 MachineBasicBlock *MBB = MI.getParent();
1566
1567 if (MI.getOpcode() == AMDGPU::SI_INIT_WHOLE_WAVE) {
1568 assert(MBB == &MBB->getParent()->front() &&
1569 "init whole wave not in entry block");
1570 Register EntryExec = MRI->createVirtualRegister(TRI->getBoolRC());
1571 MachineInstr *SaveExec = BuildMI(*MBB, MBB->begin(), MI.getDebugLoc(),
1572 TII->get(LMC.OrSaveExecOpc), EntryExec)
1573 .addImm(-1);
1574
1575 // Replace all uses of MI's destination reg with EntryExec.
1576 MRI->replaceRegWith(MI.getOperand(0).getReg(), EntryExec);
1577
1578 if (LIS) {
1580 }
1581
1582 MI.eraseFromParent();
1583
1584 if (LIS) {
1585 LIS->InsertMachineInstrInMaps(*SaveExec);
1586 LIS->createAndComputeVirtRegInterval(EntryExec);
1587 }
1588 return;
1589 }
1590
1591 if (MI.getOpcode() == AMDGPU::SI_INIT_EXEC) {
1592 // This should be before all vector instructions.
1593 MachineInstr *InitMI = BuildMI(*MBB, MBB->begin(), MI.getDebugLoc(),
1594 TII->get(LMC.MovOpc), LMC.ExecReg)
1595 .addImm(MI.getOperand(0).getImm());
1596 if (LIS) {
1598 LIS->InsertMachineInstrInMaps(*InitMI);
1599 }
1600 MI.eraseFromParent();
1601 return;
1602 }
1603
1604 // Extract the thread count from an SGPR input and set EXEC accordingly.
1605 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
1606 //
1607 // S_BFE_U32 count, input, {shift, 7}
1608 // S_BFM_B64 exec, count, 0
1609 // S_CMP_EQ_U32 count, 64
1610 // S_CMOV_B64 exec, -1
1611 Register InputReg = MI.getOperand(0).getReg();
1612 MachineInstr *FirstMI = &*MBB->begin();
1613 if (InputReg.isVirtual()) {
1614 MachineInstr *DefInstr = MRI->getVRegDef(InputReg);
1615 assert(DefInstr && DefInstr->isCopy());
1616 if (DefInstr->getParent() == MBB) {
1617 if (DefInstr != FirstMI) {
1618 // If the `InputReg` is defined in current block, we also need to
1619 // move that instruction to the beginning of the block.
1620 DefInstr->removeFromParent();
1621 MBB->insert(FirstMI, DefInstr);
1622 if (LIS)
1623 LIS->handleMove(*DefInstr);
1624 } else {
1625 // If first instruction is definition then move pointer after it.
1626 FirstMI = &*std::next(FirstMI->getIterator());
1627 }
1628 }
1629 }
1630
1631 // Insert instruction sequence at block beginning (before vector operations).
1632 const DebugLoc DL = MI.getDebugLoc();
1633 const unsigned WavefrontSize = ST->getWavefrontSize();
1634 const unsigned Mask = (WavefrontSize << 1) - 1;
1635 Register CountReg = MRI->createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1636 auto BfeMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_BFE_U32), CountReg)
1637 .addReg(InputReg)
1638 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
1639 auto BfmMI = BuildMI(*MBB, FirstMI, DL, TII->get(LMC.BfmOpc), LMC.ExecReg)
1640 .addReg(CountReg)
1641 .addImm(0);
1642 auto CmpMI = BuildMI(*MBB, FirstMI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
1643 .addReg(CountReg, RegState::Kill)
1644 .addImm(WavefrontSize);
1645 auto CmovMI =
1646 BuildMI(*MBB, FirstMI, DL, TII->get(LMC.CMovOpc), LMC.ExecReg).addImm(-1);
1647
1648 if (!LIS) {
1649 MI.eraseFromParent();
1650 return;
1651 }
1652
1654 MI.eraseFromParent();
1655
1656 LIS->InsertMachineInstrInMaps(*BfeMI);
1657 LIS->InsertMachineInstrInMaps(*BfmMI);
1658 LIS->InsertMachineInstrInMaps(*CmpMI);
1659 LIS->InsertMachineInstrInMaps(*CmovMI);
1660
1661 LIS->removeInterval(InputReg);
1662 LIS->createAndComputeVirtRegInterval(InputReg);
1663 LIS->createAndComputeVirtRegInterval(CountReg);
1664}
1665
1666/// Lower INIT_EXEC instructions. Return a suitable insert point in \p Entry
1667/// for instructions that depend on EXEC.
1669SIWholeQuadMode::lowerInitExecInstrs(MachineBasicBlock &Entry, bool &Changed) {
1670 MachineBasicBlock::iterator InsertPt = Entry.getFirstNonPHI();
1671
1672 for (MachineInstr *MI : InitExecInstrs) {
1673 // Try to handle undefined cases gracefully:
1674 // - multiple INIT_EXEC instructions
1675 // - INIT_EXEC instructions not in the entry block
1676 if (MI->getParent() == &Entry)
1677 InsertPt = std::next(MI->getIterator());
1678
1679 lowerInitExec(*MI);
1680 Changed = true;
1681 }
1682
1683 return InsertPt;
1684}
1685
1686bool SIWholeQuadMode::run(MachineFunction &MF) {
1687 LLVM_DEBUG(dbgs() << "SI Whole Quad Mode on " << MF.getName()
1688 << " ------------- \n");
1689 LLVM_DEBUG(MF.dump(););
1690
1691 Instructions.clear();
1692 Blocks.clear();
1693 LiveMaskQueries.clear();
1694 LowerToCopyInstrs.clear();
1695 LowerToMovInstrs.clear();
1696 KillInstrs.clear();
1697 InitExecInstrs.clear();
1698 SetInactiveInstrs.clear();
1699 StateTransition.clear();
1700
1701 const char GlobalFlags = analyzeFunction(MF);
1702 bool Changed = false;
1703
1704 LiveMaskReg = LMC.ExecReg;
1705
1706 MachineBasicBlock &Entry = MF.front();
1707 MachineBasicBlock::iterator EntryMI = lowerInitExecInstrs(Entry, Changed);
1708
1709 // Store a copy of the original live mask when required
1710 const bool HasLiveMaskQueries = !LiveMaskQueries.empty();
1711 const bool HasWaveModes = GlobalFlags & ~StateExact;
1712 const bool HasKills = !KillInstrs.empty();
1713 const bool UsesWQM = GlobalFlags & StateWQM;
1714 if (HasKills || UsesWQM || (HasWaveModes && HasLiveMaskQueries)) {
1715 LiveMaskReg = MRI->createVirtualRegister(TRI->getBoolRC());
1716 MachineInstr *MI =
1717 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(AMDGPU::COPY), LiveMaskReg)
1718 .addReg(LMC.ExecReg);
1720 Changed = true;
1721 }
1722
1723 // Check if V_SET_INACTIVE was touched by a strict state mode.
1724 // If so, promote to WWM; otherwise lower to COPY.
1725 for (MachineInstr *MI : SetInactiveInstrs) {
1726 if (LowerToCopyInstrs.contains(MI))
1727 continue;
1728 auto &Info = Instructions[MI];
1729 if (Info.MarkedStates & StateStrict) {
1730 Info.Needs |= StateStrictWWM;
1731 Info.Disabled &= ~StateStrictWWM;
1732 Blocks[MI->getParent()].Needs |= StateStrictWWM;
1733 } else {
1734 LLVM_DEBUG(dbgs() << "Has no WWM marking: " << *MI);
1735 LowerToCopyInstrs.insert(MI);
1736 }
1737 }
1738
1739 LLVM_DEBUG(printInfo());
1740
1741 Changed |= lowerLiveMaskQueries();
1742 Changed |= lowerCopyInstrs();
1743
1744 if (!HasWaveModes) {
1745 // No wave mode execution
1746 Changed |= lowerKillInstrs(false);
1747 } else if (GlobalFlags == StateWQM) {
1748 // Shader only needs WQM
1749 auto MI =
1750 BuildMI(Entry, EntryMI, DebugLoc(), TII->get(LMC.WQMOpc), LMC.ExecReg)
1751 .addReg(LMC.ExecReg);
1753 lowerKillInstrs(true);
1754 Changed = true;
1755 } else {
1756 // Mark entry for WQM if required.
1757 if (GlobalFlags & StateWQM)
1758 Blocks[&Entry].InNeeds |= StateWQM;
1759 // Wave mode switching requires full lowering pass.
1760 for (auto &BII : Blocks)
1761 processBlock(*BII.first, BII.second, BII.first == &Entry);
1762 // Lowering blocks causes block splitting so perform as a second pass.
1763 for (auto &BII : Blocks)
1764 lowerBlock(*BII.first, BII.second);
1765 Changed = true;
1766 }
1767
1768 // Compute live range for live mask
1769 if (LiveMaskReg != LMC.ExecReg)
1770 LIS->createAndComputeVirtRegInterval(LiveMaskReg);
1771
1772 // Physical registers like SCC aren't tracked by default anyway, so just
1773 // removing the ranges we computed is the simplest option for maintaining
1774 // the analysis results.
1775 LIS->removeAllRegUnitsForPhysReg(AMDGPU::SCC);
1776
1777 // If we performed any kills then recompute EXEC
1778 if (!KillInstrs.empty() || !InitExecInstrs.empty())
1779 LIS->removeAllRegUnitsForPhysReg(AMDGPU::EXEC);
1780
1781 return Changed;
1782}
1783
1784bool SIWholeQuadModeLegacy::runOnMachineFunction(MachineFunction &MF) {
1785 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1786 auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
1787 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
1788 auto *PDTWrapper =
1789 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
1790 MachinePostDominatorTree *PDT =
1791 PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
1792 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
1793 return Impl.run(MF);
1794}
1795
1796PreservedAnalyses
1799 MFPropsModifier _(*this, MF);
1800
1806 SIWholeQuadMode Impl(MF, LIS, MDT, PDT);
1807 bool Changed = Impl.run(MF);
1808 if (!Changed)
1809 return PreservedAnalyses::all();
1810
1816 return PA;
1817}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void analyzeFunction(Function &Fn, const DataLayout &Layout, FunctionVarLocsBuilder *FnVarLocs)
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
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:58
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
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)
SI Optimize VGPR LiveRange
#define LLVM_DEBUG(...)
Definition Debug.h:114
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:270
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
bool hasExtendedImageInsts() const
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.
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
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:69
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 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 & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
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,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
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:19
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:102
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:74
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:78
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:356
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
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:181
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
self_iterator getIterator()
Definition ilist_node.h:130
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 int getVOPe32(uint16_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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ Define
Register definition.
@ Kill
The last use of a register.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:634
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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:1712
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
unsigned MCRegUnit
Register units are used to compute register aliasing.
Definition MCRegister.h:30
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:71
FunctionPass * createSIWholeQuadModeLegacyPass()
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
char & SIWholeQuadModeID
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
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