[llvm] [AMDGPU] Introduce ABI occupancy for object linking (PR #199475)

via llvm-commits llvm-commits at lists.llvm.org
Sun May 24 19:17:22 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-amdgpu

Author: Shilei Tian (shiltian)

<details>
<summary>Changes</summary>

[AMDGPU] Introduce ABI occupancy for object linking

This PR introduces ABI occupancy as the contract used to compile functions under object linking. The default is derived from the occupancy needed for a 1024 workitem workgroup, can be overridden with `-amdgpu-abi-waves-per-eu`, and can be overridden per function by `amdgpu-flat-work-group-size` or tightened by an accepted `amdgpu-waves-per-eu` hint.

The backend emits the selected occupancy in `.amdgpu.info` and uses it to enforce the object linking register budget.

---

Patch is 40.04 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/199475.diff


20 Files Affected:

- (modified) llvm/docs/AMDGPUUsage.rst (+53-7) 
- (modified) llvm/include/llvm/Support/AMDGPUObjLinkingInfo.h (+3) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp (+67-35) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUMCResourceInfo.cpp (+37-3) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp (+32-2) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h (+7) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp (+7) 
- (modified) llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.h (+1) 
- (modified) llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp (+6) 
- (modified) llvm/lib/Target/AMDGPU/GCNSubtarget.cpp (+11-1) 
- (modified) llvm/lib/Target/AMDGPU/GCNSubtarget.h (+17) 
- (modified) llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp (+4) 
- (modified) llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h (+1) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-device-no-attr.ll (+27) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-flat-workgroup-lower.ll (+24) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-flat-workgroup-reject-override.ll (+24) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-kernel-no-attr.ll (+31) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-override.ll (+18) 
- (added) llvm/test/CodeGen/AMDGPU/object-linking-abi-occupancy-preserves-attr.ll (+34) 
- (modified) llvm/test/MC/AMDGPU/amdgpu-info-roundtrip.s (+6) 


``````````diff
diff --git a/llvm/docs/AMDGPUUsage.rst b/llvm/docs/AMDGPUUsage.rst
index f2bda0d3ec0b3..fbce95193db90 100644
--- a/llvm/docs/AMDGPUUsage.rst
+++ b/llvm/docs/AMDGPUUsage.rst
@@ -2174,8 +2174,10 @@ The AMDGPU backend supports the following LLVM IR attributes.
                                                       CLANG attribute [CLANG-ATTR]_. This is an optimization hint,
                                                       and the backend may not be able to satisfy the request. If
                                                       the specified range is incompatible with the function's
-                                                      "amdgpu-flat-work-group-size" value, the implied occupancy
-                                                      bounds by the workgroup size takes precedence.
+                                                      "amdgpu-flat-work-group-size" value, the occupancy bounds
+                                                      implied by the workgroup size take precedence. Under object
+                                                      linking, this hint cannot lower the ABI occupancy budget;
+                                                      see :ref:`amdgpu-abi-occupancy`.
 
      "amdgpu-ieee" true/false.                        GFX6-GFX11 (Except GFX11.7) Only
                                                       Specify whether the function expects the IEEE field of the
@@ -2583,6 +2585,48 @@ unit's worst case (i.e, maxima) ``num_vgpr``, ``num_agpr``, and
 symbolic expressions. These three symbols are ``amdgcn.max_num_vgpr``,
 ``amdgcn.max_num_agpr``, and ``amdgcn.max_num_sgpr``.
 
+.. _amdgpu-abi-occupancy:
+
+ABI Occupancy (Object Linking)
+------------------------------
+
+When object linking is enabled, the AMDGPU backend no longer assumes
+whole-program visibility. Individual translation units must agree on an ABI that
+callers and callees can rely on without seeing each other's register usage. The
+compiler enforces this by using an *ABI occupancy* as a resource-budget floor
+for separately compiled functions. The default ABI occupancy is the number of
+waves per EU required to support a 1024-workitem workgroup:
+
+``ceil(ceil(1024 / wavefront-size) / EUs-per-CU)``.
+
+For example, on ``gfx900`` (wave64, 4 EUs/CU) the default ABI occupancy is
+``ceil(ceil(1024 / 64) / 4) = 4``, yielding a VGPR budget of
+``getMaxNumVGPRs(4) = 64``. On a gfx12 target such as ``gfx1200`` (wave32,
+4 EUs/CU), the default ABI occupancy is ``ceil(ceil(1024 / 32) / 4) = 8``,
+yielding a VGPR budget of ``getMaxNumVGPRs(8) = 192``. The backend option
+``-amdgpu-abi-waves-per-eu=N`` overrides the default ABI occupancy floor. A
+value lower than the default accepts a looser ABI contract; a value higher than
+the default requests a stricter one.
+
+``amdgpu-flat-work-group-size`` is ABI-significant. If a function carries this
+attribute, the occupancy implied by its maximum flat workgroup size replaces
+the default ABI occupancy for that function, so it can either raise or lower the
+register budget.
+
+``amdgpu-waves-per-eu`` remains a hint, and it does not define the ABI
+occupancy. It affects the ABI register budget only if the backend accepts it as
+an effective occupancy request. In that case, a minimum higher than the ABI
+occupancy makes the register budget stricter; a lower minimum cannot lower the
+ABI budget. The maximum side of an accepted ``amdgpu-waves-per-eu`` hint can
+still cap occupancy by inflating reported resource usage. Under object linking,
+the effective maximum used for this inflation is raised to at least the ABI
+occupancy, so the emitted resource usage does not describe a looser contract
+than the ABI budget.
+
+The backend records the register-budget occupancy in each function's
+``.amdgpu.info`` metadata so link-time object linking can reject incompatible
+occupancy contracts across translation units.
+
 .. _amdgpu-elf-code-object:
 
 ELF Code Object
@@ -3015,11 +3059,10 @@ if needed.
 .. _amdgpu-info-section:
 
 ``.amdgpu.info``
-  Per-function metadata for AMDGPU object linking, emitted only in relocatable
-  code objects when object linking is enabled
-  (``-amdgpu-enable-object-linking``).  The linker uses this section to
-  propagate resource usage (registers, stack, LDS) and resolve call graph
-  dependencies across translation units.
+  Per-function metadata emitted only in relocatable code objects when object
+  linking is enabled.  The linker uses this section to propagate resource usage
+  (registers, stack, LDS) and resolve call graph dependencies across
+  translation units.
 
   Each entry uses a tagged, length-prefixed binary encoding:
 
@@ -3048,6 +3091,7 @@ if needed.
      8     ``INFO_CALL``                  8B symbol ref; direct call edge
      9     ``INFO_INDIRECT_CALL``         u32 strtab offset; indirect call type-ID
      10    ``INFO_TYPEID``                u32 strtab offset; function type-ID
+     11    ``INFO_OCCUPANCY``             u32; occupancy used to compile the function
      ===== ============================== ==========================================
 
   .. table:: AMDGPU Info Function Flags (``INFO_FLAGS``)
@@ -21581,6 +21625,7 @@ The following sub-directives may appear inside the block:
      ``.amdgpu_num_vgpr`` *value*           Architectural VGPRs used (u32)
      ``.amdgpu_num_agpr`` *value*           Accumulator VGPRs used (u32)
      ``.amdgpu_private_segment_size`` *n*   Private segment size in bytes (u32)
+     ``.amdgpu_occupancy`` *value*          Occupancy used to compile the function (u32)
      ``.amdgpu_use`` *symbol*               Resource dependency (LDS or barrier)
      ``.amdgpu_call`` *symbol*              Direct call edge to *symbol*
      ``.amdgpu_indirect_call`` *"type-id"*  Indirect call with given type-ID string
@@ -21597,6 +21642,7 @@ Example:
      .amdgpu_num_vgpr 32
      .amdgpu_num_agpr 0
      .amdgpu_private_segment_size 0
+     .amdgpu_occupancy 4
      .amdgpu_use lds_var
      .amdgpu_call helper
      .amdgpu_indirect_call "vi"
diff --git a/llvm/include/llvm/Support/AMDGPUObjLinkingInfo.h b/llvm/include/llvm/Support/AMDGPUObjLinkingInfo.h
index e65161e6545fc..ef71e836bfc40 100644
--- a/llvm/include/llvm/Support/AMDGPUObjLinkingInfo.h
+++ b/llvm/include/llvm/Support/AMDGPUObjLinkingInfo.h
@@ -58,6 +58,9 @@ enum class InfoKind : uint8_t {
   /// string (at the given `.amdgpu.strtab` offset) so the linker can match
   /// it against INFO_INDIRECT_CALL entries.  [u32]
   INFO_TYPEID = 10,
+  /// Occupancy used to compile the function.
+  /// [u32]
+  INFO_OCCUPANCY = 11,
 };
 
 /// Per-function flags packed into INFO_FLAGS entries.
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp b/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
index f1c015312d9a7..8a516a0fff6c2 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
@@ -449,7 +449,7 @@ const AMDGPUMCExpr *createOccupancy(unsigned InitOcc, const MCExpr *NumSGPRs,
 }
 
 void AMDGPUAsmPrinter::validateMCResourceInfo(Function &F) {
-  if (F.isDeclaration() || !AMDGPU::isModuleEntryFunctionCC(F.getCallingConv()))
+  if (F.isDeclaration())
     return;
 
   using RIK = MCResourceInfo::ResourceInfoKind;
@@ -465,6 +465,43 @@ void AMDGPUAsmPrinter::validateMCResourceInfo(Function &F) {
     return false;
   };
 
+  // Register allocation normally respects the ABI register budget. Final
+  // resource accounting can still exceed it when the IR names fixed physical
+  // registers, e.g. inline asm clobbers. Check the resolved per-function
+  // resource symbols here so object-linking metadata is not emitted for a
+  // function that cannot satisfy its ABI occupancy.
+  if (AMDGPUTargetMachine::EnableObjectLinking) {
+    const unsigned BudgetVGPR = STM.getMaxNumVGPRs(F);
+    const unsigned BudgetSGPR = STM.getMaxNumSGPRs(F);
+    const unsigned BudgetAGPR = STM.getMaxNumAGPRs(F);
+
+    auto CheckBudget = [&](RIK Kind, unsigned Budget, const char *What) {
+      MCSymbol *Sym = RI.getSymbol(FnSym->getName(), Kind, OutContext);
+      uint64_t Used;
+      if (!Sym->isVariable() ||
+          !TryGetMCExprValue(Sym->getVariableValue(), Used))
+        return false;
+      if (Used <= Budget)
+        return false;
+      F.getContext().diagnose(DiagnosticInfoResourceLimit(
+          F, What, Used, Budget, DS_Error, DK_ResourceLimit));
+      return true;
+    };
+
+    if (CheckBudget(RIK::RIK_NumVGPR, BudgetVGPR,
+                    "VGPRs under object-linking ABI"))
+      return;
+    if (CheckBudget(RIK::RIK_NumAGPR, BudgetAGPR,
+                    "AGPRs under object-linking ABI"))
+      return;
+    if (CheckBudget(RIK::RIK_NumSGPR, BudgetSGPR,
+                    "SGPRs under object-linking ABI"))
+      return;
+  }
+
+  if (!AMDGPU::isModuleEntryFunctionCC(F.getCallingConv()))
+    return;
+
   const uint64_t MaxScratchPerWorkitem =
       STM.getMaxWaveScratchSize() / STM.getWavefrontSize();
   MCSymbol *ScratchSizeSymbol =
@@ -537,20 +574,17 @@ void AMDGPUAsmPrinter::validateMCResourceInfo(Function &F) {
         TryGetMCExprValue(NumVgprSymbol->getVariableValue(), NumVgpr) &&
         TryGetMCExprValue(NumAgprSymbol->getVariableValue(), NumAgpr)) {
       const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
-      unsigned MaxWaves = MFI.getMaxWavesPerEU();
+      unsigned MaxWaves = STM.getWavesPerEU(F).second;
       uint64_t TotalNumVgpr =
           getTotalNumVGPRs(STM.hasGFX90AInsts(), NumAgpr, NumVgpr);
-      uint64_t NumVGPRsForWavesPerEU =
-          std::max({TotalNumVgpr, (uint64_t)1,
-                    (uint64_t)STM.getMinNumVGPRs(
-                        MaxWaves, MFI.getDynamicVGPRBlockSize())});
-      uint64_t NumSGPRsForWavesPerEU = std::max(
-          {NumSgpr, (uint64_t)1, (uint64_t)STM.getMinNumSGPRs(MaxWaves)});
-      const MCExpr *OccupancyExpr = createOccupancy(
-          STM.getOccupancyWithWorkGroupSizes(*MF).second,
-          MCConstantExpr::create(NumSGPRsForWavesPerEU, OutContext),
-          MCConstantExpr::create(NumVGPRsForWavesPerEU, OutContext),
-          MFI.getDynamicVGPRBlockSize(), STM, OutContext);
+      auto [EffectiveSGPRs, EffectiveVGPRs] =
+          STM.getEffectiveNumGPRsForWavesPerEU(MaxWaves, NumSgpr, TotalNumVgpr,
+                                               MFI.getDynamicVGPRBlockSize());
+      const MCExpr *OccupancyExpr =
+          createOccupancy(STM.getOccupancyWithWorkGroupSizes(*MF).second,
+                          MCConstantExpr::create(EffectiveSGPRs, OutContext),
+                          MCConstantExpr::create(EffectiveVGPRs, OutContext),
+                          MFI.getDynamicVGPRBlockSize(), STM, OutContext);
       uint64_t Occupancy;
 
       const auto [MinWEU, MaxWEU] = AMDGPU::getIntegerPairAttribute(
@@ -720,30 +754,25 @@ bool AMDGPUAsmPrinter::doFinalization(Module &M) {
   // LDS/named-barrier use edges, indirect calls, and address-taken type IDs).
   emitAMDGPUInfo(M);
 
-  // Assign expressions which can only be resolved when all other functions are
-  // known.
-  RI.finalize(OutContext);
-
-  // Switch section and emit all GPR maximums within the processed module.
-  OutStreamer->pushSection();
-  MCSectionELF *MaxGPRSection =
-      OutContext.getELFSection(".AMDGPU.gpr_maximums", ELF::SHT_PROGBITS, 0);
-  OutStreamer->switchSection(MaxGPRSection);
-  getTargetStreamer()->EmitMCResourceMaximums(
-      RI.getMaxVGPRSymbol(OutContext), RI.getMaxAGPRSymbol(OutContext),
-      RI.getMaxSGPRSymbol(OutContext), RI.getMaxNamedBarrierSymbol(OutContext));
-  OutStreamer->popSection();
-
-  // In the object-linking pipeline per-function resource MCExprs reference
-  // external callee symbols that cannot be evaluated here, so cross-TU limit
-  // checks would silently no-op for every non-leaf function. Defer resource
-  // sanity checking to the linker, which re-validates against the aggregated
-  // call graph in the combined .amdgpu.info metadata.
+  // Finalize non-object-linking resource propagation and emit the
+  // `amdgpu.max_num_*` fallback symbols.
   if (!AMDGPUTargetMachine::EnableObjectLinking) {
-    for (Function &F : M.functions())
-      validateMCResourceInfo(F);
+    RI.finalize(OutContext);
+
+    OutStreamer->pushSection();
+    MCSectionELF *MaxGPRSection =
+        OutContext.getELFSection(".AMDGPU.gpr_maximums", ELF::SHT_PROGBITS, 0);
+    OutStreamer->switchSection(MaxGPRSection);
+    getTargetStreamer()->EmitMCResourceMaximums(
+        RI.getMaxVGPRSymbol(OutContext), RI.getMaxAGPRSymbol(OutContext),
+        RI.getMaxSGPRSymbol(OutContext),
+        RI.getMaxNamedBarrierSymbol(OutContext));
+    OutStreamer->popSection();
   }
 
+  for (Function &F : M.functions())
+    validateMCResourceInfo(F);
+
   RI.reset();
 
   return AsmPrinter::doFinalization(M);
@@ -906,11 +935,14 @@ bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
   if (AMDGPUTargetMachine::EnableObjectLinking) {
     const AMDGPUResourceUsageAnalysisWrapperPass::FunctionResourceInfo &RU =
         *ResourceUsage;
+    uint32_t Occupancy =
+        static_cast<uint32_t>(STM.getWavesPerEU(MF.getFunction()).first);
     FunctionInfos.push_back(
         {/*NumSGPR=*/static_cast<uint32_t>(RU.NumExplicitSGPR),
          /*NumArchVGPR=*/static_cast<uint32_t>(RU.NumVGPR),
          /*NumAccVGPR=*/static_cast<uint32_t>(RU.NumAGPR),
          /*PrivateSegmentSize=*/static_cast<uint32_t>(RU.PrivateSegmentSize),
+         /*Occupancy=*/Occupancy,
          /*UsesVCC=*/RU.UsesVCC,
          /*UsesFlatScratch=*/RU.UsesFlatScratch,
          /*HasDynStack=*/RU.HasDynamicallySizedStack,
@@ -1307,7 +1339,7 @@ void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
 
   // Adjust number of registers used to meet default/requested minimum/maximum
   // number of waves per execution unit request.
-  unsigned MaxWaves = MFI->getMaxWavesPerEU();
+  unsigned MaxWaves = STM.getWavesPerEU(MF.getFunction()).second;
   ProgInfo.NumSGPRsForWavesPerEU =
       AMDGPUMCExpr::createMax({ProgInfo.NumSGPR, CreateExpr(1ul),
                                CreateExpr(STM.getMinNumSGPRs(MaxWaves))},
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMCResourceInfo.cpp b/llvm/lib/Target/AMDGPU/AMDGPUMCResourceInfo.cpp
index 2d43019a8d66b..6dfd67ac31baf 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUMCResourceInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUMCResourceInfo.cpp
@@ -14,6 +14,7 @@
 
 #include "AMDGPUMCResourceInfo.h"
 #include "AMDGPUTargetMachine.h"
+#include "GCNSubtarget.h"
 #include "Utils/AMDGPUBaseInfo.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
@@ -256,7 +257,12 @@ void MCResourceInfo::gatherResourceInfo(
   MCSymbol *MaxSGPRSym = getMaxSGPRSymbol(OutContext);
   MCSymbol *MaxNamedBarrierSym = getMaxNamedBarrierSymbol(OutContext);
 
-  if (!AMDGPU::isEntryFunctionCC(MF.getFunction().getCallingConv())) {
+  // These candidates feed the `amdgpu.max_num_*` fallback symbols used by
+  // non-object-linking resource propagation. Under object linking we emit local
+  // per-function resource values only, so there is no fallback maximum to
+  // track.
+  if (!AMDGPU::isEntryFunctionCC(MF.getFunction().getCallingConv()) &&
+      !AMDGPUTargetMachine::EnableObjectLinking) {
     addMaxVGPRCandidate(FRI.NumVGPR);
     addMaxAGPRCandidate(FRI.NumAGPR);
     addMaxSGPRCandidate(FRI.NumExplicitSGPR);
@@ -279,9 +285,37 @@ void MCResourceInfo::gatherResourceInfo(
   if (AMDGPUTargetMachine::EnableObjectLinking) {
     LLVM_DEBUG(dbgs() << "MCResUse:   object linking enabled, no call-graph "
                          "propagation; emitting local resource values only\n");
-    SetToLocal(FRI.NumVGPR, RIK_NumVGPR);
+    const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
+    unsigned MaxWaves = ST.getWavesPerEU(MF.getFunction()).second;
+    unsigned DynamicVGPRBlockSize =
+        AMDGPU::getDynamicVGPRBlockSize(MF.getFunction());
+    if (DynamicVGPRBlockSize == 0 && ST.isDynamicVGPREnabled())
+      DynamicVGPRBlockSize = ST.getDynamicVGPRBlockSize();
+
+    uint64_t TotalVGPR =
+        AMDGPU::getTotalNumVGPRs(ST.hasGFX90AInsts(), FRI.NumAGPR, FRI.NumVGPR);
+    unsigned ExtraSGPRs =
+        AMDGPU::IsaInfo::getNumExtraSGPRs(ST, FRI.UsesVCC, FRI.UsesFlatScratch,
+                                          ST.getTargetID().isXnackOnOrAny());
+    uint64_t TotalSGPR = FRI.NumExplicitSGPR + ExtraSGPRs;
+    auto [EffectiveSGPRs, EffectiveVGPRs] = ST.getEffectiveNumGPRsForWavesPerEU(
+        MaxWaves, TotalSGPR, TotalVGPR, DynamicVGPRBlockSize);
+
+    int32_t EffectiveNumVGPR = FRI.NumVGPR;
+    if (EffectiveVGPRs > TotalVGPR) {
+      if (ST.hasGFX90AInsts() && FRI.NumAGPR)
+        EffectiveNumVGPR = static_cast<int32_t>(EffectiveVGPRs - FRI.NumAGPR);
+      else
+        EffectiveNumVGPR = static_cast<int32_t>(EffectiveVGPRs);
+    }
+
+    int32_t EffectiveNumSGPR = FRI.NumExplicitSGPR;
+    if (EffectiveSGPRs > TotalSGPR)
+      EffectiveNumSGPR += static_cast<int32_t>(EffectiveSGPRs - TotalSGPR);
+
+    SetToLocal(EffectiveNumVGPR, RIK_NumVGPR);
     SetToLocal(FRI.NumAGPR, RIK_NumAGPR);
-    SetToLocal(FRI.NumExplicitSGPR, RIK_NumSGPR);
+    SetToLocal(EffectiveNumSGPR, RIK_NumSGPR);
     SetToLocal(FRI.NumNamedBarrier, RIK_NumNamedBarrier);
     SetToLocal(FRI.PrivateSegmentSize, RIK_PrivateSegSize);
     SetToLocal(FRI.UsesVCC, RIK_UsesVCC);
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp b/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp
index fb4728609c877..0e47cc9cb2df6 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.cpp
@@ -16,6 +16,7 @@
 #include "AMDGPUInstructionSelector.h"
 #include "AMDGPULegalizerInfo.h"
 #include "AMDGPURegisterBankInfo.h"
+#include "AMDGPUTargetMachine.h"
 #include "R600Subtarget.h"
 #include "SIMachineFunctionInfo.h"
 #include "Utils/AMDGPUBaseInfo.h"
@@ -26,6 +27,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsR600.h"
 #include "llvm/IR/MDBuilder.h"
+#include "llvm/Support/MathExtras.h"
 #include <algorithm>
 
 using namespace llvm;
@@ -41,7 +43,7 @@ AMDGPUSubtarget::getMaxLocalMemSizeWithWaveCount(unsigned NWaves,
   const unsigned WaveSize = getWavefrontSize();
   const unsigned WorkGroupSize = getFlatWorkGroupSizes(F).second;
   const unsigned WavesPerWorkgroup =
-      std::max(1u, (WorkGroupSize + WaveSize - 1) / WaveSize);
+      std::max(1u, divideCeil(WorkGroupSize, WaveSize));
 
   const unsigned WorkGroupsPerCU =
       std::max(1u, (NWaves * getEUsPerCU()) / WavesPerWorkgroup);
@@ -224,7 +226,35 @@ AMDGPUSubtarget::getWavesPerEU(std::pair<unsigned, unsigned> FlatWorkGroupSizes,
   // Requested minimum/maximum number of waves per execution unit.
   std::pair<unsigned, unsigned> Requested =
       AMDGPU::getIntegerPairAttribute(F, "amdgpu-waves-per-eu", Default, true);
-  return getEffectiveWavesPerEU(Requested, FlatWorkGroupSizes, LDSBytes);
+  std::pair<unsigned, unsigned> WavesPerEU =
+      getEffectiveWavesPerEU(Requested, FlatWorkGroupSizes, LDSBytes);
+  if (!AMDGPUTargetMachine::EnableObjectLinking)
+    return WavesPerEU;
+
+  unsigned FunctionABIOccupancy = getFunctionABIOccupancy(F);
+  unsigned EffectiveMinWaves =
+      F.hasFnAttribute("amdgpu-waves-per-eu")
+          ? std::max(WavesPerEU.first, FunctionABIOccupancy)
+          : FunctionABIOccupancy;
+  return {EffectiveMinWaves, std::max(WavesPerEU.second, EffectiveMinWaves)};
+}
+
+unsigned AMDGPUSubtarget::getDefaultABIOccupancy() const {
+  unsigned Override = AMDGPUTargetMachine::ABIWavesPerEU;
+  if (Override)
+    Override = std::clamp(Override, getMinWavesPerEU(), getMaxWavesPerEU());
+
+  constexpr unsigned DefaultMaxWorkGroupSize = 1024;
+  return Override ? Override
+                  : getWavesPerEUForWorkGroup(DefaultMaxWorkGroupSize);
+}
+
+unsigned AMDGPUSubtarget::getFunctionABIOccupancy(const Function &F) const {
+  if (!F.hasFnAttribute("amdgpu-flat-work-group-size"))
+    return getDefaultABIOccupancy();
+
+  std::pair<unsigned, unsigned> FlatWorkGroupSizes = getFlatWorkGroupSizes(F);
+  return getWavesPerEUForWorkGroup(FlatWorkGroupSizes.second);
 }
 
 std::optional<unsigned>
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h b/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h
index 07746c087904d..9f24d8137ac8b 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h
+++ b/llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h
@@ -132,6 +132,13...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/199475


More information about the llvm-commits mailing list