From a2f007a46e256b53006081484c11d94c6750b37a Mon Sep 17 00:00:00 2001 From: seedds Date: Fri, 20 Nov 2026 18:53:26 -0800 Subject: [PATCH 1/3] gfx/dmsh: specialize the blend fix-up away for pipelines whose blend words are both 0 (chain change) dm_blend0 (dmsh_rewrite.py blend_zero) reads two words per draw: the zero-weight NaN rule and NVIDIA's float32 rounding into normalized targets. For most draws both are 0, and the read alone cost 2-6 % of Ocarina of Time's hottest pixel shaders on an M2 (fsbench: the words as constants run as fast as no fix-up at all). A new function constant dm_blend_off (DMSH_BLEND_OFF_FC 217) makes dm_blend0 return first. The host sets it per pipeline when the draw's words are both 0 (pso_key.blend_live, the key's former spare word; fn_off now takes a mask: FN_OFF_BORDER, FN_OFF_BLEND), as it does for the border corrections. That is 89 % of Ocarina of Time's draws and every hot pixel shader. Prewarm (pre_fn) and offline pipelines (pso_offline.py) take the common specialization; mesh, feedback and wide-line pipelines keep the fix-up. Pipelines with nonzero words read them as before, so the NaN and rounding cases are unchanged. Co-Authored-By: Claude Opus 5.5 --- dm/gfx/nvn/dmsh_abi.h | 4 ++ dm/gfx/nvn/dmsh_chain.h | 2 +- dm/gfx/nvn/nvn_mtl.m | 57 +++++++++++++++++----------- dm/gfx/nvn/nvn_pso_skey.h | 7 ++-- dm/gfx/tests/t_pso_skey.m | 14 +++---- dm/gfx/tests/test_dmsh_blend_zero.py | 6 +++ dm/gfx/tools/dmsh_rewrite.py | 4 +- dm/gfx/tools/pso_offline.py | 2 +- 8 files changed, 61 insertions(+), 35 deletions(-) diff --git a/dm/gfx/nvn/dmsh_abi.h b/dm/gfx/nvn/dmsh_abi.h index dbe3e567c6..81591ca7f3 100644 --- a/dm/gfx/nvn/dmsh_abi.h +++ b/dm/gfx/nvn/dmsh_abi.h @@ -194,6 +194,10 @@ // The corrections' function constant (bool, every stage): true turns them off, for a pipeline whose draw or dispatch binds no sampler with a // twin (nvn_mtl.m border_need, fn_off). The twin samples go, and the registers they kept: Ocarina of Time's 1080p material passes spilled 300-400 bytes a thread with them. Undefined, every sample corrects as its bit says #define DMSH_BORDER_FC 216 +// The blend fix-up's function constant (bool, pixel shaders with dm_blend0, dmsh_rewrite.py blend_zero): true for a pipeline whose blend words are both 0 (nvn_mtl.m bz_word / rop_word: +// no zero-weight NaN rule and no NVIDIA rounding for any of its targets, which 89 % of Ocarina of Time's draws are), so the fix-up and the read of its words go. Undefined or false, the +// words are read at DMSH_BLEND_BUFFER as before (T-126 v2: the read alone cost 2-6 % of the hottest pixel shaders on an M2) +#define DMSH_BLEND_OFF_FC 217 // The logic operation's state (dm/gfx/tools/dmsh_logic.py, the _l entry points of the _bx libraries): uint operation (NVN_LOGIC_OP_*), 12 bytes of padding, a uint4 channel mask per colour target, at this fragment buffer index (nvn_mtl.m lo_bind) #define DMSH_LOGIC_BUFFER 29 // Its function constants: bool, colour target n is attached (the variant reads it only then), at this index + n (nvn_mtl.m lo_fn specializes the entry point per pass's targets) diff --git a/dm/gfx/nvn/dmsh_chain.h b/dm/gfx/nvn/dmsh_chain.h index 36ebb0e686..22bada8d3f 100644 --- a/dm/gfx/nvn/dmsh_chain.h +++ b/dm/gfx/nvn/dmsh_chain.h @@ -1,3 +1,3 @@ // Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game; // the host loads only /b-/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change -#define DMSH_CHAIN "648a020c093b" +#define DMSH_CHAIN "1ae20f269d98" diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 8c340a0644..b5bc26ae04 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -7016,15 +7016,22 @@ @implementation FnDev @end // cached by that descriptor. nil: f has no variant (no library descriptor, or its entry point does not declare the constant), and off builds what on builds @interface FnOff : NSObject { @public MTL4FunctionDescriptor *d4; MTLFunctionConstantValues *cv; id dev; int none, dev_failed; } @end @implementation FnOff @end +// T-126 v2: off is a mask: FN_OFF_BORDER (the border corrections off, as before) and FN_OFF_BLEND (the blend fix-up off, DMSH_BLEND_OFF_FC, for a pipeline whose blend words are +// both 0: pso_key.blend_live 0). One FnOff per descriptor and mask; a mask whose constants f's entry point does not declare is none (it builds as on) +enum { FN_OFF_BORDER = 1, FN_OFF_BLEND = 2 }; +@interface FnOffSet : NSObject { @public FnOff *m[4]; } @end +@implementation FnOffSet @end static os_unfair_lock g_fn_off_lock = OS_UNFAIR_LOCK_INIT; -static NSMapTable *g_fn_off; // MTL4FunctionDescriptor (fn4_of) → FnOff -static FnOff *fn_off(id f) { +static NSMapTable *g_fn_off; // MTL4FunctionDescriptor (fn4_of) → FnOffSet +static FnOff *fn_off(id f, int mask) { + mask &= 3; if (!mask) return nil; MTL4FunctionDescriptor *fd = fn4_of(f); if (!fd) return nil; // no library to specialize from (diagnostic overrides) os_unfair_lock_lock(&g_fn_off_lock); if (!g_fn_off) g_fn_off = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPointerPersonality valueOptions:NSPointerFunctionsStrongMemory capacity:0]; - FnOff *o = [g_fn_off objectForKey:fd]; - if (!o) { o = [FnOff new]; [g_fn_off setObject:o forKey:fd]; } + FnOffSet *set = [g_fn_off objectForKey:fd]; + if (!set) { set = [FnOffSet new]; [g_fn_off setObject:set forKey:fd]; } + FnOff *o = set->m[mask]; if (!o) o = set->m[mask] = [FnOff new]; os_unfair_lock_unlock(&g_fn_off_lock); @synchronized(o) { if (o->d4 || o->none) return o->none ? nil : o; @@ -7035,26 +7042,28 @@ @implementation FnOff @end } MTL4LibraryFunctionDescriptor *ld = [fd isKindOfClass:MTL4LibraryFunctionDescriptor.class] ? (MTL4LibraryFunctionDescriptor *)fd : nil; // NOLINTNEXTLINE(clang-analyzer-nullability.NullablePassedToNonnull): the descriptor's name is set when it is made (fn4_note refuses a nil name, pre_fn takes the name its function was made from) and never changed - if (!ld || ![ld.library newFunctionWithName:ld.name].functionConstantsDictionary[@"dm_border_off"]) { o->none = 1; return nil; } // the entry's, not f's: a specialized f lists no constants + NSDictionary *fc = ld ? [ld.library newFunctionWithName:ld.name].functionConstantsDictionary : nil; // the entry's, not f's: a specialized f lists no constants + int border = (mask & FN_OFF_BORDER) && fc[@"dm_border_off"], blend = (mask & FN_OFF_BLEND) && fc[@"dm_blend_off"]; + if (!border && !blend) { o->none = 1; return nil; } if (!cv) cv = [MTLFunctionConstantValues new]; - BOOL yes = YES; [cv setConstantValue:&yes type:MTLDataTypeBool atIndex:DMSH_BORDER_FC]; + BOOL yes = YES; if (border) [cv setConstantValue:&yes type:MTLDataTypeBool atIndex:DMSH_BORDER_FC]; if (blend) [cv setConstantValue:&yes type:MTLDataTypeBool atIndex:DMSH_BLEND_OFF_FC]; MTL4SpecializedFunctionDescriptor *sd = [MTL4SpecializedFunctionDescriptor new]; sd.functionDescriptor = ld; sd.constantValues = cv; o->cv = cv; o->d4 = sd; return o; } } // f's Metal 4 descriptor, without the border corrections when off -static MTL4FunctionDescriptor *fn4_of_b(id f, int off) { FnOff *o = off ? fn_off(f) : nil; return o ? o->d4 : fn4_of(f); } +static MTL4FunctionDescriptor *fn4_of_b(id f, int off) { FnOff *o = fn_off(f, off); return o ? o->d4 : fn4_of(f); } // off: the FN_OFF_* mask // The function an MTLDevice pipeline is built from (fn_dev), without the border corrections when off: specialized through its library, once. A failed specialization keeps the corrections static id fn_dev_b(id f, int off) { - FnOff *o = off ? fn_off(f) : nil; + FnOff *o = fn_off(f, off); if (!o) return fn_dev(f); @synchronized(o) { if (!o->dev && !o->dev_failed) { MTL4LibraryFunctionDescriptor *ld = (MTL4LibraryFunctionDescriptor *)((MTL4SpecializedFunctionDescriptor *)o->d4).functionDescriptor; // NOLINTNEXTLINE(clang-analyzer-nullability.NullablePassedToNonnull): fn_off made o->d4 from this ld after looking its name up; names are never nil (fn4_note, pre_fn) NSError *e = nil; o->dev = dev_fn(ld.library, ld.name, o->cv, &e); - if (!o->dev) { o->dev_failed = 1; MLOG("[RED] function %s: specializing it without the border corrections failed: %s (its pipelines keep them)", f.name.UTF8String, e.localizedDescription.UTF8String); } + if (!o->dev) { o->dev_failed = 1; MLOG("[RED] function %s: specializing it without the border corrections or the blend fix-up (mask %d) failed: %s (its pipelines keep them)", f.name.UTF8String, off, e.localizedDescription.UTF8String); } } if (o->dev) return o->dev; } @@ -10958,7 +10967,7 @@ static void pso_fixed4(MTL4RenderPipelineDescriptor *m, MTLRenderPipelineDescrip return m; } static void pbase_key_of(MTLRenderPipelineDescriptor *d, int off, pbase_key *k) { - memset(k, 0, sizeof *k); k->off = off != 0; + memset(k, 0, sizeof *k); k->off = (uint32_t)off; // the FN_OFF_* mask k->vf = (__bridge const void *)d.vertexFunction; k->ff = (__bridge const void *)d.fragmentFunction; k->samples = (uint32_t)d.rasterSampleCount; k->a2c = d.alphaToCoverageEnabled; k->rast = d.rasterizationEnabled; k->topo = (uint32_t)d.inputPrimitiveTopology; k->amp = (uint32_t)d.maxVertexAmplificationCount; MTLVertexDescriptor *vd = d.vertexDescriptor; @@ -11098,6 +11107,8 @@ static void pbase_key_of(MTLRenderPipelineDescriptor *d, int off, pbase_key *k) } static id pso_build(MTLRenderPipelineDescriptor *d, int off, NSError **e) { return pso_build_ex(d, off, e, 1); } // off: !pso_key.border of the key d was made from // Pipeline key: current state S + pass formats (normal pass; a merged pass additionally carries lmap / specialized function, filled in by pso_get) +// The FN_OFF_* mask a pipeline of key k is built with (fn_off): without the border corrections when no bound sampler has a twin, without the blend fix-up when its words are both 0 +static inline int pso_off(const pso_key *k) { return (k->border ? 0 : FN_OFF_BORDER) | (k->blend_live ? 0 : FN_OFF_BLEND); } static void pso_key_fill(pso_key *k, NvShader *vs, NvShader *fs, const uint32_t cfmt[8], uint32_t dfmt, uint32_t sfmt, uint32_t samples, int lmap) { memset(k, 0, sizeof *k); k->vs = (__bridge void *)vs; k->fs = (__bridge void *)fs; @@ -11106,6 +11117,7 @@ static void pso_key_fill(pso_key *k, NvShader *vs, NvShader *fs, const uint32_t for (int i = 0; i < 8; i++) if (k->cfmt[i] || lmap) k->blend[i] = S.blend[i]; k->logic = lop_key(k, fs, lmap); k->border = border_need(vs, vs->stage) || border_need(fs, 1); // as prog_border, which the draw compares + k->blend_live = fs && fs->has_bz && (bz_word(g_pso_lmap) | rop_word(g_pso_lmap)) != 0; // the words bz_bind binds for this draw (draw_ passes its copy of g_pso_lmap) (T-126 v2): both 0 → the fix-up specialized away (FN_OFF_BLEND) const nvn_refl *rf = &vs->rf; for (int v = 0; v < rf->nv; v++) { int a = rf->v[v].nvn; if (a < 32 && a < S.nattr) { if (a < 16) k->attr[a] = S.attr[a]; else k->attr_hi[a - 16] = S.attr[a]; int st = S.attr[a].stream; if (st < 16) k->stream[st] = S.stream[st]; } } pso_key_norm(k, lmap); @@ -11199,7 +11211,7 @@ static int pso_pend_kick_d(const pso_key *k, MTLRenderPipelineDescriptor *d, int } pthread_mutex_unlock(&g_pp_mu); if (slot < 0) return 0; - pso_pend_start(slot, gen, d, !k->border, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)); + pso_pend_start(slot, gen, d, pso_off(k), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)); return 1; } static int pso_pend_kick_budget(const pso_key *k, NvShader *vs, NvShader *fs, int spec, PsoPredictBudget *budget) { // the submit thread @@ -11229,7 +11241,7 @@ static int pso_pend_demand(const pso_key *k, NvShader *vs, NvShader *fs) { if (hm_get_id(&g_pso, k)) return 0; pthread_mutex_lock(&g_pp_mu); uint32_t gen = 0; int slot = pso_pend_slot(k, 0, &gen); pthread_mutex_unlock(&g_pp_mu); if (slot < 0) return 0; - pso_pend_start(slot, gen, pso_desc(k, vs, fs, nil, 0), !k->border, pp_bg_queue()); + pso_pend_start(slot, gen, pso_desc(k, vs, fs, nil, 0), pso_off(k), pp_bg_queue()); return 1; } // Called by the submit thread: a build in the table is taken (waited for while its worker runs it; made here at once while it is still queued, so a draw that waits waits for its @@ -11240,7 +11252,7 @@ static int pso_pend_demand(const pso_key *k, NvShader *vs, NvShader *fs) { if (at >= 0 && !g_pp[at].done && !g_pp[at].run && g_pp[at].d) { MTLRenderPipelineDescriptor *d = g_pp[at].d; g_pp[at].d = nil; g_pp[at].used = 0; g_pp_stolen++; pthread_mutex_unlock(&g_pp_mu); - NSError *e = nil; return pso_build(d, !k->border, &e); + NSError *e = nil; return pso_build(d, pso_off(k), &e); } if (at >= 0) { g_pp[at].taking = 1; // lookup workers may admit/reclaim while the condition wait releases g_pp_mu @@ -11294,7 +11306,7 @@ static void hy_base_kick(MTLRenderPipelineDescriptor *d, int off) { if (h) return h; MTLRenderPipelineDescriptor *d = vs->has_pull ? pso_desc_pull(k, vs, fs) : nil; if (!d) return nil; - NSError *e = nil; int off = !k->border; id ps = pso_build_ex(d, off, &e, 0); + NSError *e = nil; int off = pso_off(k); id ps = pso_build_ex(d, off, &e, 0); if (!ps) { hy_base_kick(d, off); g_hy_none++; return nil; } g_hy_made++; hm_put_id(&g_pso_hy, k, ps); return ps; @@ -11311,7 +11323,7 @@ static void hy_base_kick(MTLRenderPipelineDescriptor *d, int off) { if (hm_get_id(&g_pso_pull_fail, k)) return nil; if (hybrid_on() && hm_get_id(&g_pso, k)) return hybrid_get(k, vs, fs); MTLRenderPipelineDescriptor *d = pso_desc_pull(k, vs, fs); - NSError *e = nil; uint64_t t0 = bp_now(); id ps = d ? pso_build(d, !k->border, &e) : nil; + NSError *e = nil; uint64_t t0 = bp_now(); id ps = d ? pso_build(d, pso_off(k), &e) : nil; g_bp_pso_n++; g_bp_pso_ns += bp_now() - t0; if (!ps) { if (d) MLOG("[RED] pulling pipeline for vertex %s fragment %s: %s (its draws convert their vertex attributes on the CPU)", vs->key, fs ? fs->key : "-", e.localizedDescription.UTF8String); @@ -11426,6 +11438,7 @@ static int pre_lib_absent(NSString *key, NSString *suffix) { if (!f.functionConstantsDictionary.count) return ld; MTLFunctionConstantValues *cv = [MTLFunctionConstantValues new]; if (f.functionConstantsDictionary[@"dm_border_off"]) { BOOL yes = YES; [cv setConstantValue:&yes type:MTLDataTypeBool atIndex:DMSH_BORDER_FC]; } + if (f.functionConstantsDictionary[@"dm_blend_off"]) { BOOL yes = YES; [cv setConstantValue:&yes type:MTLDataTypeBool atIndex:DMSH_BLEND_OFF_FC]; } // and the blend fix-up (FN_OFF_BLEND), as most draws MTL4SpecializedFunctionDescriptor *sd = [MTL4SpecializedFunctionDescriptor new]; sd.functionDescriptor = ld; sd.constantValues = cv; return sd; } static NSDictionary *pre_json(NSString *key) { NSData *d = msl_data([NSString stringWithFormat:@"%@/%@_b.json", g_msl_dir, key]); return d ? [NSJSONSerialization JSONObjectWithData:d options:0 error:nil] : nil; } @@ -11664,7 +11677,7 @@ static void pso_prebuild_bg(void) { // after the prewarm, in the app without a if (i < g_sm_amp_n) { id ps = g_sm_amp[i].done ? g_sm_amp[i].ps : nil; os_unfair_lock_unlock(&g_sm_amp_lock); if (ps) { hm_put_id(&g_pso, k, ps); return hm_get_id(&g_pso, k); } return nil; } if (g_sm_amp_n >= SM_AMP_MAX) { os_unfair_lock_unlock(&g_sm_amp_lock); return nil; } g_sm_amp[i].k = *k; g_sm_amp[i].ps = nil; g_sm_amp[i].done = 0; g_sm_amp_n++; os_unfair_lock_unlock(&g_sm_amp_lock); - MTLRenderPipelineDescriptor *d = pso_desc(k, vs, fs, nil, 0); int off = !k->border; + MTLRenderPipelineDescriptor *d = pso_desc(k, vs, fs, nil, 0); int off = pso_off(k); int face = k->fsfn == FSP_MARK; dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ @autoreleasepool { NSError *e = nil; id ps = pso_build(d, off, &e); if (!ps) MLOG("[RED] %s: no amplified pipeline for vertex %s fragment %s: %s (%s)", face ? "face-split draw" : "slice-merged pass", vs->key, fs ? fs->key : "-", e.localizedDescription.UTF8String, @@ -11684,7 +11697,7 @@ static void pso_prebuild_bg(void) { // after the prewarm, in the app without a if (cached) return cached; if (hm_get_id(&g_pso_fail, &k)) return nil; NSError *error = nil; - id ps = pso_build(pso_desc(&k, vs, nil, nil, 0), !k.border, &error); + id ps = pso_build(pso_desc(&k, vs, nil, nil, 0), pso_off(&k), &error); if (ps) hm_put_id(&g_pso, &k, ps); else { MLOG("[RED] rasterizer-discard pipeline (vertex %s): %s", vs->key, error.localizedDescription.UTF8String); hm_put_id(&g_pso_fail, &k, NSNull.null); } return ps; @@ -11712,7 +11725,7 @@ static void pso_prebuild_bg(void) { // after the prewarm, in the app without a int st = pso_pend_try(&k, &ps); if (st == 2) took = 1; // built in the background (nil: it failed, and is built again below for its message) else { - if (st == 0) ps = pso_build_ex(pso_desc(&k, vs, fs, nil, 0), !k.border, &e, 0); // its base made or archived: no compile + if (st == 0) ps = pso_build_ex(pso_desc(&k, vs, fs, nil, 0), pso_off(&k), &e, 0); // its base made or archived: no compile if (!ps) { // Demand first (main's order): the draw's own pipeline is queued before the prediction admits speculative builds; with a stand-in nothing waits for it __unsafe_unretained id h = hybrid_get(&k, vs, fs); @@ -11730,7 +11743,7 @@ static void pso_prebuild_bg(void) { // after the prewarm, in the app without a if (ps) g_pp_taken++; else { MTLRenderPipelineDescriptor *d = pso_desc(&k, vs, fs, ms_fn ? ms_fn : g_pso_fsfn, g_pso_lmap != NULL); - ps = pso_build(d, !k.border, &e); + ps = pso_build(d, pso_off(&k), &e); } if (!took) { // the draw waited (built here, made from its queued build, or waited for its running build) uint64_t w = bp_now() - bt - (g_pt_pred_ns - pred0); g_pw_n[why]++; g_pw_ns[why] += w; @@ -11915,7 +11928,7 @@ static void warm_task(WarmTask *t) { int pull = !sk.merged && !sk.fz && pull_conversion(vs, &k); // the layout's pipeline is its pulling one (pull_pso) MTLRenderPipelineDescriptor *desc = pull ? pso_desc_pull(&k, vs, fs) : nil; if (!desc) { pull = 0; desc = pso_desc(&k, vs, fs, fsfn, sk.merged); } - NSError *e = nil; id ps = pso_build(desc, !k.border, &e); + NSError *e = nil; id ps = pso_build(desc, pso_off(&k), &e); g_warm_done++; if (!ps) { g_pre_warm_failed++; MLOG("[RED] background render pipeline creation failed: %s", e.localizedDescription.UTF8String); continue; } if (g_pre_tool) { g_warm_rps++; continue; } // the prebuild tool: the base is in the serializer; keep nothing @@ -14215,7 +14228,7 @@ static int pso_base_made_d(const pso_key *k, NvShader *vs, NvShader *fs, MTLRend pso4_init(); if (!g_comp4) return 0; MTLRenderPipelineDescriptor *d = pso_desc(k, vs, fs, nil, 0); if (dp) *dp = d; if ([d.label isEqualToString:PSO_WHOLE] || !pso_ds_valid((uint32_t)d.depthAttachmentPixelFormat, (uint32_t)d.stencilAttachmentPixelFormat)) return 0; - pbase_key bk; pbase_key_of(d, !k->border, &bk); if (bkp) { *bkp = bk; *bkp_ok = 1; } + pbase_key bk; pbase_key_of(d, pso_off(k), &bk); if (bkp) { *bkp = bk; *bkp_ok = 1; } os_unfair_lock_lock(&g_pbase_lock); int made = hm_get_id(&g_pbase, &bk) != nil; os_unfair_lock_unlock(&g_pbase_lock); return made; } @@ -14903,7 +14916,7 @@ static int fb_tile_ready(NvShader *vs, NvShader *fs, id fn, const u return 1; } if (g_fb_tp_n >= FB_TP_MAX) { os_unfair_lock_unlock(&g_fb_tp_lock); static int once; if (!once++) MLOG("same-pass feedback sampling: %d tile-reading pipelines built; later ones keep the snapshot", FB_TP_MAX); return 0; } g_fb_tp[i].k = k; g_fb_tp[i].ps = nil; g_fb_tp[i].done = 0; g_fb_tp_n++; os_unfair_lock_unlock(&g_fb_tp_lock); - MTLRenderPipelineDescriptor *d = pso_desc(&k, vs, fs, fn, 1); int off = !k.border; + MTLRenderPipelineDescriptor *d = pso_desc(&k, vs, fs, fn, 1); int off = pso_off(&k); dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ @autoreleasepool { NSError *e = nil; id ps = pso_build(d, off, &e); if (!ps) MLOG("[RED] same-pass feedback sampling: no tile-reading pipeline for vertex %s fragment %s: %s (its draws keep the snapshot)", vs->key, fs->key, e.localizedDescription.UTF8String); os_unfair_lock_lock(&g_fb_tp_lock); g_fb_tp[i].ps = ps; g_fb_tp[i].done = 1; os_unfair_lock_unlock(&g_fb_tp_lock); } }); diff --git a/dm/gfx/nvn/nvn_pso_skey.h b/dm/gfx/nvn/nvn_pso_skey.h index 18e8d1bcfa..49bff7b91b 100644 --- a/dm/gfx/nvn/nvn_pso_skey.h +++ b/dm/gfx/nvn/nvn_pso_skey.h @@ -11,8 +11,9 @@ typedef struct { uint32_t atest, logic; // atest: 1 = drawn with the alpha test, the fragment from the shader's side library _bx (nvn_mtl.m atest_key); last, so a prewarm row written before it reads as 0 // logic: 1 = drawn with a logic operation, the fragment from the side library _bx (lop_key); in what was padding (0 in older rows) va_st attr_hi[16]; // NVN2's attributes 16 to 31 (pso_key_attr); last, so a prewarm row written before them reads as 0 - uint32_t border, border_spare; // border: 1 = a sampler the draw binds has a twin, so the shaders keep their border colour corrections (nvn_mtl.m border_need); 0 = specialized without - // them (fn_off); last, so a prewarm row written before it reads as 0. border_spare keeps the key a whole number of 8-byte words + uint32_t border, blend_live; // border: 1 = a sampler the draw binds has a twin, so the shaders keep their border colour corrections (nvn_mtl.m border_need); 0 = specialized without + // them (fn_off); last, so a prewarm row written before it reads as 0. blend_live (T-126 v2; was a spare word, 0 in older rows): 1 = the draw's blend words + // (bz_word / rop_word) are not both 0, so the pixel shader keeps its blend fix-up; 0 = specialized without it (DMSH_BLEND_OFF_FC, fn_off) } pso_key; static inline va_st pso_key_attr(const pso_key *k, int a) { return a < 16 ? k->attr[a] : k->attr_hi[a - 16]; } @@ -53,7 +54,7 @@ static inline void pso_skey_hex(const pso_skey *key, char *out) { } static inline int pso_skey_parse(const char *hex, pso_skey *out) { - size_t n = sizeof *out * 2, old2 = n - 2 * (sizeof out->k.border + sizeof out->k.border_spare), old1 = old2 - 2 * sizeof out->k.attr_hi, old = old1 - 2 * (sizeof out->k.atest + sizeof out->k.logic); // a row from before the border field, before the high attributes, or also before the alpha test field: the key without them + size_t n = sizeof *out * 2, old2 = n - 2 * (sizeof out->k.border + sizeof out->k.blend_live), old1 = old2 - 2 * sizeof out->k.attr_hi, old = old1 - 2 * (sizeof out->k.atest + sizeof out->k.logic); // a row from before the border field, before the high attributes, or also before the alpha test field: the key without them if (!hex || (strlen(hex) != n && strlen(hex) != old2 && strlen(hex) != old1 && strlen(hex) != old)) return -1; if (strlen(hex) != n) { n = strlen(hex); memset(out, 0, sizeof *out); } uint8_t *p = (uint8_t *)out; diff --git a/dm/gfx/tests/t_pso_skey.m b/dm/gfx/tests/t_pso_skey.m index 401f1e39e5..7fb85acfa4 100644 --- a/dm/gfx/tests/t_pso_skey.m +++ b/dm/gfx/tests/t_pso_skey.m @@ -33,9 +33,9 @@ int main(void) { NvShader *vs = [NvShader new]; snprintf(vs->key, sizeof vs->key, "vs-a"); pso_skey a, b; char hex[sizeof a * 2 + 1]; pso_skey_from(&k, vs, nil, 0, NULL, &a); pso_skey_hex(&a, hex); - size_t old = strlen(hex) - 2 * (sizeof k.attr_hi + sizeof k.atest + sizeof k.logic + sizeof k.border + sizeof k.border_spare); hex[old] = 0; + size_t old = strlen(hex) - 2 * (sizeof k.attr_hi + sizeof k.atest + sizeof k.logic + sizeof k.border + sizeof k.blend_live); hex[old] = 0; assert(pso_skey_parse(hex, &b) == 0); assert(b.k.atest == 0 && b.k.logic == 0); - a.k.atest = a.k.logic = a.k.border = a.k.border_spare = 0; memset(a.k.attr_hi, 0, sizeof a.k.attr_hi); assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): a pso_skey is its bytes (pso_skey_from zeroes it, pso_skey_hex writes them, the maps key on them) + a.k.atest = a.k.logic = a.k.border = a.k.blend_live = 0; memset(a.k.attr_hi, 0, sizeof a.k.attr_hi); assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): a pso_skey is its bytes (pso_skey_from zeroes it, pso_skey_hex writes them, the maps key on them) } // A row written before pso_key.attr_hi (NVN2's vertex attributes 16 to 31): they read as 0, the fields before them stay { @@ -43,9 +43,9 @@ int main(void) { NvShader *vs = [NvShader new]; snprintf(vs->key, sizeof vs->key, "vs-h"); pso_skey a, b; char hex[sizeof a * 2 + 1]; pso_skey_from(&k, vs, nil, 0, NULL, &a); pso_skey_hex(&a, hex); - hex[strlen(hex) - 2 * (sizeof k.attr_hi + sizeof k.border + sizeof k.border_spare)] = 0; + hex[strlen(hex) - 2 * (sizeof k.attr_hi + sizeof k.border + sizeof k.blend_live)] = 0; assert(pso_skey_parse(hex, &b) == 0); assert(b.k.atest == 1 && b.k.logic == 1); - a.k.border = a.k.border_spare = 0; memset(a.k.attr_hi, 0, sizeof a.k.attr_hi); assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): the key is defined byte by byte, padding included: pso_skey_from clears it and its hex form is every byte + a.k.border = a.k.blend_live = 0; memset(a.k.attr_hi, 0, sizeof a.k.attr_hi); assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): the key is defined byte by byte, padding included: pso_skey_from clears it and its hex form is every byte } // A row written before the border specialization keeps its high attributes and prewarms the no-correction pipeline. Live draws needing corrections have a different key. { @@ -53,9 +53,9 @@ int main(void) { NvShader *vs = [NvShader new]; snprintf(vs->key, sizeof vs->key, "vs-b"); pso_skey a, b; char hex[sizeof a * 2 + 1]; pso_skey_from(&k, vs, nil, 0, NULL, &a); pso_skey_hex(&a, hex); - hex[strlen(hex) - 2 * (sizeof k.border + sizeof k.border_spare)] = 0; - assert(pso_skey_parse(hex, &b) == 0 && b.k.border == 0 && b.k.border_spare == 0); - a.k.border = a.k.border_spare = 0; assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): a pso_skey is its bytes (pso_skey_from zeroes it, pso_skey_hex writes them, the maps key on them) + hex[strlen(hex) - 2 * (sizeof k.border + sizeof k.blend_live)] = 0; + assert(pso_skey_parse(hex, &b) == 0 && b.k.border == 0 && b.k.blend_live == 0); + a.k.border = a.k.blend_live = 0; assert(memcmp(&a, &b, sizeof a) == 0); // NOLINT(bugprone-suspicious-memory-comparison): a pso_skey is its bytes (pso_skey_from zeroes it, pso_skey_hex writes them, the maps key on them) a.k.border = 1; assert(memcmp(&a, &b, sizeof a) != 0); // NOLINT(bugprone-suspicious-memory-comparison): a pso_skey is its bytes (pso_skey_from zeroes it, pso_skey_hex writes them, the maps key on them) } // pso_key_attr: attribute 16 is the first of the high table diff --git a/dm/gfx/tests/test_dmsh_blend_zero.py b/dm/gfx/tests/test_dmsh_blend_zero.py index 3d0f932545..77c71802c5 100644 --- a/dm/gfx/tests/test_dmsh_blend_zero.py +++ b/dm/gfx/tests/test_dmsh_blend_zero.py @@ -112,6 +112,12 @@ def test_every_return_of_main0(self): self.assertLess(out.index('struct main0_out'), out.index('void dm_blend0(thread main0_out& dm_o')) # the helper takes main0's local output: after its struct, before main0 self.assertLess(out.index('void dm_blend0('), out.index('fragment main0_out main0(')) + def test_blend_off_constant_returns_before_the_words(self): # T-126 v2: a pipeline specialized dm_blend_off = true reads no word and changes nothing + out, _ = blend_zero(PLAIN) + self.assertIn(f'constant bool dm_blend_off [[function_constant({dmsh_abi.BLEND_OFF_FC})]];', out) + h = out[out.index('void dm_blend0('):]; h = h[:h.index('\n}\n')] + self.assertLess(h.index('if (is_function_constant_defined(dm_blend_off) && dm_blend_off) return;'), h.index('dm_s.zero')) + def test_each_float4_colour_by_its_index(self): out, _ = blend_zero(PLAIN) bits = dmsh_abi.BLEND_ZERO_BITS diff --git a/dm/gfx/tools/dmsh_rewrite.py b/dm/gfx/tools/dmsh_rewrite.py index 011a4e9c88..ee18793e27 100644 --- a/dm/gfx/tools/dmsh_rewrite.py +++ b/dm/gfx/tools/dmsh_rewrite.py @@ -930,8 +930,10 @@ def frag_z_snap(msl): float4 s = m == %du ? float4(255.0f) : (m == %du ? float4(65535.0f) : float4(1023.0f, 1023.0f, 1023.0f, 3.0f)); return rint(precise::clamp(c, 0.0f, 1.0f) * s) / s; // precise: NaN goes to 0, as both store it; the product is float32's, rint rounds it to nearest even } +constant bool dm_blend_off [[function_constant(%d)]]; // abi.BLEND_OFF_FC: the pipeline's blend words are both 0 (nvn_mtl.m fn_off), so nothing to fix up static inline __attribute__((always_inline)) void dm_blend0(thread main0_out& dm_o, constant dm_blend_state& dm_s) { + if (is_function_constant_defined(dm_blend_off) && dm_blend_off) return; uint m = dm_s.zero, r = dm_s.round; if ((m | r) == 0u) return; %s} @@ -953,6 +955,6 @@ def blend_zero(msl): body, k = re.subn(r'^([ \t]*)return out;$', lambda m: f'{m.group(1)}dm_blend0(out, dm_blend);\n{m.group(1)}return out;', body, flags=re.M) if not k or k != n: return msl, 0 bits, rb = abi.BLEND_ZERO_BITS, abi.BLEND_ROUND_BITS - helper = BLEND_ZERO % ((1 << bits) - 1, (1 << rb) - 1, abi.ROUND_8, abi.ROUND_16, + helper = BLEND_ZERO % ((1 << bits) - 1, (1 << rb) - 1, abi.ROUND_8, abi.ROUND_16, abi.BLEND_OFF_FC, ''.join(f' dm_o.{nm} = dm_rop(dm_bz(dm_o.{nm}, m >> {bits * c}u), r >> {rb * c}u);\n' for nm, c in cols)) return msl[:e['start']] + helper + '\n' + msl[e['start']:e['head'] - 1] + (', ' if e['params'] else '') + BLEND_ZERO_PARAM + ')' + body + msl[e['end']:], k diff --git a/dm/gfx/tools/pso_offline.py b/dm/gfx/tools/pso_offline.py index a1ad37ced7..4c9e73964d 100644 --- a/dm/gfx/tools/pso_offline.py +++ b/dm/gfx/tools/pso_offline.py @@ -56,7 +56,7 @@ # The function constants the host's prebuild sets in a base's functions (nvn_mtl.m pre_fn), by name: (index, bool value). A pair whose functions declare another constant is left to the # device: the host leaves it at its default, which metal-tt can do too, but no other constant was tried there, and one function metal-tt fails fails its whole group -HOST_CONSTANTS = {'dm_border_off': (abi.BORDER_FC, True)} +HOST_CONSTANTS = {'dm_border_off': (abi.BORDER_FC, True), 'dm_blend_off': (abi.BLEND_OFF_FC, True)} # the common draw's specialization, as nvn_mtl.m pre_fn BATCH = 1000 # bases per metal-tt run: Odyssey's largest compiler lifetime footprint at this size was 2.065 GiB on an 8 GB M2 MAX_FAILED = 8 # pipelines of one group metal-tt may fail on before the run counts as failed (compile_isolating) From 2405ff41688031e3d96cd5717298374a955987c0 Mon Sep 17 00:00:00 2001 From: seedds Date: Sat, 21 Nov 2026 10:53:26 -0800 Subject: [PATCH 2/3] gfx/tests: t_blend_zero and t_rop_round load their pixel shaders specialized, as shader_load does The blend helper now declares dm_blend_off, and Metal builds no pipeline from a function with constants that was not specialized (shader_load specializes every such function with empty values; the tests took the plain function). Co-Authored-By: Claude Opus 5.5 --- dm/gfx/tests/t_blend_zero.m | 4 ++-- dm/gfx/tests/t_rop_round.m | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dm/gfx/tests/t_blend_zero.m b/dm/gfx/tests/t_blend_zero.m index 473ab122a4..6201510cd4 100644 --- a/dm/gfx/tests/t_blend_zero.m +++ b/dm/gfx/tests/t_blend_zero.m @@ -58,7 +58,7 @@ static void merged_case(NSString *source, prog_t *program, int on) { " out.m_0 = float4(v, v, v, x < 4u ? 0.0 : 1.0);\n dm_blend0(out, dm_blend);\n dm_merged_out r = {};\n r.m_1 = out.m_0;\n return r;\n}\n"]; NSError *error = nil; id lib = [g_dev newLibraryWithSource:merged options:nil error:&error]; CHECK(lib != nil); if (!lib) { fprintf(stderr, "%s\n", error.localizedDescription.UTF8String); return; } - id fn = fn4_note([lib newFunctionWithName:@"main_m"], lib, @"main_m", nil); + id fn = fn_spec(lib, @"main_m", [MTLFunctionConstantValues new], nil); // as shader_load: a function with constants (dm_blend_off) is specialized CHECK(fn != nil); if (!fn) return; static tex_t unused = {.magic = MAGIC('T', 'E', 'X', 0), .serial = 98202}, target = {.magic = MAGIC('T', 'E', 'X', 0), .serial = 98203}; unused.d = (nvn_texdesc){.width = 8, .height = 1, .depth = 1, .samples = 1, .levels = 1, .target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA8}; @@ -113,7 +113,7 @@ int main(int argc, char **argv) { @autoreleasepool { NvProg *pr = [NvProg new]; pr->sh[0] = [NvShader new]; pr->sh[0]->fn = [lib newFunctionWithName:@"vertex_main"]; pr->sh[0]->stage = 0; snprintf(pr->sh[0]->key, sizeof pr->sh[0]->key, "vblend_b"); NvShader *ps = [NvShader new]; pr->sh[1] = ps; - ps->fn = fn4_note([lib newFunctionWithName:@"main0"], lib, @"main0", nil); ps->stage = 1; ps->has_bz = 1; snprintf(ps->key, sizeof ps->key, "pblend_b"); + ps->fn = fn_spec(lib, @"main0", [MTLFunctionConstantValues new], nil); ps->stage = 1; ps->has_bz = 1; snprintf(ps->key, sizeof ps->key, "pblend_b"); // as shader_load: a function with constants (dm_blend_off) is specialized CHECK(ps->fn != nil); static prog_t program; program.serial = 98200; serial_put(program.serial, pr); merged_case(source, &program, on); diff --git a/dm/gfx/tests/t_rop_round.m b/dm/gfx/tests/t_rop_round.m index 71788793b0..3529220427 100644 --- a/dm/gfx/tests/t_rop_round.m +++ b/dm/gfx/tests/t_rop_round.m @@ -40,7 +40,7 @@ static void merged_case(NSString *source, prog_t *program, int on) { "{\n main0_out out = {};\n out.m_0 = float4(as_type(0x3e858586u));\n dm_blend0(out, dm_blend);\n dm_merged_out r = {};\n r.m_1 = out.m_0;\n return r;\n}\n"]; NSError *error = nil; id lib = [g_dev newLibraryWithSource:merged options:nil error:&error]; CHECK(lib != nil); if (!lib) { fprintf(stderr, "%s\n", error.localizedDescription.UTF8String); return; } - id fn = fn4_note([lib newFunctionWithName:@"main_m"], lib, @"main_m", nil); + id fn = fn_spec(lib, @"main_m", [MTLFunctionConstantValues new], nil); // as shader_load: a function with constants (dm_blend_off) is specialized CHECK(fn != nil); if (!fn) return; static tex_t unused = {.magic = MAGIC('T', 'E', 'X', 0), .serial = 98310}, target = {.magic = MAGIC('T', 'E', 'X', 0), .serial = 98311}; unused.d = (nvn_texdesc){.width = 8, .height = 1, .depth = 1, .samples = 1, .levels = 1, .target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA16F}; @@ -90,7 +90,7 @@ int main(int argc, char **argv) { @autoreleasepool { NvProg *pr = [NvProg new]; pr->sh[0] = [NvShader new]; pr->sh[0]->fn = [lib newFunctionWithName:@"vertex_main"]; pr->sh[0]->stage = 0; snprintf(pr->sh[0]->key, sizeof pr->sh[0]->key, "vrop_b"); NvShader *ps = [NvShader new]; pr->sh[1] = ps; - ps->fn = fn4_note([lib newFunctionWithName:@"main0"], lib, @"main0", nil); ps->stage = 1; ps->has_bz = 1; snprintf(ps->key, sizeof ps->key, "prop_b"); + ps->fn = fn_spec(lib, @"main0", [MTLFunctionConstantValues new], nil); ps->stage = 1; ps->has_bz = 1; snprintf(ps->key, sizeof ps->key, "prop_b"); // as shader_load: a function with constants (dm_blend_off) is specialized CHECK(ps->fn != nil); static prog_t program; program.serial = 98300; serial_put(program.serial, pr); merged_case(source, &program, on); From f0b0e1ce14cbdccd7203b1b4a84fb2c5c043c24b Mon Sep 17 00:00:00 2001 From: seedds Date: Sun, 22 Nov 2026 00:14:35 -0800 Subject: [PATCH 3/3] gfx/nvn: predicted base lookups take the draw's whole FN_OFF mask pso_bg_look's caller still passed the border-only flag (!qk->border), so a prediction looked up and built its base without dm_blend_off while the draw asks for pso_off(k): the worker never found the base the draw would use, and the draw compiled again. t_pso_bg_look builds its pulling base as a draw does (pso_off), and t_border's fn_off call takes the mask. Co-Authored-By: Claude Opus 5.5 --- dm/gfx/nvn/nvn_mtl.m | 2 +- dm/gfx/tests/t_border.m | 2 +- dm/gfx/tests/t_pso_bg_look.m | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index b5bc26ae04..eab80454c9 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -14337,7 +14337,7 @@ static void pso_predict_rest_(void) { if (hy && d && bk_ok) { if (hm_get_id(&g_pp_looked, &bk)) continue; // its base is being looked up, or was: found it is made by now, missing its build was admitted or its draw waits hm_put_id(&g_pp_looked, &bk, NSNull.null); - pso_bg_look(qk, d, qv->has_pull ? pso_desc_pull(qk, qv, qf) : nil, !qk->border, i < na ? 2 : 1, budget); + pso_bg_look(qk, d, qv->has_pull ? pso_desc_pull(qk, qv, qf) : nil, pso_off(qk), i < na ? 2 : 1, budget); continue; } if (hy && hybrid_get(qk, qv, qf) != nil) continue; // a whole pipeline (no base to look up): its stand-in, as before diff --git a/dm/gfx/tests/t_border.m b/dm/gfx/tests/t_border.m index 88ecda11b5..d5c8a31668 100644 --- a/dm/gfx/tests/t_border.m +++ b/dm/gfx/tests/t_border.m @@ -96,7 +96,7 @@ static void specialization_cases(void) { id f = deferred == 2 ? geo_mesh_entry(lib, @"probe") : deferred ? fn_spec(lib, @"probe", cv, &error) : fn_lib_spec(lib, @"probe", cv, &error); CHECK(f != nil, "original specialization exists (%d)", deferred); if (!f) continue; id off = fn_dev_b(f, 1); // the variant is no function object of its own (fn_off): a descriptor and a device function beside f's - CHECK(fn_off(f) && fn4_of_b(f, 1) != fn4_of(f) && fn4_of_b(f, 1) == fn4_of_b(f, 1) && fn4_of_b(f, 0) == fn4_of(f), "border specialization has a descriptor of its own, cached (%d)", deferred); + CHECK(fn_off(f, FN_OFF_BORDER) && fn4_of_b(f, 1) != fn4_of(f) && fn4_of_b(f, 1) == fn4_of_b(f, 1) && fn4_of_b(f, 0) == fn4_of(f), "border specialization has a descriptor of its own, cached (%d)", deferred); CHECK(off && off != fn_dev(f) && off == fn_dev_b(f, 1) && fn_dev_b(f, 0) == fn_dev(f), "its device function is distinct and cached (%d)", deferred); MTL4SpecializedFunctionDescriptor *pre = (MTL4SpecializedFunctionDescriptor *)pre_fn(lib, @"probe"); id warm = fn_lib_spec(lib, @"probe", pre.constantValues, &error); diff --git a/dm/gfx/tests/t_pso_bg_look.m b/dm/gfx/tests/t_pso_bg_look.m index 609b46acaf..5d59d66c32 100644 --- a/dm/gfx/tests/t_pso_bg_look.m +++ b/dm/gfx/tests/t_pso_bg_look.m @@ -70,7 +70,7 @@ int main(void) { @autoreleasepool { // is then a specialization of that base, with no compile { NvProg *p = program(library(.25f), "pull", 1); static prog_t pg = {.serial = 990100}; serial_put(pg.serial, p); pso_key k; state_reset(); S.prog = &pg; pso_key_fill(&k, p->sh[0], p->sh[1], (uint32_t[8]){70}, 0, 0, 1, 0); - NSError *e = nil; CHECK(pso_build(pso_desc_pull(&k, p->sh[0], p->sh[1]), !k.border, &e) != nil, "the pulling base builds (the prebuild's part)"); + NSError *e = nil; CHECK(pso_build(pso_desc_pull(&k, p->sh[0], p->sh[1]), pso_off(&k), &e) != nil, "the pulling base builds (the prebuild's part)"); uint64_t made = g_hy_made, n0 = g_bgl_n, found = g_bgl_found, admit = g_pp_admit, kicked = g_pp_kicked; predict(&pg); CHECK(hm_get_id(&g_pso_hy, &k) == nil && g_hy_made == made, "the prediction makes no stand-in on the submit thread");