[llvm] [MLGO] Saturate out-of-range regalloc priority advice (PR #224062)

Arseniy Obolenskiy via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 16 23:19:11 PDT 2026


https://github.com/aobolensk updated https://github.com/llvm/llvm-project/pull/224062

>From a2586414552d16f37418b1fe8a574c5a75f9ede1 Mon Sep 17 00:00:00 2001
From: Arseniy Obolenskiy <arseniy.obolenskiy at amd.com>
Date: Wed, 16 Sep 2026 18:10:01 +0200
Subject: [PATCH 1/2] [MLGO] Saturate out-of-range regalloc priority advice

Converting the float advice to unsigned is undefined outside `[0, 2^32)` interval

Negative advice wrapped to near UINT_MAX and flipped the priority order, NaN or advice below 1.0 made every priority 0
---
 llvm/lib/Analysis/models/interactive_host.py  |  9 ++-
 .../lib/CodeGen/MLRegAllocPriorityAdvisor.cpp | 20 ++++--
 .../MLRegAlloc/Inputs/interactive_main.py     | 68 ++++++++++++++-----
 .../CodeGen/MLRegAlloc/interactive-mode.ll    | 27 +++++++-
 4 files changed, 100 insertions(+), 24 deletions(-)

diff --git a/llvm/lib/Analysis/models/interactive_host.py b/llvm/lib/Analysis/models/interactive_host.py
index f2c2b640e7f4f..5bc7f5a9db9a7 100644
--- a/llvm/lib/Analysis/models/interactive_host.py
+++ b/llvm/lib/Analysis/models/interactive_host.py
@@ -23,9 +23,12 @@
 def send(f: io.BufferedWriter, value: Union[int, float], spec: log_reader.TensorSpec):
     """Send the `value` - currently just a scalar - formatted as per `spec`."""
 
-    # just int64 for now
-    assert spec.element_type == ctypes.c_int64
-    to_send = ctypes.c_int64(int(value))
+    if spec.element_type == ctypes.c_int64:
+        to_send = ctypes.c_int64(int(value))
+    elif spec.element_type == ctypes.c_float:
+        to_send = ctypes.c_float(float(value))
+    else:
+        raise ValueError(f"unsupported advice element type {spec.element_type}")
     assert f.write(bytes(to_send)) == ctypes.sizeof(spec.element_type) * math.prod(
         spec.shape
     )
diff --git a/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp b/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
index 50ecd3ce2c88c..b30145af00305 100644
--- a/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
+++ b/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
@@ -33,6 +33,8 @@
 #include "llvm/PassRegistry.h"
 #include "llvm/Support/CommandLine.h"
 
+#include <limits>
+
 #if defined(LLVM_HAVE_TFLITE)
 #include "llvm/Analysis/ModelUnderTrainingRunner.h"
 #include "llvm/Analysis/NoInferenceModelRunner.h"
@@ -325,6 +327,16 @@ MLPriorityAdvisor::MLPriorityAdvisor(const MachineFunction &MF,
   Runner->switchContext(MF.getName());
 }
 
+// Converting a NaN or an out-of-range float advice to unsigned is undefined.
+// Saturate instead.
+static unsigned convertAdviceToPriority(double Advice) {
+  if (!(Advice > 0.0)) // Also catches NaN.
+    return 0;
+  if (Advice >= static_cast<double>(std::numeric_limits<unsigned>::max()))
+    return std::numeric_limits<unsigned>::max();
+  return static_cast<unsigned>(Advice);
+}
+
 float MLPriorityAdvisor::getPriorityImpl(const LiveInterval &LI) const {
   const unsigned Size = LI.getSize();
   LiveRangeStage Stage = RA.getExtraInfo().getStage(LI);
@@ -337,7 +349,7 @@ float MLPriorityAdvisor::getPriorityImpl(const LiveInterval &LI) const {
 }
 
 unsigned MLPriorityAdvisor::getPriority(const LiveInterval &LI) const {
-  return static_cast<unsigned>(getPriorityImpl(LI));
+  return convertAdviceToPriority(getPriorityImpl(LI));
 }
 
 #ifdef LLVM_HAVE_TFLITE
@@ -348,10 +360,10 @@ llvm::createDevelopmentModePriorityAdvisorAnalysis() {
 
 unsigned
 DevelopmentModePriorityAdvisor::getPriority(const LiveInterval &LI) const {
-  double Prio = 0;
+  unsigned Prio = 0;
 
   if (isa<ModelUnderTrainingRunner>(getRunner())) {
-    Prio = MLPriorityAdvisor::getPriorityImpl(LI);
+    Prio = convertAdviceToPriority(MLPriorityAdvisor::getPriorityImpl(LI));
   } else {
     Prio = getDefaultAdvisor().getPriority(LI);
   }
@@ -385,7 +397,7 @@ DevelopmentModePriorityAdvisor::getPriority(const LiveInterval &LI) const {
   Log->logTensorValue(CurrentFeature, reinterpret_cast<const char *>(&Ret));
   Log->endObservation();
 
-  return static_cast<unsigned>(Prio);
+  return Prio;
 }
 
 RegAllocPriorityAdvisorProvider *
diff --git a/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py b/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
index 1f62a5c6c9a3b..3052784f21713 100644
--- a/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
+++ b/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
@@ -4,24 +4,60 @@
 
 from typing import Sequence
 
-def main(args):
+
+def evict_advice(tensor_values: Sequence[log_reader.TensorValue]):
     # this advisor just picks the first legal register to evict, which is
     # identifiable by the "mask" feature
-    class Advisor:
-        to_return = False
-
-        def advice(self, tensor_values: Sequence[log_reader.TensorValue]):
-            for tv in tensor_values:
-                if tv.spec().name != "mask":
-                    continue
-                for i, v in enumerate(tv):
-                    if v == 1:
-                        return i
-            # i.e. invalid:
-            return -1
-
-    a = Advisor()
-    interactive_host.run_interactive(args[0], a.advice, args[1:])
+    for tv in tensor_values:
+        if tv.spec().name != "mask":
+            continue
+        for i, v in enumerate(tv):
+            if v == 1:
+                return i
+    # i.e. invalid:
+    return -1
+
+
+def li_size(tensor_values: Sequence[log_reader.TensorValue]) -> float:
+    for tv in tensor_values:
+        if tv.spec().name == "li_size":
+            return float(tv[0])
+    return 0.0
+
+
+# A constant policy is indistinguishable from any other, because RAGreedy then
+# breaks all the resulting ties on the vreg number.
+def split_policy(large_advice: float):
+    def advice(tvs):
+        size = li_size(tvs)
+        return large_advice if size > 100 else size
+
+    return advice
+
+
+PRIORITY_POLICIES = {
+    "low": split_policy(0.0),
+    "high": split_policy(4.0e9),
+    "negative": split_policy(-1.0),
+    "nan": split_policy(float("nan")),
+    "huge": split_policy(1.0e30),
+}
+
+
+def main(args):
+    if args[0].startswith("--priority="):
+        name = args[0][len("--priority=") :]
+        if name not in PRIORITY_POLICIES:
+            sys.exit(
+                f"unknown priority policy {name!r}, expected one of "
+                f"{sorted(PRIORITY_POLICIES)}"
+            )
+        advice = PRIORITY_POLICIES[name]
+        args = args[1:]
+    else:
+        advice = evict_advice
+
+    interactive_host.run_interactive(args[0], advice, args[1:])
 
 
 if __name__ == "__main__":
diff --git a/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll b/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
index 51af5891c4e0f..b702716fee695 100644
--- a/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
+++ b/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
@@ -1,6 +1,6 @@
 ; REQUIRES: x86_64-linux
 ; RUN: rm -rf %t.rundir
-; RUN: rm -rf %t.channel-basename.*
+; RUN: rm -rf %t.channel-basename.* %t.chan.* %t.*.s
 ; RUN: mkdir %t.rundir
 ; RUN: cp %S/../../../lib/Analysis/models/log_reader.py %t.rundir
 ; RUN: cp %S/../../../lib/Analysis/models/interactive_host.py %t.rundir
@@ -21,3 +21,28 @@
 
 ; CHECK:      index_to_evict: 9
 ; CHECK-NEXT: index_to_evict: 10
+
+;; Out-of-range or NaN priority advice is saturated, not converted.
+
+; DEFINE: %{prio} = %python %t.rundir/interactive_main.py --priority=
+; DEFINE: %{llc} = llc -mtriple=x86_64-linux-unknown -regalloc=greedy \
+; DEFINE:   -regalloc-enable-priority-advisor=release %S/Inputs/two-large-fcts.ll
+
+; RUN: %{prio}low %t.chan.low %{llc} \
+; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.low -o %t.low.s
+; RUN: %{prio}high %t.chan.high %{llc} \
+; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.high -o %t.high.s
+; RUN: %{prio}negative %t.chan.neg %{llc} \
+; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.neg -o %t.neg.s
+; RUN: %{prio}nan %t.chan.nan %{llc} \
+; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.nan -o %t.nan.s
+; RUN: %{prio}huge %t.chan.huge %{llc} \
+; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.huge -o %t.huge.s
+
+;; Without saturation, -1.0 wrapped to near UINT_MAX and 1e30 converted to 0.
+; RUN: cmp %t.neg.s %t.low.s
+; RUN: cmp %t.nan.s %t.low.s
+; RUN: cmp %t.huge.s %t.high.s
+
+;; Guard against the above passing vacuously: the two references must differ.
+; RUN: not cmp -s %t.low.s %t.high.s

>From 1ec31b8a9be8414036e501ad3cf8ca667b731519 Mon Sep 17 00:00:00 2001
From: Arseniy Obolenskiy <arseniy.obolenskiy at amd.com>
Date: Thu, 17 Sep 2026 08:18:53 +0200
Subject: [PATCH 2/2] Assert on NaN

---
 llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp          | 4 +++-
 llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py | 1 -
 llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll        | 5 +----
 3 files changed, 4 insertions(+), 6 deletions(-)

diff --git a/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp b/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
index b30145af00305..0fc98b399a1a6 100644
--- a/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
+++ b/llvm/lib/CodeGen/MLRegAllocPriorityAdvisor.cpp
@@ -33,6 +33,7 @@
 #include "llvm/PassRegistry.h"
 #include "llvm/Support/CommandLine.h"
 
+#include <cmath>
 #include <limits>
 
 #if defined(LLVM_HAVE_TFLITE)
@@ -328,8 +329,9 @@ MLPriorityAdvisor::MLPriorityAdvisor(const MachineFunction &MF,
 }
 
 // Converting a NaN or an out-of-range float advice to unsigned is undefined.
-// Saturate instead.
+// Saturate instead. A NaN is a model error, so also assert on it.
 static unsigned convertAdviceToPriority(double Advice) {
+  assert(!std::isnan(Advice) && "model produced a NaN priority");
   if (!(Advice > 0.0)) // Also catches NaN.
     return 0;
   if (Advice >= static_cast<double>(std::numeric_limits<unsigned>::max()))
diff --git a/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py b/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
index 3052784f21713..f31c65e1cad65 100644
--- a/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
+++ b/llvm/test/CodeGen/MLRegAlloc/Inputs/interactive_main.py
@@ -39,7 +39,6 @@ def advice(tvs):
     "low": split_policy(0.0),
     "high": split_policy(4.0e9),
     "negative": split_policy(-1.0),
-    "nan": split_policy(float("nan")),
     "huge": split_policy(1.0e30),
 }
 
diff --git a/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll b/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
index b702716fee695..82088c80882c3 100644
--- a/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
+++ b/llvm/test/CodeGen/MLRegAlloc/interactive-mode.ll
@@ -22,7 +22,7 @@
 ; CHECK:      index_to_evict: 9
 ; CHECK-NEXT: index_to_evict: 10
 
-;; Out-of-range or NaN priority advice is saturated, not converted.
+;; Out-of-range priority advice is saturated, not converted.
 
 ; DEFINE: %{prio} = %python %t.rundir/interactive_main.py --priority=
 ; DEFINE: %{llc} = llc -mtriple=x86_64-linux-unknown -regalloc=greedy \
@@ -34,14 +34,11 @@
 ; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.high -o %t.high.s
 ; RUN: %{prio}negative %t.chan.neg %{llc} \
 ; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.neg -o %t.neg.s
-; RUN: %{prio}nan %t.chan.nan %{llc} \
-; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.nan -o %t.nan.s
 ; RUN: %{prio}huge %t.chan.huge %{llc} \
 ; RUN:   -regalloc-priority-interactive-channel-base=%t.chan.huge -o %t.huge.s
 
 ;; Without saturation, -1.0 wrapped to near UINT_MAX and 1e30 converted to 0.
 ; RUN: cmp %t.neg.s %t.low.s
-; RUN: cmp %t.nan.s %t.low.s
 ; RUN: cmp %t.huge.s %t.high.s
 
 ;; Guard against the above passing vacuously: the two references must differ.



More information about the llvm-commits mailing list