https://github.com/danzimm created 
https://github.com/llvm/llvm-project/pull/243204

This is an alternative approach to 
https://github.com/llvm/llvm-project/pull/221115 - instead of automatically 
determining when it's profitable to insert padding, we'll put the control in 
the kernel writer's hands.

## Overview

In the aforementioned PR the goal is to optimize code of the form:
```
int i = ...;
int j = ...;
T v0 = load(i);
T v1 = Default;
if (Condition(j)) {
  v1 = load(j);
}
use(v0);
[... long pile of unrelated work ...]
f(..., v, ...);
```
At the moment this code will require a `s_waitcnt vmcnt(0)` instruction prior 
to the use of `v0`, even though, in theory, the load associated with `v1` could 
be left outstanding. The reason being: if `Condition(j)` is false, then there's 
no `v1` load that can be left outstanding.

On gfx9, to improve the situation, we can insert `buffer_inv 0` instructions in 
`else` branches, so that instead of falling through without bumping `VMcnt`, 
the counter is incremented, allowing `s_waitcnt vmcnt(1)`, i.e. leaving the 
`v1` load outstanding. The performance characteristics of `buffer_inv` were 
investigated and documented in 
https://github.com/llvm/llvm-project/pull/233528. 

The above PR tried to automatically determine when to insert the `buffer_inv` 
padding, but ended up regressing, among other examples, [a gemv in 
rocblas](https://github.com/ROCm/rocBLAS/blob/defce200a69e5346eeadd7ac1e199238758add61/library/src/blas2/gemv_device.hpp#L315-L487).
 After determining a root cause, I realized the only way to definitively 
determine if inserting padding is profitable is to essentially try every 
possible codegen of inserting/not-inserting padding at each branch. For obvious 
reasons this isn't ideal.

## This PR

Instead of automatically inserting padding this PR introduces a 
builtin/intrinsic/rocdl binding to generate a `buffer_inv 0` instruction. A 
couple of notes:
- We need an explicit padding pseudo instruction, instead of having the user 
write a buffer_inv builtin/intrinsic 
(https://github.com/llvm/llvm-project/pull/228497), because `SIInsertWaitcnts` 
can't reason about `EXEC` state. Namely, `StructurizeCFG` will emit code which 
makes the branching scheme opaque (see more details in 
https://github.com/llvm/llvm-project/pull/221115#issuecomment-5938060304).
- For now only `VMcnt` on gfx9 is supported, but I plan to extend this to 
support `DScnt`, by using `ds_nop` instead of `buffer_inv 0`, as well as 
`LOADcnt` and `STOREcnt` on gfx125x.

Once this PR is merged the plan is to teach triton (and possibly flydsl) to 
emit these padding statements directly for e.g. masked operations (the PR 
mentioned at the top shows an example grouped gemm- this applies to any jagged 
operations, though).

## AI Disclosure

This was co-authored by claude. I told it everything specific to implement / 
how to implement it. It knows more LLVM APIs, than me, though, so I leaned on 
it where needed. This is a draft right now because I want to do one more pass 
through on e.g. docs to make sure claude didn't change what I said.

>From e1112a5a0982384b67288cc8ec59ff41e9d880f0 Mon Sep 17 00:00:00 2001
From: Dan Zimmerman <[email protected]>
Date: Thu, 29 Oct 2026 10:23:13 -0700
Subject: [PATCH 1/2] [AMDGPU] Add the counter padding intrinsic and builtin

Assisted-by: Claude Opus 5.5
---
 clang/include/clang/Basic/BuiltinsAMDGPU.td   |  4 ++
 .../include/clang/Basic/BuiltinsAMDGPUDocs.td | 27 ++++++++++++
 clang/lib/Headers/amdgpuintrin.h              |  5 +++
 .../builtins-amdgcn-pad-counter.cl            | 27 ++++++++++++
 .../SemaOpenCL/builtins-amdgcn-pad-counter.cl | 11 +++++
 llvm/docs/AMDGPUUsage.md                      |  4 ++
 llvm/include/llvm/IR/IntrinsicsAMDGPU.td      |  7 ++++
 llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp  |  8 ++++
 llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp  |  1 +
 .../AMDGPU/AMDGPURegBankLegalizeRules.cpp     |  1 +
 llvm/lib/Target/AMDGPU/SIInstructions.td      | 16 +++++++
 .../AMDGPU/waitcnt-pad-counter-intrinsic.ll   | 42 +++++++++++++++++++
 mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td  | 21 ++++++++++
 .../test/Target/LLVMIR/rocdl-pad-counter.mlir | 40 ++++++++++++++++++
 14 files changed, 214 insertions(+)
 create mode 100644 clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
 create mode 100644 clang/test/SemaOpenCL/builtins-amdgcn-pad-counter.cl
 create mode 100644 llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
 create mode 100644 mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir

diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.td 
b/clang/include/clang/Basic/BuiltinsAMDGPU.td
index b098ddd6da836f..e218f442248112 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.td
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.td
@@ -155,6 +155,10 @@ def __builtin_amdgcn_wave_barrier : 
AMDGPUBuiltin<"void()">;
 def __builtin_amdgcn_sched_barrier : AMDGPUBuiltin<"void(_Constant int)">;
 def __builtin_amdgcn_sched_group_barrier : AMDGPUBuiltin<"void(_Constant int, 
_Constant int, _Constant int)">;
 def __builtin_amdgcn_iglp_opt : AMDGPUBuiltin<"void(_Constant int)">;
+def __builtin_amdgcn_pad_counter : AMDGPUBuiltin<"void(_Constant int, 
_Constant int)"> {
+  let Documentation = [DocPadCounter];
+  let ArgNames = ["counter", "count"];
+}
 def __builtin_amdgcn_s_dcache_inv : AMDGPUBuiltin<"void()">;
 def __builtin_amdgcn_buffer_wbinvl1 : AMDGPUBuiltin<"void()">;
 def __builtin_amdgcn_fence : AMDGPUBuiltin<"void(unsigned int, char const *, 
...)">;
diff --git a/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td 
b/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td
index 87a7663e75e46c..3809b6fb4d027a 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td
+++ b/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td
@@ -1050,3 +1050,30 @@ to instruction memory, with the length specified by 
``len``, which should be
 0-31 (1-32 chunks, units of 128 bytes).
 }];
 }
+
+//===----------------------------------------------------------------------===//
+// Wait Counter Builtins
+//===----------------------------------------------------------------------===//
+
+def DocCatAMDGPUWaitcnt : DocumentationCategory<"Wait Counter Builtins"> {
+  let Content = [{
+These builtins provide hints that influence how the backend inserts waits on
+hardware dependency counters.
+}];
+}
+
+def DocPadCounter : Documentation {
+  let Category = DocCatAMDGPUWaitcnt;
+  let Content = [{
+Optional hint that requests exactly ``count`` extra events on hardware counter
+``counter`` along the opposite edge of the branch whose arm contains the call.
+Balancing the counter histories of both arms lets waits after the join be
+relaxed. Both arguments must be compile-time constants. ``counter`` 0 selects
+the LOAD (VM) counter; no other selectors are currently defined.
+
+The hint is advisory: zero counts, unsupported selectors, counts, targets, or
+control-flow shapes are ignored rather than diagnosed. The call itself issues
+no counter event and never permits a wait to be weakened; waits are always
+computed from the instructions that are actually emitted.
+}];
+}
diff --git a/clang/lib/Headers/amdgpuintrin.h b/clang/lib/Headers/amdgpuintrin.h
index eb9c95281075ce..d7c1c95ff86f29 100644
--- a/clang/lib/Headers/amdgpuintrin.h
+++ b/clang/lib/Headers/amdgpuintrin.h
@@ -27,6 +27,11 @@ _Pragma("omp begin declare variant match(device = 
{arch(amdgcn)})");
 #define __gpu_global __attribute__((address_space(1)))
 #define __gpu_generic __attribute__((address_space(0)))
 
+// Counter selectors for __builtin_amdgcn_pad_counter.
+enum __amdgpu_pad_counter {
+  __AMDGPU_PAD_COUNTER_LOAD = 0,
+};
+
 // Returns the number of workgroups in the 'x' dimension of the grid.
 _DEFAULT_FN_ATTRS static __inline__ uint32_t __gpu_num_blocks_x(void) {
   return __builtin_amdgcn_grid_size_x() / __builtin_amdgcn_workgroup_size_x();
diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
new file mode 100644
index 00000000000000..f8671d7812bae1
--- /dev/null
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -emit-llvm 
-o - %s | FileCheck %s --check-prefix=IR
+// REQUIRES: amdgpu-registered-target
+
+// The void hint must survive optimization in the conditional load arm.
+// IR-LABEL: @hinted_kernel(
+// IR: [[A:%.*]] = load i32
+// IR: br i1 {{.*}}, label %[[JOIN:[^, ]+]], label %[[LOAD:[^, ]+]]
+// IR: [[LOAD]]:
+// IR: [[B:%.*]] = load i32
+// IR-NEXT: {{(tail )?}}call void @llvm.amdgcn.pad.counter(i32 0, i32 1)
+// IR: [[JOIN]]:
+// IR-NEXT: [[V:%.*]] = phi i32 [ [[B]], %[[LOAD]] ], [ 0, %{{.*}} ]
+// IR: store i32 [[A]]
+// IR: store i32 [[V]]
+
+kernel void hinted_kernel(global int *data, global int *out,
+                          int condition) {
+  unsigned index = __builtin_amdgcn_workitem_id_x();
+  int a = data[index];
+  int v = 0;
+  if (condition) {
+    v = data[index + 64];
+    __builtin_amdgcn_pad_counter(0, 1);
+  }
+  out[index] = a;
+  out[index + 64] = v;
+}
diff --git a/clang/test/SemaOpenCL/builtins-amdgcn-pad-counter.cl 
b/clang/test/SemaOpenCL/builtins-amdgcn-pad-counter.cl
new file mode 100644
index 00000000000000..ee8d5a7effdb94
--- /dev/null
+++ b/clang/test/SemaOpenCL/builtins-amdgcn-pad-counter.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -fsyntax-only 
-verify %s
+// REQUIRES: amdgpu-registered-target
+
+void immediate_arguments(int counter, int count) {
+  __builtin_amdgcn_pad_counter(counter, 1); // expected-error {{must be a 
constant integer}}
+  __builtin_amdgcn_pad_counter(0, count); // expected-error {{must be a 
constant integer}}
+  // Unsupported values are optional hints, not frontend errors.
+  __builtin_amdgcn_pad_counter(0, 0);
+  __builtin_amdgcn_pad_counter(0, -1);
+  __builtin_amdgcn_pad_counter(1, 1);
+}
diff --git a/llvm/docs/AMDGPUUsage.md b/llvm/docs/AMDGPUUsage.md
index 8a8eb1d0b6fc40..ad2540053ca902 100644
--- a/llvm/docs/AMDGPUUsage.md
+++ b/llvm/docs/AMDGPUUsage.md
@@ -2620,6 +2620,10 @@ The AMDGPU backend implements the following LLVM IR 
intrinsics.
     The iglp_opt intrinsic cannot be combined with sched_barrier or 
sched_group_barrier.
 
     The iglp_opt strategy implementations are subject to change.
+* - llvm.amdgcn.pad.counter
+  - Optional exact-count hint to add counter events on the opposite edge of a 
supported single-block triangle or diamond arm. Both i32 arguments are 
immediate: counter 0 selects LOAD/VM and count selects the exact number of 
extra events. The hint itself emits no event and grants no permission to weaken 
a wait.
+
+    Available through __builtin_amdgcn_pad_counter(counter, count) and 
rocdl.pad.counter.
 * - llvm.amdgcn.s.getpc
   - Provides access to the s_getpc_b64 instruction, but with the return value 
sign-extended from the width of the underlying PC hardware register even on 
processors where the s_getpc_b64 instruction returns a zero-extended value.
 * - llvm.amdgcn.implicit.buffer.ptr
diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index a4abe8d2c4e0d8..ed84e6c6e0cb91 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -409,6 +409,13 @@ def int_amdgcn_iglp_opt : 
ClangBuiltin<"__builtin_amdgcn_iglp_opt">,
   Intrinsic<[], [llvm_i32_ty], [ImmArg<ArgIndex<0>>, IntrNoMem, 
IntrHasSideEffects, IntrConvergent,
                                 IntrWillReturn, IntrNoCallback, IntrNoFree]>;
 
+// Optional exact-count hint to pad the opposite arm of a supported branch.
+// The hint itself has no hardware counter effect.
+def int_amdgcn_pad_counter : ClangBuiltin<"__builtin_amdgcn_pad_counter">,
+  Intrinsic<[], [llvm_i32_ty, llvm_i32_ty],
+    [ImmArg<ArgIndex<0>>, ImmArg<ArgIndex<1>>, IntrNoMem, IntrHasSideEffects,
+     IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]>;
+
 def int_amdgcn_s_waitcnt : ClangBuiltin<"__builtin_amdgcn_s_waitcnt">,
   Intrinsic<[], [llvm_i32_ty], [ImmArg<ArgIndex<0>>, IntrNoMem, 
IntrHasSideEffects, IntrWillReturn, IntrNoCallback, IntrNoFree]>;
 
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp
index b391761e3b9062..736ee6b4e9d770 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp
@@ -421,6 +421,14 @@ void AMDGPUAsmPrinter::emitInstruction(const MachineInstr 
*MI) {
       return;
     }
 
+    if (MI->getOpcode() == AMDGPU::PAD_COUNTER) {
+      if (isVerbose())
+        OutStreamer->emitRawComment(" pad_counter(" +
+                                    Twine(MI->getOperand(0).getImm()) + ", " +
+                                    Twine(MI->getOperand(1).getImm()) + ")");
+      return;
+    }
+
     if (MI->getOpcode() == AMDGPU::SI_MASKED_UNREACHABLE) {
       if (isVerbose())
         OutStreamer->emitRawComment(" divergent unreachable");
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp
index 0125a402d0b187..ee6c200c811b1f 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp
@@ -397,6 +397,7 @@ bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, 
AAResults *AA) {
     case Intrinsic::amdgcn_sched_barrier:
     case Intrinsic::amdgcn_sched_group_barrier:
     case Intrinsic::amdgcn_iglp_opt:
+    case Intrinsic::amdgcn_pad_counter:
       return false;
     default:
       break;
diff --git a/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp
index f20fb24714e278..ff4bec53810903 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp
@@ -1819,6 +1819,7 @@ RegBankLegalizeRules::RegBankLegalizeRules(const 
GCNSubtarget &_ST,
   addRulesForIOpcs({amdgcn_asyncmark,
                     amdgcn_endpgm,
                     amdgcn_iglp_opt,
+                    amdgcn_pad_counter,
                     amdgcn_init_exec,
                     amdgcn_s_barrier,
                     amdgcn_s_barrier_leave,
diff --git a/llvm/lib/Target/AMDGPU/SIInstructions.td 
b/llvm/lib/Target/AMDGPU/SIInstructions.td
index 0a5ca88cdd8f9d..49d00357723330 100644
--- a/llvm/lib/Target/AMDGPU/SIInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SIInstructions.td
@@ -579,6 +579,22 @@ def IGLP_OPT : SPseudoInstSI<(outs), (ins i32imm:$mask),
   let isMeta = 1;
 }
 
+// An advisory branch-arm hint for llvm.amdgcn.pad.counter. The hint itself
+// emits no code.
+def PAD_COUNTER : SPseudoInstSI<(outs),
+  (ins i32imm:$counter, i32imm:$count),
+  [(int_amdgcn_pad_counter (i32 timm:$counter), (i32 timm:$count))]> {
+  let SchedRW = [];
+  let hasNoSchedulingInfo = 1;
+  let hasSideEffects = 1;
+  let mayLoad = 0;
+  let mayStore = 0;
+  let isConvergent = 1;
+  let FixedSize = 1;
+  let Size = 0;
+  let isMeta = 1;
+}
+
 // SI pseudo instructions. These are used by the CFG structurizer pass
 // and should be lowered to ISA instructions prior to codegen.
 
diff --git a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll 
b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
new file mode 100644
index 00000000000000..524ad602fa3634
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
@@ -0,0 +1,42 @@
+; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | 
FileCheck %s --check-prefix=ISEL
+; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa 
-stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL
+; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s 
--check-prefix=ASM --implicit-check-not=buffer_inv
+
+; Both instruction selectors keep the hint in the arm that requests padding.
+; ISEL-LABEL: name: hint_counter_intrinsic
+; ISEL: bb.{{[0-9]+}}.long:
+; ISEL: GLOBAL_LOAD_DWORD
+; ISEL-NEXT: PAD_COUNTER 0, 1
+; ISEL: bb.{{[0-9]+}}.join:
+
+; The hint itself emits nothing.
+; ASM-LABEL: hint_counter_intrinsic:
+; ASM: s_waitcnt vmcnt(0)
+; ASM-NEXT: global_store_dword
+define amdgpu_kernel void @hint_counter_intrinsic(ptr addrspace(1) %data,
+                                                  ptr addrspace(1) %out,
+                                                  i32 %condition) {
+entry:
+  %index = call i32 @llvm.amdgcn.workitem.id.x()
+  %wide = zext i32 %index to i64
+  %a.ptr = getelementptr i32, ptr addrspace(1) %data, i64 %wide
+  %a = load i32, ptr addrspace(1) %a.ptr, align 4
+  %offset = add i64 %wide, 64
+  %cond = icmp ne i32 %condition, 0
+  br i1 %cond, label %long, label %join
+long:
+  %b.ptr = getelementptr i32, ptr addrspace(1) %data, i64 %offset
+  %b = load i32, ptr addrspace(1) %b.ptr, align 4
+  call void @llvm.amdgcn.pad.counter(i32 0, i32 1)
+  br label %join
+join:
+  %v = phi i32 [ %b, %long ], [ 0, %entry ]
+  %a.out = getelementptr i32, ptr addrspace(1) %out, i64 %wide
+  store i32 %a, ptr addrspace(1) %a.out, align 4
+  %v.out = getelementptr i32, ptr addrspace(1) %out, i64 %offset
+  store i32 %v, ptr addrspace(1) %v.out, align 4
+  ret void
+}
+
+declare i32 @llvm.amdgcn.workitem.id.x()
+declare void @llvm.amdgcn.pad.counter(i32 immarg, i32 immarg)
diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td 
b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
index 6a73dd60a46ffa..21a8dbcb5bfede 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
@@ -813,6 +813,27 @@ def ROCDL_IglpOpt : ROCDL_ConcreteNonMemIntrOp<"iglp.opt", 
[], 0, [0], ["variant
   }];
 }
 
+def ROCDL_PadCounterOp
+  : ROCDL_ConcreteNonMemIntrOp<"pad.counter", [], 0, [0, 1],
+      ["counter", "count"]>,
+    Arguments<(ins I32Attr:$counter, I32Attr:$count)> {
+  let assemblyFormat = "$counter `,` $count attr-dict";
+  let summary = "optional exact-count hint to pad the opposite branch arm";
+  let description = [{
+    Requests exactly `count` extra counter events on the opposite edge of a
+    supported triangle or diamond. Counter 0 selects LOAD/VM. The hint itself
+    issues no event and does not authorize weaker waits.
+
+    Both arguments are immediate attributes. The operation lowers to
+    `llvm.amdgcn.pad.counter`.
+
+    Example:
+    ```mlir
+    rocdl.pad.counter 0, 1
+    ```
+  }];
+}
+
 //===---------------------------------------------------------------------===//
 // Xdlops intrinsics
 
diff --git a/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir 
b/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir
new file mode 100644
index 00000000000000..c4894b7fe1580f
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir
@@ -0,0 +1,40 @@
+// RUN: mlir-translate -mlir-to-llvmir %s -o %t.ll
+// RUN: FileCheck %s --check-prefix=IR < %t.ll
+
+// IR-LABEL: @rocdl_hint_kernel(
+// IR: [[A:%.*]] = load i32
+// IR: br i1 {{.*}}, label %[[LOAD:[^, ]+]], label %[[JOIN:[^, ]+]]
+// IR: [[LOAD]]:
+// IR: [[B:%.*]] = load i32
+// IR-NEXT: call void @llvm.amdgcn.pad.counter(i32 0, i32 1)
+// IR-NEXT: br label %[[JOIN]]
+// IR: [[JOIN]]:
+// IR-NEXT: [[V:%.*]] = phi i32 [ [[B]], %[[LOAD]] ], [ 0, %{{.*}} ]
+// IR: store i32 [[A]]
+// IR: store i32 [[V]]
+
+module attributes {llvm.target_triple = "amdgpu9.50-amd-amdhsa"} {
+  llvm.func @rocdl_hint_kernel(%data: !llvm.ptr<1>, %out: !llvm.ptr<1>,
+                             %condition: i32) attributes {rocdl.kernel} {
+    %index = rocdl.workitem.id.x : i32
+    %wide = llvm.zext %index : i32 to i64
+    %a_ptr = llvm.getelementptr %data[%wide] : (!llvm.ptr<1>, i64) -> 
!llvm.ptr<1>, i32
+    %a = llvm.load %a_ptr : !llvm.ptr<1> -> i32
+    %offset = llvm.mlir.constant(64 : i64) : i64
+    %b_index = llvm.add %wide, %offset : i64
+    %zero = llvm.mlir.constant(0 : i32) : i32
+    %cond = llvm.icmp "ne" %condition, %zero : i32
+    llvm.cond_br %cond, ^load, ^join(%zero : i32)
+  ^load:
+    %b_ptr = llvm.getelementptr %data[%b_index] : (!llvm.ptr<1>, i64) -> 
!llvm.ptr<1>, i32
+    %b = llvm.load %b_ptr : !llvm.ptr<1> -> i32
+    rocdl.pad.counter 0, 1
+    llvm.br ^join(%b : i32)
+  ^join(%v: i32):
+    %a_out = llvm.getelementptr %out[%wide] : (!llvm.ptr<1>, i64) -> 
!llvm.ptr<1>, i32
+    llvm.store %a, %a_out : i32, !llvm.ptr<1>
+    %v_out = llvm.getelementptr %out[%b_index] : (!llvm.ptr<1>, i64) -> 
!llvm.ptr<1>, i32
+    llvm.store %v, %v_out : i32, !llvm.ptr<1>
+    llvm.return
+  }
+}

>From a37c5b31491da09469ccd4e2ec25bda435606c33 Mon Sep 17 00:00:00 2001
From: Dan Zimmerman <[email protected]>
Date: Tue, 10 Nov 2026 10:21:00 -0800
Subject: [PATCH 2/2] [AMDGPU] Lower counter padding hints in SIInsertWaitcnts

Assisted-by: Claude Opus 5.5
---
 .../builtins-amdgcn-pad-counter.cl            |  19 +
 llvm/docs/AMDGPUUsage.md                      |   4 +-
 llvm/lib/Target/AMDGPU/CMakeLists.txt         |   1 +
 llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp   |  55 +-
 llvm/lib/Target/AMDGPU/SIInstructions.td      |   5 +-
 llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp   | 171 +++++
 llvm/lib/Target/AMDGPU/SIWaitcntPadding.h     |  43 ++
 .../AMDGPU/waitcnt-pad-counter-intrinsic.ll   |  27 +-
 .../AMDGPU/waitcnt-pad-counter-optnone.mir    |  30 +
 .../waitcnt-pad-counter-preserve-analyses.mir |  55 ++
 .../CodeGen/AMDGPU/waitcnt-pad-counter.mir    | 626 ++++++++++++++++++
 .../secondary/llvm/lib/Target/AMDGPU/BUILD.gn |   1 +
 mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td  |  10 +-
 .../test/Target/LLVMIR/rocdl-pad-counter.mlir |  15 +
 14 files changed, 1042 insertions(+), 20 deletions(-)
 create mode 100644 llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp
 create mode 100644 llvm/lib/Target/AMDGPU/SIWaitcntPadding.h
 create mode 100644 llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-optnone.mir
 create mode 100644 
llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-preserve-analyses.mir
 create mode 100644 llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter.mir

diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
index f8671d7812bae1..d175efb9fbebe6 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-counter.cl
@@ -1,4 +1,6 @@
 // RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -emit-llvm 
-o - %s | FileCheck %s --check-prefix=IR
+// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -S -o - %s 
| FileCheck %s --check-prefix=ASM
+// RUN: %clang_cc1 -triple amdgpu9.0a-amd-amdhsa -cl-std=CL2.0 -O2 -S -o - %s 
| FileCheck %s --check-prefix=NO_PAD --implicit-check-not=buffer_inv
 // REQUIRES: amdgpu-registered-target
 
 // The void hint must survive optimization in the conditional load arm.
@@ -13,6 +15,23 @@
 // IR: store i32 [[A]]
 // IR: store i32 [[V]]
 
+// The real padding belongs to the skipped edge, not beside the extra load.
+// ASM-LABEL: hinted_kernel:
+// ASM: global_load_dword
+// ASM: s_cbranch_scc{{[01]}} [[PAD:\.LBB[0-9]+_[0-9]+]]
+// ASM: global_load_dword
+// ASM-NOT: buffer_inv
+// ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]:
+// ASM-NEXT: s_waitcnt vmcnt(1)
+// ASM-NEXT: global_store_dword
+// ASM: s_endpgm
+// ASM: [[PAD]]:
+// ASM-NEXT: buffer_inv
+// ASM-NEXT: s_branch [[JOIN]]
+// NO_PAD-LABEL: hinted_kernel:
+// NO_PAD: s_waitcnt vmcnt(0)
+// NO_PAD-NEXT: global_store_dword
+
 kernel void hinted_kernel(global int *data, global int *out,
                           int condition) {
   unsigned index = __builtin_amdgcn_workitem_id_x();
diff --git a/llvm/docs/AMDGPUUsage.md b/llvm/docs/AMDGPUUsage.md
index ad2540053ca902..4d503bc3dc4947 100644
--- a/llvm/docs/AMDGPUUsage.md
+++ b/llvm/docs/AMDGPUUsage.md
@@ -2621,7 +2621,9 @@ The AMDGPU backend implements the following LLVM IR 
intrinsics.
 
     The iglp_opt strategy implementations are subject to change.
 * - llvm.amdgcn.pad.counter
-  - Optional exact-count hint to add counter events on the opposite edge of a 
supported single-block triangle or diamond arm. Both i32 arguments are 
immediate: counter 0 selects LOAD/VM and count selects the exact number of 
extra events. The hint itself emits no event and grants no permission to weaken 
a wait.
+  - Optional exact-count hint to add counter events on the opposite edge of a 
supported single-block triangle or diamond arm. Both i32 arguments are 
immediate: counter 0 selects LOAD/VM and count selects the exact number of 
extra events. The current implementation emits BUFFER_INV 0 on targets 
supporting that instruction and accepts counts 1 through the hardware wait 
limit minus one (1..62 on gfx942/gfx950).
+
+    The backend materializes accepted hints immediately before waitcnt 
insertion, which then analyzes the padding like any other counter event. The 
hint itself emits no event and grants no permission to weaken a wait. Zero, 
invalid counts/selectors, optnone or opt-bisect skipped functions, unsupported 
shapes/targets, and repeated valid requests for one controlling branch are 
ignored. Accepted requests require an unambiguous arm in the same innermost 
loop as its branch and join; loop-header/latch joins are excluded. 
Profitability and later padding removal are not automated.
 
     Available through __builtin_amdgcn_pad_counter(counter, count) and 
rocdl.pad.counter.
 * - llvm.amdgcn.s.getpc
diff --git a/llvm/lib/Target/AMDGPU/CMakeLists.txt 
b/llvm/lib/Target/AMDGPU/CMakeLists.txt
index a188c691c29d12..8a325c5d4357a1 100644
--- a/llvm/lib/Target/AMDGPU/CMakeLists.txt
+++ b/llvm/lib/Target/AMDGPU/CMakeLists.txt
@@ -191,6 +191,7 @@ add_llvm_target(AMDGPUCodeGen
   SIProgramInfo.cpp
   SIRegisterInfo.cpp
   SIShrinkInstructions.cpp
+  SIWaitcntPadding.cpp
   SIWholeQuadMode.cpp
   SIPostRA16BitMovFolding.cpp
 
diff --git a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp 
b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
index c93338eeb2b205..932d5019ce1d7d 100644
--- a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
@@ -28,8 +28,10 @@
 #include "AMDGPUWaitcntUtils.h"
 #include "GCNSubtarget.h"
 #include "SIMachineFunctionInfo.h"
+#include "SIWaitcntPadding.h"
 #include "Utils/AMDGPUBaseInfo.h"
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineLoopInfo.h"
 #include "llvm/CodeGen/MachinePassManager.h"
@@ -349,9 +351,11 @@ class SIInsertWaitcnts {
   DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
   DenseMap<MachineBasicBlock *, PreheaderFlushFlags> PreheadersToFlush;
   MachineLoopInfo &MLI;
+  MachineDominatorTree *MDT;
   MachinePostDominatorTree &PDT;
   AliasAnalysis *AA = nullptr;
   MachineFunction &MF;
+  bool SkipPadding;
 
   struct BlockInfo {
     std::unique_ptr<WaitcntBrackets> Incoming;
@@ -378,6 +382,7 @@ class SIInsertWaitcnts {
   DenseMap<MachineInstr *, bool> EndPgmInsts;
 
   AMDGPU::HardwareLimits Limits;
+  bool ChangedCFG = false;
 
 public:
   const GCNSubtarget &ST;
@@ -389,15 +394,17 @@ class SIInsertWaitcnts {
   bool IsExpertMode = false;
   const bool TgSplit;
 
-  SIInsertWaitcnts(MachineLoopInfo &MLI, MachinePostDominatorTree &PDT,
-                   AliasAnalysis *AA, MachineFunction &MF)
-      : MLI(MLI), PDT(PDT), AA(AA), MF(MF), 
ST(MF.getSubtarget<GCNSubtarget>()),
-        TII(*ST.getInstrInfo()), TRI(TII.getRegisterInfo()),
-        MRI(MF.getRegInfo()),
+  SIInsertWaitcnts(MachineLoopInfo &MLI, MachineDominatorTree *MDT,
+                   MachinePostDominatorTree &PDT, AliasAnalysis *AA,
+                   MachineFunction &MF, bool SkipPadding)
+      : MLI(MLI), MDT(MDT), PDT(PDT), AA(AA), MF(MF), SkipPadding(SkipPadding),
+        ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
+        TRI(TII.getRegisterInfo()), MRI(MF.getRegInfo()),
         TgSplit(ST.hasTgSplitSupport() &&
                 AMDGPU::isTgSplitEnabled(MF.getFunction())) {}
 
   const AMDGPU::HardwareLimits &getLimits() const { return Limits; }
+  bool changedCFG() const { return ChangedCFG; }
 
   PreheaderFlushFlags getPreheaderFlushFlags(MachineLoop *ML,
                                              const WaitcntBrackets &Brackets);
@@ -843,9 +850,12 @@ class SIInsertWaitcntsLegacy : public MachineFunctionPass {
   }
 
   void getAnalysisUsage(AnalysisUsage &AU) const override {
-    AU.setPreservesCFG();
     AU.addRequired<MachineLoopInfoWrapperPass>();
     AU.addRequired<MachinePostDominatorTreeWrapperPass>();
+    AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();
+    AU.addPreserved<MachineLoopInfoWrapperPass>();
+    AU.addPreserved<MachineDominatorTreeWrapperPass>();
+    AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
     AU.addUsedIfAvailable<AAResultsWrapperPass>();
     AU.addPreserved<AAResultsWrapperPass>();
     MachineFunctionPass::getAnalysisUsage(AU);
@@ -3449,30 +3459,44 @@ SIInsertWaitcnts::getPreheaderFlushFlags(MachineLoop 
*ML,
 
 bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
   auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
+  auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
+  MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
   auto &PDT =
       getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
   AliasAnalysis *AA = nullptr;
   if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
     AA = &AAR->getAAResults();
 
-  return SIInsertWaitcnts(MLI, PDT, AA, MF).run();
+  // Waitcnt insertion is required, but counter padding is an optimization.
+  bool SkipPadding = skipFunction(MF.getFunction());
+  return SIInsertWaitcnts(MLI, MDT, PDT, AA, MF, SkipPadding).run();
 }
 
 PreservedAnalyses
 SIInsertWaitcntsPass::run(MachineFunction &MF,
                           MachineFunctionAnalysisManager &MFAM) {
   auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
+  auto *MDT = MFAM.getCachedResult<MachineDominatorTreeAnalysis>(MF);
   auto &PDT = MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
   auto *AA = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(MF)
                  .getManager()
                  .getCachedResult<AAManager>(MF.getFunction());
 
-  if (!SIInsertWaitcnts(MLI, PDT, AA, MF).run())
+  // Waitcnt insertion is required, but counter padding is an optimization.
+  const Function &F = MF.getFunction();
+  bool SkipPadding = F.hasOptNone() || shouldSkipOptimizationForOptBisect(F);
+  SIInsertWaitcnts Impl(MLI, MDT, PDT, AA, MF, SkipPadding);
+  if (!Impl.run())
     return PreservedAnalyses::all();
 
-  return getMachineFunctionPassPreservedAnalyses()
-      .preserveSet<CFGAnalyses>()
-      .preserve<AAManager>();
+  auto PA = getMachineFunctionPassPreservedAnalyses();
+  if (Impl.changedCFG())
+    PA.preserve<MachineLoopAnalysis>()
+        .preserve<MachineDominatorTreeAnalysis>()
+        .preserve<MachinePostDominatorTreeAnalysis>();
+  else
+    PA.preserveSet<CFGAnalyses>();
+  return PA.preserve<AAManager>();
 }
 
 bool SIInsertWaitcnts::run() {
@@ -3499,7 +3523,16 @@ bool SIInsertWaitcnts::run() {
 
   SmemAccessCounter = getCounterFromEvent(HWEvents::SMEM_ACCESS);
 
+  // Materialize padding before taking any entry or exit score snapshots, so 
the
+  // ordinary solver sees every real counter event from its first sweep. When
+  // padding is skipped or unsupported, hints stay as meta instructions.
   bool Modified = false;
+  if (!SkipPadding && ST.hasBufferInvInst()) {
+    AMDGPU::CounterPaddingResult Padding =
+        AMDGPU::expandCounterPaddingHints(MF, MLI, MDT, PDT, Limits);
+    ChangedCFG = Padding.ChangedCFG;
+    Modified = Padding.Changed;
+  }
 
   MachineBasicBlock &EntryBB = MF.front();
 
diff --git a/llvm/lib/Target/AMDGPU/SIInstructions.td 
b/llvm/lib/Target/AMDGPU/SIInstructions.td
index 49d00357723330..6a97a4d02ef3d1 100644
--- a/llvm/lib/Target/AMDGPU/SIInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SIInstructions.td
@@ -579,8 +579,9 @@ def IGLP_OPT : SPseudoInstSI<(outs), (ins i32imm:$mask),
   let isMeta = 1;
 }
 
-// An advisory branch-arm hint for llvm.amdgcn.pad.counter. The hint itself
-// emits no code.
+// An advisory branch-arm hint for llvm.amdgcn.pad.counter. When padding is
+// enabled, waitcnt insertion replaces it with padding for a supported request;
+// otherwise it is dropped at emission.
 def PAD_COUNTER : SPseudoInstSI<(outs),
   (ins i32imm:$counter, i32imm:$count),
   [(int_amdgcn_pad_counter (i32 timm:$counter), (i32 timm:$count))]> {
diff --git a/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp 
b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp
new file mode 100644
index 00000000000000..aa7026130831fc
--- /dev/null
+++ b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp
@@ -0,0 +1,171 @@
+//===- SIWaitcntPadding.cpp - Counter padding hints for waitcnts 
----------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Materialize exact-count padding hints before waitcnt insertion analyzes the
+// machine function. The hint itself contributes no counter event and is
+// removed once considered, whether or not its request is accepted.
+//
+//===----------------------------------------------------------------------===//
+
+#include "SIWaitcntPadding.h"
+#include "AMDGPUWaitcntUtils.h"
+#include "GCNSubtarget.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/CodeGen/MachineDomTreeUpdater.h"
+#include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineLoopInfo.h"
+#include "llvm/CodeGen/MachinePostDominators.h"
+#include "llvm/Support/Debug.h"
+#include <optional>
+
+using namespace llvm;
+
+#define DEBUG_TYPE "si-insert-waitcnts"
+
+namespace {
+
+struct PaddingEdge {
+  MachineBasicBlock *Branch;
+  MachineBasicBlock *Pred;
+  MachineBasicBlock *Join;
+};
+
+[[maybe_unused]] void printIgnored(const MachineBasicBlock &Arm,
+                                   StringRef Reason) {
+  dbgs() << "Ignoring PAD_COUNTER in " << printMBBReference(Arm) << " of "
+         << Arm.getParent()->getName() << ": " << Reason << '\n';
+}
+
+std::optional<PaddingEdge> getCounterPaddingEdge(MachineBasicBlock &Arm,
+                                                 MachineLoopInfo &MLI,
+                                                 const SIInstrInfo &TII) {
+  auto Reject = [&Arm](StringRef Reason) -> std::optional<PaddingEdge> {
+    LLVM_DEBUG(printIgnored(Arm, Reason));
+    return std::nullopt;
+  };
+
+  MachineBasicBlock *Branch = Arm.getSinglePredecessor();
+  MachineBasicBlock *Join = Arm.getSingleSuccessor();
+  if (!Branch || !Join)
+    return Reject("arm lacks a single predecessor and successor");
+  if (Branch->succ_size() != 2 || Join->pred_size() != 2)
+    return Reject("branch or join does not have exactly two edges");
+  if (Arm.isEHPad() || Join->isEHPad())
+    return Reject("arm or join is an EH pad");
+
+  MachineBasicBlock *Other = nullptr;
+  for (MachineBasicBlock *Pred : Join->predecessors())
+    if (Pred != &Arm)
+      Other = Pred;
+  if (!Other || (Other != Branch && (Other->getSinglePredecessor() != Branch ||
+                                     Other->getSingleSuccessor() != Join)))
+    return Reject("not a triangle or diamond");
+
+  MachineLoop *Loop = MLI.getLoopFor(Join);
+  if (MLI.getLoopFor(Branch) != Loop || MLI.getLoopFor(&Arm) != Loop ||
+      MLI.getLoopFor(Other) != Loop)
+    return Reject("branch, arms and join are not in the same loop");
+  if (Loop && (Loop->getHeader() == Join || Loop->isLoopLatch(Join)))
+    return Reject("join is a loop header or latch");
+
+  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
+  SmallVector<MachineOperand, 4> Cond;
+  if (TII.analyzeBranch(*Branch, TBB, FBB, Cond) || Cond.empty())
+    return Reject("branch is not an analyzable conditional branch");
+  for (MachineBasicBlock *MBB : {&Arm, Other}) {
+    if (MBB == Branch)
+      continue;
+    for (const MachineInstr &MI : MBB->terminators())
+      if (MI.getOpcode() != AMDGPU::S_BRANCH)
+        return Reject("arm has a terminator other than S_BRANCH");
+  }
+  if (Other == Branch && !Branch->canSplitCriticalEdge(Join, &MLI))
+    return Reject("branch-to-join edge cannot be split");
+  return PaddingEdge{Branch, Other, Join};
+}
+
+} // end anonymous namespace
+
+AMDGPU::CounterPaddingResult AMDGPU::expandCounterPaddingHints(
+    MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree *MDT,
+    MachinePostDominatorTree &PDT, const HardwareLimits &Limits) {
+  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
+  const SIInstrInfo &TII = *ST.getInstrInfo();
+  const SIRegisterInfo &TRI = TII.getRegisterInfo();
+
+  struct Request {
+    MachineBasicBlock *Arm;
+    PaddingEdge Edge;
+    unsigned Count;
+    DebugLoc DL;
+  };
+  SmallVector<Request, 8> Requests;
+  DenseSet<MachineBasicBlock *> SeenBranches, RepeatedBranches;
+  CounterPaddingResult Result;
+  for (MachineBasicBlock &MBB : MF) {
+    for (MachineInstr &MI : make_early_inc_range(MBB.instrs())) {
+      if (MI.getOpcode() != AMDGPU::PAD_COUNTER)
+        continue;
+      int64_t Counter = MI.getOperand(0).getImm();
+      int64_t Count = MI.getOperand(1).getImm();
+      if (Counter != 0) {
+        LLVM_DEBUG(printIgnored(MBB, "unsupported counter selector"));
+      } else if (Count <= 0 || uint64_t(Count) > Limits.LoadcntMax - 1) {
+        LLVM_DEBUG(printIgnored(MBB, "count is out of range"));
+      } else if (auto Edge = getCounterPaddingEdge(MBB, MLI, TII)) {
+        if (!SeenBranches.insert(Edge->Branch).second)
+          RepeatedBranches.insert(Edge->Branch);
+        Requests.push_back({&MBB, *Edge, unsigned(Count), MI.getDebugLoc()});
+      }
+      // An ignored hint grants no permission to weaken a wait.
+      MI.eraseFromParent();
+      Result.Changed = true;
+    }
+  }
+
+  MachineDomTreeUpdater MDTU(MDT, &PDT,
+                             MachineDomTreeUpdater::UpdateStrategy::Eager);
+  for (const Request &R : Requests) {
+    auto [Branch, Pred, Join] = R.Edge;
+    if (RepeatedBranches.contains(Branch)) {
+      LLVM_DEBUG(printIgnored(*R.Arm, "branch has multiple padding requests"));
+      continue;
+    }
+    MachineBasicBlock *PadBlock = Pred;
+    if (Pred->succ_size() != 1) {
+      bool WasLayoutEdge = Pred->isLayoutSuccessor(Join);
+      MachineBasicBlock::SplitCriticalEdgeAnalyses Analyses{};
+      Analyses.MLI = &MLI;
+      PadBlock = Pred->SplitCriticalEdge(Join, Analyses, &MDTU);
+      if (!PadBlock) {
+        LLVM_DEBUG(printIgnored(*R.Arm, "failed to split branch-to-join 
edge"));
+        continue;
+      }
+      Result.ChangedCFG = true;
+      PadBlock->setSectionID(Pred->getSectionID());
+      if (!WasLayoutEdge) {
+        // The splitter repairs branches for its initial layout. Move a taken
+        // edge out of line and repair the predecessor's fallthrough again.
+        MF.splice(MF.end(), PadBlock);
+        Pred->updateTerminator(PadBlock);
+      }
+    }
+    PadBlock->addLiveIn(TRI.getExec());
+    PadBlock->sortUniqueLiveIns();
+    auto InsertPt = PadBlock->getFirstTerminator();
+    for (unsigned I = 0; I != R.Count; ++I)
+      BuildMI(*PadBlock, InsertPt, R.DL, 
TII.get(AMDGPU::BUFFER_INV)).addImm(0);
+    LLVM_DEBUG(dbgs() << "Padded " << printMBBReference(*PadBlock) << " with "
+                      << R.Count << " BUFFER_INV for PAD_COUNTER in "
+                      << printMBBReference(*R.Arm) << " of " << MF.getName()
+                      << '\n');
+  }
+  return Result;
+}
diff --git a/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h 
b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h
new file mode 100644
index 00000000000000..9c3535bc57513b
--- /dev/null
+++ b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h
@@ -0,0 +1,43 @@
+//===- SIWaitcntPadding.h - Counter padding hints for waitcnts --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H
+#define LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H
+
+namespace llvm {
+
+class MachineDominatorTree;
+class MachineFunction;
+class MachineLoopInfo;
+class MachinePostDominatorTree;
+
+namespace AMDGPU {
+
+struct HardwareLimits;
+
+struct CounterPaddingResult {
+  /// The function was modified, including by removing ignored hints.
+  bool Changed = false;
+  /// At least one edge was split to hold padding.
+  bool ChangedCFG = false;
+};
+
+/// Remove every PAD_COUNTER hint in \p MF and materialize the padding 
requested
+/// by supported hints, so that waitcnt insertion analyzes it like any other
+/// counter event. The subtarget must support padding. \p MLI, \p PDT and, if
+/// non-null, \p MDT are kept up to date.
+CounterPaddingResult expandCounterPaddingHints(MachineFunction &MF,
+                                               MachineLoopInfo &MLI,
+                                               MachineDominatorTree *MDT,
+                                               MachinePostDominatorTree &PDT,
+                                               const HardwareLimits &Limits);
+
+} // namespace AMDGPU
+} // namespace llvm
+
+#endif // LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H
diff --git a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll 
b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
index 524ad602fa3634..4ff7059db8bd66 100644
--- a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
+++ b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-intrinsic.ll
@@ -1,6 +1,9 @@
 ; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | 
FileCheck %s --check-prefix=ISEL
 ; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa 
-stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL
-; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s 
--check-prefix=ASM --implicit-check-not=buffer_inv
+; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s 
--check-prefix=ASM
+; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s 
--check-prefix=ASM
+; RUN: llc -enable-new-pm -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck 
%s --check-prefix=ASM
+; RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa %s -o - | FileCheck %s 
--check-prefix=NO-PAD --implicit-check-not=buffer_inv
 
 ; Both instruction selectors keep the hint in the arm that requests padding.
 ; ISEL-LABEL: name: hint_counter_intrinsic
@@ -9,10 +12,28 @@
 ; ISEL-NEXT: PAD_COUNTER 0, 1
 ; ISEL: bb.{{[0-9]+}}.join:
 
-; The hint itself emits nothing.
+; The padding belongs to the skipped edge, not beside the extra load, so the
+; store of %a only waits for the older of two outstanding loads.
 ; ASM-LABEL: hint_counter_intrinsic:
-; ASM: s_waitcnt vmcnt(0)
+; ASM: global_load_dword
+; ASM: s_cbranch_scc1 [[PAD:\.LBB[0-9]+_[0-9]+]]
+; ASM: global_load_dword
+; ASM-NOT: buffer_inv
+; ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]:
+; ASM-NEXT: s_waitcnt vmcnt(1)
 ; ASM-NEXT: global_store_dword
+; ASM: s_endpgm
+; ASM: [[PAD]]:
+; ASM-NEXT: buffer_inv
+; ASM-NEXT: s_branch [[JOIN]]
+
+; Without BUFFER_INV, the hint is ignored and the store waits for both loads.
+; NO-PAD-LABEL: hint_counter_intrinsic:
+; NO-PAD: ; %long
+; NO-PAD: global_load_dword
+; NO-PAD-NEXT: ; pad_counter(0, 1)
+; NO-PAD: s_waitcnt vmcnt(0)
+; NO-PAD-NEXT: global_store_dword
 define amdgpu_kernel void @hint_counter_intrinsic(ptr addrspace(1) %data,
                                                   ptr addrspace(1) %out,
                                                   i32 %condition) {
diff --git a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-optnone.mir 
b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-optnone.mir
new file mode 100644
index 00000000000000..15687207696230
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-optnone.mir
@@ -0,0 +1,30 @@
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s 
| FileCheck %s --implicit-check-not=BUFFER_INV
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -passes=si-insert-waitcnts -o - %s | 
FileCheck %s --implicit-check-not=BUFFER_INV
+
+--- |
+  define amdgpu_kernel void @optnone_hint() noinline optnone { ret void }
+...
+---
+name: optnone_hint
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  ; CHECK-LABEL: name: optnone_hint
+  ; CHECK: PAD_COUNTER 0, 1
+  ; CHECK: S_WAITCNT .Vmcnt_0
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+  bb.1:
+    successors: %bb.2
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+  bb.2:
+    liveins: $exec, $vgpr2
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
diff --git a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-preserve-analyses.mir 
b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-preserve-analyses.mir
new file mode 100644
index 00000000000000..8986f5c212d77f
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter-preserve-analyses.mir
@@ -0,0 +1,55 @@
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa 
-passes="require<machine-dom-tree>,require<machine-post-dom-tree>,require<machine-loops>,si-insert-waitcnts,print<machine-dom-tree>,print<machine-post-dom-tree>,print<machine-loops>"
 -debug-pass-manager -filetype=null %s 2>&1 | FileCheck %s
+
+# Splitting a hinted triangle inside a loop must update the cached dominator
+# trees and loop membership without reconstructing the analyses.
+# CHECK: Running analysis: MachineDominatorTreeAnalysis on hint_loop_triangle
+# CHECK: Running analysis: MachinePostDominatorTreeAnalysis on 
hint_loop_triangle
+# CHECK: Running analysis: MachineLoopAnalysis on hint_loop_triangle
+# CHECK: Running pass: SIInsertWaitcntsPass on hint_loop_triangle
+# CHECK-NOT: Running analysis: Machine{{.*}}Analysis
+# CHECK: Running pass: MachineDominatorTreePrinterPass on hint_loop_triangle
+# CHECK: Inorder Dominator Tree:
+# CHECK: %bb.6
+# CHECK-NOT: Running analysis: Machine{{.*}}Analysis
+# CHECK: Running pass: MachinePostDominatorTreePrinterPass on 
hint_loop_triangle
+# CHECK: Inorder PostDominator Tree:
+# CHECK: %bb.6
+# CHECK-NOT: Running analysis: Machine{{.*}}Analysis
+# CHECK: Running pass: MachineLoopPrinterPass on hint_loop_triangle
+# CHECK: Loop at depth 1 containing: {{.*}}%bb.6
+
+---
+name: hint_loop_triangle
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1
+    liveins: $exec, $scc
+    S_BRANCH %bb.1
+
+  bb.1:
+    successors: %bb.2, %bb.3
+    liveins: $exec, $scc
+    S_CBRANCH_SCC1 %bb.3, implicit $scc
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $scc
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+
+  bb.3:
+    successors: %bb.4
+    liveins: $exec, $scc
+    S_BRANCH %bb.4
+
+  bb.4:
+    successors: %bb.1, %bb.5
+    liveins: $exec, $scc
+    S_CBRANCH_SCC1 %bb.1, implicit $scc
+
+  bb.5:
+    S_ENDPGM 0
+...
diff --git a/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter.mir 
b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter.mir
new file mode 100644
index 00000000000000..f50a41ba77722b
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/waitcnt-pad-counter.mir
@@ -0,0 +1,626 @@
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s 
| FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_COUNTER
+# RUN: llc -mtriple=amdgpu9.42-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s 
| FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_COUNTER
+# RUN: llc -O0 -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o 
- %s | FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_COUNTER
+# RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s 
| FileCheck %s --check-prefix=DISABLED --implicit-check-not=BUFFER_INV
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -amdgpu-waitcnt-forcezero 
-run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=FORCED 
--implicit-check-not=PAD_COUNTER
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -passes=si-insert-waitcnts -o - %s | 
FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_COUNTER
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -opt-bisect-limit=0 
-run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=DISABLED 
--implicit-check-not=BUFFER_INV
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -opt-bisect-limit=0 
-passes=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=DISABLED 
--implicit-check-not=BUFFER_INV
+
+# A hint contributes no event on its own arm. Its exact count is materialized
+# on the other edge before the ordinary solver, including force-zero mode.
+# PAD-LABEL: name: hint_diamond
+# PAD: bb.1:
+# PAD: $vgpr3 = GLOBAL_LOAD_DWORD
+# PAD-NOT: BUFFER_INV
+# PAD: S_BRANCH %bb.3
+# PAD: bb.2:
+# PAD-COUNT-2: BUFFER_INV 0, implicit $exec
+# PAD-NEXT: S_BRANCH %bb.3
+# PAD: bb.3:
+# PAD: S_WAITCNT .Vmcnt_1
+# DISABLED-LABEL: name: hint_diamond
+# DISABLED: PAD_COUNTER 0, 2
+# DISABLED: S_WAITCNT .Vmcnt_0
+# FORCED-LABEL: name: hint_diamond
+# FORCED: bb.2:
+# FORCED: S_WAITCNT .Vmcnt_0_Expcnt_0_Lgkmcnt_0
+# FORCED-NEXT: BUFFER_INV 0, implicit $exec
+# FORCED-NEXT: S_WAITCNT .Vmcnt_0_Expcnt_0_Lgkmcnt_0
+# FORCED-NEXT: BUFFER_INV 0, implicit $exec
+
+---
+name: hint_diamond
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 2
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_triangle_taken
+# PAD: bb.0:
+# PAD: S_CBRANCH_SCC1 %bb.[[TAKEN:[0-9]+]]
+# PAD: bb.1:
+# PAD: $vgpr3 = GLOBAL_LOAD_DWORD
+# PAD-NOT: BUFFER_INV
+# PAD: bb.2:
+# PAD: S_WAITCNT .Vmcnt_1
+# PAD: bb.[[TAKEN]]:
+# PAD: successors: %bb.2
+# PAD: BUFFER_INV 0, implicit $exec
+# PAD-NEXT: S_BRANCH %bb.2
+---
+name: hint_triangle_taken
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.2
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+
+  bb.2:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_triangle_fallthrough
+# PAD: bb.0:
+# PAD: S_CBRANCH_SCC1 %bb.2
+# PAD: bb.[[FALL:[0-9]+]]:
+# PAD: successors: %bb.1
+# PAD: BUFFER_INV 0, implicit $exec
+# PAD: bb.1:
+# PAD: S_WAITCNT .Vmcnt_1
+# PAD: bb.2:
+# PAD: $vgpr3 = GLOBAL_LOAD_DWORD
+# PAD-NOT: BUFFER_INV
+# PAD: S_BRANCH %bb.1
+---
+name: hint_triangle_fallthrough
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+
+  bb.2:
+    successors: %bb.1
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.1
+...
+
+# Padding can expose old B across the backedge. Normal insertion must add a
+# wait in the short arm before consuming B, while preserving A's VM1 at join.
+# PAD-LABEL: name: hint_loop_carried
+# PAD: bb.3:
+# PAD: S_WAITCNT .Vmcnt_1
+# PAD-NEXT: $vgpr5 = V_MOV_B32_e32 $vgpr3
+# PAD-NEXT: BUFFER_INV 0, implicit $exec
+# PAD-NEXT: S_BRANCH %bb.4
+# PAD: bb.4:
+# PAD: S_WAITCNT .Vmcnt_1
+---
+name: hint_loop_carried
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr3 = V_MOV_B32_e32 0, implicit $exec
+    S_BRANCH %bb.1
+
+  bb.1:
+    successors: %bb.2, %bb.3
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr3
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.3, implicit $scc
+
+  bb.2:
+    successors: %bb.4
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.4
+
+  bb.3:
+    successors: %bb.4
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3
+
+    $vgpr5 = V_MOV_B32_e32 $vgpr3, implicit $exec
+    S_BRANCH %bb.4
+
+  bb.4:
+    successors: %bb.5
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_BRANCH %bb.5
+
+  bb.5:
+    successors: %bb.1, %bb.6
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr3
+
+    S_CBRANCH_SCC1 %bb.1, implicit $scc
+    S_BRANCH %bb.6
+
+  bb.6:
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_multiple_branches
+# PAD: S_WAITCNT .Vmcnt_2
+# PAD: BUFFER_INV 0, implicit $exec
+# PAD: BUFFER_INV 0, implicit $exec
+---
+name: hint_multiple_branches
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+  bb.1:
+    successors: %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+  bb.2:
+    successors: %bb.3, %bb.4
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2
+
+    S_CBRANCH_SCC1 %bb.4, implicit $scc
+  bb.3:
+    successors: %bb.4
+    liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr5 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+  bb.4:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_repeated
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_repeated
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_both_arms
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_both_arms
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_common_header
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_common_header
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_zero
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_zero
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 0
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_invalid_selector
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_invalid_selector
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 1, 1
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_negative_count
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_negative_count
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, -1
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_above_range
+# PAD-NOT: BUFFER_INV
+# PAD: S_WAITCNT .Vmcnt_0
+---
+name: hint_above_range
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 63
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# PAD-LABEL: name: hint_count_max
+# PAD: bb.2:
+# PAD-COUNT-62: BUFFER_INV 0, implicit $exec
+# PAD-NEXT: S_BRANCH %bb.3
+# PAD: S_WAITCNT .Vmcnt_1
+---
+name: hint_count_max
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 62
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# A hint never overrides an original ordering request.
+# PAD-LABEL: name: hint_original_soft_wait
+# PAD: bb.2:
+# PAD: BUFFER_INV 0, implicit $exec
+# PAD: bb.3:
+# PAD: S_WAITCNT .Vmcnt_0
+# PAD-NEXT: S_BARRIER
+---
+name: hint_original_soft_wait
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+
+    $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1, $vgpr2
+
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+
+  bb.2:
+    successors: %bb.3
+    liveins: $exec, $vgpr2
+
+    S_BRANCH %bb.3
+
+  bb.3:
+    liveins: $exec, $vgpr2
+
+    S_WAITCNT_soft 0
+    S_BARRIER
+    $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec
+    S_ENDPGM 0
+...
+
+# The original LDS release marker is resolved on the actual padded program.
+# PAD-LABEL: name: hint_original_lds_marker
+# PAD: bb.2:
+# PAD: BUFFER_INV 0, implicit $exec
+# PAD: bb.3:
+# PAD-NOT: S_WAITCNT_lds_direct
+# PAD: S_WAITCNT .Vmcnt_1
+# PAD-NEXT: S_BARRIER
+---
+name: hint_original_lds_marker
+tracksRegLiveness: true
+machineFunctionInfo:
+  isEntryFunction: true
+body: |
+  bb.0:
+    successors: %bb.1, %bb.2
+    liveins: $exec, $scc, $vgpr0_vgpr1
+    $m0 = S_MOV_B32 0
+    GLOBAL_LOAD_LDS_DWORD $vgpr0_vgpr1, 0, 0, 0, implicit $m0, implicit $exec 
:: (load (s32), addrspace 1), (store (s32), addrspace 3)
+    S_CBRANCH_SCC1 %bb.2, implicit $scc
+  bb.1:
+    successors: %bb.3
+    liveins: $exec, $vgpr0_vgpr1
+    $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec
+    PAD_COUNTER 0, 1
+    S_BRANCH %bb.3
+  bb.2:
+    successors: %bb.3
+    liveins: $exec
+    S_BRANCH %bb.3
+  bb.3:
+    liveins: $exec
+    S_WAITCNT_lds_direct
+    S_BARRIER
+    S_ENDPGM 0
+...
diff --git a/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn 
b/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn
index 8479050ea4521a..6f2b039c0d579b 100644
--- a/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn
+++ b/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn
@@ -288,6 +288,7 @@ static_library("LLVMAMDGPUCodeGen") {
     "SIRegisterInfo.cpp",
     "SIShrinkInstructions.cpp",
     "SISpillUtils.cpp",
+    "SIWaitcntPadding.cpp",
     "SIWholeQuadMode.cpp",
   ]
 }
diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td 
b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
index 21a8dbcb5bfede..199f90042c1867 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td
@@ -821,11 +821,15 @@ def ROCDL_PadCounterOp
   let summary = "optional exact-count hint to pad the opposite branch arm";
   let description = [{
     Requests exactly `count` extra counter events on the opposite edge of a
-    supported triangle or diamond. Counter 0 selects LOAD/VM. The hint itself
-    issues no event and does not authorize weaker waits.
+    supported triangle or diamond. Counter 0 selects LOAD/VM. The current
+    backend supports `BUFFER_INV 0` and accepts counts 1..62 on gfx942/gfx950.
+    Zero, invalid, unsupported, ambiguous, and repeated requests are ignored.
+    The hint itself issues no event and does not authorize weaker waits.
 
     Both arguments are immediate attributes. The operation lowers to
-    `llvm.amdgcn.pad.counter`.
+    `llvm.amdgcn.pad.counter`. The backend materializes accepted hints
+    immediately before waitcnt insertion, which then analyzes the padding and
+    preserves completion and ordering requirements.
 
     Example:
     ```mlir
diff --git a/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir 
b/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir
index c4894b7fe1580f..c859353811e644 100644
--- a/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir
+++ b/mlir/test/Target/LLVMIR/rocdl-pad-counter.mlir
@@ -1,5 +1,7 @@
 // RUN: mlir-translate -mlir-to-llvmir %s -o %t.ll
 // RUN: FileCheck %s --check-prefix=IR < %t.ll
+// RUN: %if has_llc_binary && host-supports-amdgpu %{ llc 
-mtriple=amdgpu9.50-amd-amdhsa %t.ll -o - | FileCheck %s --check-prefix=ASM %}
+// RUN: %if has_llc_binary && host-supports-amdgpu %{ llc -global-isel 
-mtriple=amdgpu9.50-amd-amdhsa %t.ll -o - | FileCheck %s --check-prefix=ASM %}
 
 // IR-LABEL: @rocdl_hint_kernel(
 // IR: [[A:%.*]] = load i32
@@ -13,6 +15,19 @@
 // IR: store i32 [[A]]
 // IR: store i32 [[V]]
 
+// ASM-LABEL: rocdl_hint_kernel:
+// ASM: global_load_dword
+// ASM: s_cbranch_scc{{[01]}} [[PAD:\.LBB[0-9]+_[0-9]+]]
+// ASM: global_load_dword
+// ASM-NOT: buffer_inv
+// ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]:
+// ASM-NEXT: s_waitcnt vmcnt(1)
+// ASM-NEXT: global_store_dword
+// ASM: s_endpgm
+// ASM: [[PAD]]:
+// ASM-NEXT: buffer_inv
+// ASM-NEXT: s_branch [[JOIN]]
+
 module attributes {llvm.target_triple = "amdgpu9.50-amd-amdhsa"} {
   llvm.func @rocdl_hint_kernel(%data: !llvm.ptr<1>, %out: !llvm.ptr<1>,
                              %condition: i32) attributes {rocdl.kernel} {

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to