11# SPDX-FileCopyrightText: 2026 SeisSol Group
22#
33# SPDX-License-Identifier: MIT
4- from typing import List , Optional , Union , Type
4+ import os
5+ from typing import Dict , List , Optional , Union , Type
56import copy
67import functools
78import hashlib
@@ -1264,7 +1265,10 @@ def _declare_buffers(self, section) -> None:
12641265
12651266 def tracked (sym ) -> bool :
12661267 return (getattr (sym , 'stype' , None ) is SymbolType .SharedMem
1267- and not isinstance (getattr (sym , 'obj' , None ), ShrMemObject ))
1268+ and not isinstance (getattr (sym , 'obj' , None ), ShrMemObject )
1269+ # A merged run's rotated stand-in is a pointer into whichever
1270+ # slot its table selects, and the slots are tracked already.
1271+ and not getattr (sym , 'borrowed' , False ))
12681272
12691273 def block_wide (sym ) -> bool :
12701274 first = sym .get_first_user ()
@@ -1276,6 +1280,15 @@ def block_wide(sym) -> bool:
12761280 def windows (instrs ):
12771281 for instr in instrs :
12781282 for sym in tuple (instr .defs ()) + tuple (instr .uses ()):
1283+ # A write through a rotated stand-in declares nothing -- the slot
1284+ # its table selects was declared where the slot was -- but it is
1285+ # as ready to emit as any other, and saying so is this pass's job
1286+ # for every shared write there is.
1287+ if getattr (sym , 'borrowed' , False ):
1288+ for user in sym .get_user_list ():
1289+ if isinstance (user , AbstractShrMemWrite ):
1290+ user .set_window (False , False )
1291+ continue
12791292 if not tracked (sym ) or id (sym ) in declared or block_wide (sym ):
12801293 continue
12811294 declared .add (id (sym ))
@@ -1287,22 +1300,57 @@ def windows(instrs):
12871300 for region in instr .regions ():
12881301 windows (region )
12891302
1290- def lifetimes (instrs , written = frozenset ()):
1303+ def repeats (instr ) -> bool :
1304+ """Whether this instruction's regions run more than once.
1305+
1306+ The same question `pir.allocate` asks of a block it cannot read the
1307+ head of, and for the same reason: what a body carries around its
1308+ back edge is live where a single pass through it looks dead.
1309+ """
1310+ from tensorforge .backend .instructions .batch_loop import BatchLoop
1311+ from tensorforge .backend .instructions .ptr_manip import VariantLoop
1312+ return isinstance (instr , (BatchLoop , VariantLoop ))
1313+
1314+ def carried_in (instr ) -> set :
1315+ """Buffers this repeating body reads before it writes them.
1316+
1317+ A write that covers a buffer whole normally ends what was there --
1318+ nothing before it is wanted. Inside a loop that is true of one pass
1319+ and false of the loop: a merged run's rotation writes the slot the
1320+ *next* pass reads, and killing it at the write makes the stretch
1321+ from there to the read look free, which the allocator then hands to
1322+ another buffer (`pir.allocate`). SeisSol's anelastic chain shared a
1323+ rotation slot with a staged operand that way, and the kernel
1324+ computed with the operand's bytes.
1325+
1326+ Read *before* written, which is the question the loop instructions
1327+ already answer for their own operands (`VariantLoop.uses`), and not
1328+ read anywhere: a staged operand is copied in at the head of the body
1329+ and read below it, so a body that carries nothing would carry all of
1330+ them -- and the staged window would stop reusing the one the product
1331+ read the pass before, which is the reuse its barrier is there for.
1332+ """
1333+ return {id (sym ) for sym in instr .uses () if tracked (sym )}
1334+
1335+ def lifetimes (instrs , written = frozenset (), carried = frozenset ()):
12911336 seen = set (written )
12921337 for instr in instrs :
12931338 if instr .regions ():
12941339 entering = frozenset (seen )
1340+ inner = (carried | carried_in (instr )
1341+ if repeats (instr ) else carried )
12951342 for region in instr .regions ():
1296- lifetimes (region , entering )
1343+ lifetimes (region , entering , inner )
12971344 seen .update (id (d ) for d in instr .defs ())
12981345 continue
12991346 kills = []
13001347 partial = {id (d ) for d in instr .partial_defs ()}
13011348 for sym in instr .defs ():
13021349 if not tracked (sym ) or block_wide (sym ):
13031350 continue
1304- if not isinstance (instr , LoadWait ) and not (
1305- id (sym ) in partial and id (sym ) in seen ):
1351+ if (not isinstance (instr , LoadWait )
1352+ and id (sym ) not in carried
1353+ and not (id (sym ) in partial and id (sym ) in seen )):
13061354 kills .append (sym )
13071355 seen .add (id (sym ))
13081356 instr ._kills = tuple (kills )
@@ -2555,7 +2603,8 @@ def _emit_ir(self, descr_list):
25552603 self ._scopes .get_symbol (self ._section .shr_mem_obj ),
25562604 self ._num_threads ,
25572605 self ._lead_width )
2558- temporaries = Temporaries (self ._context , self ._scopes , self ._num_threads )
2606+ temporaries = self ._temporaries = Temporaries (
2607+ self ._context , self ._scopes , self ._num_threads )
25592608 # Every register image this section allocates is blocked the same way, so
25602609 # the factory carries it rather than each caller passing it along.
25612610 temporaries ._lead_width = self ._lead_width
@@ -2678,6 +2727,7 @@ def _emit_variant_loop(self, loop, builders) -> None:
26782727 GetElementPtrBuilder
26792728
26802729 body , variants = loop .decompose ()
2730+ self ._rotate_members (loop , variants )
26812731 written = {id (d .writes ().tensor ) for d in body if d .writes () is not None }
26822732
26832733 # What the body threads through itself. A destination is not accumulated
@@ -2787,8 +2837,16 @@ def carries(tensor) -> bool:
27872837 addressing = Addressing .SCALAR
27882838 else :
27892839 addressing = Addressing .NONE if resolved else stand_in .obj .addressing
2840+ # Named after the stand-in *tensor* where that is not the symbol's
2841+ # own name. A rotated stand-in resolves to its family's first slot,
2842+ # so two holes of one family share a symbol -- the hole that reads
2843+ # `dQane_d` and the hole that writes `dQane_{d+1}` -- and both tables
2844+ # would be `s11Table`, which is one declaration of two things.
2845+ table_name = (variant .stand_in .tensor .name
2846+ if stand_in .obj is not variant .stand_in .tensor
2847+ else stand_in .name )
27902848 table = DeclareOperandTable (
2791- self ._context , f'{ stand_in . name } Table' , members ,
2849+ self ._context , f'{ table_name } Table' , members ,
27922850 addressing ,
27932851 stand_in .obj .datatype ,
27942852 writable = id (variant .stand_in .tensor ) in written ,
@@ -2800,7 +2858,17 @@ def carries(tensor) -> bool:
28002858 if self ._stages (stand_in , written ):
28012859 region .extend (self ._stage_member (stand_in , table , counter ))
28022860 continue
2803- pointers .build (stand_in , table = table , variant = counter )
2861+ # A rotated stand-in resolves to its family's first slot, so two
2862+ # holes of one family share a symbol and would name one pointer
2863+ # twice -- the hole that reads `dQane_d` and the hole that writes
2864+ # `dQane_{d+1}` are two bindings on the same pass. The stand-in
2865+ # tensor's own name (`v0`, `v1`) is what tells them apart, and it is
2866+ # the name a stand-in that is no temporary would have given anyway.
2867+ rotated = stand_in .obj is not variant .stand_in .tensor
2868+ pointers .build (stand_in , table = table , variant = counter ,
2869+ name = (getattr (variant .stand_in .tensor , 'name' , None )
2870+ if rotated else None ),
2871+ obj = variant .stand_in .tensor if rotated else None )
28042872 region .extend (pointers .get_instructions ())
28052873
28062874 before = {}
@@ -2979,6 +3047,114 @@ def _establish(self, body, builders, keys) -> bool:
29793047 self ._section .ir .extend (emitted )
29803048 return True
29813049
3050+ def _rotate_members (self , loop , variants ) -> None :
3051+ """Give a run's temporary members one buffer per *slot*, not per member.
3052+
3053+ A merged run reaches its members through a table of their addresses, and
3054+ a temporary has none until an operation asks for its buffer -- so a run
3055+ that selects one per iteration used to be left written out
3056+ (`rolling._selects_a_temporary`). Handing each member a buffer of its
3057+ own would not do: SeisSol's anelastic derivative has 35 temporaries
3058+ worth 89 kB per multiplication, which the allocator aliases down to 8;
3059+ tabling them apart puts all 35 live at once and there is no such block.
3060+
3061+ What makes it work is that the run *carries* them. The dependence says
3062+ the value a pass writes is read `distance` passes later and never
3063+ after, so `distance + 1` buffers suffice and the members take them in
3064+ turn: the fifth derivative is written where the third was, because by
3065+ then nothing wants the third. Two buffers for the anelastic chain,
3066+ where five members would have been.
3067+
3068+ The ends need no special case, which is the point of rotating by the
3069+ member's own position. The value the peeled prologue leaves in member
3070+ one *is* slot zero, which the first pass reads; the last pass writes the
3071+ member the epilogue reads, in whichever slot that member sits. Both
3072+ fall out of the mapping rather than being arranged around it.
3073+
3074+ A hole and the hole it feeds are one family and must share the slots --
3075+ `dQane_1..4` read and `dQane_2..5` written are five tensors, not two
3076+ sets of four -- so the variants are merged wherever their members
3077+ overlap. Shapes within a family have to agree, since a slot is one
3078+ buffer: this refuses rather than letting two extents address one
3079+ allocation.
3080+ """
3081+ from tensorforge .backend .instructions .memory .store import ReserveShrMem
3082+ distance = getattr (getattr (loop , 'dependence' , None ), 'distance' , None )
3083+ if not distance or distance < 1 :
3084+ return
3085+ from tensorforge .generators .rolling import rotation_families
3086+ families = rotation_families (
3087+ [[v .tensor for v in variant .members
3088+ if getattr (v .tensor , 'is_tmp' , False )] for variant in variants ])
3089+
3090+ for family in families :
3091+ # In the order the run names them, which is the order they are
3092+ # written in: the slot is the member's position in the chain.
3093+ shapes = {(tuple (int (x ) for x in t .get_actual_shape ()),
3094+ tuple (int (x ) for x in t .get_bbox ().lower ()),
3095+ tuple (int (x ) for x in t .get_bbox ().upper ())) for t in family }
3096+ if len (shapes ) != 1 :
3097+ raise InternalError (
3098+ f'a merged run rotates { len (family )} temporaries through '
3099+ f'{ distance + 1 } buffers, and they do not agree on a shape: '
3100+ f'{ sorted (str (s ) for s in shapes )} ' )
3101+ slots : Dict [int , Symbol ] = {}
3102+ asked = self ._context .get_user_options ().rotate_slots
3103+ width = asked if asked else distance + 1
3104+ for position , tensor in enumerate (family ):
3105+ slot = position % width
3106+ if self ._scopes .get_symbol (tensor ) is not None :
3107+ # Already placed -- by an earlier run over the same family, or
3108+ # because it is no temporary after all. Its buffer stands.
3109+ slots .setdefault (slot , self ._scopes .get_symbol (tensor ))
3110+ continue
3111+ owner = slots .get (slot )
3112+ if owner is None :
3113+ slots [slot ] = self ._temporaries .shared_symbol (tensor )
3114+ else :
3115+ self ._scopes .alias_symbol (tensor , owner )
3116+ for symbol in slots .values ():
3117+ # Marked, so that the binding declares *these* buffers occupied and
3118+ # no others: a table over staged members is shared too, and saying
3119+ # the same of those moves a fence the loop depends on.
3120+ symbol .rotation_slot = True
3121+
3122+ # A slot nobody else writes has no first user to declare its window,
3123+ # and every other buffer gets one from a store or a load
3124+ # (`temporaries`). The rotation introduces its own, which is the one
3125+ # thing that knows their size. A slot the peeled prologue already
3126+ # writes -- the family's first member, which is slot zero -- has a
3127+ # user and is left alone.
3128+ for slot , symbol in sorted (slots .items ()):
3129+ if symbol .get_user_list ():
3130+ continue
3131+ self ._section .ir .append (ReserveShrMem (
3132+ self ._context , symbol ,
3133+ self ._scopes .get_symbol (self ._section .shr_mem_obj ),
3134+ family [0 ].get_bbox ()))
3135+
3136+ # The stand-in resolves to slot zero, and that is all it needs to be.
3137+ # `GetElementPtrBuilder` *reads* it and names a pointer of its own
3138+ # (`glb_s13`) which the loop rebinds from the table on every pass -- so
3139+ # what the stand-in has to be is a defined symbol of the family's shape,
3140+ # not a buffer. Slot zero is both, and the pointer's new name is why
3141+ # this is no circle: the table's entries are the slots, the binding is
3142+ # not one of them.
3143+ #
3144+ # A symbol of its own would be neither defined nor declared: nothing
3145+ # writes it, so the verifier would report a read with no definition,
3146+ # and nothing sizes it, so `_declare_buffers` would have no window.
3147+ for variant in variants :
3148+ tensor = variant .stand_in .tensor
3149+ if (not getattr (tensor , 'is_tmp' , False )
3150+ or self ._scopes .get_symbol (tensor ) is not None ):
3151+ continue
3152+ members = [v .tensor for v in variant .members ]
3153+ family = next ((f for f in families
3154+ if any (t is u for t in f for u in members )), None )
3155+ if family :
3156+ self ._scopes .alias_symbol (tensor , self ._scopes .get_symbol (family [0 ]))
3157+
29823158 def _member_symbol (self , view ):
29833159 """The symbol a merged run reaches an operand through.
29843160
0 commit comments