How a function goes from INCLUDE_ASM to C that compiles to exactly the game's words,
and what the game's compilers turn out to need. py below is the repository's Python
(.venv/Scripts/python), run from the repository's root; work files go in work/
(ignored by git) or any folder outside the repository.
py tools/work.py show NAME --target T > work/NAME.cwrites a work file from m2c's draft: includes, any new declarations, then the function. If m2c cannot draft it, read the asm (asm/us/T/nonmatchings/<file>/NAME.s) and write the C yourself.- Edit
work/NAME.c. Declarations in it replace those ofsrc/T/decls.hfor the same names, so a global's type or a callee's prototype can be fixed there. py tools/work.py diff work/NAME.c NAME --target Tcompiles it as its source file is built and prints its code next to the game's,*on every word that differs.- Repeat until
NAME: OK, thenpy tools/work.py put work/NAME.c NAME --target T: it checks again, puts the function in its source file and its declarations in decls.h, checks the whole file (and every file, when decls.h changed), and undoes it all if anything stops matching. - A near miss can go to the permuter:
py tools/permute.py work/NAME.c NAME --target T --minutes 10 --jobs 4(see toolchain.md).
put takes a lock (build/us/work.lock), so several people or agents can work on the
same target at once. Each works on its own functions; only put writes src/.
tools/progress.py counts what is done.
- No data of the function's own: no
staticorconsttables, no global definitions, noasm(...)for data (the GTE macros are the exception: see Hand-written assembly). GCC moves such data to the end of the file. The game's tables stay asm and the C declares themextern;putkeeps a table the C reads by name in an asm file of its own (anINCLUDE_RODATAbefore the function). - String literals are written as
"..."(the asm shows them as.asciz). A string shared with a function still in asm staysextern char D_x[]until all its users are C. - Keep every typedef on one line, and list new types in the order they depend on each
other:
putadds them at the end of decls.h in that order and moves any changed declaration that uses them after them. Prefix new type names with the target (WmActor,FdWin,BtlRect) so they don't clash. To give a global new fields without a new type, a one-lineextern struct { ... } D_x[];replaces its declaration. - A definition with bare parameter names,
void f(arg0) {, is declaredf(), so callers passing other numbers of arguments still compile. - Any
D_XXXXXXXXorfunc_XXXXXXXXname resolves by its address, named in the symbol files or not. - The compiler and assembler version and options are set per file by
tools/psyq.py(see toolchain.md); if a function only matches with other ones, its file may hold several of the game's files.
- Write it the way a 1997 programmer would: structs, arrays, plain loops. m2c's
M2C_FIELD(p, T *, off)is a cast pointer,M2C_SFIELDacts as a struct member. - Unsigned vs signed,
u8/s16parameters and returns,!= 0or nothing: all change the code.s16 v = (s8)*pgiveslbu/sll/sra, ans32variablelb. - An
s16parameter: shift counts use the raw register, other uses sign-extend. If the game copiesa0without sign extension, the parameter iss32(even if stored withsh); all-s32parameters also fix the order of register saves. - The game passes a value with another sign extension than the callee's definition, or
more arguments than its prototype has: call it through a cast,
((s32 (*)(s32, s32))func_X)(1, 0). Callers of a function returningu8often use the result withoutandi 0xFF:((s32 (*)(void))f)(). v0untouched after the last call: the function returns that call's result.- A
lhufollowed by a redundantandi 0xFFFF(orsll/sra 16after a load), or a global read again although nothing changed it: the global isvolatile.lui; addiu; sw 0(reg)storing a plain global is a volatile store,*(volatile s32 *)&D_x = v. - A "symbol" such as
func_801B0000used only through%lomay be a constant pointer,(u32 *)0x801B0000(an overlay's load address). - A real global struct array (
D_x[i].f) gives the game'ssym+off(reg)addressing; a cast((T *)D_x)[i].fputs the base in a register instead. Declaring a struct-array base the asm never names can give the game's addressing. s16field & 0x100loads withlhu; the game'slhcomes from reading the field into ans32local first.s16 n = byte + 1giveslbu s0; addiu s0, s0, 1, ans32giveslbu v0; addiu s0, v0, 1. A return value sign-extended again by the caller: declare both the callee and the locals16.- A value narrowed with the wrong registers (
a & 0xFF): pass it through a castu8prototype,((s32 (*)(s32, u8))func_X)(x, a). - Variadic functions spill
a0–a3:void f(s32 cmd, ...), the extra arguments read asargs = &cmd; args[i], au16local for the fixed one (c = cmd;) to getlhu. - An OT link,
(x & 0xFF000000) | (y & 0xFFFFFF), matches as a bitfield struct (typedef struct { u32 addr : 24; u32 len : 8; } FdTag;,->addr = ...); with masks the two constants swap registers. - 2.7.2: an array element both loaded and stored (
D[8]) gets its address in a register and the branches cross-jumped; a plain extern for that element (extern u8 D_x;) keeps the game's directlui/%loaccesses. - Write the symbols the asm names (
D_801E56D6, notD_801E56D0.pad; the array the asm indexes, not a neighbour plus an offset): tools/propagate.py renames only those, so copies of the function elsewhere get the right addresses. - A global the asm only reaches through a field symbol:
D_f[0] = v; f(&D_f[-4]), or an anonymous-struct extern for the field. A global filled then passed by address: assign its fields, pass&D_x. - Actor fields: a struct array based at the field's own address (
D_80074EFC[], never named otherwise) givessym+off(reg); a flatu8array hoists the base instead. - An index
(a*0x2E7 + b*0xD) << 2isX[a].c[b]folded by the common factor 4; only a declared global struct array gives itssym+regaddressing. - A local struct copied from rodata with
lwl/lwr:r = D_x;from an extern (put keeps the table as anINCLUDE_RODATA). A copy with anor/andi 3alignment test and two loops is a byte-aligned struct,typedef struct { u8 b[N]; } T;,*(T *)dst = *(T *)src. - Results:
sll v0, v0, 16; bltzon a returned value with a copy inv1is ans32callee and local tested(s16)r < 0; a result re-masked withandi 0xFFFFat each use is kept in ans32(callee returnings32);sll 16; sra 4on a call result is(s16)f(a, b) << 12. Amove v0, vNof an index before index arithmetic in a search loop means the function returns the index. A branch to the epilogue whose empty delay slotli v0, Ncould have filled:v0is live, the function iss32returning nothing. - A copy without sign extension whose later uses are sign-extended can still be an
s16parameter or local. - One
lhucompared to 0 over two adjacent byte fields:p->a == 0 && p->b == 0. - Hardware and polled globals are
volatile:jr ra; nopafter a store (the store kept out of the delay slot, or out of aj/jalslot) means the pointee is volatile (the GPU/DMA/SPU ports in the libraries); a spin loop on a halfword needs the global declaredvolatile u16(D_80095DD4). Declarations inmain/decls.hreach every overlay, so their types matter there too. - A
u16global read withlhneeds(s16)D_x < N, the mirror of(u8)D_xforlbu. m2c's&D_x + 0xAon ans32extern scales by 4: declareextern u8 D_x[];. - A table written both byte by byte and through a struct gets one name with the struct
type, cast to
u8 *where it is written bytewise; never a second name for data. - A
u8result the callers use withoutandi: defines32 f()returning au8local. A callee declareds32 f();whose caller doesreturn f();must be defineds32. - The pause flag
D_80062D98tested twice: plainD_80062D98 == 0tests match in most functions; when the first test's branch lands on the second test in the game, write one as*(u8 *)0x80062D98 == 0, or CSE retargets the branch past the second test. - A decremented halfword global (
lhu; addiu -1; sh; sll 16; bnez) iss16;u16givesandi 0xFFFF.(u16)p->fin ans32sum giveslhuwhere the plain field giveslh;t = *(s16 *)&G; t &= 0x1F;keepslhwhere the one-liner becomeslhu. Au8global testedx < 9givessltiu,s32 t = D_x; t < 9givesslti. - Reassigning a
u16parameter (arg2 >>= 4) keeps theandi 0xFFFFa separateu16local loses. An 8-byte struct parameter (MgSVec v) spillsa1/a2to the caller's frame and passes&von. - A volatile struct field makes 2.6.3 re-read it after a branch instead of reusing the
earlier load (which also moves constants to other registers); after an
lhof a field,((volatile T *)p)->f & 1forces thelhureload. A pause flag kept in a saved register:extern volatile u8 D_80062D98; z = D_80062D98; if (z == 0). - Spawn functions copy a 0x48-byte template: a struct type with the fields the function
writes, copied as
s->unk4 = *(T *)&D_x;. A packed word filled field by field from an uninitialised union of au32andu8bitfields gives theand/orinsertion chain on a stale register; such a union kept in a register withx.b.d2 += cre-reads the field forif (x.b.d2 >= 10)(srl), where(x.b.d2 += c) >= 10compares the masked sum. - A parameter its callers sign-extend (
sll/sra) but the callee uses raw iss32in the callee, and callers passing a sum cast it,f(0, (s16)(x + 0x2F), ...).putrefuses a function whose new prototype breaks a caller already in C ("matches alone, but not in its file"): fix the caller first, then put. - A call's
s32result assigned to ans16local leaves the raw copy in a saved register and sign-extends fromv0;s16 a = f()stored at the end of its block givesmove v0, s0; sh v0where ans32givessh s0. A function that falls off its end iss32when the game leaves abne; nopdelay slot unfilled. A leftover register passed as an extra argument: call through a cast prototype with that argument. (u8 *)0x801A0000instead of&D_801A0000(an overlay's code address) removes anaddiu v1, v1, 0.addiu s5, s4, -0xF0between two tables means one symbol with offsets: declare one struct, not two arrays. A dead local copied from rodata (c = D_x;) is kept.- A global read as
lh D_aand later throughla D_a+0x18is one struct (count at 0, bytes at 0x18); separate externs give the second access its ownlui. A global declared as an array (extern s32 D_x[]; D_x[0] = v;) gives a sharedla reg; sw 0(reg)where a scalar giveslui at; sw; the words of one packet buffer are one array, a GPU packet{ u32 addr:24; u32 len:8; u32 code[N]; }. Two externs for adjacent halfwords stop the sharedlaof element 0. s32 x = T[i]; s16 id = x;giveslh; movewith the sign-extension redone later, a singles16giveslhuplussll/sra. Au8parameter used directly asD[arg0](withi = arg0for an early use) keeps the prologue copy order and the repeatedandithats32plus masks loses;s32 arg5; u8 mode = arg5;giveslbu; ... andi 0xFF;u16 arg1instead ofs32moves the prologueandi a1, 0x7FFF. Au8local used as an index givesandi 0xff, ans16one a plainmove.(s32)f(x) << 11 >> 12givessrawhere au32prototype givessrl.- Stack argument slots holding dead values:
shat 0x10/0x14(sp) before a one-argument call arevx/vzof a localMgSVec mused asf(m.vx * m.vx + m.vz * m.vz). A second name for one address ((Spr *)((u8 *)&D_x - 4)) stops CSE from keeping a call-argument address in a saved register. - A volatile global that one function reads plainly: a second extern at a neighbouring
address (
extern BtlV14 D_80151842[];, fields read at +2) gives plain loads while decls.h's symbol stays volatile; a cast of the volatile array to a non-volatile struct matches the code but adds 16 bytes of frame (battle func_800C0630). A twin from another target whose struct has members this target's type lacks takes a local struct declared at a symbol 4 bytes below the real one (FdWinBox D_80083270[], field func_800D579C), so decls.h's type stays. (D_x & 0xFF)on ans8global giveslbu;(u8)D_xgiveslband an 8-byte frame slot.(s16)aon au16 athat is also read raw giveslhuwithsll/sraafter the join.s32 t = (u16)(t >> 1)compares withslti,u16 twithsltiu. Au8local holding a constant 0 becomes a$LC0constant-pool load (work.py: unknown relocation '.rodata'): uses32.- With
s16 i,rot.vx = i * 0x100givessll 16; sra 8andi << 8givessll 8;*frame = p->unk2 << 6loads withlhu,p->unk2 * 0x40withlh;*frame = D_x << 9on ans16global that is also incremented loads withlhu,t = D_x; *frame = t << 9;withlh. Withs16 k, separate storesq[4] = k * 0x10; q[5] = k * 0x10;keepsll 16; sra 12where the chained assignment givessrl;a << 4stored into a byte givessll 4,a * 0x10givessll 16; srl 12. - A local
s16 id = arg0;passed to ans16parameter avoids a loop-hoisted HImode truncation pseudo and its spill slot (field func_800ACC5C).s16 vfor a quotient stored in two arms avoids a v0/v1 swap; au8parameter gives repeatedandiand amove s2, a0prologue (battle func_800D01C0). - Scalar externs at consecutive words can be one array (chocobo's
s32 D_800B745C[3]). Entries whose stride (0x5C) is larger than the struct (0x5A) are indexed with an explicit* 0x5Con au8 *. A(sum) * 8 + 0x108displacement is a struct{ u8 pad[0x108]; T m[1]; }(rec, idx operand order); a temp forx + 0x38stops the constant folding into the displacement. - A struct global read once at its start is a scalar extern reached through a cast
pointer (
w = (CondorWin *)&D_8010BDE0): a struct-typed extern lets CSE share onelabetween the read and the pointer. A pointer global reloaded after every store isextern u8 *volatile(main text5.c). A short string literal copied into a word-aligned struct array element comes out in pieces:strcpy(D[1].name, "..")giveslh; lb; sh; sb. loc = D_x;into a 4-byte struct local passed as*(s32 *)&locgiveslwl; lwrthenlw(main func_8003FE98).*(volatile u16 *)(D_8009AC2B + 0x15)through the neighbouring array givesla; lhu 0(reg),*(volatile T *)&D_xthe directlui; lhu %lo.- A table that put keeps as
INCLUDE_RODATAand the C reads must beextern const: the scheduler then lifts its load above earlier stores (battle func_800A9DA0:const s8 D_800A0398moved thelbabove the firstswand removed anop). - A run of scalar globals declared as one struct global (
D_80095D88.f0...) keeps table loads in source order where separate scalars get hoisted; three adjacent globals written through a cast struct pointer pin a load after them (main func_80034FC8). Splat may name a vector's second field as a symbol of its own:D_801D5358.vx += 0x12C; D_801D5358.vy += 0x190;gives load, load, add, add, store, store, where a separateextern s32 D_801D535Cdoes not match (nadare func_801B19CC). - A pointer local to such a constant address instead of the volatile neighbour form folds
back to
lui; lhu(main batch 10). In 5-primitive draw functions,u8colour constants (0xF0/0xC8/0xA0) giveoriwheres8givesaddiu -16(main func_80028030). - A function that falls off its end must be
s32to keep the last loop'sbnez; nop(nadare func_801B11C4). (s16)*(u16 *)p - 7givesaddiu -7where plainu16 - 7givesli 0xFFF9; addu(battle func_800C223C).k = 0x4B0; q->f = q->f - k + rand() % N;keeps the constant on the field where(u16)q->f - 0x4B0makes a hoisted HImode constant (64336) that takes a saved register (thundg2, rakuseki func_801B0D04);u = i * 0x258 - 0x12C; t = ang + u;keepsaddiu -300unfolded whereang + (i * 0x258 - 0x12C)folds it (rocket func_801B11FC).k << 4on ans16 kstored to a byte givessll 4,k * 0x10givessll 16; srl 12(ho_den func_801B0148). Ans8 c = D_x * 6;colour local stored into several byte globals gives the game's load order wheres32 cdoes not (osen func_801B02DC); au8global read once into ans32 cused twice (a halfword store and the 4th argument) giveslbu a3directly, whereu8 caddst0and amove(thundg2).- An
s16parameter used only inshstores keeps itsmove s2,a2out of the prologue;s32swapped three registers (rakuseki func_801B00AC). A callee defined with one parameter that the game calls with two is called through a cast prototype (altema func_801B0580). - A pause-flag test that needs
andi v0,v1,0xFFmatched withextern volatile u8 D_80062D98in that spell's decls.h; CSE then reuses the register as the zero of a later0 < nloop guard (rocket func_801B0D98). - A global m2c types
u16that the code also reads withlhiss16:extern s16 D_x[]; D_x[0] += -D / 2 + p->unk2 % 2 * D;givesla a1; lhu 0(a1); sh 0(a1)and reloadsp->unk2after the store (lasboss func_801B21C8). (u32)(f(x) * 0x19) >> 7stored into ans16givessrl: keep the shareds32prototype and cast at the use (atomic func_801B03AC).x * 0x200giveslhwherex << 9giveslhu;-p->unk2 * 6givesnegubefore the multiply,p->unk2 * -6does not (lasboss2 func_801B04F4, func_801B0A34).(u32)((u16)p->unk2 - 10) < 0xFgiveslhu; addiu -10; sltiu.D_x[0] = D_x[1] = D_x[2] = cwithu8 cputs the colour inv1and the base inv0;s32,s16ors8 cswap them, ands8 cgivesli v1,-128for 0x80 (club2 func_801B1468).- m2c's
return 1afterD_x = 1;can be wrong: when theli v0,1only serves the store, the function isvoid(lasboss2 func_801B1834, lasboss func_801B2A50).extern M2C_UNK D_801B0000; f(&D_801B0000)giveslui; addiu a0,a0,0where(u8 *)0x801B0000drops theaddiu(hatena func_801B105C). - An extra splat symbol right after a struct is its field:
D_801D33FCwritten asD_801D33F8.vzgroups load, load, store, store and keeps a following reload after the stores (comet). - A table several functions use needs its type settled before the first put: graviga1
func_801B0AC8 matches only with
D_801D17B4as an array of 0x24-byte structs (pointer givs fromD[i].f), but func_801B0A34 and func_801B1464 were put first with it asu8[], put refuses the type change, and casts of the byte array give other code. Put the function that fixes the type first. D[i][0] = (u16)D[i][0] + con ans16array global giveslhu(sting func_801B3F1C).v << 15 >> 16on ans16parameter givessll 15; sra 16(dia func_801B06E4);(u32)f() >> 1stored to ans16givessrl(dia func_801B118C).c = c << 1;on au8 cgives a plainsllwherec *= 2adds anandi(conf func_801B0800).- Stack arguments
sp10/sp14at a 4-byte stride are&v.vx,&v.vzof a localMgSVec(brizag func_801B0074, timedmg func_801B06E0). - An
s16local copy of ans32field load (s16 t = k;) with the arithmetic in a separates32(n = t - 0xF) fixed the saved-register order without sign extensions (antlion func_801B338C).p->unk2 * 0x100giveslhwhere<< 8giveslhu(gaisei func_801B1EA0);z = pos.vzass32loads withlhwheres16giveslhu(bushin2 func_801B1D2C). t = f() * k >> 12; D = t; c = (s16)t;with ans32 cgivessll v0,v1,16; sra a0,v0,16and stores the rawt; ans16 ckeeps a raw copy instead (bushin2 func_801B1FC8).s16 h = p->unk12 >> 1; a = h; d = a * 2;keepssra s2,s0,16; sll s1,s2,1instead of folding tosra 15(queig func_801B2274).- An
s32global passed to ans16parameter (f(D)) is loaded withlh, and two such reads share onelaregister (bushin2 func_801B1818). extern volatile u8 D_80062D98; z = D_80062D98; if (z == 0)giveslbu; andi a0,v0,0xFFand reusesa0as the zero of the next loop guard (gaisei func_801B28DC).- When work.py prints only "request for member
xin something not a structure" for a global struct pointer, a typedef the work file uses is missing from the target's decls.h: the parse error cascades and only cc1's last line shows (antlion, MgVec). A redeclaration of a global with another type than decls.h's passesputand fails only the whole-file check (lamu). - A work file's
extern u8 D_x[]replaces decls.h'su8 D_x[][N]for the whole file and broke an earlier function in it (lgirl func_801B093C): reuse decls.h's declaration. D_x[0] = p->unk2 << 5narrows the field load tolbu; going throughs32 w = p->unk2 << 5;keeps the game'slh(mrain func_801B1B24).- A callee whose result the game keeps in
fpfor much later use (move fp,v0in the delay slot of a laterjal) is declareds32(len = func_8003A08C(&w, &w), beam func_801B0774). *(u16 *)(q + 0xC) = 0x8000givesori, thes16castli -32768(queir func_801B2144).k = D_x << 11; rot.vy = k;keeps thelwthat a direct store to ans16field narrows tolhu;*(s32 *)&D_xreads a word global that decls.h types asu16without changing the declaration (satan).func_800BBEAC(fn);called with one argument keeps an earlier loop's hoistedli a1,1as its second argument (sldfang func_801B3028). A callee declared with ans16parameter that the game passes unextended is called through a cast,((void (*)(s32, s32, s32))func_801B1C9C)(..)(catastro func_801B4AB0).- When an earlier C function fixed
u8 D_x[]andputrefuses a type change, a struct view anchored at an address-only symbol 8 bytes lower (extern struct { s32 pad[2]; SatNode node[1]; } D_801E4D38;) gives the struct-arraylui at; addiu at; addu at,at,regform without touching the earlier declaration (satan). px = *(volatile u16 *)&D[i];for the first read and plainD[i]for the later ones gives exactly twolhuof one halfword: CSE does not merge across the volatile read (odin2 func_801B4B98).- A second struct view anchored at an address-only symbol (
SvShard2atD_801F92C8) givessym+regaccesses to the upper half of a record whose first view hides it behind a pad (siva func_801B3644). Adjacent halfword globals as one{ u16 x, y, z; }struct keep a load, store, load, store order (siva func_801B2FAC); a one-field{ u16 v; u16 pad; }view of matrix words read as halfwords does the same (siva func_801B47B4, odin1 func_801B5A74). - An
s32global read through a big struct view (((Vh0Big *)D_801FD928)->a[i]) hoists the 0x10080/0x10104 offsets into saved registers and lets the global's reload be CSE'd as in the game (vahamut0 func_801B563C). - A function its caller calls with no arguments is defined with bare parameter names,
void f(arg0, arg1)(vahamut2 func_801B7C4C). - Particle arrays declared as
u8[]: a struct-array view anchored 2 bytes below the symbol,typedef struct { s16 pad; SdPart e[180]; } SdParts; extern SdParts D_801E1602;, gives the game's loop with the counter eliminated, the exit compare on the pointer andsym(reg)field accesses;((SdPart *)(D + o))->fviews hoist and combine per-field pointers, ande[i].f2++keeps its store assym+regwhile the loads use the stepping pointer (sdust func_801B0DCC, func_801B1424). - One-field struct views pin a global's place in source order: a scalar store target
{ s16 v; }(D_80153BBE.v = 0xE00) is not filled into ajaldelay slot and keepslh v0,2(a2)after a halfword store (hades func_801B8084, func_801B4600);extern MgHalf D_x; .. = D_x.vkeeps anlhuafter zero stores (knights func_801B7498);MgByte D_x; n >= D_x.v(knights func_801B6F9C, func_801B5F0C) and((MgByte *)&D_801DEA40)->v(alex func_801B4118) keep anlbuaftershstores where a plainu8extern hoists it. - A struct view (
KnCam *) of a camera pointer instead ofu8 *and casts lets a later global pointer load float above its field stores (knights func_801B67C4). ReadingD_801DFA14.padof a bigger symbol instead of the separate splat symbolD_801DFA1Agives the game's base register (beam func_801B0E1C). - A global declared
s32but read twice withlhu: one read through `(u8 *)&D_801EC34C- 4
and the other through(u8 )&D_801EC348 + 8gives each its ownlui, where(u16 *)&D_801EC350shares one (knights func_801B5C5C);D_80158D02[0] += a;on au16scalar gives the pointer formlui/addiu a0; lhu 0(a0); sh 0(a0)` (alex func_801B402C).
- 4
- A callee with an
s16parameter that the game passes an unextendeds32is called through a cast prototype (alex func_801B53B0, func_801B3BAC, func_801B5584); an uninitialised local returned (s32 r; .. if (..) r = i; return r;) reproduces a garbage return ina2(tifa func_801BCD54). D_x += von ans16global loads it withlhu; a negative constant stored to au16global becomesli 0xEC78and needs ans16global to stayaddiu -0x1388;D_x[1] += vkeeps the symbol address in a register (lui/addiu a1; lhu 0(a1); sh 0(a1)) under both compilers (spells 78).- After
t = (u16)p->unk2into ans32, a second test!(p->unk2 & 3)reloads the field: the sign- and zero-extending loads are not merged (jibaku2 func_801B0D10). Au16field read as(s16)D_x[e].htakes 8 bytes of frame less than(s16)*(u16 *)&D_x[e].h(matra func_801B1558);lhu; sll 16; sra 15wants au16variable and(x << 16) >> 15, where ans16variable giveslh(lasboss2 func_801B1024). - dia func_801B16DC matched only with
-func_80042DA8() % 0x4B0written without a variable, one pointer variable instead of two of the same type, no stray third argument to a two-argument callee (an extrav.vzforcedsll/sraand moved the temps), andlhuonce into au16local, then(s16)uu % 5. - A main symbol an overlay uses cannot be retyped (
putmoves the changed declaration into the file's own block and the overlay no longer builds): a one-field view at the address-only name of the field (extern struct { s16 v; u8 pad[0x43E]; } D_8009D862[];) giveslui at; addiu; addu; lh 0(at)and puts cleanly (main func_80027408). - A
u16last parameter can change the head's instruction order (akao func_8002ED34 matched only withu16 arg2, found by the permuter); au16temp forx = *p + 0xFEFFtakesv1where ans32one takesa0(akao func_800308D4).s16locals assigned(s8)*(u8 *)&p->fgivelbu; sll 24; sra 24where ans32target folds tolb; au16-returning callee whose result the game keeps withoutandiis called through ans32 (*)(void)cast (battle func_800DEC10). - Hardware byte reads repeated in a loop need a local
volatile u8 *q;*(volatile s8 *)&D_x = vgiveslui; addiu; sb 0(reg)where a plain store giveslui at; sb; avolatile u8 sp18[8]local gives reloads with a redundantandi 0xFF(libcd func_8003E454).extern volatile s32 *volatile D_x(pointer and pointee volatile) gives a double load of one global with a store before the reload (battle func_800B4794). - highway's
HwUvis 14 bytes:(n + k) << 4addressing needs a 16-byte record type (highway func_800A71E8). - A plain
extern u8the game reaches through a register (lui; addiu; lbu 0(reg); sb 0(reg)) is written as an array element:D_80151906[0].pad2[1] |= 2, or(&D_80151909)[0x22D4] |= 0x10for D_80153BDD (battle func_800C679C). A global declared as an array and read asD_x[0]keeps its load below a preceding store where a scalar extern is hoisted above it, the array form of the one-field struct view (magic_shinra func_801B0664, magic_freeze func_801B0FC4, snobo func_800A56C4). - Per-actor fields as separate
extern u8 D_x[]indexed byid * 0x240gave the game's addressing where a 0x240-byte struct gavelui; addiu; addu at(battle func_800DCFD4). A 2-D array of structs (D_801F0004[i].q[j][buf]) lets loop.c eliminate an outer counter that a flati * 32 + j * 2index keeps, and an unfused 8-byte copy*(MgB8 *)S = *(MgB8 *)&G[i]matches directly when G is an array of 0x14-byte structs indexed by the loop counter (magic_tupon func_801B3668). - A non-void return type with no
returnkeepsv0live at the end, which stops reorg fillingbne v0,v1withli v0,-1(magic_scope func_801B06D0). A division by a constant stored to au8has no sign fix (mult; mfhi; srl 5), where ans32target adds thesra 31and au32dividend givesmultu(condor func_800AF470). - Callers passing fewer arguments than decls.h's prototype: a K&R
void f();in the work file serves them all (magic_whirl func_801B0098), or a cast call((void (*)())f)(a, b, c). Names such ask0,k1,f0,aandPair16are already macros or typedefs: a work file's typedef needs another name. - A field the game reads with two near-identical loads comes from two names for one global
(
D_8012C442[1]andD_8012C444, no volatile: volatile adds anandi 0xffff) (condor func_800A46E4); magic_tupon func_801B3A08 reads one halfword pair asD_801EDB70[0]andD_801EDB72. - A
u32table indexedc + j * 0x20is written*(u32 *)((u8 *)0x80198880 + c * 4 + j * 0x80)for the game's pre-multiplied pointer (condor func_800A427C). A one-field struct array (D_8009C766[a].a) giveslui at; addiu at; addu ataddressing where(&D)[off]givesaddu v1,v0,v1(battle func_800E60F8). - A
u8parameter gets anandion each arithmetic use: when the game's has none, the callee takess32(condor func_800A698C). Ans32temp where the game keeps a full word removesandiandsll/srapairs and turnsy = xinto amove(magic_bushin2 func_801B1580). - A halfword global as
extern u16 X[]withX[0] = ..; call((u8 *)X - 0xC)keeps the address in a register for the store and lets the nextlwmove above it; a packet tag asu32 tagwithpk->tag = 0x07000000giveslui; swwhere a bitfieldtag.len = 7givessb(magic_kujata func_801B3878). putrefuses a function that matches alone when its declarations disagree with decls.h or with other users: condor func_800AF08C neededextern s32 D_8012C50C(its C user now takes(u8 *)&D_8012C50C), and the work file's ownvoid func_800A2D68(void);conflicted with decls.h'sM2C_UNK func_800A2D68();(tools/auto_decomp.py now prints the last real error line, not the warning before it); a caller'sreturn f()needsfto returns32(condor func_800A427C).- An
adduwith its operands the other way round comes from how the address is written:q = (u32 **)(n * 4 + arg0);with ans32 arg0gave the game'saddu a0,a0,s3wherearg0 + n,&arg0[n]and(s32)arg0 + n * 4gaveaddu a0,s3,a0(battle func_800C5ADC);(T *)(j * 0x18 + (s32)base)puts the offset first (magic_hades func_801B5310). Still open: snobo func_800A0F1C wants the base first and every form gives the index first. - Globals that look separate (a byte triple and a halfword) can be one struct
{ u8 a, b, c, pad; u16 d; }: a store to a struct member invalidates a cachedp->fieldload where a store to a plain scalar does not (magic_hades func_801B64FC). A hand-stepped byte offsetj += 0x68over three tables never scheduled its zero where the game has it; the tables as arrays of a 0x68-byte struct (typedef struct { s32 w[26]; } NtFx;) indexed by the loop counter let GCC make the giv itself (magic_night func_801B1B54). - A bare K&R parameter
f(arg0)with(s16)arg0at each use gives the game's saved-register copy and a re-extension per use, where a prototypeds16 arg0does not (battle func_800D9BF4); a bare K&R definition also keeps a decls.h prototype other callers need (battle func_800DB818).((s32 (*)())f)(..)drops thesll/sraafter a call to ans16function, and((s32 (*)(void))f)()theandi 0xffafter au8one, without changing decls.h; a cast prototype with ans32parameter where decls.h hass16cancels an argument extension. - An
s16local GCC 2.6.3 loads from ans32slot comes outlhuplus a sign extension; a plains32local giveslh(highway func_800A8C0C). A u16 field writtenf - 0xAbecomesli 0xfff6; addu; through ans32temp it isaddiu -10(big5). A narrows16 k = 0x34used as an index got the game's saved register wheres32did not (condor func_800AE384). Printf strings sit in rodata in the order the function names them: two initialised localschar *dma = ".."; char *fifo = "..";at the top put them before a format passed inline (main func_800424C4). - A global that decls.h declares as a scalar can be indexed as
(&D_x)[i]without redeclaring it as an array (put refuses a redeclaration that conflicts with decls.h: jet func_800A1F18). A work file's extern that retypes a global decls.h declares makes put fail elsewhere in the file; an alias name for the same address with the other type (s48_800832A0: any name ending in_and eight hex digits names that address) avoids it (world func_800B8D4C); the same alias gives a second read of a global its own type,extern volatile u8 vol_80062D98;(see Control flow). A call through a cast with fewer parameters,((void (*)(MgMat *, MgMat *))func_8003BF3C)(a, b), matches where decls.h declares more and the game sets fewer argument registers (battle func_800D41FC). A type a port adds to main/decls.h must not reuse a name an overlay's decls.h defines (savemenu's SvCursor became MnCursor in main). - A multi-line typedef in a work file counts as a clash with decls.h: keep typedefs on one
line. In a port, an extra switch case
D_x->part = op = *script++;followed by a call matched only withopau16local and the call passing(s16)op(magic_vahamut0 func_801B03D4).
- The scheduler may swap a load through a struct pointer with a store to a plain global (it assumes they are apart), but never two accesses of the same kind. When two instructions are in the other order, try the statements the other way round, a field of a struct instead of a plain variable, or the reverse.
- 2.6.3 takes two different plain symbols as never aliasing, even indexed. A store to
symbol plus a non-zero offset (a cast pointer,
*(s16 *)((u8 *)p + 4) = 1) keeps a later load after it. - Stores through a global pointer:
M2C_SFIELD(D_x, T *, off) = vstops GCC reloading the pointer; a load that must stay after a store to a plain global:M2C_FIELD. A[i] += 1loads A's address first, then shifts i;p = &A[i]; *p += nshifts first. An operand written out inline each time ((D_x + D_y[D_z])[n]) loads the offset before the base; through a pointer temporary, the base first.- 2.6.3:
base + (i << 2)on an integer address givesaddu v0, base, idx;ptr + i * 4puts the multiply first. - 2.7.2 reassociates
(x*k + C) + yso that C joins the other operand; computet = x*k + C;in a single-use temporary to keep the game'saddiu. - A constant assignment written after a call is moved into the call's argument setup.
- 2.7.2: a plain scalar global read scheduled before indexed array stores the game has
ahead of it: declare it as an array and read
D_x[0]. - A temporary computed as its own statement moves things:
j = 3 - i;first in a loop body changes which constants are hoisted first;n = p[0];before an expression sets the operand order of itsaddu.v <<= 8; v |= x;keeps registers thatv = (v << 8) | xswaps. do { ... } while (0);(a macro's wrapper) is a scheduling barrier: register saves all before a loop's start values come from a loop wrapped so; a plain global loaded early and used once (2.6.3 moves it down to its use) stays early with the rest of the function after it wrapped so (volatile instead giveslui; addiu; lw 0(reg)).- The scheduler takes a struct and a scalar to never overlap: a load in the wrong place
around a store wants one side made a struct field (a 5th stack argument loaded after a
store through
&D_xonly ifD_xis a struct). A cast store (*(u16 *)D[i].pad = 0,*(s32 *)&p->r0 = c) keeps its place where a field store moves; a scratchpad struct at a constant address (s = (T *)0x1F800000) is never reordered with loads through struct pointers, so its statements are in source order. - Copies between two globals kept load/store/load/store: both sides
volatile. - 2.7.2's second scheduler puts stores of nonzero constants before stores of
$zero: a block of initialisations is written in its natural order anyway. - The first access to an array decides where its base is loaded: write the first access
through the pointer too (
p = &D[i]; p->f = -1;). q[b] = lo; q[b] |= hi << 8;reuses the stored value;G->a = G->b = 0loads a global pointer once for both stores; a value re-read after a store withoutvolatilewas stored in both arms of an if/else and read after the join.- A load of another symbol that 2.6.3 lifts above a store: name the stored or loaded
element through an earlier symbol plus an offset (
D_8008326B[i + 1]forD_8008326C[i],D_80151908[id][7]forD_8015190F[id][0]). Adjacent halfword globals declared as one struct keep a load/store/load/store order. A halfword reload is not forwarded after a store to a neighbouring halfword of the same struct. - Operand order of
addu:ptr + idxthrough a named variable gives (idx, ptr),M2C_FIELD(&ptr[idx], T, k)(ptr, idx);e = (T *)(o + (s32)base)witho = j * 0x18gives (off, base) where&base[j]gives the other order; forp = idx + pwrite the sum into another variable, or the expander swaps it back. - Reassociation:
a/16 + (c - 1)becomes(a/16 - 1) + c,(t + 8) + basebecomes(base + 8) + t: compute the parts in separate statements (u = t + 8;). Pointer arithmetic keeps(x*4 + 0x70) + D:(s32)((u32 *)D + (v >> 2) + 0x1C). - The prologue's argument copies follow where each parameter is first copied: name the
parameter differently and write
x = arg0;after the initialisations to move it. - Cast stores keep later loads after them where struct-field stores let them float above:
*(s32 *)(q + 0x14) = vthrough au8 *q; all-cast stores to a primitive in the game's order (*(s16 *)((u8 *)p + 0xA) = i;, not*(s16 *)&p->y); cast stores through a possibly-NULL slot pointer keep thelw/nop/swalternation.extern struct { u8 v; } D_x;keeps a byte load after a halfword store where a plainu8extern floats above it. - Load/store pairs across fields stay in source order only when the fields belong to one
struct array under one base symbol; separate per-field arrays let the loads float above
the stores. A global read twice around stores through a struct pointer is reloaded only
when read as a struct member (
((MgSVec *)D_x)->vx). - Equal-priority independent stores come out in source order. A store of 0 must be written
after the load it follows in the game, or it is hoisted ahead. In
d.vx = q->f = eq is stored first, and only the last store of a chain is forwarded without a reload;p->w == 0 || p->w > 0xFEFFreloads afterp->w -= xwhere a local copy forwards the stored value.*(u16 *)&Dread before a store toDloads the old halfword withlhufirst. - An explicit address variable (
fp = &D_x;beforecol = &D_y;, orb = &tbl; sp = b + n * 5) puts that address first in the prologue. Inf(D + 0x70 + ((n >> 2) << 2), q)the operand written first decides which one the result's register ties to; `t = (n >> 2)- 4 + 0x70; f(t + D, pkt);
as its own statement keeps the result ina0;k = 0x70;before the call, written((r >> 2) << 2) + k + D, gives theaddiu 0x70` after the global load.
- 4 + 0x70; f(t + D, pkt);
- Chained stores
a = b = c = vevaluate the outer lvalue's address first and store the rightmost first:rot.vx = rot.vz = 0storesvzfirst,*q = D_B9 = D_BA = vthe globals first, andD[i][0] = D[i][1] = D[i][2] = 0keeps one address register for the inner stores with the outer one assym+reg. - Array elements store like struct members:
extern u8 D[]; D[0] = D[1] = D[2] = c;keeps a laterp->fload after the stores where three scalar externs let it float above. Scratchpad globals as one-field structs (extern MgWord D_1F800028; D_1F800028.v = v;) keep their stores ahead of struct-field stores. A volatile global read floats above struct-member stores but not above cast or array-element stores;*(s16 *)((u8 *)p + 2) = t;keeps a later byte load after it. - A zero vector after a computed field:
a.vz = f(...); a.vy = 0; a.vx = 0;puts the zero stores after thelh/li. A dead first storeq->f = a; q->f = b;is dropped when adjacent; one other store between them keeps it. In a run of read-modify-write statements the loads follow source order: permute the statements. - Frame descriptors addressed below a symbol:
D_x[0] = v; *(s32 *)&D_x[-5] = w; f(&D_x[-5]);givessw -0xA(t0)andaddiu a0, t0, -0xAwhere a pointer `(u8 *)frame- 0xA
folds tolui at; sw`; a store at offset 0 of its symbol floats up, one at a non-zero offset of an earlier symbol stays.
- 0xA
- Stall-slot fill: a counter
i = 0;set inside theifright after the call and before the loop fills the load stall and moves the address setup before thelh; set before theif, the order flips.f(.., q); q++;puts the increment before thejal. - Base before index:
b = D_80162978; q = &b[f()]gives the baselui/addiubefore thesll;r = f(); q = D_x; g(a, b, &((T *)q)[r]);withqalso set in other blocks (a multi-set pseudo is not sunk) keeps the base in a saved register where inline&D_x[f()]giveslui a2after the call. - Many stores of pointer constants that force spills: the spilled set and the slots match
when the stores are in ascending order of the constant. A 32-byte struct copy followed
by
f(&m, &D_x)giveslwx4/swx4 groups; a K&Rf()calledf(&m), with the base left ina1, gives the game's 3/3/2 grouping. - Stores through a global pointer cast to a struct: CSE reloads the pointer after each
byte store but keeps it across halfword and word stores, and the scheduler moves a run's
byte store ahead of the group: write each run as the halfword/word group first and the
byte store last. A one-field struct global (
MgByte) written afterq->fstores stays after them where plains8externs float above;*(s16 *)((u8 *)w + 4) = 0;keeps a followinglhuafter it wherew[2] = 0lets it float up. - Stores to distinct stack slots reorder freely; a statement that loads before them keeps
them after that load (write
a.x, a.y, a.z, b.x, b.y, b.z). A load through a pointer written before a store to the same array (w = ((s32 *)p)[1];) keeps load-before-store. Trying every order of a group of stores (work/battle20/stperm.py, work/spells27/perm.py), or swapping two adjacent field stores, often finishes a function. - Chained stores through a struct global:
D_x.vx = D_x.vz = v;storesvzfirst, three separate byte externsD_94 = D_95 = D_96 = vstore 96 first; with a ternary on the right (D.r = D.g = D.b = c ? A : B;) the three addresses are built before the branch and the stores come after the join. A ternary stored straight to memory emits a store per arm: set a local in if/else and store it once, through a one-field struct pointer (MgHalf *f = (MgHalf *)((u8 *)q + 0xA); ... f->v = c;). - Frame descriptors below an array symbol:
MgHalf D_x[]; D_x[0].v = ...; *(s32 *)&D_x[-4] = ptr; f(&D_x[-4], ...)givessw -8(frame)in the call's delay slot; as a struct global,T *q = &D_x; q->a = ptr; q->f = ...; f(q, ...), where au16 *store schedules the argument first.M2C_SFIELD(frame, u16 *, 0) = v;schedules a laterlwdifferently from*frame = v. f(..); flag = 1;puts the flag'sliin thejaldelay slot,flag = 1; f(..)before it;f(x); x++;keeps an increment after the call,f(x++)orr = p; p++; f(a, r);puts it before.if (A && (f = x | y | z, !(B & 4)) && !(f & 0x800))puts the loads offahead of an earlier test.*(volatile s32 *)&D_xas an argument giveslui; addiu; ... lw a3, 0(v0); a volatile global read twice with its address kept in a register isvolatile u32 *t = &D_x; *t / 3600 ... *t % 3600.- The scheduler treats different plain symbols as never aliasing, so a plain global store
floats above a table load; writing both through one symbol (the table as
((s32 **)((u8 *)D_x + 6))[i], the store asD_x[0] = v) keeps the store after the load (quasar func_801B05B0). Likewise a scalar array element at an earlier symbol (D_800F5BC8[i][0x19] |= 8) keeps its load after a store where a struct member at the later symbol floats above (battle func_800AA1C8), and naming an address through a neighbouring symbol (D_8015190A[o - 1]forD_80151909[o]) stops two accesses sharing an address register. - What kills a CSE'd global or global pointer: halfword and word struct-member stores
keep it, byte stores and stores through casts (
*(s16 *)(r + 0x28)) kill it, so later statements re-read it as the game often does. A game that reloads a pointer only after byte stores uses a fresh pointer variable per store group. Stores through cast pointers reload a stack-slot pointer per field; a one-field struct pointer (d->a = ev->a; d->b = ev->b) loads it once. - One-field struct globals (
MgHalf,MgByte) keep a followingp->unk2reload after their store, and in a chain (*rgb = D_1815.v = D_1816.v = (u8)D_x << 4;) keep the stores ahead of later loads where plains8/u8externs let the loads float above (kakusan func_801B0580). A chained assignment of a register variable to three plain byte globals adds amove; three statements avoid it. - Scratchpad stores as
D_1F800040[n] = ...(elements of one extern array) keep later pointer loads after them; plain externs and*(s32 *)0x1F8000xxlet the loads float above. Two uses of one constant scratchpad address (*(s32 *)0x1F800004 = f(*(s32 *)0x1F800004)) giveli reg, 0x1F800004and0(reg); a single use stayslui; lw %lo. A field read into a local before scratchpad stores keeps the load first. - Two
lhuof one halfword through a parameter stay two loads above later global stores only through a struct pointer (arg0->v); through au16 *the second sinks below the first store. Readingt = p->unk2;once before the packet stores, when the game passes it as an argument, avoids a reload after a store throughq. - Argument set-up: a 3-argument call leaves the previous call's result in
a3: write the 3-argument call rather than passing it as a fourth argument. A ternary argumentf(&p->unk4, c ? 0x2000 : 0x3000, 0)putsli a1at the top, if/else puts it in the branch delay slot.scale.vx = scale.vz = expr;moves the argument set-up above the arithmetic, the value through a local puts it after (reito func_801B1968). Call-argument sums are reassociated: one single-use temp per case (D_y + t) keeps the game's order (eqipmenu func_801D4760). - A global pointer base kept in a local assigned after the call,
r = f(); q = (T *)D_x; g(&q[r]), gives the baseluiafter the call;&D_x[f()]loads it at the end.u = p->unk14;written before an unrelated computation loads early; inline in the expression it loads late.n = (u16)(x - 1); x = n;as a block's first statement puts thelhufirst. - Folding:
q->f = q->f - 0x12C + rand() % 600folds the constant onto the remainder;u = rand(); k = (u16)q->f - 0x12C; q->f = k + u % 600;keeps it on the field.((w >> 4) & 0x100) >> 4folds tosrl 8; andi 0x10; the game's unfoldedsrl 4; andi 0x100; srl 4comes from((y & 0x100) >> 4) | x | ((y & 0x200) << 2)with another term between the two uses ofy(field func_800ACC5C).(T *)((s32)p + t + 0x124DC)(integer arithmetic) keeps a large offset in a register whereu8 *arithmetic folds it into the displacement;base = (s32)D_a; prim = D_b + base; prim += 4;keepsaddu; addiu 4. a | bis evaluated in source order when split (v = x; v |= y;); as one expression GCC puts the simpler operand first.!(v > lim - 0x160 && v < lim)loads the field before the globallim,!(lim - 0x160 < v && ...)the other way round.D[0][0] |= 4; D[1][0] |= 4; D[2][0] |= 4;in source order gives the game's [0], [2], [1] load order (battle func_800B30E4). One local reused for consecutive copies (t = A; d.x = t; t = B; d.y = t;) keeps load/store/load/store.- CSE follows a
||jump into its then-part and reuses everything there; a second name for the pointer ((&D_8004AB54)[1]forD_8004AB58) forces the reload.q = &D_x; ... *qgives a sharedlaregister even for a scalar. Volatile reads (*(volatile u16 *)&D_x) stop cross-jumping from merging identical argument set-ups (main func_800138EC).rot.vy = p->unk2 * 0x20;beforerot.vz = 0; rot.vx = 0;swaps the index and base registers in the prologue. q = &D[i]; q->c = 0; q->b = 0; D[i].a = 0;gives a hoisted base for theqfields andsym(reg)for the direct access. A ternary on the right of a chained cast store,*(u8 *)(D + g + K1) = *(u8 *)(D + g + K2) = (x & 8) ? 0xB0 : 0x50;, gives one address register per store with the stores after the join.- A stored halfword is not forwarded to a later load that spells the address differently:
D_801D5372 = c;then*(s16 *)((u8 *)&D_801D536C + 6) != 0x80gives the game'sshthenlh(nadare func_801B19CC); a store in both arms instead lets cross-jumping move it to the join. h = &p->unk2; *h += 1; if (*h >= D_x[4])keeps the global pointer load after theshwherep->unk2++lets it float up (beat func_801B0778). A store through a one-field struct pointer,fd->p = ptr, keeps a following global pointer load below it;*fd = ptron au8 **lets it float above (saikyo func_801B035C).D_x[a].f--; D_x[a].f &= 0x1F;keepsaddiu -1and a reload after the byte store;-= 1forwards the value asaddiu 255(battle func_800C1908).(*(s16 *)(q + 0x10) << 2) < *(s16 *)(q + 0x12)schedules the two loads as the game,* 4does not (battle func_800A3ED0);if (v > best)andif (best < v)order a load and anslldifferently (nadare func_801B11C4).- Scale vector stores
sc.vz,sc.vy,sc.vxin that order give0x30, 0x2C, 0x28(beat func_801B01BC).q->unk10 = 0written after theunkEstatement leaves thenopafter the firstmfhiunfilled (iyashi func_801B0A74). f(D + 0x70 + ((r >> 2) << 2), q)with the global first keepsrina0and theaddiu 0x70before the add;((r >> 2) << 2) + 0x70 + Ddoes not (iyashi func_801B0624).tab = base; j = 0; tab += D_x;withj * 16 + (s32)tabgives the preheader andadduoperand order (nadare func_801B1350).- A pointer local used in one expression (
b = D_8009A074; ... b + 0x10) puts the+0x10after the add (addu; addiu 16) while other uses ofD_8009A074 + 0x10stay in a hoisted register (main batch 10);b = D_x;keeps(base + idx) + 0x270unfolded only whenblives across calls (iyashi func_801B0D64). - Re-reading
D_8004AB54afterD_8004AB54 += 1as the index stops(n+1)*8folding inton*8+8(main batch 10).id = T[D]; e[8] = D; D++; e[0] = id;giveslh,move v1,a0,addiu a1,v1,1(hiwind func_801B08DC). r = f(); q = (MgTask *)((u8 *)D_80162978 + 4); g(..., (u8 *)q + (r << 5));gives the baselui; addiuafter the call andqins1(nadare func_801B1C54).- Stores the game places after a call go after it in source, and each zero store after the load it follows in the game (rakuseki func_801B02F8, func_801B0A54; work/spells27/perm.py found the order of about nine blocks in spells batch 38).
- Byte globals as array elements,
D_x[2] = D_x[1] = D_x[0] = 0, keep a followingp->unk2reload after them; consecutive word or halfword globals as array elements keep the game's load/store alternation (thundg1 func_801B0724, altema func_801B0074; not everywhere:D_800F8380as an array broke itslui; lbu).*bp = D_09.v = D_0A.v = ewithMgByteglobals keeps the three stores ahead of later loads, andextern struct { s16 v; } D_xscalars stop pointer loads moving above their stores; a neighbour read as*(s16 *)((u8 *)&D_58 + 2)does not share the address register ofD_x(ho_den func_801B06C4, heart2 func_801B0F9C). - Packet stores as
*(s32 *)((u8 *)p + N) = vkeep a laterD_801517C0load after all of them where struct-member stores let it float above;((u8 *)p)[7] = code;written last gives thep+7stepping register (reazer func_801B102C).q->unk8 = p->unk8; q->unkA = 0;(copy first) gives the earlylhu(thundg1). - Scratchpad:
D_1F800000[0..3]as anextern s32array keeps later global loads after the stores (seald func_801B0974). A pointer locals = (MgSVec *)0x1F800000assigned at the top keeps the stores in source order, but only whensitself is the call argument: with the literal address GCC deletes the stores (grenade func_801B0880, func_801B03EC); used for the offset-0 store and the argument it shareslui a0(faiga func_801B0284). A struct-member store before the call stops thelui a0,0x1F80argument being hoisted (seald func_801B0D4C). - More frame descriptors:
D_x[0] = v; f(&D_x[-5], ...)lets a later argument load float above the store,frame = &D_x; *frame = v;keeps it after (osen func_801B08F0, tail func_801B0894). A pointer stored through a one-field struct,((HoPtr *)frame)->p = ptr, lets laterlwargument loads float above it;*(u8 **)frame = ptrkeeps them below (ho_den func_801B06C4).*p = 0; D_x[2] = ...; m = (MgMat *)(p - 5)on a descriptor pointer givesaddiu s0,a1,-0x14in abeqzdelay slot (choco0 func_801B1F68);D_x[0] = v; f(&D_x[-4])with plain externs matches where extern pointer variables add saved registers (choco0 func_801B1B40). - After a base-before-index spawn (
a = D_80162978; p = &a[f()];), later plain&D_80162978[f()]reuse the CSE'd base;p = &b[D_8015169C]insideif (D_80062D98 == 0) {puts its loads after the branch (faiga func_801B0D48, func_801B062C). - A struct view on a
u8symbol,((Rec *)(D_x + o))->fwith a localtypedef struct { s16 flag; s16 frame; s16 vx; s16 vy; s16 vz; s16 pad[5]; } Rec;, keeps decls.h'su8 D_x[]for earlier callers, thelui at; addiu at; addu at,at,oform, and a laterframeload after thevzstore where scalar casts let it float above;((Rec *)D_x)[i]hoists the base into saved registers, and++((Rec *)(D_x + o))->frame == 0x1Eforwards the value without a reload (lasboss2 func_801B0D8C). - One-field struct and array globals keep their stores ahead of later loads:
D_x[0] = D_y.v = expr;withD_yanMgWordkeeps a followinglh p->unk2reload after it (atomic func_801B09C8);extern u8 D[]elements keep theirlbuafter a struct-membershwhere a plainu8extern hoists it (h_blow func_801B04DC);D_x[0] = D_x[1] = D_x[2] = con au8array with(u8 *)D_y - 8for the frame keepslhu p->fafter the byte stores (spark func_801B0FAC, mizufuki func_801B05E0); a halfword global written asD[0] = vkeeps a finallhuafter it (club2 func_801B2BD8). - More frame descriptors:
extern T *D_x[]; D_x[0] = ptr; f(D_x, ..)givessw 0(s0)thensw 0(a0)(comet func_801B0608);extern struct { u8 *src; s32 mode; s16 pad; s16 val; } D_x;keeps laterp->unk2loads below its stores (comet func_801B0850); a byte colour descriptorextern u8 D_x[]; D_x[0] = c; *(s32 *)&D_x[-4] = tbl[...]; f((s32 *)&D_x[-4], ...)givessw -4(v1)wherecol = &D_x; *(s32 *)(col - 4) = ..folds tolui at; sw, and the colour-only twins match with `col = &D_x; *col = c; f((s32 *)(col- 4), ..)
(lasboss2 func_801B013C, func_801B0948).t = &D_x; m = (MgMat *)((u8 *)t - 0x14); ... *t = 0;keeps the symbol address inv0(lasboss func_801B2A50). Unsolved: the game loadsD_801517C0 + 0x70intoa1above a pointer storesw ptr,-0xA(s0)` (atomic func_801B0B44, tbreath func_801B071C).
- 4), ..)
- Scratchpad: stores through
((MgScratch *)0x1F800000)->flet symbol loads float above them where raw*(s16 *)0x1F8000xxstores keep a table load below (club2 func_801B1164); a final store repeated in each arm of an if chain matched where one store at the join sank below the argument loads (club2 func_801B1E38, func_801B1C2C). MgMat D_x; D_x.m[0][0] = D_x.m[1][1] = D_x.m[2][2] = v;keeps the game's order and a sharedla a1(comet func_801B0608);m.t[0] = m.t[1] = m.t[2] = 0storest[2]first. Zero stores go after the load they follow:t = p->unk8; q->unk1A = 0; q->unk8 = t;(triangle func_801B0BDC),rot.vx = ..; rot.vy = ..; rot.vz = 0;(hyper func_801B179C, club2 func_801B1A54),rot.vy = ..; rot.vx = rot.vz = 0;(triangle func_801B091C).p->unk16 = D;beforep->unk2++; if (p->unk2 == N)forwards the incremented value instead of reloading it (atomic). Products written inline keep the game'slhu/lhu/multorder where a temp loads the shared field first (lasboss2 func_801B0824). Packet constants are materialised in the order of their first store in source (spark func_801B0700).- Plain symbol stores written as one-field structs (
extern ChWord D_x; D_x.v = k;) stay ahead of a following struct-pointer store and itslh(cho_kyu func_801B0F24); a plainu16global read after a struct-member store floats above it, read as((DiHalf *)&D_x)->vit stays after (dia func_801B07F0). Casting the first stores as*(s16 *)((u8 *)q + 0xC) = ..keeps the next scalar-global load after them where struct-member stores let it hoist (wpyu func_801B14A4, func_801B1878). Scratchpad adds through*(u16 *)sv += D_x; ((u16 *)sv)[1] += ..keep later symbol loads in place wheresv->vx += D_xlets them float up (graviga2 func_801B09D0). - Frame descriptors:
s16 *frame = &D_x; *frame = v; f((u8 *)frame - 0xA, D_801517C0 + 0x70, 0xC, D)putsli a2and theshbefore the argument loads,extern s16 D_x[]; D_x[0] = v; f((u8 *)D_x - 0xA, ...)gives the loads first (dia func_801B1004, func_801B07F0); other functions of the same spell matched with theframeform (func_801B04C8, func_801B05D4), so try both.q = D_x; q[0] = v; m = (MgMat *)(q - 5); D_x[1] = ..; D_x[2] = ..;matched a pointer-first-store plus array-element descriptor (cho_kyu func_801B19C4).q++; D_x = (s32)q;matched whereD_x = (s32)(q + 1);gaveaddiu v1,s0,40(sflea func_801B07C8). - Repeat a store chain in each arm of an if chain (
D_a = D_b = D_c = expr;per arm) where one chain after the join gives other registers or lets the scheduler hoist the next argument setup above the stores: the arms are cross-jumped together only after scheduling (graviga1 func_801B0634, func_801B03A8, timedmg func_801B0F74;u8 c[3]form in graviga2 func_801B0CF8).D_x[0] = D_x[1] = D_x[2] = cgave byte stores in 0xE, 0xD, 0xC order (timedmg func_801B0F74). q->unk18 = d; q->unk16 = q->unk14 / d;reloadsq->unk14: stores to neighbouring halfwords block forwarding (brizag func_801B210C).- A single-set pointer
s = &D_xis moved to its first use by the scheduler wherever it is written, so an earlylui s0; addiu s0after a call is not reproduced that way (conf func_801B2350, unsolved). - Constant stores such as
q->unkC = 0x200go after the statement with the lastrand()call: the game fills the divide stalls with them (gospel func_801B1A48, func_801B3414). - One temp for two copies,
t = A; X = t; t = B; Y = t;, keeps the second load after the first store (gospel func_801B3914). Read a table into a temp before scratchpad stores through((MgScratch *)0x1F800000)->fto keep its load above them (nanntoka func_801B0FAC); in a scratchpad store block,unk0 = D_x[p->unk14]written as the first store put the table load first (queig func_801B29E0). f(p->unk1C); i = 0;giveslh a0beforemove s0,zero;i = 0; f(..)swaps them (blaster func_801B12C8).- A final block of field stores matched in plain field-offset order (unk0, unk2, unk4,
...) where a hand-picked order did not (lamu func_801B1C24, found by hc.py).
Read-modify-write order decides the load order:
p->unk14 += 0x60;before `n = p->unk2- 1; p->unk2 = n;
gave the game'slhu` order (bushin2 func_801B0740); fields in unk4, unk6, unk8, then unk2 order (func_801B0494).
- 1; p->unk2 = n;
- A local holding the scratchpad address of a source variable (
k = 0x1F800000; *(s16 *)k = ..) changed the prologue schedule to the game's (lamu func_801B1A10, found by the permuter). n = 6 - p->unk2as a temp stops reassociation (gaisei func_801B2EEC);u = *g; u += 0x20; u -= x; *g = u;keeps the game's add order (gaisei func_801B2DFC).- Colour bytes as array elements
D[0] = D[1] = D[2] = cgive the game's store order where a chain of scalars swapped it (lgirl func_801B07D4); a flag byte asD[3]reloadsp->unk2after the byte store as the game (lgirl func_801B00F8). Byte globals stored as array elements (D_800F5B70[0] = 0x48) make the nextp->unk2reload as the game (lunatic func_801B0B28). Colour bytes throughrgb = D_xwrittenrgb[2],rgb[1],rgb[0]givelui atstores for the first two and0(s0)for the last (lunatic func_801B0484). - A struct view for a count byte,
typedef struct { u8 cnt; u8 pad[2]; Fx e[1]; }, lets the count load hoist above scalar byte stores (lgirl func_801B00F8). A store through a one-field struct pointer (struct { s16 v; } *p3; p3->v = ..) lets the next global pointer load hoist above it where a plains16 *store keeps it below (deadsef func_801B2908). - A plain-global byte store before a later
p->unk2read in the same arm makes CSE reload the field and the scheduler hoist thelhabove thesb(D_800F8380 &= 0xF8; k = 0x1000 - (p->unk2 - 0x48) * 0x200;): the game's plain reload, no volatile needed (sdust func_801B2F04). extern struct { s16 v; s16 y; s16 z; } D_x;letsD_x.y/.zstores keep the next field loads below them (wpsi func_801B1ADC). A frame descriptor seen as a struct{ s32 unk0; s32 unk4; s16 unk8; s16 unkA; }and stored through members keeps thep->unk2reload after the stores where plain externs do not (freeze func_801B0AC0). A halfword global writtenD_x.v = ..throughMgHalfas the first store of a chain stays ahead of later loads (freeze func_801B0CA8, func_801B0828, mrain func_801B0A08).- G4 packet functions storing through
*(s32 *)((u8 *)p + N)with xy3 (+0x20) written fourth and the code byte((u8 *)p)[7] = 0x3Alast keep theD_801517C0load below the stores (wpsi func_801B078C, death func_801B07A8; twin of reazer func_801B102C). - A
%expansion has a branch: ani++written before the%statement is hoisted to the loop top (into the first call's delay slot), so write it after (m_break func_801B04E8); a constant stored = 0xFC0;written afterq->unkC = r % 0x1000;lands in thebgezdelay slot, before it in the earlierjalslot (daisenp func_801B0B18).r = f() % 3000 + 0x7D0;as one statement puts the magic constant before themove, wherer = f(); r %= 3000;does not (freeze func_801B026C). - A separate single-set
p = q - 0x2E76;written right after a call puts itsaddiuin that call's delay slot;q -= Korq = &D - Kfloat it into the first call's slot (deadsef func_801B384C).(u8 *)frame - 0xAwritten at each call, with a pointer variable per branch, schedules the add right before the call (riva func_801B1744). n = (u16)p->unk2 & 3;read before the scratchpad stores hoists itslhuabove them;t -= 0x16; c = 0x80 - t * 0x10;keepstin place (lunatic func_801B05F0).k = a + b + c + d; k = k >> 4;as two statements fixed the load order and registers (death func_801B0494, permuter).- Operand grouping:
t = D_x + (0x400 + (rand() & 0x7FF))gave the game's order (deadsef func_801B3108);((t << 12) * 3) / 200gavesll 12; sll 13; addu(deadsef func_801B361C). - Particle update tails:
p->unk4 += p->unkC; p->unk8 += p->unk10; p->unk2++; p->unkC -= p->unkC >> 4; p->unk10 -= p->unk10 >> 4;(the increment after the last add, the decays last) gives the game's load order (sldfang func_801B1720); the same under GCC 2.7.2 with>> 3(garyu func_801B2654);unk2++afterunk14 += unk16(garyu func_801B00B0). - m2c's order of tail statements is often not the game's: s_beam func_801B1550 needs
unk4 += unkCbeforeunk6 += unkEand thesv->vz = 0store last. An all-orders search over the tail lines, run in parallel, takes seconds for 6 lines and solved s_beam func_801B1550, func_801B1F78 and ifleet func_801B34AC: run it over an update tail before anything else. - Scratchpad words written in natural order
m->t[0],[1],[2]give the game's 0x14, 0x1C, 0x18 store order: the scheduler moves the middle load, and hand-picked orders matched worse (vahamut func_801B2970). Copy a twin's packet store order verbatim: re-sorting the stores into the emitted order cost an 8-minute hill-climb and still left an inversion (titan func_801B3014 from gaisei func_801B181C). - Three words written through a cast,
((MgVec *)&D_801E0838)->vx = ..; ->vy = 0; ->vz = .., keep the game's load/store order with the zero store after the load where scalar casts hoisted the loads;q = &e->pos;assigned before the compare puts itsaddiuin the first branch's delay slot (satan func_801B58DC, func_801B639C).*(s16 *)((u8 *)q + k) = ..cast stores keep later loads below them only when the loaded values come from a global; loads through a local pointer still float up (vahamut func_801B2DA8). v.vz > *(s16 *)(table + o)instead oftable < v.vzputs the stack-local load before the table address (odin2 func_801B5264). Aw = (c2 * c0) >> 12;temp written beforecbput that multiply first (queir func_801B0ECC).- One variable per axis computed in place with the two axes interleaved (
x = sum; x /= 4; z = sum; z /= 4; x += 0x888; z += 0xE70; x /= 0x200; z /= 0x200;) keeps+0x888out of the+0x1FFof the negative-case add;r = z * 0x24 + (s32)tab; cell = (s32 *)(x * 4 + r);gives theadduoperand order (satan func_801B2048, func_801B1E60). m = 0x3E8; (u16)f - m + r1 % 2000with one single-set variable perrand()result avoids a hoistedli 0xFC18andmove a2,v0copies (catastro func_801B40C8, func_801B3184).p->unk4 = p->unk4;is kept aslhu; shand holds the load order of a tail (odin1 func_801B3660); several tails matched only in plain field-offset orderunk4, unk6, unk8(siva func_801B3188), found by the parallel all-orders search in under a minute; over a 5-line store block it foundt[0], t[1], t[2], v0/v8, v4, one swap from the natural order (vahamut0 func_801B3708).- A packet tag stored through a one-field struct
((MgWord *)k)->v = 0x06000000;while the other stores are casts lets theD_801517C0load float above the tag store only (odin1 func_801B4A38, func_801B47E0).*((u8 *)p + 0x14) += 8casts keep a tail's byte loads in the game's order where struct byte fields do not (vahamut2 func_801B6868, func_801B3904);*(s16 *)((u8 *)p + 4)loads stay after the earlier global stores (kujata func_801B521C). - Direct
D_x->m.t[i]accesses keep one pointer load where a locals = D_xhoists it (kujata func_801B7028, func_801B7CFC); a constant assigned first to a local moves itslui/orito the prologue, andM2C_SFIELD(D_x, s32 *, 0x24)keeps the pointer load after the stores (kujata func_801B66F8);t = (u16)pt->a - 0x100; pt->a = t + r % 0x200;keeps thelhufirst (kujata func_801B42B8). n -= 0x100written before the lastrand()statement of a spawn loop lands in thebeqzdelay slot; a constant store goes after the statement holding the%expansion (vahamut2 func_801B48E8, func_801B6A2C). work/spells71/sweep.py moves one statement through every position of a body and scores each: it found the first.- Two independent division chains with fix-up branches (
f = ((s16)(t % 16) << 12) / 16;andq = t / 16;) match only withffirst (tupon func_801B22B4).m = &D; tp = (u16 *)((u8 *)m + 0x14); f(m, ..)makestpderive froma0instead of the reverse;i = 0;after the first call fixed the prologue order (odin1 func_801B379C). u = D.a; if (D.b == 0) t = u + K; else t = u - K;loadsbfirst and puts the else arm in thebnezdelay slot;t = a - K; if (..) t = a + K;loadsafirst (hades func_801B8084). WritingD->vx = 0first moves a pointer load early (knights func_801BA2E8); cast loads*(s32 *)((u8 *)D_x + 0x18)pin the order of three loads that otherwise hoist (phoenix func_801B3D30).f(.., q); r += 0x18; q += 0x18;after the call matched where apk = qcopy did not (phoenix func_801B2138);h->pos[i++] = p;withh->pad10 = cur;before it and the four field stores at the end putssw curin thebnedelay slot (hades func_801B35F0). work/spells63/pperm.py found pause-flag tail orders of 4-5 field updates in seconds (tifa func_801B7090, func_801B8128; knights func_801B7090, func_801B5C5C).- An OT link written inline twice,
q->tag.addr = ((MgTag *)D_801517C0 + (D->r >> 2) + 0x1C)->addr;and the same expression on the left of the next store, re-readsD->ras the game (knights func_801B4BF8); readingp->unk14afresh in eachD_80151A4C[p->unk14].vx/vy/vzreproduces the reloads (tifa func_801B8380). - Chain stores go innermost first:
q->a = q->b = xstoresbfirst;D->b28 = D->b29 = D->b2A = 0;through a global pointer loads it once and stores 2A, 29, 28, where separate statements reload it after each byte store (odin2 func_801B447C);D[0] = D[1] = D[2] = 0xFF;on au8array reloads a laterp->unk2after the stores (sflea func_801B0F7C);q->unk16 = rot.vy = (u32)(i << 16) >> 8matched where two statements did not (jibaku2 func_801B0D10);q->unkE = D = ..forwards the stored value (odin1 func_801B5D14). - 8-byte copies: through a local source pointer,
sp = (MgB8 *)D_80151A4C[i]; *(MgB8 *)&D_x = *sp;, the destinationlui/addiumoves after the index arithmetic and the copy registers change (erave func_801B1AD0, 29 to 17 words);dst = base + off; ptr = dst; *(MgB8 *)ptr = *(MgB8 *)src;puts the destination address before the source's (riva, spells 79). c = p->unk14++or another read of the same member makes cse emit the game'smove a1,a0copies;(u16)q->unk4 + (rand() % n - C)instead of.. - C + rand() % nkeepsCfrom being hoisted into a savedli; vector initialisers invx, vy, vzorder schedule closer to the game than m2c's order (tifa, titan, spells 79).t <<= 16; t >>= 16; t -= 0xF; t >>= 2;as separate statements gives the in-place chain (jibaku2 func_801B0D10); a block-scopeg = D + 0x400; D = g + (r & 0x7FF);keeps the game's add order (odin1 func_801B5D14);MgHalf D_801EBD60; D.v = kkeeps a laterlhu p->unk2after the store (sflea func_801B0F7C).- A pointer local assigned between a call and the arithmetic (
m = rand(); g = D_801DF4A0; t3 = m % 66 + 0x84; g[0] = t3;) puts thelaearly and keeps the pointer out of the saved registers; a deads = lencopy right after a call keepsmove s2,v0next to thejal; a second product computed into a temp early (y = (w2 * v.vz) >> 12) fixed themult/mfloschedule (conf func_801B0F00). - A pointer local assigned before the call,
b = D_80162978; q = &b[func_800BBEAC(..)];, puts thelui/addiubefore thesllwhere&D[f()]puts thesllfirst (hades func_801BA75C);i = 0;written afterq = &b[f()]inside theif, not before it, giveslui a0; addiu a0; lh v0; nop; slland lets reorg takemove s1,zerointo thebnezslot from the fall-through (saikyo func_801B0A68). - Store forms that stay where the plain form moves: a zero store between two stores
written as a one-field struct (
D_801DF4B0.v = 0) stays ahead of the loads (conf func_801B2350);((MgWord *)q)->v = b->unk4;keeps the*qstore after plain-global stores (thundg2 func_801B0224);*(s16 *)((u8 *)p + 4) = ax;stays early wherep->unk4 = ax;sank and changedax's register (s_beam func_801B0028); a cast store*(u16 *)&p->unk2 = n;keeps theshright after themultandninv0(vahamut2 func_801B4AE4); the chained cast store*(s32 *)((u8 *)p + 0xC) = *(s32 *)((u8 *)p + 4) = c1;stores +4 first and swaps the temps (sldfang func_801B04BC). - A frame descriptor's pointer store written
((MgWord *)&D_x[-5])->v = (s32)ptr;(or((MgWord *)0x1F800000)->v = (s32)D_x;for a scratchpad descriptor) lets theD_801517C0 + 0x70load float above it as in the game (atomic func_801B0B44, tbreath func_801B071C, heist func_801B048C);a.vy = p->unkC - 0x400 + p->unk10;gives the game'slhuorder andadduoperand order (heist);q->unk4 = 0;beforeq->unk6 = 0x96;fixed alhuregister (vahamut0 func_801B42F0). - Repeated sums used as call arguments stay expressions (
arg1 + 0xDwritten each time): naming them (y0 = arg1 + 0xD) put themove a1,regafter a ternary argument's branch, where CSE of the inline form keeps it before, as in the game (main func_80020B68, func_800206E4). if (c) v = 7; else v = 6;givesbeqz; ori v,6; ori v,7with the else arm in the delay slot, wherev = 6; if (c) v = 7;hoists theli(main func_80027408).- Reloads after stores through a request struct: making the globals read after them
volatile(D_8009A004 ... D_8009A014 in main/decls.h) gave the game's order exactly (akao func_8002DA7C; 39 overlays that use them were rebuilt and still match). - Cast stores through a global pointer (
*(s16 *)((u8 *)D_801EF1CC + off) = ..) reload the pointer and field stores keep it: the game's first three stores are casts and the rest fields (magic_vahamut func_801B25E4). A one-field struct store((MgHalf *)&D_x)->v = vbefore a call keeps the next loads before it where a volatile store does not (magic_ifleet func_801B301C). - A load the game puts above zero stores: read it into a local before them and store the
local after (
w = a->unk4[1]; .. rot[2] = 0; v[1] = w;; magic_whirl and magic_tornado func_801B0098). One local reused across statements keeps loads in source order where separate locals are hoisted (submar func_800A10E0). One shifted term of an OR chain in its own local right after its load (s = tw[1] << 15;) puts thatsllin the game's place (main func_80044FA0). (u8)n0 + (u8)n1instead of(n0 & 0xFF) + (n1 & 0xFF)moves the field-clearandafter bothsrls (snobo func_800A318C); a chained assignment split in two with the second field stored first, found by hc.py over the store order (p->unkE = -0x28; p->unk16 = .., magic_trainn func_801B054C).- A struct view of an address-only global,
((BtlQ6 *)D_800F9DA8)->id, moves itslhabove a store to the plain global next to it, where*(s16 *)D_800F9DA8stays below (battle func_800C5CC0). A one-field struct or[0]array view of a volatile global keeps later loads below its store but shares one hoistedlui/addiubase, where a plainvolatile s32extern gives alui/lwper access (snobo func_800B0ACC, battle func_800ACE88). A global read through a cast of a volatile neighbour (((s32 *)&D_80062D04)[2]for D_80062D0C) stays below stores where an array element or a volatile global is hoisted (main func_80045A24). Fields read through a struct pointer are hoisted above stores to scalar globals where*(u16 *)(p + 2)reads are not (highway func_800A5D6C). D_8012C3CC++; D_8012C5BC++;(not+= 1) with a locald = D_8012C400;read just before gave the game's three loads first (condor func_800B7874). Ans32 arg0copied intos16locals, the second copy moved just beforei = D_80100F30;, placed thelhandli t0,0x1f(snobo func_800B4CDC). Reads through(volatile u8 *)fix the order of printf argument loads (main func_8003F830).- One
u32temp reused for three byte swaps givessrlbeforesll(separateu16temps the reverse);d++after theq->r/g/bstores fixes ali/addiuorder;*(u16 *)&D_8012C6ECand((u16 *)&D_8012C6EC)[2]inline instead of a pointer variable move theluibelow the set-up of the call's address arguments (condor func_800B21A8). - The OT address read into a temp before the tag store (
z = D_801517C0 + 0x406C;thenfunc_80046794(z, pk)) moves itslui a0; lw a0before the store (magic_alex func_801B4970); mask constants assigned just before their statement inside a loop give the game's operand and load order (magic_hmoon func_801B05E8).tk = (r >> 2) * 4; tk += 0x70; tk += D;keeps(x * 4 + 0x70) + Dwith D loaded after the stores, where one expression reassociates toD + x * 4 + 0x70(magic_whirl func_801B0398). u8 ci = i;set before an inner loop and used asci + j * 0x10gives the game'smove v0,a3thenandiin thebeqslot;(u8)iin the index givesandi a0,a3,0xffat once (condor func_800A427C). A call and the load that uses its result as separate statements (r = f(); x = (u16)D[..] - 0x80; D[..] = x + r % 0x100;) keep the load after the call (magic_tupon func_801B3A08).- Still open: an add on a callee-saved register right before a call (
addiu s1,s2,240) sinks below thejalin our build where the game keeps it in thejalslot (battle func_800C2704, main func_80028930); a cast store*(u16 *)rc = 0changes the scheduling of a neighbouringsh(condor func_800A5B64). Anopright after anlhucan be the assembler's nop before ash sym(reg)macro storing the loaded value, not an unfilled slot (battle func_800B54B8). - Volatile globals: stores to
volatileglobals (lui at; sw) stay out ofjaldelay slots and move the next call's argument set-up to where the game has it; making the CdRead state globals volatile matched main func_80041D28, func_80041AFC and func_800418D8 (whoseblezslot then stays empty). A struct field store right before a call fills the jal slot only when non-volatile: with avolatile T *volatileglobal, cast the last store (((BtlSprt *)D_80062F24)->v = 8). - A one-field struct view (
((MainV *)&D_8009C6C0)->v,((HwW *)&D_x)->v,extern struct { MainCdr *cd; } D_8007054C) keeps a load below a preceding store where plainvolatilebreaks a CSE reuse; a volatile field store*(volatile u16 *)&p->s0 = 0stays ahead of a following load; a volatile read as an expression statement reproduces a straylhu(main func_80040CA8).if (a < (p[n] += K))compares the register holding the new value wherep[n] += K; if (a < p[n])reloads it;a > bagainstb < achanges which load comes first (big11). - Constants hoisted out of a loop come out in the order of their first appearance in the
source (magic_ifleet:
tag = ..beforergbc = ..). With six or more uses GCC 2.6.3 hoists a constant (0x30 in sprintf) into a saved register for the whole function. In a ring-walk loop the index increment matched only at the end of the body, after the calls (magic_hades func_801B40FC and its family, magic_tifa func_801B4F70). A pointer local for a cached scratchpad constant at the start of a block gives the game's order of constant loads; the first offset-0 store to a scratchpad constant goes through the cached pointer unless written through another base that nothing else uses (magic_tifa func_801B416C). x + 0xBE + rem(andq->a + (k*2 - 0x180)) is reassociated; a temp (t = rem + 0xBE; x + t) orq->a - 0x180 + k*2pins the order; a separates16 a = t;copy stops CSE foldingt - 2 - 12intoa - 14; a sum stored to ans16field and used again needs its own local or the field is reloaded (magic_hades). GCC folds a shift-add-shift of single-use values inside one basic block, not across a branch (magic_ifleet func_801B24C4). GCC 2.7.2 treats adivwith its zero check as one insn and hoists it and its loads; ado { } while (0)around the block before it keeps the order (submar func_800A6778).- GCC 2.6.3's first scheduler is a backward list scheduler:
work/spells19/dump.py TARGET WORK.c NAME -dSwrites its dump ("ready list at T-n"). Ties go by the insn's original order (the later insn is picked first and so ends up later), then by the number of insns that depend on it: the order of two independent statements decides which of two equal stores comes first, and one more use of a base register moves itslui(magic_dethfo func_801B09A0: the base pointer has two dependents in joker1's form and one in a plain form). Independent low-priority insns fill load stalls, which sank the adds below the call in main func_80028930. do { } while (0);around a statement is a scheduling barrier: it emits NOTE_INSN_LOOP_* notes, the first real insn after them cannot move and nothing crosses them (main func_80028930: one around the pointer advance and one around the call pin the y-adds to the call's delay slots). Port a twin's literal locals and wraps, not only its operations.- Extra stack stores before a call that has fewer arguments than the game stores are a
dead local array, not a many-argument call:
s32 v[3]; v[0] = p->unk18; v[2] = 0x4000; v[1] = 0x4000;before a 3-argument call gave the game's stores to 0x18, 0x14, 0x10 and left a3 unloaded (magic_dokufuki func_801B01E8, magic_dokueki func_801B01A8); the order of the assignments is the scheduler's tie-break. - A store through a volatile cast,
*(volatile s8 *)&D[i] = f();, stops GCC reusing the stored value for a laterD[i]read: the game'ssbthenlb(a volatile load or a struct view did not; battle func_800ABB0C). sched.c keeps a load below an earlier store to another constant address only when both are volatile or an address is not constant (highway func_800AB738: struct views, array views and a volatile store alone failed). reorg stops its delay-slot search at a volatile insn, so a constant set after a volatile load cannot fill the slot before it (main func_8001E040); reading the global through*(const s32 *)&D_80062FC4lets an earlier store move after the load. - A
move v1,s3the game has in a call's delay slot comes from an assignment after the call (r = call(); v1 = arg0; if (r == 0)), not from an else branch (battle func_800ABB0C).y = 0;beforeif (h != 0)is moved into the preceding branch's delay slot and costs a word; inside the if it is not (condor func_800B8954). A beq whose slot the game fills from the branch target, a copy of the loop increment, needs the loop asfor (; i < 3; i++): reorg predicts the jump to the loop's test as taken, and ado { } whilefilled from the fall-through (battle func_800E2098). - A mask the game reloads at each branch target (
lui a0,0x7fffcopied into delay slots by the filler) comes from the constant written in the expression with no local:X = (void *)((D[1] & 0x7FFFFFFF) + ((s32)D - 4));(battle func_800B9568). Reading a value into a variable and subtracting in place (t = s->w0; b = s->s40; t -= b; s->m.t[0] = t;) givessubu v1,v1,a1, where storinga - cand thena -= cmakes CSE share the value and gives the game's load order (magic_vahamut2 func_801B6EF4). When a store's left side is complex (D->p[k][j].vx = f(..)) GCC expands the right side's call first and then the address: the array lvalue gives the game's base-firstadduandj*8 + k*128order, the cast form((MgSVec *)((u8 *)D->p + off))->vxgave the offset first (magic_garyu func_801B0480).*p & mthenp = p - 8; .. m + (s32)pgave an in-placeaddiu v1,v1,-8(battle func_800B9568). - sched1's
birthing_insn_pboosts only a producer whose destination register hasreg_n_sets == 1, hard registers included (ana3 = 0constant is boosted,a1anda2are not); a newly-ready predecessor carries the 7f000001 priority and is picked at once; all other ties go to the later insn, so a chain stays contiguous. sched2's priority is cumulative from the block start, and the first insn after ado { } while (0)is a barrier every later register user depends on at cost 2: whether it is ansll(cost 1) or anlbudecides whether a latersllsinks into a delay slot (battle func_800A4BA4). Combine merges a single-use argument temp into the call's move. - reorg's
fill_simple_delay_slotsrejects every earlier candidate once a volatile memory reference sits between the candidate and the branch (resource_conflicts_ptests the volatile flag): that leaves anopwhere an earlierliwould fill the slot, and avolatileglobal on the store between them decides it (magic_vahamut func_801B2DA8:D_801EF26A,D_801EF27Aasvolatile s16,w = u; D_801EF27A = w; D_801EF26A = w;). A volatile store can pin an order too (the 0x78 store volatile, the table load into a local first: main func_80032614's tail). - A plain scalar global is a non-struct MEM, so the scheduler lets its load rise above
stores to array elements (
mem/s); reading it through a one-field struct view at an address a few bytes lower (extern struct { s32 pad; s32 idx; } D_80062D00;used asD_80062D00.idxfor D_80062D04) keeps the load after the stores and the directlui; lw sym(reg)address, where(&D_x)[0]gives the same order with ala regaddress (main func_80045A24);volatileon struct members does not change the order. In the spawn templateD_80162978[D_8015169C].unk0 = -1; func_800D3994(g, D_8015190F[g][0], ..)the load written asD_8015190F[g][0]is independent of the store and the index chain floats above it; the same load asD_80151909[g][6](base symbol plus offset) keeps the store group first (magic_beast, garyu, spark). - In sched1 a load into a multi-set variable stays where the source puts it, but a load
into a single-set temp is dragged toward its use. Reusing the stored variable as the
destination of a later load (
p->unk34 = v; v = p->unk72;) adds an anti-dependence, so the load cannot rise above the store; with the other operand loaded into a multi-set variable before the store it gave the game's lh/sw/lh/lw order (snobo func_800A88A8). A fresh single-set local per statement fixes ties where a shared multi-set variable gets no boost:m2 = ifor a call argument putli a0,0x115first, and three more single-set locals matched battle func_800B9568 (755 instructions); a variable shared across unrelated places is one global pseudo that takes a conflict from every segment and is pushed out of v1 (per-use locals fixed func_800ABB0C's second region). - The position of the source statement that stores a spilled value decides where sched2
puts its reload:
q->col = rgb;moved earlier moved thelwto the top and removed anop(hmoon, smog2). Ado { } while (0);wrap raises a variable's reference count and is also a scheduling barrier, and it can change control flow when it wraps anif/elseas a whole (the branch layout flipped): search by allocation first (work/spells87/prio.py), then by score, because the two can disagree. - sched1's memory dependences (GCC 2.7.2's sched.c):
(plus reg symbol_ref)addresses of two different arrays are independent, so a load rises above a store; a field at a nonzero offset from its base symbol is(const (plus sym off)), for whichfind_symbolic_termreturns 0 (CONST is rtx class 'o'), somemrefs_conflict_passumes a conflict and the program order stays. Writing the store through a LOWER base symbol with the field at +0xC (D_800F5E5C[i].a = 0forD_800F5E68[i].a, a work-file typedef with the s16 at +0xC) kept it before a later load (battle func_800AEC10); a one-field struct view of a scalar global (((LamW *)&D_801517C0)->v) read after a struct-pointer store keeps the load after the store (magic_lamu func_801B24A8: the whole loop shape followed). A pointer register is known to sched1 only with a single set and a REG_EQUAL note; a two-set pointer is unknown, so conflicts are assumed. A load and a store of different symbols are independent (a wrap on the statement between them, or the same symbol for both, gives the game's order); a stack store before loads through a register pointer gets a highref_countand cannot sink below them: write the stores of the loaded values first and the stack stores last (magic_tifa func_801B5C74).D_x[D_n++] = i;asD_x[D_n] = i; D_n++;gives the game's store order. - Reversing the arms of an
if(if ((b ^ a) < 0) { w = a + b; } else { complex }) made reorg fill thebltzslot from the target where the other arm order was refused (snobo func_800A88A8); a quotient kept in its own variable (q = (i << 12) / 16) lets reorg fill thebgezslot from the join (magic_garyu func_801B02B0);ch = ch + 1;(a second set) withmask = 0;as the first statement putlui/addiu s1beforeli v0,0x101(main akao_menu_sfx_start);move a0,s0; j L; sh v0,N(a0)appears when the final call is duplicated in the first path instead of shared (condor func_800B4060).tools/work.py putkeeps the old near-miss body under#elseof#ifndef NON_MATCHINGwhen it replaces one. - The lower-base-symbol alias works for loads too:
D_800F5BE0[arg0].b[0]forD_800F5BE1[arg0][0]keeps albuafter a store toD_800F3A04[arg0].awithout a do-while barrier (battle func_800A4BA4); it only works for register-indexed addresses (for a constant-address scalar the const form just gets anlathat cse shares between the store and the load). sched1 never boosts an insn whose destination is a SUBREG (s8 t = arg1 + 0x20sets(subreg:SI (reg:QI t))), so it floats to the top of its block. A multi-set pointer loses to a single-set copy: in condor func_800A5B64 the multi-setp = D_80129F34load floated abovemove a0,zero; a fresh single-setu8 *b2 = (u8 *)D_80129F34; p = (CondorCell *)(b2 + 0x5330)is boosted, so the load lands right before the call. - wrapall on a draft that has no wraps at all found
do { return *p; } while (0);for battle func_800DDCE8 (wrapping the final return changes sched2) anddo { off += 0x34; if (++i < n) goto loop; } while (0);for the loop registers of battle func_800B5AAC (i=a0, off=a1): run it on a plain draft before hand-placing wraps. - A volatile STORE between a candidate insn and a branch does not stop reorg from filling
the delay slot with the candidate, a volatile LOAD does: with the struct non-volatile,
the stores written as
*(volatile s32 *)&r->b = -1and a plaink = r->a,li t0,3went into thebeqslot (battle func_800A5AC8). A store through a struct pointer (typedef struct { s32 *p; } MdPtr; q->p = ...) does not conflict in sched1 with a later load of a plain scalar global, so the load rises above it; the same store throughs32 **qkept the load below (magic_mod func_801B0994). In sched2, insns of equal priority are taken in insn order even when the other has the higherref_count(snobo func_800AAB88:move a1,s2with count 1 beforeandiwith 2). - cse1 folds every
q + constload whose result goes straight into a register store into an absolutelui; lhu %lo(sym)access, even after a volatile asm, so the game'slhu -48(a3)/lw 4(a3)through a base register is not reachable that way; a load that is itself an asm operand (q[-4]) is not folded (submar func_800A7FC4, 2 insns left). Reorg fills abeqzslot with anandionly if the shifted value is in a different register from the compare result:x = z & 0xFFFF;as the first statement insideif (lim < y)does it (submar func_800A9130);i = 0;before theif, withi++as the first statement of the do-while body, putsaddiu s1,s1,1in thebeqzslot (u32 igivessltu) (field func_800B0618). Wrapping only one store in a do-while pins itslui/oriafter the next store. - A pointer returned after two stores while it lives in a stack slot:
arg0->cnt = idx; arg0->prim = p; return e;givessw; sw; lw v0where the game haslw v0; sw; sw. The .sched2 dump shows the load marked true-dependent on both stores because after reloadspis not treated as a fixed base, so the game's RTL had the move into v0 before the stores; a plainr = e;is removed by cse and combine, andgte_useor a do-while(0) around it does not help. An empty volatile asm that copies the value (gte_copy(r, e):=r(r) :0(e)) keeps the copy where it is (magic_satan func_801B11F8); a tied=r/0pair in a volatile asm reloads its input before every other operand whatever the operand order, and the volatile asm blocks any other load from moving above it, where a non-volatile one lets sched2 sinklw v0below the stores. cse does not reuse an HImode load across a conditional branch: a secondarg0->vB8.vzafter anifis re-read from memory; held in a local it is not. - Writing the tag store of a packet through a struct member (
((MgPolyT *)pk)->tag = ...) lets sched1 hoist a global load above it. A scratchpad store likelui at; sw v0,0x1F800088is not a plain constant store: explow.c forces constant addresses into pseudos, so cse shares them with later call-argument constants; the game's separatelui t0/lui a0per argument means those pseudos got no hard register and reload rematerialized the constant, which is why such a function head only matches once the loop pseudos take the s registers first. Tail-duplicated call blocks in both arms of anifare merged by the late jump pass (magic_brizag2 func_801B498C is written that way). - A
do { } while (0)around an init block is a scheduling barrier for the first insn after the loop-end note (that insn depends on every pending store), so a store written inside the wrap cannot sink below the next load; without the wrap the schedule is a different one (magic_tifa func_801B5C74). cse.c of GCC 2.7.2 does not flush its table on a volatile asm (it only makes ASM_OPERANDS costly): an empty clobber asm after a call does not stop a value computed before the call from being reused after it (main func_80021F58); the clobber macros steer allocation only.(x << 6) + 6followed by+ 0x20folds to+ 38in fold-const:cnt = 6; ... ((x << 6) + cnt) + 0x20keepsaddiu v0,v0,6andaddiu a1,a1,32apart (limtmenu func_801D042C). A colour wordcol = (g << 16) | ((g << 8) | K) | g;in one expression foldsg << 16into a later shift, three single-set temps (c16 = g << 16; cv = (g << 8) | K; col = c16 | cv | g;) reproduce the game's head (magic_osen). - A
movethat the game keeps before a store but ours puts after it: sched1 boosts a producer whose variable has ONE set (reg_n_sets == 1,birthing_insn_p), which is what happens to a single-set pointer or copy that is live out of its block (chars = D_8009C738;landed after the first loads; themove v1,v0of a call result landed after the store in savemenu func_801D06B0). The fix is a variable with TWO sets that is live out of the compare block (ret = f(...); D_x = 0; if (ret == 1) { ret = D_y[0].row; ... } else { gte_use(ret); ... }: the second set in the then arm reusesretas the row temp), or assigning the pointer right after the first call;gte_use(ret)in the else arm stops combine from merging the copy into the branch. A call with no argument (func_8001DE70();) lets reorg steal the else-armli a0,0x32into thebeqzdelay slot, passing 0x32 in the then-arm does not;i++;orys += 0xC;written AFTER a call is moved by sched1 above the call into its delay slot; the same call written in BOTH arms of anif(f(0x10, 0xB, A, 7)againstf(0x10, 0xB, B, 7)) gives the game's shared jal with the constant argument in each arm and a filled delay slot. A single-symbol alias makes cse share the address register of many scalar globals: name one lower-address symbol that decls.h does not use (extern u8 D_801D8AAA[]) and read each global as an element (*(s8 *)&D_801D8AAA[1],*(s16 *)&D_801D8AAA[0xA]), or give a block of cursors one struct array (SvCursor D_801E379C[], 0x12 bytes each:D_801E37A7is [0].row): that gave the game'slui/addiu s1,...; lb a1,0(s1)andaddiu a0,s0,97/addiu a0,s1,-15(eqipmenu func_801D0BD0 197 to 109 words, savemenu 124 to 49). gte_use(i);between two stores acts as a barrier in sched1: it stops the scheduler from pulling every store after the argument moves (rect[0] = 0; gte_use(i); rect[1] = 0;putsh zero,32(sp)first in cnfgmenu func_801D080C's post-loop store block). Agte_use(icon)right after a call keeps the single-setmove s7,v0of its result from being boosted down toward its use, so thesll/sraof an argument lands after thesw v0,16/20(sp)stores as in the game (eqipmenu func_801D1D5C);gte_use(id)right after a load orders it before the next load (both loads are boosted and the first one ready is placed last). A movable that loop.c hoists (r = 0at the top of a loop body) is emitted in loop order: it lands last in the preheader only if it comes after the other movables, and one behind a conditional branch is not hoisted at all: compute the address unconditionally first (q = D_x; p = q + c; r = 0;;p = &D_x[c];as one statement made the sll/lui order wrong): main func_8003DE9C and func_8003DFD4.- A load of a struct member does not rise above an earlier store to a struct-typed global
in sched1 or sched2, a load of a scalar global does (
MainBox D_801D88B8keptlhuafterD_801DF6C8.f0 = 4, eqipmenu func_801D54B0). A shared pointer variable that several switch arms set (cp = &D_801DF673) is multi-set, so sched1 assumes it aliases a later global load and keeps source order; ONE POINTER VARIABLE PER ARM (cp1..cp4) lets the load rise above thesband gives the game'sli v1,N; sb v1,0(s0)tail that cross-jumps (62 to 40 lines, eqipmenu func_801D5BD0). A call written in each switch arm instead of agoto, with the constant held in a variable (kc = 0x35; y = i * 0x2A + (D_801D88CC * 5 + kc)), makes the jump pass cross-jump the shared tail like the game (without the variable fold reassociatesyb + (dd * 0x2A + 0x44): 77 to 25 lines);if (mode == 0) {...} else switch (mode) { case 2: ...; case 1: ... }gives the game's layout where a three-case switch makes another compare tree;gte_use(b)before a slot read stops sched1 hoisting that load above thebchain. - What cse does with stores (GCC 2.7.2's cse.c:
note_mem_written,find_best_addr): a store through a struct member or areg+constaddress does NOT invalidate scalar globals in the table, only a store through a plain-register address does (that givesaddiu 64plus0(a0)instead of64(v1)). A pointer to a struct-array element at a constant address (cu = &D_801DF590[3]; D_8009CE60[cu->top + cu->pos]) folds to directlui; lhreads in cse and a later store through an array element invalidates them: that gavelw s0,64(v1)/sw v0,64(v1)and the reload of both cursor fields after the store (eqipmenu func_801D6C2C), whereD_x[3].topwritten directly gave a hoistedlaand extra frame and an asm memory barrier shared theD_8009CE60base in a register where the game re-derives it withlui at. cse follows a taken branch when the else label has one use and a barrier precedes it:else if ((&D_80062D7E)[-1] & 0x20)gives the game's reload of a button word, a differently-formed address stops the reuse. - A shift (or any single-set result) that the game has in a CALL's delay slot with the
argument move ahead of it (
move a0,s4; jal; srl s1,s1,9), where ours hasjal; move a0,s4 (slot); srl: sched1 keeps a pseudo whosereg_n_calls_crossed == 0from moving below the next call (sched_before_next_call) and boosts a single-set result (a birthing insn) to the priority of the call that was just scheduled, so in the backward pass the shift is picked right after the call and ahead of the unboostedmove a0; reorg's backward scan then takes the insn nearest the call into the slot. The source form is a FRESH single-set variable that is never live across a call anywhere (rx = v2; if (rx != 0xFFFF) { id = v2 & 0x1FF; ry = (u32)rx >> 9; ks = f(id); ... rc = ry; g(..., rc, ...); }): a function-level variable such asrcthat lives across calls elsewhere does not work, cse merges a second variable that holds the same value (the compare and the shift must read the same freshrx), andrc = ry;before the third call givesrcits references back; declare the fresh variables at the end of the list so that no other pseudo number changes (itemmenu func_801D0E80). In reorg.cstop_search_pstops the backward scan at any asm insn, so a call with an asm right before it takes its slot from the forward scan. A free statement written after a call (rf = 5;) is hoisted above the call by sched1; two identicalrb = 0;sets before twoif (rg != 0)guards let thread_jumps send the first guard to the end (a separate counter variable for the second loop keeps the branch target); the aligned diff tools that normalise branch addresses can hide a branch-target difference. - A
move a0,zero(or any argument move) that ends up last in a block where the game has it first: a multi-set variable (ra = rg * 8; ra += tbl;) keeps thesllafter the move; a FRESH single-set variable declared last (rq = rg * 8 + (s32)tbl;) is boosted by sched1, thesllthen goes ahead of the unboosted argument move in the backward pass and the move ends up first (mgicmenu func_801D0490). A running offset written as `k = i- 0x440;
at the top of a loop body, orrb * 0x14 + (s32)D_x, makes loop.c emit its init after the hoisted constants (the game'smult; move s1; li s4,0xff; move s0; sra; mfhiorder);rd++written once after a whole if/else-if/else chain, not in every arm, puts the increment in thejdelay slot and lets the two arms cross-jump;f(0x64, expr)written in BOTH arms of anifwith the expression inline and no variable gives temps in v0/v1 and a cross-jumped tail; a fresh variable for a short result declared last (w = f(...), thenw / 2 - k) puts itsmove s0,v0in the next call's delay slot; a hoistedli 8of two identical calls is merged and spilled by loop.c so reload rematerialises it asli t1:do { k5 = 0xCE; } while (0);in the first arm brings back the game'sli v0,8` before the stores.
- 0x440;
- sched1 can pin a stack store behind loads: in the
-dSdump a stack-argument store (li v0,7; sw 16(sp)) has REG_DEP_ANTI on loads through an unknown pointer (agte_copynresult, any non-constant pseudo) because sp is not a fixed base: whether the base is a known symbol (a single-set pointer, which cse1 gives a REG_EQUAL note) decides it: a plainwp4 = &D_801D70A6;with the field read as*(s16 *)((u8 *)&D_801D70A6 - 2)lets theswrise above the loads and stays register-relative as-2(s0), wherewp4[-1]folds to absolutelui; lh(cse1 folds areg + constload address only when the register has a known constant value; a bare-register address (offset 0) is never folded). A multi-set user constant such asksmakes a stack-argliUNBOOSTED in sched1 and it floats to the top of the block ahead of the a0 move, while a literal in the call is a boosted single-set temp that stays next to itssw; a single-set user constant at the function top (w = 0x30;) is boosted and sinks past the first call: a LIVE no-op second set (gte_copyn(pb, pb)) makesreg_n_sets2 and thelamoves up into a load shadow (a dead pre-set such aspb = 0;does not help: it is deleted before sched1). An empty volatile asm that reads a value (gte_use(y1)) is a ONE-WAY barrier in sched1: it orders a value chain before the next load without changing the code. A temp that has two sets in different blocks is not boosted and lands early in its block; a constant stored on the stack that loop.c would hoist stays local if its variable has a dead first set in the loop body. - Arms of a switch that end with the same call (battle func_800B1D48): the game has NO
shared
push:label: every arm ends with its own call (D_800F4AC4[11] = x; func_800B16D0(N); break;); jump.c's cross-jump, which runs AFTER reload and sched2 (toplev.c:jump_optimize(insns, 1, 1, 0)), needs two identical insns before two jumps to one label (the store plus the call insn), so the arms keep their ownli a0,Nand the compute insn lands in thej Lslot; witha = N; goto push;only the store matches and nothing merges (28 shape lines to 0). It also means that shared store tails need the same HARD registers in every arm: the allocation decides the tails (block-local temps take the lowest free register before a global variable is allocated;gte_clob_a0()between a temp's load and use moved it from a1 to a0). fold-const.c turnsx & (1 << i)into(x >> i) & 1: keep the mask in a variable (ym = 1 << i; x & ym) for the game'ssllv/and; reorg'srelax_delay_slotsturnsbnez top; j endintobeqz end; j topwhen no label lies between: an emptydo { } while (0);after the outer loop prevents it (it adds 2 weighted references to a variable:gte_usetwice restores the order); a fresh single-set variable per arm for a call result that crosses calls puts theandiin the nextjal's slot; a loop pointer copyt4 = D_x; m = ((T *)t4)->mask[0]; q = t4;keeps the game'slw v0,V; move a1,v0; two loads ofV[1]come from a store toV[11]between them (a store through V invalidates cse's memory):c = P[V[1]]; V[11] |= c; t6 = V[1] + 1; V[1] = t6 + z;. calls.c expands register arguments first, then stores the stack arguments, then loads the registers, so amove a1,...after a conditional stack argument is the natural order; calling through a cast prototype withs32arguments removes thelbuandandi 0xFFFFthatu8/u16prototypes add. breakorreturn 0decides which copy cross-jump keeps: jump.c's cross-jump (after reload and sched2) merges identical tails and the chain head is the last jump in program order:return 0arms are redirected to the end label one by one in forward order, so each later arm merges into the FIRST copy;breakarms are all in the chain from the start, so earlier ones merge into the LAST copy (battle func_800A8E84: four cases matched only afterreturn 0becamebreak). cse.cnote_mem_written/invalidate_memory: a QImode store invalidates every cached scalar load, HImode and SImode stores throughreg+constinvalidate only struct mems and varying-address mems, a pointer pseudo set before a loop isvarying; by cse.c a store through a struct member or areg+constaddress does not invalidate scalar globals, only a store through a plain register does. A switch with an emptycase 0: break;gives thebeq 1; slti v0,v1,2; bnez end; li 2; beqshape. A compound assignment for a head (D_80062F4C = A4; D_80062F4C |= A5 << 8;) reproduces the game's twosh v1,520(gp)and the load order. A literal0x1C6B0added to a pointer folds into the address (lui at,2; sb -14668(at)), a held constant (kk = 0x1C6B0;before the loop) givesaddu v1,v1,t7; sb v0,4(v1). Base-first adds:*pb + *pi * 0x28always givesaddu prod,base(expand_binop puts a register ahead of a MEM operand); the game'saddu base,prodcomes from an ARRAY_REF on a struct-array member (((ChoBufZ *)*pb)->r[*pi].qwithtypedef struct { u8 pad0[0x4010]; ChoRowZ r[1]; } ChoBufZ).- A VOLATILE insn between two statements keeps combine from merging across them:
can_combine_prefuses to merge across a volatile insn (thevolatile_insn_ploop), sot &= 0x1F; gte_use(t); w = t;(an emptygte_clob_t7();works too) keeps the zero_extend of a QImode register as a secondandi s1,v1,0xffwhere every asm-free form folded it into oneandi(battle func_800DC0CC: about 25 forms had failed). Per-arm calls and cross-jump: jump.c's cross-jump first triesfind_cross_jump(jump, JUMP_LABEL, 1)where ONE equal call insn before the jump suffices: it redirects the jumps to a new label placed before the last arm's call, and the loop over the other jumps to the same label is then skipped because the new label's uid is at leastmax_uid, so the arms' bodies are never merged: writing the call in EVERY arm keeps two identical 50-insn copies of script cases (the game's layout), a sharedgoto calllabel or one call after the switch merges them.g1 = f(..); t = D_x[..]; gte_clob_t7(); gl = g1;in each arm keepsmove s3,v0after thelbuinstead of in thelwshadow;wid += w;written after a call thatwidcrosses lets sched1 hoist the add back above the call, so its priority no longer ties with the argument move and the move lands first in the block. sched1's birthing boost applies only to insns that become ready through a dependent inside the same block: pre-loop constants and pointers whose only user is in the loop are not boosted and their preheader order is creation order; a higher priority places an insn earlier (gte_use(kk)afterkk = ...movedkkbeforepb/pi). The game's packet stores are STRUCT accesses (((BtlTileZ *)D_x)->x: the stack-slot reloads and the global reload come in the game's order, where M2C_FIELD forms are plain derefs). - A PSY-Q primitive (sprite, tile) is written in the macro order:
setXY0,setUV0,setWHare stores of x, y, u, v, w, h. A QImode store invalidates cse's cached load of a global index and an HImode store does not, so that order fixes which stores share one load of the index (battle func_800DA380: 265 to 201 aligned lines). The ordering-table links of such a builder are inline SINGLE-SET temps, not user pointers:((BtlTag *)&D_800F5194[D_800F1994].s[0])->addr = ((BtlTag *)arg0)->addr; ((BtlTag *)arg0)->addr = (u32)&D_800F5194[D_800F1994].s[0];(a multi-set user pointer shared by several arms is not boosted by sched1 and its address chain rises above other stores; 171 to 80 lines and the game's exact insn count). Each tile pointer is a fresh variable per site (t1 = &T[idx]; ..; t2 = &T[idx]; ..: register-only 98 to 40). - sched1 (battle func_800BEA38, func_800BCB1C): ties go to the higher LUID, and a boosted
insn is picked as soon as it becomes ready. Memory conflicts: a store to
(const (plus sym off))(a field at a nonzero offset of a base symbol) conflicts with every(plus reg sym)load, while struct-array loads at varying addresses do not conflict with fixed-address scalar stores, so struct-array reads rise above scratchpad stores and a field store through the lower base symbol stays before a later load. A table lookup is written with fresh single-set variables per site (chK = IDX * 0xB9C; bbK = sp->p[pos++]; bsK = (s32)D_8015190F_x; LHS = *(u8 *)(chK + bsK + bbK);): thelalands after the multiply chain and is boosted by LUID order. A comma expression(tmp = lookup, LHS = tmp)expands the lvalue address first (the three tails EC/EA/E8 of func_800BEA38 then cross-jump like the game).
- Register choice follows the order variables are declared and how long they live; caller-saved temporaries are allocated in declaration order. A C variable has one register for the whole function: reuse one variable where the game keeps one register, give temporaries their own single-use variables.
- An address kept in a register was usually a pointer variable (
p = &x; ... p->a). A global re-read through a register several times is a pointer variable to it. - A local used once (
mask = D_x;) changes registers where CSE of the global would not. - A remainder written
i - i / 91 * 91gives the game's registers (or saves amove) wherei % 91does not. - A loop bound kept in a register (
li t3, 31hoisted,sltin the loop) is a local:n = 31; for (i = 1; i < n; i++). - A table value re-read into the same register:
c = byte; if (T[c] != 0xFF) { c = T[c]; ... }withcans32.m = 0xFF; if (c != 0xFF) m = T[c];lets CSE carry values across the join where the game re-reads: if/else with ans16 m. - A copy
orig = t;lets CSE givet's usesorig's register: assign the result back tot(t = (t * n + orig * (0x100 - n)) >> 8; return t;). &D_xkept in a register for several stores: a pointer locals16 *p = &D_x, even when neighbouring globals still uselui $at.for (i = 0, n = 0; ...)givesiits register beforen.- A loop-invariant flag in a saved register:
c = (a & 4) ? X : Yinside the loop. - Local allocation runs before global allocation: temporaries local to one block that
live across a call take
s0,s1... first; one that spans a branch becomes global and waits. Reusing one variable (a pointer for every spawned particle, oneifor a clamped value and then the loop counter) raises its priority. - A
return 0whosev0 = 0is hoisted to the top of its block holdsv0for the whole block: if/else with onereturn 0at the end frees it.r = cond; if (r) ...gives the result variablev0and keeps it off a dying argument's register. a = 1; if (c != 0xFF) a = f();keeps 0xFF in a saved register across the call where the if/else form reloads it, as the game may.sll 16; sra 16of a call result into a saved register: one single-set variable per use,s32 x1 = (s16)f();. A flag that must sit in a callee-saved register across a call:flag = 0;right before that call. The first scheduler moves an instruction that sets a single-set pseudo live across a later call to just before the call (its delay slot); a pseudo set twice is not moved.- Two same-width accesses of one global in an extended basic block can share
la sN, symeven across calls; a second name for the same address (D_8010C35EforD_8010C35C + 2) avoids it. - When nothing else moves a register, a no-op
q++; q--;after the pointer's last use, or a separate single-block temporary for a copy (a temporary used in other blocks coalesces with its copy), changes the priorities. - A
u8copy defeats CSE:g = f; if (c) g = f + 1;withs32 gbecomesg += 1in f's register;u8 gkeepsmove a1,a0/addiu a1,a0,1. The same value writtenh * 2orh << 1,-t << 7or-t * 0x80, changes temp creation order and can swap saved registers: try arithmetic equivalents early. - Only element 0 of an array or struct global gets a shared
lafor repeated accesses (offsets 2 and 4 get their ownlui); a struct global used for related offsets (&D_A.m,&D_A) keeps its address in a saved register, two symbols for the parts avoid it.*(u16 *)&G |= cand pointer locals keep the address in a register: the first access through it, later ones folded tolui at. - A scratchpad pointer assigned at the top lands in
s0with itsluiafter the last call; assigned right before use it takes a temporary.mp = &m;just before the first call that uses it, inside a loop body, puts&min a saved register hoisted before the loop. - A constant kept in a register (
ori t0, 0x4D; addu v0, t0, v0):kx = 0x4D;before the loop andkx + vwith the constant first;v + 0x4Dgivesaddiu. % 16contains a branch, so arand() & 0xFFFtemp around it is function-wide and takes a register afterp; with% 6it is block-local and getss1beforep.- Loop-invariant values in
s16locals give the game'smovecopies before the loop (s32copies do not); an explicits32 k = i;copy of ans16counter takes the lower saved register. - Spawn blocks:
id = arg0;insideif (arg1 != 0)putsmove t2, a0in thebeqzdelay slot, a second block gets its ownid2 = arg0;; blocks of different kinds need their owni,n,p,s, blocks of one kind can share them. - Variables set in several places are allocated after the block-locals: one variable
reused for two values (
m = ...; p = ... m ...; m = ...;), or a two-stepv = x; v = v | y;in one case, moves registers for a whole switch. Ones16counter reused for two loops, and inner-loop temporaries reused after the loop, give the game's s-register order where separate variables swap them. - Wrapping a few statements, or a whole run, in
do { } while (0);changes the weight of the pseudos inside and can flip the allocation order (work/battle19/wraprange.py tries every contiguous range). The;; N regs to allocate:line of a-dgdump gives the global allocation order directly. - Shared address registers: a plain scalar global read is a direct
lui/lw; struct members and cast dereferences go through an address register that CSE shares across calls (*(u32 *)&Ggiveslw a0, 0(s0)after each call;((T *)&D[i].f)->vxgivesla sym+16; addu; lhu 0(v)whereD[i].fgiveslui at; addu; lhu sym+16(at)). An earlier store toD_x+2makes later offset-0 accessesreg-2and breaks the sharing: declare that field as its own extern.base = (u8 *)D_x; q = base + 0x1F62; p = base + id * 0x34;shares one base register. p++written as its own statement raises the pointer's reference count and can flips0/s1; two frame-address variables instead of one reused pointer change the temp registers.- Parameters used in place (
arg1 += 8,arg2 = arg2 % 0x1000; if (arg2 < 0) arg2 += 0x1000;) instead of copies keep their saved registers and the prologue copy order;s16 mode = arg0;at the top gives an extramovecopy of a parameter. One variable reused for two values (v = f(v); if (c) v = 0; r = g(v);, or onehfor a clamp and a laterx % N) shares one register;p->e -= p->e / 4; p->f += p->e;written directly kept the registers ans16temporary swapped. - A clamp written as one nested ternary with no user locals (
p->w = p->w < 0 ? 0 : (D < p->w ? D : p->w);) kept registers that if/else with locals swapped; elsewhere separate locals per block matched. Two typed source pointers for adjacent loops matched where one sharedu8 *srcflipped registers. Goto loops lower the loop weight and can flip which variable gets the lower saved register. - HImode narrowing:
lh v0; move v1, v0; slti v0, v0, Kis the then-arm ofif (x >= K) { c = C - f; c <<= 4; } else c = K2;withs16 c((C - f) * 0x10has no copy); storingk << 4from ans16 kinto a byte givessll v0, s0, 4,k * 0x10givessll 16; srl 12.f((u16)(i | 0xC600))loadsli -14848,j = i | 0xC600; f(j);givesori. .lregdumps' "used N times across L insns" give each pseudo's priority,floor_log2(N) * N / L; it explains saved registers rotating between a few long-lived variables (field func_800A8F88). Spill slots follow pseudo-number order: parameters first, then locals in declaration order (swapping two declarations swapped 0x28 and 0x30); one variable reused for a computed value can keep it in a saved register where a fresh one spills.- Reusing a variable raises its priority: a loop counter reused for a later value, an
outer variable reused as a second loop's counter, or one local for a value set before a
call and then a loop counter put them in the game's saved registers (eqipmenu
func_801D3490, main func_80019978, battle func_800B4E30). The other way, a separate
counter for case loops (condor), one variable per loop (
j1...j4) so a parameter keeps its argument register (field), or oneqfor the first spawn blocks and anrfor the rest (reito func_801B1D74) lower a shared variable's priority. A deadi = 0;in an earlier block can change which register a shared loop counter takes. - Near-identical blocks each with their own block-scope locals get the same registers;
shared function-level locals change the priorities. Clamp blocks comparing a
sign-extended
lhand then using it in halfword arithmetic in both arms need a separates16local per block (a shared one adds anlhu); store inside each arm. do { stmts } while (0);around the first statements of a loop body, orforinstead ofdo/while, flips allocation order (hmoon func_801B0B00, pink func_801B0C94); work/battle19/wraprange.py and work/spells26/wrap.py try every range. In ado/while,q->f = rand(); i++;keeps thei + 1temp out of a saved register.- Copies of old values written before the display calls (
oa = a;) go to saved registers in declaration order.rp = &rot;as the first statement gives theaddiu s6, sp, 0x60at the top,vp = &v;just before its first use a later register.m = &D_x; q = (u8 *)m + 1;gives a pair of saved registers for a struct and its byte view. - A join statement
s = arg0 & 0xFFwritten once after an if/else gives the delay-slot copy; per-arm assignments are CSE'd into amove.a = 8; if (k >= C) a = X - k;lets CSE share a baseluiacross the whole function (one more saved register, 8 more frame bytes); if/else or a ternary reloads it after the call. Packet links through a bitfield tag (pk->tag.addr = ot->addr; ot->addr = (u32)pk;) put0xFF000000in the game's register where the mask form swaps them. - Block-scope locals become local pseudos and get
v0..a3; function-level temporaries compete with the arguments (main batch 10). A temp shared by several statements takes a saved register across calls; one single-use temp per statement keeps it inv0(saikyo func_801B0A68). - A permuter run found a parameter copy
u32 addr = arg1;between two table loads that fixed the parameter-copy order and the saved register (main func_80037050). - A spawn pointer used in two blocks (a loop and a later
if) is allocated high; one variable per block put the loop's ins0(iyashi func_801B0A74), while hiwind func_801B05B4 matched with one sharedq. - User locals assigned in the game's order before a loop (
code = 0x6A; head = 0x02000000; layer = 0x40;) give the hoisted-constant registers; a user variable gets a lower pseudo than an expression temp, so it takes the higher register on ties (fubuki func_801B032C).one = 1; p = &D_x;as locals before a loop put the constant int2and the address int1; without the local the address is not hoisted (battle func_800A9DA0). tab = base + D_x; tab += 4;in two statements givestabmore references so it outranksidx(nadare func_801B11C4). A variable of its own for a middle loop's value stops it takings0(battle func_800A3ED0); reusing a loop counter for a call result moves it froma3tot2(battle func_800CD860).D_x++ / 32 % 3inline in a call argument keeps the post-increment temp as the dividend, adjusted in place (move a1,v0; addiu a1,a1,31); a namedt = D_x++does not (battle func_800A3ED0).- One variable per role (not one
v/t/nreused across blocks) keeps live ranges apart: it fixed three registers in battle func_800AF9C8, and one variable per clamp arm matched altema func_801B0850. Not always: one loop counter shared by three loops (with its own innerj) matched thundg2 func_801B0908, and one multi-setqfor three divisions in different blocks ties thesuburesult to the sign register and stops tail merging (fullcare func_801B0AB4). Try both. k -= 1;in place inside an if / else-if chain onkkeeps the game'sv0/v1and the delay-slotliwhere a tempk - 1swaps them (thundg1 func_801B002C, choco0 func_801B14A8).((MgScratch *)0x1F800000)->unkA = c = 0x80;keeps the constant ina0for a laterc - ...where a separatec = 0x80;does not (altema func_801B01E0). A named maskmk = 0x400040; if (v & mk)puts theluiearly in a delay slot (battle func_800AF9C8).if (1 << i & D) { n++; if (n == 1) ... }with a literal 1 shares one register for1 << iandn == 1and hoists the global load (faiga func_801B0D48).- Two
i == 0 ? A : Bternaries on ans16 iin one loop are merged by CSE across a call into a sign-extension in an extra saved register (frame 0x70 instead of 0x68); storing each ternary straight to memory,q->f = i == 0 ? A : B;, givessll v0,s2,16; bnezper test (rakuseki func_801B07E4, func_801B0A54). u16 *g = &D_x; *g += a * b;giveslui; addiu a0; lhu 0(a0); sh 0(a0)(rakuseki func_801B0C58);u = *g; r = p->unk2 % 2; u -= 8; u += r * 0x10; *g = u;with ans32 ugiveslhu; addiu -8where one expression givesli 0xFFF8; addu(rocket func_801B0D98).n = p->unk14; p->unk14++; D[f()][0] = n;avoids an HImode copy ofnbefore the call and its spill slot;p->unk14 = n + 1keeps both (reazer func_801B17F8).k = amp >> 1; k *= k;givessra s2,s4,1; mult s2,s2where(amp >> 1) * (amp >> 1)usesv0.D[i][0] += xon au16 D[][0x5CE]recomputeslui/addiu/adduper use as the game does;*(u16 *)D[i] += xshares one address (heart2 func_801B1518).pa = &ta[i]; pa->vxgivesaddu base,idxandta[i].vxwith a hoistedtagivesaddu idx,base(rocket func_801B0D98);i * 4 + (s32)pkgives(off, base)and&pk[i]the reverse (battle func_800C223C).- A pointer variable for a second frame descriptor (
frame2 = &D_x; ... (u8 *)frame2 - 8) withi++after the call putiins0and the pointer ins2(napalm func_801B07D4). Reload hands out registers round-robin: a spilled loop limit reloads intoa2, thena3(seald func_801B0074). - More on one variable per role: one
kfor two multiplier groups put the multiplier ina1as the game (spark func_801B0700); oner1...r7perrand()and onekper field avoidmove a1,v0copies (triangle func_801B0DC4); a separaterforrand()next to a function-widetavoided a saved register (mizufuki func_801B0E40). - Store of a call result after later work:
r = f(..); k = field / 65; D_x = r; g(k, k, k);keepsv0live through the divide and the temporaries ina1/v1(lasboss2 func_801B06DC);q = (x << 12) / 10; D_x = q;givessubu v1,v0,v1whereD_x = (x << 12) / 10;givesv0(h_blow func_801B01E0).p->f + (rand() % N - K)keeps-Kon the remainder (cometeo func_801B0C4C). a = D_x;read once and used as the index of two byte stores keeps the index register; reading the global each time reloads it after thesb(h_blow func_801B078C).ab = D_80151A24;inside the first block pluspb = ab + 0x28;keepsaddiu s0,s6,0x28unfolded where an inline cast symbol folds the constant into thelwldisplacement (h_blow func_801B0BAC).if (p->unk2 < 0xC) D = p->unk2; else D = (p->unk2 - 0xC) % 4 + 0xC;with no local giveslh a0; move v1,a0; locals swappeda0/v1or added 8 bytes of frame (club2 func_801B1468). Withs16 n = p->unkE;,p->unk6 += p->unkE;and+= ngive oppositeadduoperand orders (atomic func_801B0B44).- A constant-address pointer keeps
2($s)offsets only after a loop or label, where CSE loses the constant equivalence; in straight-line codet->vyfolds tolui; lh sym+2(spark func_801B0A38, unsolved). - A dead test with identical arms,
if (t + i + j) { f(); } else { f(); }, keeps values live across a call in saved registers as the game does: it survives allocation and jump2 cross-jumps it away; the permuter found the first form,if (t) { p->unk2++; } else { p->unk2++; }after the join (sting func_801B37F8, with a comment in the source). Use it only when the asm keeps values in saved registers that nothing reads. do { } while (0)changes the allocation order: aroundb = (MgTask *)D_80162978;it swapped the saved registers ofband&p->unk4(sflea func_801B17C8, found with wrap.py); around the statements of one if-chain arm it flipped a saved-register swap no declaration order fixed (timedmg func_801B0F74, found with the permuter).- One function-level
s32 kreused as a multi-set temp (k = p->unk2 <= 0; if (k) .., laterk = rand..) puts the loop temps ina1as the game does; declared and used once it stays inv0(conf func_801B05D0, func_801B0A40).u = p->unk2; t = u;thenu -= 10; ... u -= 5stays an in-placeaddiu a1,a1,-10wheret = p->unk2; u = t;folds tot - 15; a repeateda = 0in a later arm survives only if the earliera = 0sits inside its own arm (timedmg func_801B0DD0). b = D_80162978;inside the branch givesmove s3,a0;for (i = 0, b = ..; ..)orders the moves;(MgTask *)((f() << 5) + (s32)b)givesaddu idx, basewhere&b[f()]givesaddu base, idx(graviga2 func_801B1220, wpyu func_801B23C8, conf func_801B1D64). Two loops with a block-local angle each: one shared variable becomes global and swaps s0/s1 (graviga2 func_801B0EDC).- An 8-byte struct copy is
movstrsi(v1, a0, a1, a2 as scratch); a destination pointer used in two copy blocks becomes global-allocated and takesa2with the source ina1as the game (graviga2 func_801B1AB8). Constants kept in registers by chained scratchpad stores,((MgScratch *)0x1F800000)->unk4 = c8 = 8;(dethper func_801B11FC). - A dead
k = 0;after a copyn = k;keeps CSE from foldingnback intok, sonstays block-local and takess1withpinfpas the game;n = k;has to follow the first call or two address registers swap (blaster func_801B08FC). - Arms of an if chain setting a function-level
u, thenk = u;after the join, with address locals (mp = &m;,ep = ..;) also written after the join, gave the game'ss0..s3order (antlion func_801B2DF8). - A global struct pointer reloaded after a call and used for
addiu a0,s,0x10lands ina1only as a variable assigned twice:s = D; f(&s->m); s = D; s->m.t[0] = ..; g(&s->m);(gospel func_801B2D34, func_801B286C, func_801B2620). t = (t << 12) / N;in place on a multi-settputst, the temps and the colour in the game'sv1/a0; where the quotient is used once, a separate variable (gospel func_801B22E8, func_801B2D34, func_801B1A48 vs func_801B286C).- Two tests
t = p->unk2; if (t < K)in a row matchlh; move v1,v0; sltiwith ones16variable per test; one reused variable giveslhuor one register (bushin2 func_801B1D2C). Two spawn loops each reducing% 256want one function-level variable reused by both; separate variables add a saved register (lamu func_801B2050). - The dead identical-arm test again:
if (p->unk12) { ang = t << 10; } else { ang = t << 10; }raisedang's priority so it tooks0and the scratchpad pointers2(hakou func_801B0488). - A pointer variable for a leftover argument (
id = D_x; .. f(.., id, q), where the game leaves&D_xina2) changed which table pointer tooka1(bushin2 func_801B352C, found by the permuter). k = p->unk0; k = k * 0x10; e = D; e = e + k;andk = p->unk0 * 0x10; e = D + k;pick different registers: try both in each arm (hvshot func_801B0680 needs the split form in arm 1 and the combined one in arm 2). A constant localone = 1;withm & (one << i)keepsli 1in a register and theandoperand order (sennkoku func_801B0650).- Values stored into address-taken locals and then used in a dot product come from
separate
s32temps, or GCC reloads them from the stack;scale.vy = scale.vz = xstoresvzfirst; one local reused for dot, angle and scale kepts2(beam func_801B0774). do { } while (0)around three colour byte stores keeps theaddiu a0,s0,8argument after them (m_break func_801B0370); around a loop-init block it fixed a pointer/counter swap (aqua func_801B0254);do { sc->vx = k; *(s32 *)0x1F800024 = k; } while (0);after astore:label fixed a swap between the scale pointer and the task pointer (tornado func_801B0A1C, whirl func_801B0A08); aroundt = func_80042DA8(c) & 0x100;it fixed theandiposition (riva func_801B309C, wrap.py, with the permuter'sD_801F49AC = id = arg1;andint cforu8 c).u16 *tbl = D_x; .. tbl[1] / tbl[k]stops GCC hoisting&tbl[1]into its own register, and arms writtenif (k >= 2) {tbl[k]} else {tbl[1]}give the game's order (bioga1 func_801B0C8C). GCC 2.7.2:s = (MgScratch *)0x1F800000;assigned beforetbl = &A; if (flag) tbl = &B;kept the flag load behind the table address, with only the first scratchpad store throughsand the rest through the cast constant (beam func_801B0C40).- One multi-set
xshared by a call result and a loop temp (lv4jibak func_801B128C), andk = 0x17C0inside the loop withk = 0;before it (wep3 func_801B1514), keep the game'sv0copies andli a1; a tempk = D_8015190F[arg1][0]swappedk/nto the game's registers (lv4jibak func_801B128C, permuter). - Separate counters for a clearing loop and a later search loop (sdust func_801B3418,
death func_801B1D20), and
b = D_80162978; p = &b[f()], fixed the register order. - Block-scope temps
w1/w2in each arm, a function-levelqand cast stores*(s16 *)((u8 *)q + 4) = w1putqina1and keep the plain-global load after the stores (freeze func_801B13A8). Scratchpad pointer locals assigned at the top (sv = (MgSVec *)0x1F800060;) land in saved registers (mrain func_801B0A08, freeze func_801B026C). Single-element arraysD_x[0] ^= 0x80; D_y[0] += ..share onelafor element 0 (mrain func_801B0A08). - Reusing a variable for a second value fixed registers:
y = (x * x + z * z) / k;into the variable that held the averagey(queir func_801B0094, func_801B033C); the last tempang = rand() % 2560 + 0x800reusingang(garyu func_801B2AF4).n = t + 1; if (n >= 0x36) { n = t - 0x35; .. }shares one saved register between both values (catastro func_801B42A8). - A function returning its pointer argument (
return arg1;) keepsarg1in the lowest-priority saved register and stores throughv0(queir func_801B0ECC).d = k; scale.vx = d; scale.vy = p->unk16; scale.vz = k;put a quotient inv1(queir func_801B237C, still 4 words off). - A call result used by several stores stays in
v0only with its own block-scope variable; a function-levelqassigned in several arms getsmove v1,v0and swapsv0/v1with the temps (titan func_801B4910). A function-levelwused for one call result only also stays inv0(vahamut func_801B31D8). Several functions took their temps from separate block-scope variables (ax/ay/az,lo/hi) rather than function-level ones (ifleet, s_beam). extern struct { s32 t0; s32 t1; s32 t2; } D_801D3930; D_801D3930.t0 = ..; f((MgMat *)((u8 *)&D_801D3930 - 0x14), ..);givessw v1,0(v0)and a related-valueaddiu a1,v0,-0x14with the load/store alternation; scalar externs and anMgMat *mcomputed first did not (titan func_801B40A0).- Copy-first prologue: use the parameter in place (
arg0 = -arg0;); a separatedx = arg0puts itsmovein the branch delay slot (odin2 func_801B2F70). if (t < 10) k = 0x1000; else {..}puts the constant in thebnezdelay slot andkinv0, wherek = 0x1000;before theifgavea0(vahamut func_801B18F0);a = 0x1800; D = t << 10;instead of the reverse movedatoa0(vahamut func_801B1C48). Likewiseif (!(x & 1)) D.v = -0x64; else D.v = 0x64;through a one-fieldMgHalfglobal putsori v0in thebnezdelay slot, where a presetc = 0x64; if (..) c = -0x64;putcina0orv1; a second extern view at a lower symbol (extern struct { s16 pad; s16 v; } D_800FA664;) for the second store gives its ownlui at; shinstead of a sharedla(catastro func_801B1D00).- A byte global read after an
shstore as an array elementD_x[0]keeps thelbuafter the store (catastro func_801B2BA4, func_801B2C64). Divisors held in locals (kx = 23; kz = 28;) givedivwith them in saved registers (satan func_801B5388). - A function-level
qfor both spawn blocks with a plain&D_80162978[f()](no base variable) gave the game'ss0/s1split; a scratchpad base held in the loop counter variable (i = 0x1F800000;theni = 0;) matched;e = D_801D9860; e = e + f() % 137;loads the base after the call (ifleet func_801B1E58). - A signed division by a constant assigned to a fresh single-set variable (
u = (t << 12) / 60;) gives the game's in-placemfhi a0; addu a0,a0,v0; sra; subu a0,a0,v0; reassigningtadds a copy at the end (tupon func_801B2CD0, func_801B2760), whilet = (t << 12) / 5;keeps the quotient int's register (kujata func_801B5D88). A quotient used once inside an expression wants to stay an expression temp (tupon func_801B2A50). - One function-level
kfor the quotients of several arms, or for a quotient and a later value (k = (t << 12) / N; D = k;..k = 0x1000 - *g;), puts them in the game's registers,a1where a single-set variable tied tov0(vahamut0 func_801B5B90, func_801B493C; vahamut2 func_801B3904, func_801B606C; kujata func_801B5AE0, func_801B62C0). - A multi-set
tstops combine from folding(n << 12) >> 1inton << 11:u = t << 12; t = u >> 1;keepssll 12; sra 1; ans16 c = k;copy at the join givesmove v0,a0(kujata func_801B521C). func_8003B35C(m, s)withsitself as the second argument leaves the reloaded pointer ina1;&s->v8gives the other form (vahamut2 func_801B6868).func_800D44E8(&D_801F0310[i], m = &D_801F0B74[i])fixed which stepping giv getss2and whichs3(siva func_801B3E00).tp = &D_801DD634; *tp = v.vx; m = (MgMat *)(tp - 5)givesaddiu s0,v1,-0x14(odin1 func_801B65A0).D_801F2A44[off] = q[5] = q[6] = c;withq = D_801F2A40 + offmatches colour byte stores 4/5/6 (odin1 func_801B4DBC); chained byte storesp->u0 = p->u2 = t0elsewhere make loop-invariant copies, and separate stores in the game's order withu8 t0, a3give a per-armmove t0,v0(tupon func_801B3464).- cse.c
make_regs_eqvmakes the register that lives longest past the block the canonical one, sou = t; t -= Kbecomest = u - K; a constant in a spare variable (t = 4; .. *(void **)(c + t)) fixed it (phoenix func_801B39D0). - The pause flag in the loop counter or the call-result variable:
i = D_80062D98 == 0; if (i) {fixed a rotation between the counter and hoisted constants (alex func_801B359C),k = D_80062D98 == 0; if (k)withkalso the call result gave the multiply operand its copy (knights func_801B6CAC); both found by the permuter. - Random values:
ang = rand(); ang &= 0xFFF;as two statements swapss0/s1(phoenix func_801B1F80);r = 0; r = func_80042DA8(); a = r / 0x1000; a = r - a * 0x1000;putsrina1(sdust func_801B0DCC);t = rand(); t %= 0x600;with ans16 h = u * (t + w) >> 12;local gave in-place registers (hades func_801B9DD4);s16 t = rand() % 4hoists thei++of a four-iteration spawn loop (hades func_801B6C34). - One variable for several roles: a function-wide temp reused as the loop counter (
i = 0x1000 / n * a;thenfor (i = 0; ..)) shares the game's saved register (hades func_801B2D04); one function-levelkfor every quotient of a camera timeline's arms ands = constafter the call fixed saved-register swaps (knights func_801B9AA0, func_801BA604, func_801B9E4C, func_801B786C); with separate tempsw = k << 8; t = s * f2();, reusingwfor a later call argument (w = D_801517C0 + 0x4064;) fixed a swapped order (knights func_801BB548, func_801BB8C4). Storingm.t[1]in each arm instead of through a shared local gave the game'sv0(tifa func_801B135C). t = (t << 12) / 57; t = (t * 0x300) >> 12;as in-place statements keeps everything inv1; the same shape with<< 10wants the single-expression form (knights func_801BBA64, func_801BB6EC).- Merging two user variables into one (
nintos,iintoc) gives it two sets: a variable with a single constant set lets combine turns + 0xD0intooriwhere the game hasaddiu, and the merge gave the game's saved-register priorities (matra func_801B1558). One function-level temp reused in several cases becomes global and, if it crosses a call in one case, takes a saved register in all of them: separate block-scope temps keep the others inv/aregisters (conf func_801B0F00). - Nested call results written as one expression,
D = f(f(f(f(D / 4) / 4) / 4) / 4), give the game's in-place signed/4on each result (bgez; nop; addiu v0,v0,3; sra a0,v0,2), where named temps copy intoa0(odin1 func_801B5D14). In division blocks, block-scopex,y,zwritten in place (x = load; x /= n;) get the game's registers, and one function-levelnholding the negated counter, reused for a constant (n = 0x640before* n >> 12), lands last ina2(satan func_801B3AD4). - Packet stores through a struct pointer (
pk->tag,pk->c1, ..) keep the loaded packet pointer in its register whereu32 *word stores reload it;g = &D_80153ECC;before a test gives the earlylui a1and themove s0,a1in the then-arm;D_801F2AC0[0]as an array givesla a3witha1 = a3 - 0x18(odin1 func_801B51AC). A counter that is thepadof theMgSVecnext to it (cam.dst.pad--) gives themove a1,v0copy in the delay slot, and a camera as one struct{ MgVec dir; SatCam cam[3]; }makes&D.dirans0 - 0x10(satan func_801B3AD4). - A saved-register swap between
pandmwas fixed by reusingmfor a laterxafter the join and wrapping thep-heavy tail in a dead identical-arm test (if (q) {tail} else {tail}, merged back by cross-jumping) (club2 func_801B2040). - Local pseudos are allocated before global ones: a pointer variable set twice, even in
disjoint ranges, is global and takes its register after the temps and the
movstrsiscratch registers;q = &D_80162978[D_8015169C]; q->unk0 = -1;for the first store, instead of a direct element store, movedqfromv0toa2as in the game (conf func_801B2170). - Quotient registers:
u = (p->unk2 << 12) / 15;into an existing function-leveluset elsewhere, instead of a freshk, puts the quotient inv1(tupon func_801B2460); reusingtfor a later sum (t = (p->unk2 << 12) / 10; .. t = (t * 0xE00 >> 12) + 0x200;) puts it ina0(s_beam func_801B1760); one variable for a quotient and a call result (r = (t << 12) / 30; D = r; r = f(r, ..)) (antlion func_801B290C); a fresh variable forrand() % 0x400 + Cused by three products gives the game's in-placev1expansion where a shared function-levelkgavea1and amove v1,v0(knights func_801B9408). s32 h; h = (s16)((s16)p->unk10 >> 1); d = h >> 1;puts thesll 16; sra 16ofhbefored'ssra(brizag2 func_801B46E0);c = q->unk10 = tab[id[0]][2];gives the in-place sign extension (bushin2 func_801B352C); a byte copy through a function-levelu8 c(c = t; e[9] = c;) fixed ak/eswap (hvshot func_801B0258);t = k;placed after ak == 0early return instead of before it fixed thek/tregisters (antlion func_801B290C).- The sched1 bump puts an
andiafterlui/addiu a0when its output is inv0; a variable set in two places escapes the bump, but local-alloc does not tie a multi-set output to a dying input, so it lands in another register (kujata func_801B88A4, still 2 words off). - reorg rewrites the first use after a
move a0,s0that carriesREG_DEAD s0:.greg,.sched2and.jump2dumps havemove a0,s0; sll v1,a0,1, the.dbrdumpsll v1,s0,1, where the game keepsa0(jammer2 and daionpa func_801B06E4, cho_kyu func_801B1B3C; no source form found). - A load copied into a second register (
lhinto one register, its copy in another) comes from named struct fields with+=and a re-read of thes16field (p->f10 += step; if (p->f10 > clip)), whereM2C_FIELDcasts andt = (s16)fnever gave it: declare a struct for the object a function works on (snobo2 func_800A8AFC, func_800A8804). Two slot-allocation loops in a row want their own counter and pointer each (q,i2) (snobo func_800ABF74, snobo2 func_800AFEFC). b = D_80162978; p = &b[D_8015169C]; p->unk0 = -1; p = &b[f()];keeps the baselaabove the firstjalin a saved register (sldfang func_801B2D80, seald func_801B0D4C);D = (s32)sym; out = (MgSVec *)D;givesla v0; .. move s1,v0with later stores froms1(kujata func_801B54CC); reading a neighbour as a struct member (D_801D6B44.vy) instead of its own scalar (D_801D6B46) keeps anlhafter theshstores and shares the base register (dia func_801B09E0).- A sum written in each arm (
D_80158D04 += (u16)D_801EE234;, cross-jumped later) makes it a block-local pseudo with the game's registers and operand order (alex func_801B2D94); a function-level temp set once and used once (o = D_801B8378 * 0xB9C;) can flip two saved registers (iyashi func_801B0028);k = c8 - t;moved into the arm where the game computes it makesc8global, allocated after the block-local pseudos (dethper func_801B173C). - work/spells87/prio.py TARGET FILE NAME prints the global allocator's order, refs, live
length and hard register of each pseudo (priority
floor_log2(refs) * refs / length, refs inside a loop weigh 2): use it to see why two saved registers are swapped before trying forms. i + (u32)M2C_FIELD(g, u8 **, 0x1C)givesaddu v0,s1,v0whereptr + igives the other operand order (snobo2 func_800A2EF0); the same 1-wordadduorder stays unsolved in snobo func_800A0F1C and snobo2 func_800A19C4.- Several uses of one scratchpad constant (
(MgSVec *)0x1F800038) are hoisted into saved registers: writing the first ones ass1[1].vxwiths1 = (MgSVec *)0x1F800030keeps them aslui ataccesses, and a lates3 = (MgSVec *)0x1F800038takes the game'soriafter the call (battle func_800D5D28); permuting three field stores (48 orders) then found the scheduler's order. - A loop counter dead across calls gets a temp register only as its own variable; a
u8parameter used directly asD[arg0]fixed a saved-register order (main func_80015D64). In blocks cloned from a C twin,s32 arg0with a separates16 idN = arg0;per block gives the earlymovethe game keeps (snobo func_800B8550 and func_800B8F78 from func_800B63E0). - GCC keeps
&D_800AE978ins0across a function only when the first read and the first store both go through a pointer; fields reached as(u8 *)D_800AE8D0 + offremove extraluis (submar func_800A76C8, still off). q = (u8 *)cp; cp = (s8 *)q;aftercp = &D_x;gives alui; addiuplus amovecopy of the address (shopmenu func_801D1868, still off).do { i = 0; } while (0);around a loop counter's init flipped an entry pointer / counter swap (magic_kujata func_801B3EA8, found by wrap.py). work/spells87/prio.py shows most saved-register swaps are priority ties or near ties: priority isfloor_log2(refs) * refs / length, a swap flips when a pseudo's refs cross a power of two or its live length changes enough, and a tie goes to the lower pseudo number (magic_vahamut2 func_801B2AAC: the pointer's 15 refs over 204 against the counter's 13 over 203).- An
s32temp for a halfword load (s32 y = p->f;) giveslhwhere a load that only feeds a narrowing store, or avolatile s16read, giveslhu(snobo func_800AA69C, battle func_800D3520).u = (t << 12) / 45;as its own statement and then-D * u >> 12gives the game's v0/v1 split andmultoperand order (magic_vahamut2 func_801B3028). A local copy of a volatile pointer global, used in one branch only, fixed a swap (main func_8003DACC). - A
static inlinehelperptr_add(base, off)for a hoistedsym + (u8)x * 32puts thelui/addiubefore thesll(field func_800CDC28, func_800CE6F4); a declared local for a sum used as an index (bi = b2A * 2;) fixed the register of the finaladdu(condor func_800AC498). - Registers follow assignment order rather than declaration order: the pointer assigned
before the counter gave the game's v1/v0 in a descending clear loop (condor
func_800A2D68). A counter and a parameter tied in the allocator (same references, same
live length) go to the lower pseudo number:
n = 3moved after a load shortened n's range and gave it s0 (main func_8003E100; prio.py shows the tie). - One variable per recomputation of
D_8015169C << 5(o,o1,o2,o3) moved the reloads to their own register, andraw = *(s16 *)p; t = raw;gave an extramove a0,v0in abnezslot (battle func_800CE970). A sharedo = i * 8;temp deleted andi * 8written inline gave a fresh t0 where r had reused o's register (magic_lasboss3 func_801B5270). - GCC copy-propagates
n = t; if (t == 0)into a compare on n and merges t and n; the compare stored first (z = t == 0; n = t; if (z) n = 0x63;) keeps them apart (condor func_800AEB90).a = e->b10; t = a - g; a = t; if (t < 0) a = 0;moved a to s0, andone = 1; if (D != -one)keeps -1 out of a register (condor func_800AF08C). A decrement through two locals (v = t - 1) takes two registers; the in-placeaddiu v0,v0,-1ist = t - 1;. i0 *= 8; i0 += tab;gives the in-placesll a3,a3,3; addu a3,a3,t6where `i0 = i0 * 8- tab
shifts into a temp (magic_riva func_801B142C). A call result reused in place (k = f(); k = k * (0x2000 - u);) gives the game's a3/t0 order where a separate local swaps them (magic_kujata func_801B68C4). A field the game loads into a temp for several sums and copies later into a long-lived register is two locals,ww = r->w;used in the sums andw = ww;` just before the call (magic_lamu func_801B1090).
- tab
- A counter shared by several loops can outrank a loop variable; keeping that variable
live to the end (reused for a final
p->unk2 + 1) flipped s3/s4 to the game's (magic_tsurara func_801B06D0). A localnz = -0xC81;before a loop gives the game's earlyli s6,-3201(magic_kujata func_801B3878). A call result kept in ans32and truncated for the call goes straight to a0/a1 where au16temp adds amove(magic_s_beam func_801B03A0). - Code GCC inlined from a helper with parameters is allocated differently from the same
code on locals: a
static inline u8 dig0(u32 n, u32 d)for the first digit of a number fixed an n/d swap (locals gave n in a1, d in a0) and matched condor func_800A427C from 72 words off. do { } while (0)around one statement or range changes register priorities and copy registers far from the wrap: work/wrapall/wrapall.py TARGET NAME FILE [JOBS] tries every range of sibling statements in every block, one wrap at a time, scores each withwork.py diffand writes matching variants to work/wrapall/out/. It matched magic_dia1 func_801B1500 from 59 words off (do { if (k == 0) { k = 3; } } while (0);, then a few store orders by hand), magic_vahamut2 func_801B6C18 from 37 words off (p and a swapped; the wrap goes around the last if/goto chain of its frame-count ladder), and magic_queig func_801B1CDC, func_801B2274 and magic_erave func_801B0494. The best-scoring wrap may match only after a new local is added inside it (magic_tupon func_801B3A08:yfor the first wrapped statement;-(a * t >> 12) + (s >> 4)instead of the subtraction the other way round fixed its temporaries).- Still open: when a quotient and its copy appear (
u = c / 3; c = u), cse2 flips the copy direction for every quotient but the first, leaving one merged (magic_brizag2 func_801B0F78, onemoveshort). - Which blocks share one pointer local changes its register: blocks 1-2 sharing one local
and 3-4 another matched (magic_tupon func_801B5EE8); one local
s16 *q_n = &D_8009A000;per block that stores to it (seven) gave the saved register per block (highway func_800ADD6C). A second loop with a counter of its own and the first counter reused in a third loop fixed an i/pointer swap, andang << 1instead ofang * 2took the value from the right register (highway func_800A8C0C). One scratch local for several unrelated constants can give the game's register (magic_hades func_801B8D48); one local per switch case gives the cases their own registers (big5). - Spilled locals get their stack slots in declaration order (the first declared at the
lowest slot): declare a spilled local first for slot 0x28, or replace a named local with
its expression to move its slot late (magic_escape func_801B009C, magic_knights). An
unused spilled pseudo of two separate
T[D*0x240]andT[D*0x240 + 1]expressions added 8 bytes of frame; one named index local removed it (work/spells19/dump.py.gregshows it). - Register swaps of two variables follow work/spells87/prio.py's priorities
(floor_log2(refs) * refs / length, ties to the lower pseudo number): eqipmenu
func_801D1D5C's card mask (6 references, 0.094) outranks the icon (5, 0.081), and battle
func_800E1C40's
pneeds 15 references or fewer instead of 17; a 45-minute permuter run then got eqipmenu to the game's length with the spill right. A running offsetc += 0x690that is reallyi * 0x690, written as a giv, lets loop.c put its increment in the branch delay slot with the other givs (magic_ifleet). - A temp that lives in one basic block (
t0 = D_8010FD78 + 0x400;used in that block only) is a local-alloc pseudo and gets v1; the same value in a variable shared with another block is global-alloc and gets another register (highway func_800AB738). A pseudo that crosses a call anywhere gets a saved register for its whole life. One pointer local per switch case, per statement group or per use (w = &D_X;for one loop,w2 = &D_X;for the next) gave the game's saved registers and its repeatedlui/addiu; one pointer shared by the whole function changed the registers of every case (battle func_800B9568, condor func_800B8954). Oneu32 cset in two blocks (c = (u32)D_8009AC32; .. s3 = (u8 *)(c - 0x3D)and laterc = s6[0]) gave a live s0 base the way the game has it, because loop.c does not move a variable set in two blocks (main func_80011C1C). - A local compared equal to another and read after a call is replaced by the other by CSE
and its register vanishes: give the later blocks a variable of their own (battle
func_800E2098).
s16for a flag local givesmove v0,s5; beqz v0whereu8givesandiands32beqz s5;y = k << 4keeps y's register wherey = k * 0x10leaves a copy CSE prefers; au16local holdings16 + 3giveslhuwhere the game haslh: keep such localss32(main func_8001E040). A throwawayu16 vtemp for one statement changed the allocator's priorities enough to flip two saved registers (magic_garyu func_801B0480); reusing the incoming parameter as the index local gave the game's s0 for the index (battle func_800ABB0C); a loop-invariantx = bitswritten inside the if rather than before it gave the preheaderandiof the game (condor func_800AE384). - A local
u8 (*E)[0x440] = D_8009D84C;assigned at the top reproduces a base the game hoists at entry (battle func_800E2098). In a loop where the counter has 20 references over 68 insns andu = i << 66 over 11, prio.py explains why the counter takes the first saved register: a separate counter for the last loops did not change the s1/s2 order (formmenu func_801D0E94 before it matched). do { } while (0);around ONE statement (wrapall.py finds it) changes the loop-depth weight of references in register priority: it fixed an s3/s4 swap and a frame of 96 against 88 in magic_garyu func_801B0480 and every register difference of jet func_800A1CD8. A fresh single-set local per step fixes an add that picks the wrong register where a reused multi-set local makes local alloc tie the output to the other operand (w = D->w4; x = ((w >> 2) << 2) - 0x10; f(x + D_801517C0, q);, magic_vahamut2 func_801B57F4); splitting a three-statement chain in two flips which variable gets s0 (magic_knights func_801B2048); an unrelated variable reused for a constant stored in a conditional block and later for theandiresult (t = 0x800; ..; t = f() & 0x100;) is a global multi-set pseudo, so theandiis unboosted and lands as in the game while the compare stays a local pseudo tied to its first operand (magic_debucho func_801B1D64).- The game's s0 can be one pseudo used for several unrelated values (a wrap-around
difference, a pointer, a constant, a node and an address in world func_800A71E8):
writing it that way gives the game's roles, and prio.py's numbers confirm which variable
should outrank which. A bare-name definition
s32 f(arg0, arg1)is needed when a caller passes no arguments (put refuses the prototyped form), and a function returning the sum (s32) puts it in v0 where the same body asvoidputs it in a1 (battle func_800D3520). - A temp used for two different values is one pseudo and so one register: in magic_alex
func_801B5C14 the section-1 temp
xand the section-3x = p->unk2share v1 as in the game, while the same temp shared with section 2 went to a0.a = q; a = 0x1000 - a;as two statements puts the quotient straight in a0 and the constant in its own register; asa = 0x1000 - q / 30the constant takes the other register. A work file can reuse a parameter as the working variable (void f(s32 i, ...)), which keeps the game's prologue copy order a0, a1, a2 (battle func_800AEC10); typing a parameter as the struct (FdObjQ *p) instead ofp = arg0;flips the order ofmove s3,a0andmove s1,zero. - A temp that is a single-set local in a straight chain gets the chain's tied register
from local-alloc where the same value in a multi-block variable gets a global-alloc
register. A priority flip is often one weighted reference away: read
refs * floor_log2(refs) / lenfrom prio.py, then try one or twodo { } while (0)wraps (a wrap oni = 0flippediand the saved-register layout in magic_geki2 func_801B10BC;do { x0 = r0 - 0x40; } while (0);lengthens x0's life and fixes local-alloc order). A pseudo with a hard-register copy preference (a call's first argument, a0) makes the other global pseudos skip that register: in condor func_800BADD8 that is whyiavoids a0 andottakes it where the game keepsotin t2. - Reload's
last_spill_regcarries over between the functions of one cc1 run: compiled alone, magic_hades func_801B14A0 gets t0 as its first reload register where the game, with func_801B0C24 before it, gets t1. The t-register names of reloads depend on the functions before it in the file, whichwork.py diffand the alone check ofputdo not see.tools/work.py put --in-fileskips the alone check and lets the whole-file check decide; a function put in C changes the reload registers of the ones after it (magic_brizag2 func_801B2548 matched only after func_801B1B68 and func_801B200C were C); and when a hand-written function that stays asm ends a source file, split the file there (tools/split_file.py magic_hades text text2 801B14A0, moving the.rodatasubsegment by hand when the jump tables belong to the later functions). - Reload: a constant or memory expression passed to an asm "r" operand is folded into the
asm_operandsby cse and combine, so reload needs one register per such operand for that insn, keeps them as spill registers and inherits laterlui/oriconstants between uses; a cast tos32oru32(gte_SetBackColor_k((s32)arg1[0], (s32)arg1[1], (s32)arg1[2])) makes each operand a pseudo again, so every constant is reloaded as in the game (field func_800B1E40). In-dg, "Need N regs of class GR_REGS (for insn X)" followed by "Spilling reg Y" shows reload's spill registers; pseudos in a spill register end up on the stack (a hoisted14 - arg2becomeslw s7,48(sp)). A mfc2 result used after ajallands in a callee-saved register. - Using the parameter directly (
arg2,((VhModel *)arg0)->at each use) instead of a typed local copy keeps the param-entrymoveorder a0, a1, a2 (a local copy makes the scheduler place that move last) and lets the parameter pseudo take a saved register (magic_vahamut2 func_801B0184, eight overlays); a copy of a stack-passed parameter (e8 = arg8;) spills to its own slot instead of its incoming one, and declaring that local before the others orders the slots. A variable shared by two blocks, one of which crosses calls, is one global pseudo (48 refs in magic_tifa func_801B2F08, 7 saved registers in vahamut2): give each block its own pointer variable, or rebuild the pointer at each use as the game does after calls. Pseudo priority is linear in loop depth, so no number ofdo { } while (0)wrappers lifts a pseudo above one with twice the weighted references (magic_elevator func_801B05E4); splittinglist += 2intolist++; list++;raises the weighted count without changing the code. - A multiply written as
s0 = i << 4; s0 += i; s0 <<= 2;puts every step in one register ands0 += (s32)&D_x; *(u8 *)s0 = 0; s0--reuses it as the loop pointer (battle func_800AEC10). In the cse1 dump a constant address used before and after ado { } while (0)becomes two pseudos (the wrapper ends cse's basic-block extent in the first pass) and cse2 turns the second set into amove: that is themove a0,s2where the game readslhu v0,0(s2)directly;-dLreports these wrappers as phony loops. cse2 also turns constants hoisted by loop.c intomoves from registers that already hold them (the fourmove t5..t2of magic_tifa func_801B5C74): they appear when the loop body names the globals directly (*(MgB8 *)((u8 *)D_80151A4C + o)) and not when base/q/r are variables;bl = bp - 12;as its own statement in a loop body gives themove t2,a3copy of the pre-loopaddiu a3,s4,-12. - Nested
do { } while (0)around ONLY one pseudo's own mentions adds one weighted reference per level to that pseudo without touching its giv: ten levels aroundgte_mv12(&verts[i])took the vertex-base copy of magic_elevator func_801B05E4 from 8 to 18 references and its register now goes before the packet giv's (a wrapper around more than that pseudo's mentions also deepens the loop nest for the others, which is why wrapping a whole statement could not do it); it works in local-alloc too (the.lregdump showsused N times across M insns;t0 = D_800F38A0 << 3;wrapped ordered the registers of battle func_800E368C arm 0;do { k = 0; } while (0);anddo { sc = (u8 *)0x1F800000; } while (0);ordered magic_nanntoka func_801B1D48's saved registers). A same-block multi-set local (k = (u16)e->x; k &= 0x1FF;) is unboosted (its load goes to the top) and is allocated by local-alloc before the constants, so it gets v0 where a shared global temp got v1 (condor func_800B0404: separatek5,k6for cases 5 and 6). if (a > 0) { h = X; } else { h = X; }makes an s16ha multi-set pseudo, so combine cannot fold its sign copies and thesll 16; sra 16truncation stays (snobo func_800A4D38 and its twin snobo2 func_800A5F00, where about 100 other forms had been folded); thenb = h << 16; a = ...; t = b >> 16;withban existing multi-set local splits the two shifts around the chain because sched1 does not boost the first shift. A loop pointer and a later temp made one variable give the temp the register the pointer gets in the loop, where four temps are live and first-fit lands on a2 (magic_tifa func_801B2F08); a table base in a user variable set before the tag puts itslaahead of the taglui(magic_garyu func_801B02B0).- The operand order of an add: a base register that cse knows to be constant (a symbol
address) always goes second in
base + n * k, and base-first needs a base that is not known constant at that point.do { b = D_x; rec = b + ...; } while (0)gives base-first in cse1 (it stops at NOTE_INSN_LOOP_END) but cse2 ignores the note, replacesbby the constant register loop.c hoisted and flips the operands back: only a real CODE_LABEL between the two uses would keep it, which the game's asm does not have (snobo func_800A0F1C, one word left). A user variable that holds a product (ib = id * 0xB9C;declared afteroff) fixed such an order in battle func_800B5AAC, andk = 0xF;kept in a variable stops fold turning(m + 15) - curintom - (cur - 15)(magic_hades func_801B8404). When every hand-made variant fixes one difference and breaks another, run wrapall on the nearest draft (631 wraps found the hades match); for a function over 250 insns wrap a chosen window of lines and log each score, since a whole-function run can time out before it prints anything. - A variable with two sets and two deaths is allocated by global alloc, after all
single-death temps: reusing one temp for two different values (the OR result and the
mfc2 result) put the OR result in the game's register and left v0/v1 to the other temps
(submar func_800ACCA8); a quantity merged with an
orresult carries both quantities' references over its whole life (-dl).do { } while (0)around a SINGLE mention adds one weighted reference, so the global-alloc order of three near-equal pseudos can be chosen: two nested levels plusgte_use(i)orgte_use(p)gave the exact order tri, i, p, cross (snobo func_800A39CC, whose twin took the same C unchanged). An emptyasm volatile("" : : : "$6")that clobbers registers steers the allocator without changing the code: a value live across it avoids them (include/gte.h: gte_clob_a2, gte_clob_t01, gte_clob_t123_89, gte_clob_t0123_89, gte_clob_tmp; gte_use(x) is an empty asm that only reads x, one more register reference). cse numbers the registers of an extended block in order of first mention and puts the later one second in a commutative op:m = arg1; q = 0x1000 / arg2; arg1 = q * m;gavemult v0,a1wherearg1 * (0x1000 / arg2)gavemult a1,v0(magic_matra func_801B0EE0). A scratchpad struct pointersp = (T *)0x1F800020; sp->p = m; sp->m = *m;gives a block copy as offsets from one hoisted base register where two separate constants gave two registers; a short variable per copy is a block-local pseudo for local-alloc and takes the lowest free registers. Two copies of&sc->w1Cgiveaddiu a2,a0,28plus amovein the preheader, one variable gives one register (magic_hades func_801B3354). - Reload picks its spill registers by
hard_reg_n_uses, and registers named in asm clobbers count as heavily used: when a pseudo sits in t0, clobbering v1, a0 to a3, t1 to t3, t8, t9 and t7 (gte_clob_va, gte_clob_t123_89, gte_clob_t7) keeps t0 the first reload register for the rest of the function, and a volatilegte_copy(k, idx)pair then giveslw t0; lw v0; sw t0; sw s2(magic_satan func_801B1790). local-alloc sorts the quantities of a block with an exchange sort that compares quantity numbers (birth order) instead of the sorted order: with exactly three local quantities only the orders [2,1,0], [0,1,2] and [0,2,1] come out, so some register orders cannot be reached by priority tweaks (priority = floor_log2(refs) * refs / (death - birth), birth 2n for a set, death 2n for the last use, a label counts as an insn); wraps andgte_usecould not give the game's order in magic_lasboss3 func_801B0C18, an empty clobber asm (gte_clob_v1()after the colour word, before the store) did. More of them in include/gte.h: gte_clob_s012() (a scratchpad base set before a loop takes s3 and the loop pointers s0 to s2), gte_clob_a0() (a model pointer live across it keeps out of a0: magic_odin2 func_801B1C40 from 133 to 25 differing words). Declaration order sets pseudo numbers and spill slots:ibeforeidxgivesis7 andidxfp,n,sh,egives slots 0x20, 0x28, 0x30. - A clobber of a register placed in the HOLE of a loop-carried pointer's live range
(between its last use and its re-set after
rtpt) steers a giv away from that register: gte_clob_t2() swappedvcand the pk+0x1C giv between t2 and t3 and took magic_vahamut2 func_801B0E54 from 38 lines to 0. A colour worda = c | (c << 8); w = a | (c << 16); gte_use(a); *(u32 *)(pk + 4) = w | K; gte_use(w);keepsaalive past the firstorandwpast the second, which makes local-alloc tie each result to the second operand (eight other forms of the same expression gave the same wrong registers). local-alloc gives s0 to a block-local arg0 that is live across the first call, so arg3 lands in s1; making arg0 global (if (n > 0) { gte_use(arg0); do { ... } while (i < n); }) gave arg3 in s0 and arg0 in s1 (theifplusforform adds a duplicate guard).gte_use(arg9)in the loop lifts a stack parameter's priority above arg4 and arg5. reload spills the hard register that holds the cheapest pseudos, so which parameter ends up spilled follows the allocation order of the pseudos in the last saved registers (.gregshowsSpilling reg N). A pure rotation of the reload registers (t0/t1/a3) islast_spill_regcarried over from the previous function in the file:tools/work.py put --in-file(magic_brizag2 func_801B29DC).gte_clob_s012()at the top of the loop body steers loop-carried pseudos away from s0 to s2 and letsi = 0;be the first statement, where a volatile asm in the function head blocks combine from foldingi = 0into the guard, splits the sched regions and changes the frame (magic_lasboss3 func_801B057C).arg0itself as the model pointer withgte_clob_a0()first gives a singlemove t8,a0prologue (magic_odin2 func_801B1C40). - Short stack parameters lose the stack-slot equivalence of the later stack parameters:
after a
short(s16/u16/s8/u8) stack parameter the following ones have no REG_EQUIV note (-dr), so reload spills them to fresh slots, as the game does: the frame grows by 8 and the incoming-argument copies appear (lw s5,164; sw s5,88). A caller's(s16)casts are the clue;putrewrites the prototype in decls.h (magic_kujata func_801B2250 with arg5 and arg6 s16, func_801B1AF4 with arg7 s16): for a near miss whose frame is too small or that spills one stack argument where the game spills two, try it first. The allocation order can be pushed with weighted references: prio.py printsfloor_log2(refs) * refs / len, a mention at loop depth 2 adds 2 references andgte_use10(x)(an empty asm that reads x ten times) adds ten; a window of about 0.0007 cannot be hit with integer counts (kujata 1AF4, 570 knob combinations). movstrsi (a struct copy of 8 bytes or more) clobbers four scratch registers that local-alloc assigns real hard registers (v1,a0,a2,a3 for the first copy, v1,a0,a1,a2 for the second): a global pseudo live across the copy conflicts with a2 and a3 (magic_tifa func_801B5C74:qends in t0 where the game has a2). In limtmenu func_801D042C counters that cross roles between loops (one pseudo is the inner counter of loop 1 and the outer of loop 2) were given roles A, B, C and every s0..s4 assignment followed; a user variable shared between a shift amount and a call argument took v1, writing the expression twice (cse shares it) gave a1 and removed the delay-slot move.k = 0; if (k < n) {in place ofif (n != 0) {gave the game's frame and spill slots withoutu8 pad[8](magic_lgirl). - A variable that spans regions keeps its register out of s0 where a block-local pointer
sits: splitting
tintot/bit/tb(andyintoy/yb) madetblock-local so local-alloc gave it s0;gte_clob_s0()between twoifs pushed a u16 out of s0 (cnfgmenu func_801D080C 99 to 24 lines). global.c's priority isint(floor_log2(refs) * refs / len * 10000)and a tie goes to the lower regno: in magic_sting func_801B0B40arg2(5 refs, len 413) tied with a loop temp (3 refs, len 124), and fourgte_use(i)of an untouched variable between two loops lengthened arg2's range and spilled it as the game does (a cheap lever to lengthen a parameter's range). loop.c's combine_movables only merges movables whosen_times_used == 1: two equal constants in two arms merge and are hoisted, ONE user variable set before theifand used in both arms (k3 = 0x24000000;) is not hoisted and itsluithen fills thebeqzslot. A 2-byte constant pseudo (rect[3] = 0xB) hoisted by loop.c occupies a register where the game has none and reload rematerialises it withori t0,zero,0xB. Identical string literals in one file merge: the game has two copies of"bu10:", so the rodata came out 16 bytes short until the extern names (D_801D03B8,D_801D03C0) were used (put keeps them as INCLUDE_RODATA asm). Reaching a volatile pointer global with another struct type:(*(T *volatile *)&D)->ftakes&Dinto a shared register, reading through a lower-base array (extern T *volatile D_80062EFC[]; D_80062EFC[10]->fforD_80062F24) gives the game'slui; lwbefore every store. - Address contexts:
*(p + (j + i*4)*6 + 0x4C)in one expression expands with the MULT first (addu t,j; addu t,p), separate statementsk = j + i*4; q = p + k*6; c = *(q + 0x4C);give the game's operand order;i = 0; if ((u32)i < (u32)n)gave 8 extra frame bytes (statmenu func_801D14E0). Weighted references can flip near-equal priorities where an old note said 'one more reference would flip them': six moregte_use(icon)raised the icon to 9 references so that it takes s7 and the 0x2AAAAAAB constant takes s8; a call result in its own variable, thengte_clob_s2_6()(an empty asm clobbering s2 to s6), then the call that uses it puts the colour in s7 while theandistays in the first jal's delay slot;gte_use(s0)right aftericon = f(id)makes the table byte cross two calls so it takes s0. A constant stored in two blocks (0x100) is merged by loop.c into one spilled pseudo that reload rematerialises asli t1:cst = 0; cst = 0x100;with a separate variable per block gives the game'sli v0,0x100;-dgshows which spill register a rematerialised constant uses (Spilling reg 9gave t1 where the game has v0). A commutativeortakes its operand order from the cse quantity order (the first mention in the extended block): reusing the old multi-sets2as the masked temp and a freshtmpfors2 - 1(tmp = s2 - 1; s2 = D.unk2 & 0xFFFC; D.unk2 = s2 | tmp; f(tmp);) gave (masked, s2-1); an increment BEFORE a call (s2 = s2 + 1; f(1);) lets the sum cross the call and use s0 in place;n = 0; i = 0;first andfor (; i < 9; ...)gavemove a1,zero; move t0,zerobefore a lui chain. - The game's intermediates in a switch with many arms are block-local temps (local-alloc
registers): shared multi-set variables (
p0,q0,t) take global-alloc registers (a0/a3) instead, so a FRESH SINGLE-BLOCK VARIABLE PER ARM for every intermediate (p0/p1/p2,q1/q2,c1,c2) fixes the register order and also cross-jumps the shared tail (eqipmenu func_801D5BD0 154 to 0 lines; func_801D6C2C 269 to 184 lines with its ownchNperc = (EqpChar *)...use);p2 = c*0x84 + base; p = p2 + D_801DF6DCkeeps the game's association andc1 = idx; p = base + c1*0x84; c2 = idx2; q = base + c2*0x84;before a call gives the game's interleaving of loads (40 to 7 lines). As32return with a barereturn;makes v0 live at the epilogue so reorg stops filling delay slots withli v0,1orslti v0(three slot differences at once on a function with many exits). A loop base written asD_8009CBDC - 0x464 + ...andD_8009CBDC - 0x444 + ...makes cse share one register (184 to 165 lines);while (1)with the check at the top gives a loop shape wherefor (;;)rotates it. - For
sym[off + k]withoff = ch * 0x84in its own variable GCC gives thelbu v1,sym+k(a0)memory operand and abeqzto the shared fail block; without theoffvariable a separatelapseudo (au8temp compared< 0xFFgivessltiu). A deadi = 0;before the firstifof a function whosefor (i = 0; ...)init already gives the game's prologue order is to be deleted; a switch default arm written asif (D_x != 0) goto L2;withL2:on the case body keeps the case arm (an identical copy of the arm inside theifmakes cross-jump keep the later copy and drop the case arm); separate pointers per phase (pl,p) fix saved-register swaps;yt = e[0]; x0 = e[-1]; gte_copy(y0, yt);withgte_clob_a1();at the top of awhilebody reproduceslb v0; lb a0; move a1,v0. A call with field-offset arguments cast to ans32-parameter prototype (func_801D0228,func_8002708C) removes thesll/sra; a call argument written as(u8 *)&D_x + kfrom the same symbol as an earlier field read is derived from thelaregister by cse; a dynamic cursor access through an alias array symbol typed with the field at offset 0 (D_801D3DDE[n].top) gives thesym+2plus-register form. A switch written in the ordercase 0x67,case 0x62,defaultgives the game's layout where a three-wayiforder did not;if (b != 0) { ...; return; } fail; return;gives the game's shared fail placement;gte_use(n)between the first two stores andoff = n * 0x12keeps the product after the stores. - A big menu function reuses about 7 FUNCTION-LEVEL variables across its loops and blocks
(s0..s6 plus arg0 in s7): all loop counters, pointers and indices share them. A draft
with one variable per loop (about 30 of them) never converged; with the shared variables
the priority order s0 > s1 > s2 > s3 > s4 was set by adding about 12 weighted references
to the s0 variable (
gte_use10(ra)plus twogte_useinside loops: work/spells87/prio.py shows the order) and the register-only lines went from 108 to 35 at once (itemmenu func_801D0E80). Reading a global as an array element in the pre-loop call (D_801D3D74[0].x) and assigning the pointer variable after that call giveslui v0; addiu v0; move s3,v0ahead of the pointer and counter inits;ka = 0; kt = ...; ka = 0xFF; if (kt != ka)keepsli v0,0xffin the loop,kf = 0xFF;before the loop givesli s2,0xff/move s1,zeroin the game's order;kd = id - 0x57; q = kd << 1; q = q + kd; q = q + (q << 4); q = q << 1; q += basegives a game chain's registers;gte_clob_v0()before a constant's second store pushedli 0xAinto v1. For a big function that m2c cannot draft (mgicmenu func_801D0490): write the head and the first cases from the asm and align them first;s16 D_801D2A74[]-style array aliases make cse share the window address in s0 as in the game. - The FRAME of a big function:
.frameshowsvars=, and an 8-byte slot with no code comes from a dead(use (reg))pseudo: a three-insn combine (symbol set, add, load) leaves the symbol set alive when its pseudo has another user, combine cannot place the add pseudo's REG_DEAD note anddistribute_notesinserts a(use (reg))after the last jump; the pseudo's class isST_REGS or none, it gets no hard register and reload gives it an 8-byte slot (everyassign_stack_localslot is rounded to 8). Reload slots come after the declared locals, sou8 pad[N]moves the other slots instead of adding space. In mgicmenu exactly six arms readD_8009CBDC[D_801D2AE8]twice with the second read reusing the symbol register (each leaves a deadlui s0; addiu s0pair); dead compare pseudos from an unfolded guard are the same mechanism: a guard whose constant0sits in a variable set in the same block (rc = 0; ... (u32)rc < (u32)rf) is folded by combine to(ne rf 0)and leaves the pseudo and its slot: a frame short by a multiple of 8 can be tried that way (three sites gave the missing 24 bytes); it adds one weighted reference to the constant's variable per site, which can flip two allocation priorities (remove agte_use10of that variable). In a big menu function whose allocation matches nine function-level variables:gte_use10(p)afterp = (u8 *)D_x;lifts a loop pointer abovei(register-only lines 137 to 43);extern s8 D_x[]read asD_x[0]twice gives the sharedlui s0; addiu s0; lb 0(s0);D_801D2A4C[9]in place ofD_801D2A5Ein shared tails giveslui s0plusaddiu a0,s0,14; a single-setcp = &D_x; v = *(volatile u16 *)cp;with a latergte_use(cp)giveslui s1; addiu s1; lhu 0(s1); the same item index written with two associations gives the game's recompute (tbl[(re + (AA2 * 3 + rb)) * 8]for the compare,(AA2 * 3 + (re + rb))for the argument); a name with a suffix such as an alias symbol is only in the ELF aftertools/build.py NAME --splitregenerated the address file. - A dead set in a SKIPPED arm: a
wp += 12; wp -= 12;pair inside anif (arg0 & 2)arm makes cse forget the pointer, so a read after the join stayslh a0,-24(s0)as in the game (cse1's skip-block path invalidates the pseudos that are set in the skipped arm; a redundantwp = &D_x;there is deleted before that happens); one variable set again in the skipped arm (dt = id - 0x80...dt = id - 0x100) forces cse to recompute an expression in each arm. In a big menu function written in full (shopmenu func_801D1CC4: 3706 lines to 0 in five batches) the game's intermediates are block-local temps: a fresh single-set variable per switch arm, per loop and per sum moves the allocation (by priority flips via pseudo order and block-local allocation: splittingwp,i,y,off,type,vper draw case cut register-only lines from ~340 to 163, while splittingn,color,qtymade it worse: those stay function-level); a row count used by another switch needs its own variable (combine then knows it is only 5, 6, 10 or 11 and the draw loops getbeqz); a different symbol per read (D_x[..].pad,D_y,D_z + 1for three reads of one count) stops cse sharing one address; the game's in-placeaddiu s0,s0,-2; jal; move a0,s0:yd = wp4 - 1; func(yd); gte_use(yd);;gte_use(m); gte_use10(cp);after a call makesmcross the call and keepscpahead of it. Operand order:D_x[i3 + D_y.top]givesaddu v0,s1,v0and a fresh variable for the sum (yc = w4 + ya) givesaddu a1,v0,a1;case 2: break;inswitch (type)gives the game's compare chain and shares the compare's constant 1 with a later store asli s0,1in thebeqzslot; the same call written in both arms (a clamp inside each decrement arm) lets cross-jump merge the tails with no reload. - The game's
move a2,v1; andi v1,a2,0xffpair (a copy before a mask) comes from a QImode local (u8 u; u = c;withs32 c = (s8)*p;, the copy made before theif): GCC 2.7.2 keeps the copy because its quantity mode differs and theandiis its zero_extend (every other form folded it away);gte_copyn(w2, 0x30);as the first statement putsli s4,0x30first and a loop that uses a counteri(D_x[i], offsetsi * 0x38 + 0x20) lets loop.c build the givs itself and fixes a prologue order (patymenu func_801D0250). The second batch matched what the first could not by a different shape of the SAME code, not by more tricks: when a difference survives all forms of a statement, change the loop form or the arm structure around it. - A u16 read-modify-write in the
la; lhu 0(reg); or; sh 0(reg)form needs an alias ARRAY at an unused lower address (D_800F7DDE[1]forD_800F7DE0): decls.h declares the global as a scalar and the array form givesla+0(reg); alias arrays also give shared address registers (D_8009D2A3[1]forD_8009D2A4gavelui s1/addiu s1) where a pointer variable is folded to absolute addressing by cse and agte_copynpointer is unknown to sched1. A user pointer variable for a constant address (pa = &D_x;once, not&D_xtwice) has the right allocation priority;for (i = 0; ...)before a loop keepsmove s8,zeroin the first call's delay slot wherei = 0;at the top let sched1 float it to the head. A fresh single-set variable per site for each repeated chain (per link site, per tail re-read, per flag) is what keeps shared multi-set variables from becoming global pseudos in the wrong registers (chocobo func_800A8AE8: frame 80 instead of 72); spilled variables go last in the declaration list;do { y += 0x3C; } while (0)around each running increment ranks y1 to y3 above yc; onegte_use(x)at the loop end gives x its register. The movable threshold in loop.c: deadk = N;sets form a movable chain and lower it (each hoist lowers the threshold by 3),k = i + N;sets do not: ten of them keep two tablelas in the loop while a pre-loop colour constant is still hoisted; DEST_ADDR versus DEST_REG giv order: directsa[i].faccesses make DEST_ADDR givs so the a0/a1 moves land first in the preheader. chocobo/text.c and text3.c build with-funroll-loops: a plain 6-iterationforwith a small body is unrolled 3 times (write a normalfor). A word-aligned struct assignment (typedef struct { s32 w[0x110]; } MnRec; sp38 = *(MnRec *)p;) gives the game's movstrsi loops and frame (au8[N]struct gives byte copies). - loop.c (gcc-2.7.2 source):
combine_movablesmerges equal invariant sets only when both temps are used exactly ONCE and are not global (n_times_usedcounts SETS, not uses): with a real outerwhile (1)the mask constants of several sections are hoisted out of the outer loop into saved registers (the game does not do that: chocobo func_800A9D94); a merged group of single-use shifts is hoisted bythreshold * savings * lifetime >= insn_countso it always hoists in a big loop; inscan_loopa user variable set AFTER the first label or jump of the loop is not hoisted unless all its uses are in the same basic block as the set, compiler temps are hoisted; ado { } while (0)around the sites did not stop anarg0 * 8hoist because an inner loop keeps its own copy of the expression; four dead sets of variables used elsewhere at the top of a loop body (tx = 1; ty = 2; gl = 3; k7 = 4;) raise the real insn count past the hoist threshold (compare constants then stay in the loop as in the game). A function-level constantk6 = 6;set once at the top and used ask6 + yin a loop givesli t0,6plusaddu v0,t0,t1and no slot of its own (set in the same block as its use it is folded by cse).gte_use(arg0)FOUR times keepsarg0out of the spill slots (one use spills it, ten put it too high);gte_use10(w); gte_use10(wid);at the TOP of a loop body gave the game's order for the function-level variables (at the tail they sit next to other asm barriers and inflated sched1 priorities); a fresh block-localpq = D_x;for packet stores fixed two pointer registers (reusing the function-levelqmade it a global pseudo that took a1). A 4-case switch afterif (c == 0xFF) break;compiles to a compare tree, the same cases plus 0xFF in one switch become a jump table. Base-first adds:*pb + *pi * 0x28always givesaddu prod,base; the game'saddu base,prodcomes from an ARRAY_REF on a struct-array member. chocobo/text.c and text3.c build with-funroll-loops. - Alias symbols are the lever for
la/luiconstants. loop.ccombine_movablesmerges single-set pseudos whose sources arertx_equal_for_loop_p, and for a SYMBOL_REF that compares the NAME POINTER (XSTR (x,0) == XSTR (y,0)): tenla D_8015190Fpseudos merge into one group and are hoisted out of a big loop (savings 10, life 80, threshold 29 times the insn count) while a group of at most three stays at its use: the game does not hoist its table bases because it uses distinct spellings of one address.NAME_a = 0xADDR; // allow_duplicated:Truelines inconfig/symbols.us.<target>.txtplustools/build.py <target> --splitgive the spellings (battleD_8015190F_a .. _f,D_80151214_a .. _c,D_800F5194_a .. _c): the tail arms that cross-jump must use the SAME alias, or theirladiffer and cross-jump cannot merge them. A different spelling is also what makes the game rematerialiselui/addiuafter a join instead of sharing one saved register (cse follows the skip-block path). A spelling that does not exist yet can be tried in the work file asD_8015190f(lowercase hex) orfunc_8015190F. - loop.c hoists a pointer such as
&D_80151844[idx]only if the loop's real insn count is at mostthreshold * savings * life(func_800BCB1C: (26 - 3 x 4 moved) x 6 x 17 against 1428): retyping the reads of one arm as struct-array elements (the EXTERN retyped; a cast(BtlPos74 *)D_8015120Eadds alapseudo and fails) cut the count under it and fixed the hoist, a saved register and the allocation.u8 idx = arg0;(a widearg0 & 0xFFvariable gives another hoist) givesmove s3,a1; a barearg0passed to an s16 parameter becomes a hoisted zero_extend +sll(writearg0 & 0xFF);gte_use(i);after the last store of an arm flips two registers by block-local priority (floor_log2(refs) x refs / length); a multi-set pointertp = D_801A0004fixes a head's v0/v1 order; threegte_use(v8);afterv8 = arg2;put v8 in a higher saved register.
while (1)matches wherefor (;;)does not.- A
switchtable runs from the smallest to the largest case; emptycase N: break;lines may be needed to make it as long as the game's. Case blocks are laid out in source order. - GCC merges identical tails (cross-jumping): one store or call written in each branch
often matches where an if/else into a temporary does not, and calls in both arms
become one
jalat the join with the arguments computed in each arm. - 2.7.2 lays out
if (c) return A; return B;reversed: use if/else into a temporary and one return. Anelseblock placed first in the game means the condition is inverted. - An instruction that starts both arms of an
if/elselands in the branch delay slot: repeat the test in both arms.if (r <= 0) { if (r >= -1) ... }nested, not&&. - A two-case
switchgives the game's block layout whereif/elsedoes not. m = 0; if (!(x & 0x20)) m = 3;givessltiu/negu/andi;(x & 0x200) != 0through a temporary givesandi/sltu;v & (1 << n)with a mask local keepsli 1; sllv; and.return 1sharing a register with a store of 1: aretvariable.- 2.6.3 lays out
if (c) { A; return 0; } else { B; return 1; }with B first. - In a switch,
if (cond) break; return 1;keeps the cases apart; the invertedif (!cond) return 1; break;gets cross-jumped into one tail. - A
sltiuclamp after a< 0test:(u32)v > 11. - A hoisted
sltiflag and-(i > 0) & 8:(rows >= 2 && i > 0) ? 8 : 0. lw 0(reg); ... jr ra; sw 0(reg)on a global (the store in the delay slot): a pointer local,p = &D_x; *p += n;(a volatile store stays out of the delay slot).- A retry loop with the result zeroed in a jump's delay slot:
do { ... } while (dir == 0 && i < 100); if (dir != 0) { ... } else { mask = 0; } return mask;. x < 0 ? -x : xgivesbgez x; move t, x; negu t, t; the if form does not. Chained ternaries put the value blocks out of line in reverse order; an else-if chain keeps them inline.- Five consecutive cases make a jump table; leaving one to
defaultgives the game's compare tree. (x & 4) || (x & 8)folds to oneandi 0xC; the game's two tests areif (x & 4) f(1); else if (x & 8) f(1);(the calls are cross-jumped).- A call common to every branch, written once after the switch, changes the layout and the frame: write it in each branch.
- A then-arm that branches into the else-arm's store (
beqz → store; j end): m2c's goto shape matches. - Cross-jumping keeps the textually last of identical tails in place: in opcode handlers
that end each branch with
D_800831FC[D_800722C4] += N; return 0;, order the branches so the game's copy comes last. Two cases with identical bodies merge whole; where the game shares only inner blocks, write them once with labels andgotointo them. Tworeturn 0the game shares: a label andgoto. - A
switchwithdefaultlast avoids a tail merge thatdefaultfirst or an if chain causes; a jump table with holes needs the holes as explicit cases (case 0: case 3: ... default:).switch (a) { case 0: v = 0; break; case 1: v = 1; break; default: v = 0; }keepsbeqz/bne/jwhere if/else becomesxori/sltiu. - A range test the game does as two compares is nested,
if (c < 5) { if (c >= 3) ... }, or GCC makes onesltiu. Two identical tests in a row are threaded into one: write them as two separate ifs to keep the reload. if (!c) break; goto l9;givesbeq end; j L9;if (!c) return 0; goto l9;threads into onebnez. A found block placed first:goto start; found: ...; goto after; start: ... if (hit) goto found;. Early returns and if/else give different block orders: tryif (s >= 0) return a << s; return a >> -s;andif (c) {A; r = x;} else {B; r = y;} return r;both.- A non-void function falling off its end keeps
v0live: reorg then cannot fill abnezdelay slot from the loop head, or leaves ali v0out of a delay slot. if (t == 0) {A} if (t == 0) {B}loses the secondbnezto CSE;z = t == 0; if (z) {B}keeps it.i = 0; if (i < n)keeps a guard a repeatedif (n > 0)loses to jump threading.if (A || B)followed by a second test of the same field keeps the first branch threaded to the else part.- An else-if chain cross-jumps a shared tail (
sra); the ternary form keepsj L; srawith the shift in the delay slot.k = 0xBC; ... p->f = k;gets theliinto a branch delay slot; a deadid2 = arg0 & 0xFF;in an else-if arm survives whenid2is assigned again at the join, and fills a delay slot as in the game. if (F & a) {...} else if (F & b) {...} else v = 0;lets the flag's temp andvshare a register wherev = 0; if (F & b)does not.switch (t) { case 0: x = 1; case 2: break; default: goto skip; }reproduces a three-way test that if/else inverts.m = 8; ... k < m ...; m = r; if (m != 0)givesmove v0, a0before the branch.- An inlined callee's body: each
returnasr = N; goto done;, then testr. A search loop with no finalmove v0, zerohas noreturn 0: thesltiresult left inv0is returned; an exit path reusingv0:r = (void *)(i < 0x960); goto loop;withr = p; goto done;in the hit branch. - No form found yet: two constants
if (c) x = A; else x = B;that the game branches over always becamesltu/subu/andi(condor func_800A427C). - A merged store tail: write the run of stores in each arm; cross-jumping keeps the merged
copy at the textually last arm (the join,
j REST, then the out-of-line exit). Two arms that each copy global to global (loads in both, stores after the join) are such cross-jumped copies. - A linear compare chain (0x19, 0x1A, 0x1E, 0x1F) needs if/goto; a switch gives a balanced
tree, and its case order sets the tree (
case 1: case 2: ... case 0: case 3:versus 0, 3, 1, 2). A store in the default arm thenreturn, with the same store after the switch, matches where if-chains do not. An earlyif (c) return 1;chain, then a switch, then a finalreturn 0puts thereturn 1block first. if (id == 0 && (fl & 2)) A; if (id != 0) B;is threaded straight into B.if (t < 10) k = 0; else if (t >= 0x13) k = 9; else k = t - 10;keeps copies ofta nested if loses.d = d < 0 ? -d : d;givesbgez; nop; neguwhere the if form hoists the next load above the branch.(r & 0xFF)on a single-set or boundedris dropped by combine; a second, unbounded set keeps theandi.while (1) { if (p[0] == END) { p++; break; } ... }gives abne/jexit withp++in the delay slot;p += 3once after an if/else join gives one shared back-edge (in both arms: two increments and no reduced pointer).if (!(x & 0x80)) f(p, 0); else f(p, 1);keeps the branches a 0/1 ternary folds intosrl.- Switch case order sets the block order (
case 1, 2, 3, 4, 0xB..0xF, 7, 5, 6, default);case 0xF: base += 0x100; case 0xD:as a fallthrough chain gives the game's compare tree; cases 4, 8, 9, 0xB, 0xC become a jump table, so a== 4 / (u32)(x - 8) < 2 / (u32)(x - 0xB) < 2chain comes from||tests. An explicitdefaultplus one sharedreturn 0after the switch gives the delay-slotmove v0, zero. - A function declared
voidwhose code leaves a value in v0 for its callers returnss32:move v0, zerobefore the epilogue isreturn 0;(main func_80024A3C), a tail call whose result callers use isreturn f(...)(battle func_800B0B94), and a switch whose range check leaves anopin its delay slot falls off its end; callers passing arguments then needs32 f()with an empty list, as(void)breaks the file (battle func_800DDFEC). - Branches GCC turns into arithmetic: if/else or goto forms assigning
0xFFor0becomesltiu/negu(/andi), and only an inlined helperreturn 0xFF; ... return 0;keeps the branches (condor func_800A3304).if (A || B) { if (C) { f = 1; goto done; } } f = 0; done:keeps the branches with the zero in a delay slot.u = (w & 0x3F) != 2 ? arg3 : 0;orct = arg3 & -((e & 0x3F) != 2);as its own statement givesxori; sltu; negu; and; inside a larger expression it becomes a branch, and a ternary creates the constant 2 early, shared with a later compare. A two-constant diamondif (c1 && c2) { v = ...; a = 0; if (v == 0) goto L; } else { L: a = N; }keepsbnez; addu a, 0/j; ori a, N. - Max of two bytes:
a = src[0]; if (a < src[1]) a = src[1]; b = a >> 1;withs16 a, bgivesslt, a reload in the arm andsrl;s32 agives amoveandsra,u8 agivessltuwithandi. One multi-set variable (n = f & 0x8000; f &= 0x7FFF;) givesbeqzthenblez, a single-set onebeqzin both. - Switch layouts: an empty
case 4: break;above cases 1 and 3 gives thebeq 3; slti 4; beqz end; bne 1tree; a dispatch testing 2, then 0, then 1 isif (m != 2) switch (m) { case 0: ... case 1: ... }; in a jump-table switch,case 0:joined todefault:givessltiu 8with no-1bias (main func_80039034). A switch's last case gets its shared join duplicated into each arm; agototo a shared else avoids it. - Cross-jumping and threading: the same store run written in every arm of an if / else-if
chain tested with
(t -= 2) < Ngives the tail-merged layout with the stores right after the second test (dejon func_801B0238);if (x < N) { A } if (x >= N) { B }with calls in A gives the jump into B and the re-test after A. An inlined helper is a scheduling barrier thatdo { } while (0), a block or a statement expression do not replace (reito func_801B1158). - A variable divisor (
d = 100000; x / d) givesdivuwithbnez; break 7, a literal divisor the multiply sequence. A constant hoisted out of a loop (li a3, 1) lands in the stall slot before adivmacro. - An if / else-if chain with a call in each arm gives one shared
jal; agotointo a shared call (m2c's shape) does not. Ans16parameter with ans32counter gets ani << 16giv (battle func_800A38FC). - The same comparison with a global load written in both arms of an if/else, each with
its own
return -1, cross-jumps only theslt; bnez; li v0,-1tail; computing the limit into one variable gives one load after the join (main batch 10). - A switch over a
u16global withcase 1: goto ret0shares the earlyreturn 0block and ends the CSE path before the next case, so a constant1is not kept across calls ins3(main batch 10). if (f >= 12) k = 0x14 - f; else k = 8;givesbnez; ori sN, Kwith the else constant in the delay slot;k = 8;before theifis hoisted instead (hiwind func_801B0730).p->unk2 ^= 1written afterif (D_x < 2)lands in thejrdelay slot (iyashi func_801B0D04).t = p->unk2; if ((u16)(t - 0x1E) < 0x12U) { k = p->unk2 - 0x1E; ... }keepsk's subtraction as its ownaddiuin the call's delay slot (nadare func_801B15C8).(f & 4) && (f & 8)folds into(f & 0xC) == 0xC; a tempt4 = f & 4for the first test only, with the later(f & 4) == 0inline, keeps two tests and the delay-slotandi(battle func_800AF9C8).- Shared store blocks:
if (t < 0xD) { k = 0xD; k -= t; goto store; } if (t >= 0x16) { k = t - 0x16; store: ... }(faiga func_801B0284;k = 0xD - tput the second test in the first branch's delay slot); with a fail arm,if (t < 2) { c = t << 6; goto store; } if ((t -= 2) < 0x1E) { c = 0x80; store: ... } else { p->unk0 = -1; return; }(heart2 func_801B11C4), or the fail block first and the label after the if/else (fullcare func_801B0AB4). Acopy: c = k;label after the if/else, not inside the third arm, keeps two copies (at the join and in the second arm's delay slot) instead of a cross-jump (heart2 func_801B0F9C). i = 0;written once after an if/else join lands themovein one arm'sjdelay slot and at the end of the other; set inside each arm it floats up (reazer func_801B102C).- Identical case bodies are cross-jumped; three identical cases stayed apart only when followed by an outer case with an inner switch of two or more cases (battle func_800C679C, not the whole rule).
p->f += 0x50;in one arm and-= 0x28in the other giveslhu; addiuand one sharedsh; a temp stored once givesv1(lasboss func_801B1620). Complementary tests as two ifs,if (p->unk2 < 8) {...} if (p->unk2 >= 8) {...}, give a reload ofunk2after thesh(lasboss2 func_801B04F4).- A call argument with an inline ternary,
f(&p->unk4, k2 + (p->unk16 == 0 ? 0x1000 : 0x2000), ...), putsaddiu a0,s0,4early; a local set in an if/else keeps it late (atomic func_801B0548).D[0] = D[1] = D[2] = c ? A : B;on ans32array builds the address registers before the branch and stores after the join (atomic func_801B0E88). - Reorg fills a
bneslot with the nearest independent instruction above it:c = 0x60; if (x == 4) c = 0x40;gotori a1,0x60into the slot only with the following pointer setup written after theif(triangle func_801B008C);i = 0;written after a% 4store (a new basic block) is pulled into thebgezslot (triangle func_801B0DC4). - A master timeline
t = p->unk2; if (t == 0) {..} t -= 4; if (t == 0) {..} if (t == 0xC) ..is sequential ifs on a modifiedt; aswitchgives a binary tree with reloads (graviga1 func_801B0E54). if (p->unk2 <= 0) { p->unk2++; return; }before the loop gives the game'sbgtzover the first-placed else arm (conf func_801B05D0, func_801B0A40).- A range test the game does as
slti; bltzis nested ifs with the else arm written twice (if (t < 8) { if (t >= 0) {..} else {..} } else {..});t < 8 && t >= 0becomes onesltiu(queig func_801B2F34, func_801B2BBC). - A tail the game shares after an if/else is written in full in both arms (or the whole
expression inline in both,
7 - t/t - 9); cross-jumping rebuilds the game's jump, and a call result stored after the join isD_x = f()in each arm (raise func_801B1D04, func_801B14BC, queig func_801B29E0). The same call written in both arms matched where a pointer chosen first and one call did not (lamu func_801B38E8). - A reload of a field into the register an earlier compare loaded is deleted by reorg (jump threading): the branch jumps past it (queig func_801B2274, func_801B1CDC near misses).
- An else arm
p->unk0 = -1; return;gives the game'sjto the epilogue (gospel func_801B2418, func_801B22E8, func_801B3414). A 6-entry jump table needs the trailing emptycase 5: break;(nanntoka func_801B14B8). - A slot allocator in array-index form,
for (i..) if (T[i] == 0) { T[i] = a; S[i].f = 0; return &S[i]; }, gives both of the game's address registers; pointer variables did not (gospel func_801B1294). - Kill-label layout:
if (t < 4) {A} else { t -= 4; if (t >= 4) goto kill; B }, then the stores,goto draw; kill: p->unk0 = -1; return; draw: ..gives the game's block order (m_break func_801B0258); a finalif (p->unkA > 0) { kill: p->unk0 = -1; }that earlier tests jump into matches a shared kill block (m_break func_801B0370, hvshot func_801B0680, func_801B03C0). - Kill block with a shared tail: arm A calls and does
goto tail; arm B's stores come first, thenelse { kill; return; }, then arm B's call, withtail:on the flag test (riva func_801B21B0). D_x = f(..)written in both arms of an if/else is cross-jumped into one store at the join (riva func_801B1744); an if/else with the constant in the else arm gives the game's delay-slotori(lunatic func_801B0B28).- A jump-table state machine whose last case falls into
default: p->unk0 = -1;puts without trouble;q->unk4first,q->unk6 = 0second,q->unk8third in cases 4-6 gave the load order (queir func_801B2590). if (c) { copies } else { p->unk0 = -1; return; }gives the game's kill-block-last layout wheregoto killput the kill block inline (s_beam func_801B0028).- Timeline functions with shared tails: labels inside the later arms (
call4434:,test0:,call:) withgotofrom the earlier arms merge the tails as the game;b = D_80162978; p = &b[..]; q = &b[..]keeps the base ins1(odin2 func_801B4DD4). Sequential range testst -= N; if (t < M) { ..; goto end; }with spawn blocks matched on first drafts (titan func_801B4910, func_801B3358, vahamut func_801B31D8); there(f() << 5) + (s32)bgives the operand order of the later spawns, andD[0] = D[1] = D[2] = 0againstD[2] = D[1] = D[0] = 0picks the order of three zero-byte stores. - When two arms' computations differ only in a register, give the second arm its own
variable, or cross-jumping merges the tails (odin2 func_801B3D10). A random pick
written as the same call in both arms of an if/else matched, where
a = &X; if (r & 0x100) a = &Y;left theandiafter the address load (vahamut func_801B3AB8). - A scale
c = expr << 10 >> 12written in each arm, the default armc = 0xC00, is cross-jumped into the game's shared tail; one multi-setcgavea3/a2instead ofv0(odin1 func_801B4654). Likewise amultwhose result is stored at a join matches when the store is written in each arm: the merged tail islui; lw; mflo; sra; swwithmultin thejdelay slot (vahamut2 func_801B6EF4, func_801B57F4). - Timelines with a shared store tail: positive tests with the early arms first (
if (t < A) { zero stores } else { t -= A; if (t < B) { c = K; stores } else .. }), the stores written in every arm with their own variable per arm so they land inv0, cross-jump intobnez v0,SHAREDwith theliin the delay slot (vahamut0 func_801B2888). - Kill blocks: an early-return kill (
if (t >= N) { kill; return; }) where the asm shows the kill inline, a positive test where it shows it last (kujata func_801B5EDC, func_801B6034, func_801B6CE0);goto done; kill: p->unk0 = -1; return; done:after a timeline's shared store puts it at the end of the timeline (vahamut2 func_801B4AE4); a kill block shared by two chains is laid out with a label inside anifarm (tupon func_801B2A50). - if/else with
k = 0in the else arm putsmove s1,zeroin thebnezdelay slot where a presetk = 0hoists it (tifa func_801B2980); ans32 f(void)with an earlyreturn;that falls off the end keepsv0live and leaves the pause test'sbnez v0; nopunfilled (knights func_801BAD78). - Kill blocks:
if (t < 10) { .. } else { kill; return; }puts the kill last (knights func_801B8744);goto done; kill: .. done:after three byte stores puts it after them (knights func_801BBCE0);goto killfrom the first test into a laterif (unk6 > 0) { kill: .. } else { rest }(alex func_801B3924). Nestedt -= K; if (t < N) .. elseblocks match a timeline whose armsbnez-skip andjto the tail (hades func_801BA404);i = 0; if (i < n)for a second identical guard avoids jump threading (wep4 func_801B164C). if (!(f() & 1)) { .. } i = 0; do { .. }gives the game'sbnezwith the join block'smove s0,zeroin its delay slot (lasboss func_801B22EC);if (t < 0xF || (t -= 0xF) < 0xF)gives theslti/bnez/addiu/slti/beqzpair (odin2 func_801B447C);if (t < N) {..} else { kill; return; }puts the kill block last (odin1 func_801B51AC).- The first jump pass rewrites
if (c) x = load; else x = const;intox = const; if (!c) x = load;with the constant before the branch; no source form put the game'sliinto the delay slot (reazer func_801B058C). - A range test
p->unk2 == 0 || (p->unk2 >= 2 && p->unk2 <= 4)is folded into one range check whosesave_exprcopy gives the game'slh v0; beqz; move v1,v0; addiu v0,v1,-2; sltiuand 8 more bytes of frame;(u32)(x - 2) < 3written by hand gives neither (hades func_801B7594). - Delay-slot fills: hoisting
k = n + 0x80;above itsif (n != 0)guard lets reorg put it in thebeqzslot, with that one statement wrapped indo { } while (0);for the saved registers (knights func_801B9834);if (t >= N) { t -= N; f = 1; } else { f = 0; }instead off = 0; if (..) { ..; f = 1; }keepsf = 0out of the first branch slot (knights func_801B3DB0);c = t < 0x11; if (c) ..putstinv1(erave func_801B1AD0). reorg copies the first instruction of a branch target into a delay slot only when it is a single instruction: a join that starts with the two-instructionlwof a global gets anopwhere the game's starts withaddiu a0,s1,24(knights func_801BCF1C, still 6 words off). k = ((a * 3) << 8) >> 12;written inline in each arm gives the cross-jumpedsll 8; sra 12tail with the game's registers, where a temp (s16ors32) does not (antlion func_801B3910).- reorg's fill_slots_from_thread, after a branch on
==(predicted not taken), scans the fall-through code through a call; when it cannot movemove a0,s0into the slot it rewrites the next use ofa0tos0(sll v1,s0,1where the game keepsa0). Writing that loop asfor (i = 0; i < N; i++)instead of a do-while with its own guard removed it (jammer2 and daionpa func_801B06E4, cho_kyu func_801B1B3C). - cse's copy propagation picks as canonical the register whose last textual reference is
later, so a copy's first use can be replaced by the original before reorg runs (the
.sched2dump already shows it): one variable instead of two that hold the same value fixed field func_800C13B0. Hoisting a copy above its guard (e = n;beforeif (n != 0)) makes cse test the copy; a dead latern = 0;keeps the test on the original (main func_80016340). if (t < 0x14) { A } else { t -= 0x14; if (t < 0x19) { n = 0x100; } else { kill; return; } }gives the game's then-arm-first layout withj join, where a presetn = 0x100;and one range test gave the else arm first (vahamut2 func_801B3600);switch (type) { case 0: .. case 1: .. case 2: break; }with nodefaultgives the compare treebeq 1,x > 1to the end,bnezfor case 0 (shopmenu func_801D1868).while (D[i] != X) { i++; if (i >= 4) break; }gives the peeled first test,addiu t0,t0,1in thebneslot andaddiu t0,t0,-1on the found path (submar func_800AB118).- A switch arm that shares another arm's tail needs an explicit
gotointo that arm (case 10: D_800F38A4 = 1; goto five;with the label in the case 3/5 body): separate copies are not cross-jumped into it; the game'sjwithli v0,5in its delay slot is exactly that (battle func_800DEC10). - GCC 2.7 does not cross-jump two calls whose symbols differ, even at one address:
calling the second arm's target through the address-only name (
D_801B0000, declared as a function besidefunc_801B0000) keeps the game's twojalarms apart (battle func_800D0C80). - Identical case bodies that call the entry point of different overlays loaded at one
address stay apart only with one name per case (
ovl1_801B0040,ovl2_801B0040...: tools/build.py provides any undefined name ending in_and eight hex digits), as the game's own symbols did (battle func_800C679C, 13 cases). - A store through a struct field lets the scheduler move an unrelated scalar store above
it, after which cross-jumping merges two arm tails the game keeps apart; a cast store
kept the order (battle func_800A79CC). A block the game places between the arms of an
ifneeds itsgotolabels at that place. - An
ifwhose body is a dead store keeps the deadmultof its condition (if (z * 4 % 15 == 0) { i = 0; }); an empty body drops it (magic_bioga1 func_801B03B0). - A three-case switch (-1, 1, 7) is balanced into a tree; a linear
beqchain with the bodies after it and a shared join comes fromif (a == K) goto L;chains (battle func_800C5E94).b == 4 || b == 8 || b == 9 || b == 0xB || b == 0xCgives the chainbeq 4; (b-8) < 2u; (b-0xB) < 2uwhere a switch on those cases becomes a jump table (field func_800AAB24). - A
u8compared ask < 6 && k >= 4becomesaddiu -4; sltiu 2; two signedslticome from ans16local in nested ifs (condor func_800AF278) or from two locals read separately (k = o->b2B; j = o->b2B; if (k < 4 && j >= 2), condor func_800B0604). - A fall-through
return tand a branchreturn tshare onemove v0,s1; an earlyif (arg0 == 1) return t;and one finalreturn tgave the game's duplicated move and its delay-slot fill (main func_8003CEDC). In ado { .. if (r != 0) break; .. } whileloop, the return value assigned in each break arm keeps one epilogue with returns in delay slots (main func_8003F830). A chain of call results each compared with the one before matched as flat early returns withs32results and a finalret = c; if (c == b) ret = 0;(condor func_800B3B84, 309 of 311). - An
if (o->unk4C) { o->unk60 = sp; } else { o->unk60 = sp; }with identical arms (no branch emitted) around one store put a load after twoaddius as the game has it, wheredo { } while (0)only half did (magic_satan func_801B4454, permuter). - Cross-jumping merges two stores only when their RTL is identical: a store written
through another name (
D_80051A3C[-2] = -1;for D_80051A34) stays apart, as the game has it (main func_80041AFC); a second read through another name ((&D_80051A38)[1]for D_80051A3C) keeps GCC from sharing an address register (main func_800418D8). When the game has one shared tail after several branches with the tail's loads in each predecessor, write the tail in full in each branch: GCC schedules the loads up into each branch and cross-jumping merges the identical suffix, where a goto to one shared label leaves the loads in the tail (battle func_800E0E34). - Spell timeline scripts are nested
t -= K; if (t < N) { if (t == X) .. } else { ..chains with the tail after the whole chain, not inside the last else;if (t <= 0) {..} else {..}gives abgtzout of line (magic_vahamut2 func_801B7610 and the spells99 batch). A switch-shaped dispatch needs a realswitchfor the compare tree;case 0: case 4: break;makes GCC 2.7.2 emit a jump table instead of a compare chain.t = A; if (B) t = 1;gives the game's A-then-B shape wheret = A || Bdoes not.ret = 0;moved inside an if body fixed a prologue save order (condor func_800B5678). A selected call argument written as two calls (if (c) f(j, 0); else f(j, 4);) stops GCC making it a shift (condor func_800A2640). - A second test of a global the function tested before (
if (D_80062D98 != 0) return;after a block guarded byD_80062D98 == 0) gave the game's jump, to the test itself rather than threaded to the end, only when read as volatile: through a file-scope aliasextern volatile u8 vol_80062D98;. A block-scopeextern volatileredeclaration matches alone, but GCC keeps the volatile type for the rest of the file and put refused it. The camera-script interpreter of the summon spells (about 1040 instructions, in many overlays) differs between overlays in exactly such places: an early exitif (flag & 0x80) { p->unk0 = -1; return; }whose store cross-jumps with the switch's default, one case more or less (the jump table's equal.wordtargets are case labels of one block:case 0: case 8:), other constants, a field at another offset, and where thep->matblock sits relative to the pause test (inside it in lamu, so CSE reuses&D_801E7DC0from the loop end in s1). for (c = &r->c[0]; c < &r->c[5]; c++)keeps the game's loop guard (sltuagainst the end pointer) thatdo { } whiledrops (world func_800A71E8);k = 1;before an unrelated copy andfor (; k < 6; k++)gaveli s2,1in the game's place (highway func_800AB738); two vertex loops that the game leaves unreduced and unhoisted are writtenl1: ..; n++; if (n < 16) goto l1;(magic_garyu func_801B0480). Three loops sharing one variable keep a shared sb/jal tail merged, one variable each splits it (battle func_800E7170); a call written in full in each branch of an if gives the cross-jumped tail and stops early constants being hoisted (battle func_800E2098).- cse puts an operand with a known constant value second:
mult const_reg,xneeds a constant register cse does not know, and a base-firstadduneeds a base that is not a known constant at that point (magic_hades func_801B7A70, snobo func_800A0F1C: inferred from the .cse dump, not proven). Abeqzdelay slot holds the last independent instruction written above it (snobo func_800AAFE8:q = arg0->z;before theif); writing the first iteration of a loop out by hand (v += 6; n -= 3;beforewhile (n > 0)) stopped GCC merging two loop tails into aj. - A
for (i = 0; i < n; i++)loop keeps its first guard branch pointing at the second guard;if (n > 0) { i = 0; do ... while (i < n); }lets jump threading send it to the function end, which makess1look live there so reorg fills the slot withmove v1,zeroinstead ofmove s1,zeroand 16 bytes of frame pad appear (magic_wep4 func_801B2320). Withi = 0written before thelhuof the count combine drops the "n is non-negative" knowledge and the guard becomesblez;s32 nwithfor (i = 0; i < n; ...)(the init inside thefor) gives the game'sbeqzguard and signedsltend test (magic_brizag2 func_801B1B68, func_801B200C).i = 1;written beforeif (lim > 0)lets reorg fill theblezdelay slot.
- An address stepping by a constant: write
base + i * 0x20and let loop optimisation make the stepping register, not a pointer advanced by hand. A loop that only counts a byte offset down tobgezisfor (i = N * sizeof(T); i >= 0; i -= sizeof(T)). - Loops over struct arrays:
p = &D[i];inside the loop. - Counters declared
u16giveaddu n, n, 0xFFFF+andi; wheren--sits decides which constants are hoisted first. Au8loop bound givesbeqzat the loop entry. - A constant left inside a loop with a call: a
gotoloop stops it being hoisted. - Doubled address computations (
&D[i]used twice) come from a flats32array indexedD[i * 2]andD[i * 2 + 1]. - The exception: a loop register kept at a struct's last field, the other fields at
negative offsets (
-8(s0),-16(s0)), is a pointer advanced by hand (p = D.o; ... p->x = v; p++;). - 2.7.2 reverses a loop that only stores: a counter from N-1 down to
bgezand a pointer stepping down from the array's end isfor (i = 0; i < N; i++) a[i] = c;. - Registers stepping by a constant, set up after the hoisted constants, come from an
expression of the counter at each use:
(s16)(x + i * 0x10)in a call, or a row countern * 0xB + 0x9Awithn++inside anif(two such registers swap if written as two variables). A loop ending inslt p, base + 8is aforoverireadingbase[i], withioptimised away. - A counter that must get the first free register:
n++in each branch (the tails are merged only after register allocation). - 2.6.3 reverses store-only loops too. A clearing loop
ori v, N; li a, -1; ... bne v, aisfor (i = N; i != -1; i--) *p++ = x;(an indexi < N + 1givesbgez). s = ARR; s[i].f = x;loads the base before the multiply, so strength reduction skips it (the game keepsi*5and shifts each pass);&ARR[i]gets reduced. A row base built after the multiply in the same register:name = D[n]; ... name[i]inside the loop.- A loop-bound global read as
lui; addiu; lh 0(aN)and copied withmovebefore the loop: an array readD_x[0]. A bound copied before the loop: ans16local,s16 end = i + n; for (; i < end; i++). - 2.7.2: a conditionally filled local buffer is
buf[n++] = v;(not*p++ = v; n++;). do { ... } while (--i != 0);wherei--;before anifgot the decrement scheduled before a call.- A copy loop with its guard,
lh; li -1; addiu -1; beq:n = p->cnt; while (--n != -1) *d++ = *s++;(for (i = n - 1; i != -1; i--)folds the guard intobeqz). A countdown entryli 8; addiu -1:n = 8; loop: n -= 1; if (n != 0) { ...; goto loop; }. - A ring index
k++; if (k >= N) k = 0;overD[k].fgives the game's stepping pointers and their reset at the wrap; based at the real struct start, not at field symbols. - A store-only loop
for (i = 0; i < N; i++) { o = i * K; D[o] = c; }givesli (N-1)*K; addiu -K; bgez. A byte offset advanced by hand (off += 0x4C) stays an unreducedbase + off, wherei * 0x4Cor&a[i]is strength-reduced. - Division in a loop:
forwith the expression inline hoists only the sign shift, a goto loop hoists nothing,do/whilewith a temporary hoists all of it. Values carried over from the previous pass (the game skips a first pair ofranddraws): uninitialised locals declared outside the loop. - Don't declare a strength-reduced pointer: the loop optimiser bases it on the textually
last access through
p(p->codelast givess0 = p + 7), so reorder the parts of the body to move the base; writea->unkC, not a second pointerb = a + 0xC.p++; i++versusi++; p++in the tail decides which copies land in delay slots; array bases hoisted into locals before the loop (a = D_x; ... &a[i]) give hoistedlaregisters and (base, idx) order. - loop.c hoists constants out of
for/while/doloops; in a goto loop they stay inside and the delay slot is filled from above. Goto loops for both an inner and an outer loop keep a function table'slafrom being hoisted and spilled around a call. - A loop-invariant load of a global pointer is hoisted only if the loop's stores are
struct-member accesses (scalar
*(s16 *)casts block it);-dLreports "not desirable" for a life-1 invariant when the loop has more than about 46 insns. - Strength reduction: a named giv temp
w = i*12 + 16; p->x1 = arg2 + w;after the statement creating the first giv keeps the game's stepping registers, where inline `arg2- (i8 + 8)
is reassociated into(arg2+8) + i8; the order givs are created decides which increment comes first.for (...; i++, e++)keepsea biv.arg0 + i * 0x34 + 0x20avoids the giv rebasingarg0 += 0x34causes. A struct array with fields at 0, 2, 4 gives three stepping pointers (addiu a2, a0, -2; addiu a1, a0, -4), and scans over 8-byte entries index((T *)list)[i].f7` with no biased pointer.
- (i8 + 8)
- A
forloop around an if copiesi + 1into the branch delay slot; do/while withi++at the end does not. A loop-invariant row term as a local (row = a->f; D[row][n].g) keeps a byte-offset induction variable. A constant divisor assigned before a loop (nx = 0x1F40;) gives a realdivwith it in a saved register. - 2.7.2
-funroll-loops(chocobo) gives up ("Loop too big") when twice the body exceeds 100 insns, and unrolls modulo-style when the bounds are not constant; goto loops are never unrolled, hoisted or strength-reduced. - Strength reduction uses a knife-edge size test (
-dL:giv ... not worth while, 56 vs 57): one extra insn in the loop ((u8)uforu & 0xFF) loses a stepping pointer, and a pointer variable shared by two loops makes its giv not worth it: one pointer per loop.e = e0 + i * 8withe0 = tabread before the loop gives an unbiased stepping register wheree += 8ore[5]reads get rebased. - Base registers:
tab = D_x;before the outer loop withtab[i]inside, orv = &D_tbl[i]; v->vx = ..., hoist the base and give the (idx, base) order (D_tbl[i].vxrematerialises it); base pointers assigned inside each of two loops and used as&base[i]give hoisted bases.D[a].f[i]and a pointerw = D[a].g; w[0x12 + i]give two stepping registers. Strided clears over interleaved globals:D_x[off] = 0withoff += 0x18; a flag array as fields of a struct array (D_x[i].pad3[2]) gives thelui/addiu/addu at, s0form whereD_x[i * 0x18]becomes an address giv. - Loop invariants are hoisted in statement order (
fp = &v[1]; a = ...; b = a + 8;before the loop); hoisted constants come out in stream order with acol = 0at the loop top ahead of them, and a variable set inside a conditional block is never hoisted.for (i = 0, n = 6; i < n; i++)putsi's init before the bound;do {} whilelets a constant be hoisted into a saved register, a goto loop keeps it inline. - loop.c moves an invariant only when
threshold * savings * lifetime >= insns in the loop(-dL: "savings N moved" or "not desirable"), with a threshold between 10 and 20, about half in a loop with a call. So a loop's size decides what is hoisted: a jump table's single-uselaonly while the loop is under about 104 insns (battle func_800B5138, where assigning the base pointer inside the body made it the hoisted movable), eight uses of 1 up to 730 insns and not from 746 (field func_800ACC5C, padded to the game's size with neutralx << 4 >> 4pairs that combine folds away, with a comment in the source). - What blocks or allows hoisting: a call inside the body blocks hoisting of its memory
loads (constants still move) and pointer stepping on the index, and the exit paths then
need
i++; continue;copies; adjacents16globals declared as one struct keep their loads in the loop where scalar globals are hoisted; stores through a locals16 m[36]let a plain global load be hoisted, stores through ans16 *pdo not;M2C_SFIELD(D_x, ...)lets the loop hoist a global pointer whereM2C_FIELDreloads it.while (1)withbreak/continuehoists small constants and products (id * 0x84) into registers;gotoloops recompute them per block. - Guards:
i = N; if (i < n) { init; do { ...; i++; } while (i < n); }puts hoisted constants and giv start values after the guard branch; guarding through one pointer and looping through a copy gives themove t0, v1after the guard.i = 0; if (D_x > 0) { n = D_x; do ... while (i < n); }givesblez v0plusmove a1, v0. A guardori v0, 1; beqz v0, exitcomes fromp < D_x + 0x800withpstarting at the same symbol (main func_8003FE98). - Pointers and givs: pointer accesses in a loop (
p->f24,p++) combine into one reduced pointer based at the last access ("giv ... combined");volatile T *pkeeps the original biv, and explicito += 0x34offsets next tosym + ostay unreduced. A base-pointer local (e = D_x; e[i].f) keeps one stepping pointer with field displacements and flips theadduorder,D_x[i].fgives one pointer per field;off = i * 0xB9C;at the body's top gives one stepping register shared by several symbol-plus-offset accesses (dejon func_801B0818); whenq = &D[i]is not reduced,D[i]at each use gives the stepping pointer. Readingp[1]andp[2]creates ap+4register based on the last-created giv: write them in the game's order. A localn = D_x << 5with byte offsets*(s16 *)((u8 *)D_y + n + k)shares one index register.D[i].name[0]through a struct array keeps the byte read unfused (lui; addiu; addu; lbu) where a flatu8[]fuses it. - Hoisted bases:
la T; move s, Tbefore a loop appears when an element-0 access of the same symbol comes earlier in the block; a user pointertp = &D_x[0]used as*tpin the loop fixes their order, and a sharedla s0after calls comes from a pointer-to-pointer (tp = &D_x; (*tp)[i]).*(volatile u16 *)&D_xgives a hoisted address plus anandi 0xFFFF; a plainu16 *p = &D_xassigned inside the loop's conditional block hoists only the address.D_x[n++] = id;under a condition gives the hoisted output pointer after the hoisted constants,*q++ = id; n++;sets it up earlier. - Loop shapes:
for (i = 0; i < n; i++, out += K)emitsi++first among the increments, the same increments in the body last.do { ... } while (++j < 2)withs16 jgives pre-increment tests. The length itself as the copy counter (if (n != 0) { e = n; do { copy; e--; } while (e != 0); }) fixed an inflate copy loop; an outerwhile (1)aroundfor (n = 7; n != -1; n--)keeps -1 out of a saved register. An up-counting loop with hoisted invariants and an apparently empty body isfor (; i < 10; i++) { if (mask << i & D_x) { q = &D_y[i]; } }withqused later; an emptyifbody is deleted early and gives a reversedbgezloop (faiga2 func_801B162C). - Unrolling (-funroll-loops): a 3-iteration loop over an ARRAY_REF is modulo-unrolled,
indexed through a pointer (
((s32 *)D_x)[k]) it is unrolled completely (chocobo func_800AB410). Unrolled 3x5 output loops need two-term indices (i * 8 + n * 0x18) for the game's stepping registers. for (i = 0; i < 10; i++) { if (...) }matched where the same loop asdo { ...; i++; } while (i < 10)let reorg rewritesll v1,a0,1aftermove a0,s0intosll v1,s0,1(nadare func_801B1C54; seen with-fno-delayed-branchand the.dbrdump).q = D_8009D84C[i]; p = (u8 *)&D_800F83E0[i];bases each pointer giv at field 0 as the game; hand-advancedp += 0x68is rebased to the last field (battle func_800A3ED0).off += 0xB9Cwith*(s16 *)((u8 *)D_x + off)shares one stepping register across three arrays;*(s16 *)&D_x[i]gets a pointer giv of its own (battle func_800CD860).i = 0;thenfor (; i < 3; i++)gives the game's prologue order (battle func_800A9DA0). Word scratchpad values read into locals before struct-member stores hoist above the byte stores (battle func_800CD860).- Strength reduction:
D_x[i * 0x74] = 3becomes a pointer giv;n = i * 0x74; D_x[n] = 3;in the then-arm keepsaddu at,at,s1(grenade func_801B0C64).D_x[off]withoff = i * 0x44giveslui at; addu at,at,a1with a stepping integer (battle func_800AF9C8), andoff = i * 0xB9C;at the top of the body with(u8 *)D + offgives unfusedsym+regloads andaddiu s2,s2,0xB9C(heart2 func_801B17A0). AnM2C_SFIELDstore in the loop lets loop.c hoist the global pointer asmove a2,a1. - Loop base pointers (
ta,tb,td) set beforen = ...hoist theirlui/addiuabove the guard and let the&D_xregister be reused as the counter (rocket func_801B0D98). Padding a loop body with dead arithmetic that flow deletes later stops a small invariant (addiu v0,sp,0x28) being hoisted (battle func_800C223C), as in field func_800ACC5C. - A
forloop putaddiu v0,s3,1in the branch delay slot wheredo { } whileleft anop(tail func_801B0FA4). j = i * 8; off = i * 0xB9C;at the top of a loop body gives the offset-register givs in the game's init and increment order (spark func_801B2014). Loop base pointers assigned in the orderba, bb, bdbefore the loop give t6/t5/t4, whatever the declaration order (hyper func_801B1AC0). Unsolved: h_blow func_801B0640 keeps an unfolded loop guardori s2,zero,0x200; slti; bnezthat GCC folds in every loop form.- A
forloop withn++as the increment matched wherei++lands in thebeqz/blezdelay slot (sting func_801B3AB0, func_801B35F0);a + (i * 0x34 + 0x174)gives a giv starting at 0x174 (sting).for (i = 0; i < n; m++, d += 10, i++)with a variable bound gave the delay-slot order of the increments and explained an 8-byte frame pad thatdo { } whileneeded by hand (brizag func_801B0E48). Aforloop with abreakat the top keeps aD_80162080guard inside the loop wheredo { } whilerotates it (conf func_801B05D0). - Locals for loop-invariant addresses set at the top (
fd = &D_x; tbl = D_y;) sink below the first calls; arrays used directly in afor (i = 0; i < 3; i++)put the sets where the game has them (dia func_801B0CC4). - A table indexed
(i*16 + j) * 4: an explicit byte offset (off = i << 6; ... *(s16 *)((u8 *)D + off) = ..; off += 4;) puts thesllbefore the pointer-copymove, an indexk = i * 16; D[k]gives the other order (timedmg func_801B06E0). - The first constant written in a call-free loop body is the one hoisted: writing the `i
- 7 / 10
divide first hoisted its magic multiplier as the game, where a0x606060store at the top hoisted that constant (nanntoka func_801B0C74).k = 0x320;inside the loop body keeps(u16)p->f - k + rand() % Nasaddiu -0x320`; outside, it is hoisted into a saved register (gospel func_801B31BC).
- 7 / 10
- The order of two adjacent stores at the end of a loop body decides where the counter
increment lands:
q->unk10 = 0;beforeq->unk14 = 0x200;putaddiu s2,s2,1after the secondjal(hakou func_801B1090, found by the permuter). for (i = 0; i < cnt; i++)withi = 0in the header gave the game'sbeqzguard on ans32 cntloaded asu16;i = 0;before the loop gaveblez(queig func_801B0074, func_801B034C). Aforloop around anif (n > 0)arm put thei + 1copy in theblezdelay slot and dropped the stray nop of the do/while form (bushin2 func_801B1580).&D_x[i]instead of a hand-advanced byte offset gave the game's stepping registers (hakou func_801B11D0); alen = cnt;copy before a loop putmove s3,t3ahead of a hoistedlui s4, and one counter and onee = &tc[..]pointer shared by three loops gave the game's registers (gaisei func_801B28DC).- A constant multiplier stays a register
multonly when it sits in a local first (m = 0x22AA;before the loop);0x22AA * kbecomes shifts and adds (raise func_801B07A4, func_801B04F0). - Unsolved: h_blow func_801B0640 and gospel func_801B2F00 keep an unfolded loop guard
li s1,0x100; beqz s1that GCC folds; no loop form, inline helper, field or array element kept it. off = i * 0xB9C;at the top of a loop body gives the game's init order of the stepping register and a hoisted constant (lgirl func_801B093C).- A word-copy loop
*d = *s; s++; d++;with an extrai += 4counter gives two pointer bivs plus a byte counter (slow func_801B07FC);p++gives thep + 4stepping pointer of a table loop (slow func_801B013C, func_801B0020). Pointer-increment loopsa->vx += b->vx; a->vy += b->vy; a->vz += b->vz; a++; b++;overMgSVec *parameters give the game's split pointers, one forvxand one at +4 forvy/vz(riva func_801B2670, func_801B254C, func_801B1744). - Giv reduction (
-dLdump): a giv is reduced whenlifetime * benefit * threshold >= insn_count; a load and a store to the same address combine into one giv with two uses and get reduced. Writing the store through another symbol view (*(s16 *)(D_801B4458 - 4 + o)for a store toD_801B4454 + o) stops the combining and keeps the game's unreducedsym(reg)form; one more RTL insn in the loop can flip the decision (deadsef func_801B2908). - A loop over a
u8[]symbol: an explicit offset((SdPart *)(D_x + o))->f0witho += 0x18keepslui at; addiu at; addu at,at,o, and au8 *qsteppingq += 0x18beside it gives the game's three stepping registers (sdust func_801B05BC).for (k = 0, v = 0; ..; k++, v += 0x18)putsmove k,zeroin the backward branch's delay slot. p = &D[i]; p->count = 0; p->tail = 0; D[i].head = 0;in a loop gives a giv based at offset 0 with amove a0,v0init (sldfang func_801B0754).- Index records as a struct
{ u16 a; u16 b; u16 c; u16 pad[5]; }stepped witht++give the game'sbeqzguard on anlhucount and a derived pointer giv forbandc; a plainu16 *ewithe[0..2]gives neither (queir func_801B0094). For quad-centroid loops a record struct{ u16 a, b, c, d; u16 pad[N]; }stepped withl++gives the game'ss5 = l + 6stepping register (brizag2 func_801B123C, func_801B17E8). - Pointer-increment loops with
d[i].vxindexing for the destination andb++; a++;(source first) give an unsplit destination pointer and the game's increment order; diagonal matrix stores written in each arm of at < 10 / else ifchain are not sunk below the argument setup (ifleet func_801B14E8). for (i = 0; i < 0x121; i++) { off = i * 8; .. (q + off) .. }gives one strength-reduced base register and unreducedsym+offfor the others (vahamut func_801B1804);o = i * 0xB9C;written after the first copy statement gives an unreduced byte-offset register beside two pointer givs (satan func_801B58DC). A table base assigned inside the loop right before its use is hoisted after a magic multiplier, assigned before the loop it is hoisted first; a do-while withi++written right after the first load puts the increment in thebeqdelay slot (satan func_801B2048).- In a call-free loop,
reg + &symfor an 8-byte copy becomes a reduced pointer giv (lwl 3(t2)) where the game keepslui at; addiu at,sym+3; addu at,at,t0(titan func_801B5190, unsolved). - A global used inline in a loop (
&D[i * 6 + 3],D_801EDC44as element 0) is hoisted into the preheader after the guard; a user variable holding it is set before the guard (tupon func_801B4E00, func_801B592C). A one-field struct view of a table read inside a loop (MgWord D_x[],.v) stops loop.c from hoisting itsla(vahamut0 func_801B3398); a spawn loop withpandqboth&D_80162978[i]keeps one hoistedla, a goto loop keeps it inside as the game (vahamut0 func_801B60CC).k = 0x7D0;assigned inside the loop gives amultwith the constant hoisted at loop entry (kujata func_801B54CC). - Dropping an offset variable
o += 0x30fori * 0x30 + (s32)&D[k]everywhere gives the game's three stepping registers (tupon func_801B4E00); elsewhere explicit running offsetsk = 0x1080; row = k; col = 0; .. col += 0x78; k += 0x780give the prologue order and loop registers where ani-derivedkmerges with the giv (vahamut0 func_801B5884).MgSVec D[][6]indexed[n][j]givesn*48 + j*8withj*8shared (tupon func_801B51E0);i++between two row loads with(u8 *)base + (i << 7)forms matched an unfolded second row (kujata func_801B7CFC). s32 n = *(s16 *)..instead ofs16 nkept a loop bound ass7 + s6in the condition (siva func_801B3938).i = b * 5; n = i; for (; i < n + 5; i++)gives a folded-compare guardori v0,1; beqz v0,end(odin1 func_801B32BC).- Angle tables:
f(i * step)withstep = 0x1000 / ncomputed before the loop gives the game's angle register with its init after the guard, whereang = 0; ang += stephoists themoveabove the divide;p = &d[i]insidefor (i = 0; i < n; i++)gives one reduced pointer wherep++splits it (tifa func_801B1CD8, func_801B1BEC). - Inside a loop with an explicit
a += 4biv,b = (u16 *)a + 2;becomes a giv whose preheaderaddiu t0,a0,8lands after loop.c's other givs (knights func_801B5B7C). A goto loop over ans32byte address (e += 0x18; if (e < end) goto loop;) stops GCC splitting a stepping pointer intoeande+2(wep4 func_801B164C); an outer pointer loop with unreduced field offsets matched only as a goto loop (hades func_801B8404). - A search loop
while (T[D] != 0) D = (D + 1) % 20;puts the table base before the guard and its constant ina2, whereif (..) do {} whiledoes not (phoenix func_801B2490).D[idx] <= D[idx - 1]keeps the-1out of the displacement (a hoistedD - 1register),D[idx - 1] >= D[idx]folds it (knights func_801B5E4C);D_801F1250[i].num = 0; D_801F1250[i].start = 0;with ans32 igives the game's addressing (hades func_801B51F0). - Indexing two tables with the loop counter (
D_801F2AF0[i],D_801F2B10[i]) gave the game's reduced pointer registers where explicitsrc++/w++pointers swapped them (odin1 func_801B5D14); a zero-fill loop overD_x + i * 0x18stops reloading the global when writtent = D_x + 0x948; for (..; i--, t -= 0x18) *(s16 *)t = 0;(tifa, spells 79). - The unfolded loop guard: the game tests a counter before a loop that GCC would fold
(
ori s1,0x100; beqz s1, orli s2,0x200; slti v0,s2,0x100; bnez) and its frame is 8 bytes bigger. It is a variable-start accumulator whose masked part is always zero:n = (p->unk2 * C & 0xFF) + C;with C the guard's constant (0x100 givesori; beqz, 0x200, 0x400 and 0x800slti; bnez), then `if (n >= 0x100) { do { ..; n -= 0x100; } while (n= 0x100); }
or a plainwhile (n >= 0x100) { .. }. cse1 cannot fold the guard and combine folds the masked product to 0 later; the extra pseudo gives the 8 bytes, so drop anyu8 pad[8](twelve functions in phoenix, vahamut, vahamut0, vahamut2, gospel, h_blow, siva, knights, spells 83 and 84).n -= 0x100;as the last statement of the body, after the lastrand()statement, lands in thebgezdelay slot;t = p->unk2;` before the first store loads it early (vahamut2 func_801B712C, knights func_801B9408). - A loop invariant written as its own statement before the loop guard (
kk = k * 2;right afterh = k >> 1;) lets reorg fill the guard'sbeqzslot with itssll, where an inline% (k * 2)is hoisted after thelui/addiu(tifa func_801B6938);for (i = 0; i < cnt; i++)with a bound from au16gives the game's spill slots (cntat sp+0x10, the dead compare at 0x18) with no pad (seald func_801B0074); loop.c reduces a pointerhused with offsets 12/8/4 toh+4where the game keepsh(hades func_801B3578, 5 words off). - loop.c's combine_movables merges two
li 1of a loop into one pseudo live across a call where the game keepsli v0,1andli v1,1(snobo func_800A5E80, 4 words off);p += 0x24; t++;at the end of a body flips which giv init is emitted first; a stepping pointer writtenc = r + i * 0x34;at the top of the body gives the game'smove s2,s1with+0x68displacements wherec += 0x34;gave a biased base (knights func_801B56D4). - A pointer the game addresses with one negative offset for every field (
-0xA4(sN)) is a giv: compute it inside the loop from the first pointer (p = (u8 *)ch + 0xDC) and use it only as a call argument (akao func_8002F848). - A dead assignment (
w = 0;right afterp[3] = 1;) splits the constant pseudo that combine_movables merged across a call, giving the game's separateli v0,1for the store andli v1,1for the compare (snobo func_800A5E80). - A backward
gotoloop instead offorstops loop.c hoisting invariants: the multiply chain and theluipairs stay inside, as the game has (battle func_800B5AAC).i = p->unk0 - 1;as its own statement beforen = 1;stops GCC folding(x - 1) * 16into a table offset (magic_odin2 func_801B3F54). - A variable set once is a giv candidate: setting it in both loops, or a fresh variable
per loop, stops that (magic_vahamut0 func_801B53C0). GCC 2.7.2 reduces an offset giv in
a loop with calls where 2.6.3 does not, for the same source (magic_garyu func_801B0480
against magic_tupon func_801B3668). A plain copy of a packet pointer used as a call
argument becomes a giv at offset 0 and the other stores rebase on it: pass
(s32)p++or store the last fields through a copy (magic_kujata func_801B3EA8). - GCC 2.6.3 reverses a loop to count down only when its body is bivs, givs, stores and the
compare: an address built as
base_reg + givin its own statement (tab = D_..; off = (i << 7) + j * 8; *(s16 *)(tab + off + 2) = v;) stops the reversal (magic_antlion func_801B22D4, magic_hades func_801B62E0). - Reads of the previous element through a second counter kept as its own (
for (i = 15, k = 14; i >= 0; k--, i--)) keep a separate stepping register, wherei - 1merges into i's (magic_tupon func_801B3A08). Indexing a hoisted array base (D_800F4938[s1]) gives the game's loop-invariant hoists where a pointer loop gives none (battle func_800AABBC).x = i * 0xF00 + 0x1100written from the outer counter gives spilled givs where a stepped variable does not (magic_knights func_801B33E0). - A copy loop
for (i = 7; i != -1; i--)in astatic inlinehelper keeps itsli a3,-1in each loop's own preheader, where the same loop written inline in an outerwhile (1)hoists the -1 into a saved register (main func_8003EC60). D[z].v[x]in nested loops matched where a row-pointer local strength-reduced the inner index (magic_satan func_801B23E0);func(.., q); q++;instead offunc(.., q++)gives the loop address q + 0x14 (magic_knights);t = i + 1; i = t; .. while (t < D)gives the game'saddiu; move; sll; sra; sltonly withs16i and t (big6); a sum(T + K) + co + rowith loop variables is hoisted and spilled when ro comes last after a symbol and a constant (magic_escape func_801B009C).- loop.c moves a loop invariant (a symbol's
lui/addiu) out of the loop only when threshold * savings * lifetime >= the loop's insns (threshold 1 + the non-fixed registers, halved when the loop has a call), and a user variable's set only when it runs every iteration;work/spells19/dump.py TARGET WORK.c NAME -dLprints each decision ("moved to" or "not desirable", with life N). An address set right before its single use stays in the loop:o = idx * 0x84; jj = j; q8 = D_8009C748[0] + o; a3 = q8[jj];keptlui v1; addiu v1in the loop whereD_8009C748[idx][j]was hoisted into a saved register (battle func_800E2098). - Reading a global scalar as an array element,
extern s16 D_x[];andD_x[0]twice or more, makes loop.c hoist the symbol's address as its own invariant, ordered among the loop's other hoisted constants by its first use in the loop (the game'sli s4,0xfffork != 0xFF, then the address, thenli s3,0x30: formmenu func_801D0E94, 736 instructions, which matched after many batches); with reads across calls the address lands in a saved register (highway func_800AB738: one read into a local, or other address expressions per use, stop it). A pointer variablepc = &D_x;set before the loop puts the address ahead of every other hoisted constant instead, and set inside the if it is not moved at all. Try the array form when the game holds a global's address in a register and ours useslui at(the notes of battle func_800E60F8, func_800B46B4 and condor func_800B7EC0 describe that difference). - Fields of a global window written through a struct view (
D_8010BC3C.x,.y,.h) instead of separateu16externs at the same addresses stop GCC treating the stores and the later global loads as aliasing, so it hoists the loads out of the loop as the game does (condor func_800B8954 went to the game's length). Two base pointers set up front (base = (u8 *)D_80151A4C; base2 = base - 8;) gaveaddiu a1,a1,-8plus an offset add where the global written inline gave lui/addu forms; oneo = k * 0xB9Cshared by the copies of a loop removed 16 words (magic_tifa func_801B5C74); a byte-stepped offset used for one array only stopped GCC hoisting that array's base (highway func_800AB738). - loop.c moves an add for free once the symbol it uses moves (
-dL: "cond forces savings 2 moved"), unless the add's result pseudo is set twice, and moves the symbol alone only when its life is at least 2: the game'slui s5hoisted with the add left in the loop came fromtbl = (u8 *)D_800E7B1C; b = e->b; p = tbl + o; p = *(u8 **)p; (*(void (**)(s32, s32))(p + b * 4))(e->a, e->c);(the load between the symbol's set and its use gives it the longer life, the pointer assigned twice keeps the add: battle func_800A72C8). loop.c eliminates a biv only when its pseudo has no use outside the loop by insn uid, so sharing the loop variable with another use keeps the game's biv with itsaddiu a0,a0,48andsltu(world func_800A71E8); a search loop writtenwhile (p != NULL) { if (..) break; q = p; p = p->next; }is recognised whereif+do-while(a multi-entry loop) is ignored.*(volatile s32 *)&h->f = 0stores keep4/8/12(h)addressing where loop.c combines them into oneh+4giv and eliminates the biv (magic_hades func_801B3578); a pseudo set twice in a loop is not hoisted (c = 2; ..; c = 0x3D6;keeps compare constants in the loop: battle func_800B46B4); a loop written withgotokeeps constants in the loop where aforwith a call hoists them into s4/s5, andfor (i = 6; i != -1; i--)givesli t,-1; bne(snobo func_800AAE98). - loop.c hoists a user-variable constant such as
k = 0x7FFF;set once in a loop body out of the loop; a deadk = 0;earlier in the body gives it two sets so thelistays in the loop (magic_siva func_801B1B5C). A constant held in a user variable set before the loop (cw = 0x78080000;next tocc) fixescw + toperand order, and itsluican still stay in the loop (hmoon). Declaringextern struct { u8 f; u8 pad[0xB9B]; } bt_8015190F[];as an alias of a 2-Du8 [][0xB9C]stops loop.c hoisting the symbol's address (it removed a saved register in magic_geki2 func_801B10BC and gavelui at; addiu at; addu at; lbu 0(at)).for (...; i++, p++, it++)againsti++, it++, p++decides which strength-reduced giv is initialised first. A scalar that decls.h declares and the game reads and writes through an address register (lui; addiu; lhu 0(v1); ...; sh 0(v1)) isr = &D_x; *r += k;: redeclaring it as an array in the work file makesputrefuse (an earlier function stops matching) and(&D_x)[0]gives directlui ataccesses. combine_movablesmerges identical constant loads into one hoisted pseudo (savings 2, life 2) that stays hoisted in every loop tested (up to about 140 real insns; "not desirable" only at about 159, so padding the loop is no lever). A pseudo with two sets (a dead pre-loopk2 = 0x2C000000;plus the inner set; a deadhd = 0;withhd = (s32)(hdr << 16) >> 24;inside the loop;h = 0;at the loop top plush = arg1 >> 1in theif) is not a loop.c movable: flow deletes the dead set, the constant is block-local at local-alloc and takes the game's register, and a shift stays in the loop as in the game (magic_vahamut2 func_801B0184, magic_nanntoka func_801B192C).- loop.c processes the bivs in reverse order of their increment insns: the giv inits come
out in that order and each biv's giv increments come out just before its own increment,
so
m++; e++;instead ofe++; m++;moved a giv's init and gave the game's allocation (magic_brizag func_801B116C: 56 differing lines down to 6). Frame spill slots are handed out in pseudo order and dead pseudos still get one (the slt/sext temps combine removed; afor (i = 0; i < n;)loop creates its compare pseudo before the body's pseudos):for (i = 0; i < n;)in place of a do-while and ans32local for the sign-extended loads fixed the frame size and slot offsets. Innerfor (;;)loops written asL: ... goto L;stay inside the loop for loop.c, wherefor (;;)lets it hoist an index chain and an address (main func_80021F58: 779 to 764 instructions). A pointer set after a call (qv = (MgSVec *)&D_801F5334;) used for two reads giveslhu v1,0(s0)as in the game;r = &D[i]; c = &D[i].col;gives separate value-giv registers with amove s0,t0init. - Accessing decls.h's struct array (
D_801E0EA8[found].y = ...) instead of a separateoff = found * 0x14makes the multiply one pseudo that lives across calls, directly in s0 (cse copied the variable into s0 after the first call otherwise); au8array written as*(u8 *)(D_801E0EB8 + found * 0x14)makes loop.c hoist the symbol address into s7 and s8 and adds 8 bytes of frame, while a work-file struct array does not (magic_nanntoka func_801B1D48).s32 pwith asltagainstarg0 + 0x2850, void * parameters and threep += 8;that raise p's priority above s gave magic_hades func_801B8404 the game's s0/s1. - main func_800140F4 matched with:
rect.y = 0xF0 + i * 0x4Ain place of a manual runningy(a giv ofi: the preheader order then follows the game); the first loop'siand innerkreused as the counters of the two later loops (that fixed every saved and temporary register);off = k * 8 + i * 0x40;computed in the inner loop instead of steppingoff += 0x40, which stops loop.c making atbl + offpointer giv; the table base held in a variable (tbl = (u8 *)0x8019D5EC;,off + (s32)tbl) foraddu v0,v1,a3and the hoisted a3; a constant cast ((u8 *)0x8019D5EE + off) forlui at; addu at,idx,at; andi = 0;only after theif, with no pre-set, so reorg copies the join's first insn into the branch slot. In magic_odin1 func_801B2BE0 the kill block written inline asp->unk0 = -1; return;withs = 0xF00;after theif (t >= 0x78)test gave the game's arm order (the /15 arm first, ending inj). - loop.c emits the giv inits in reverse order of the first biv increment in the loop
(
p++; i++;againsti++; p++;); a dummyp++; p--;at the top of the body gets an order that the use ofpafter the other biv's increment forbids, but adds about 8 weighted references (snobo func_800A5964).for (i = 0; i < 4; i++)witha->sxy[0][i]anda->sxy[0][(i + 1) & 3](a 2-D array field) instead of ado/whilewith aj = icopy avoids a pointer giv (magic_matra). Readingb->f1through avolatilestruct cast stops loop.c from making ab + 1address giv (field func_800B0618: 52 differing lines down to 9); stores written*(volatile u32 *)&q[k] = ...keep the8(a2)offsets where loop.c would combine q+8, q+12, q+16 into one pointer.row = D_80151A58[arg0]; e = row + i * 0x34;as two statements keeps the symbol andarg0 * 0xB9Cin the loop body with a separatei * 0x34giv, one expression&D[arg0][i * 0x34]lets loop.c merge the symbol into the giv.k = (s16)arg2 * 4 + 0x98;set in the loop body is hoisted after the guard witharg0 + kstaying in the loop; as one expression the whole sum is hoisted into an extra saved register; `t = (s16)arg2 * 4; t += 0x98; l[2] = arg0- t;
stops combine from turningarg0 + (x + 0x98)into(arg0 + 0x98) + x`.
- t;
- A stack parameter indexed as
arg5[i]in a loop whose other pointers are stepped keeps the parameter pseudo in memory and loads the giv's initial value in the preheader (lw a3,172(sp)after the guard); witharg5++the load goes to the function head; in sched2 an incoming-stack-arg load sits at the very top only if the parameter pseudo is the biv itself. Ado { } while (0);around the last statement of a body (pk += 0x20;) adds a weighted reference to the givpk+4without moving the stores before it; a constant placed after an if/else, as the first insn of the join, is moved by reorg into thebeqzslot, before theifit is not. loop.c's hoist threshold (-dL:Loop from 42 to 798: 258 real insns): a 0xFFFFFF mask was hoisted at life 13 where the game keeps it in the loop; at 261 insns it stays, and three dead sets (r = (T *)0; r = (T *)1; r = (T *)2;) before the first use add 3 insns at loop time and are deleted by flow afterwards (magic_queir func_801B104C). The14 - arg2constant is hoisted whenthreshold * savings * life >= insn_count; a dead pre-loopsh = 0;makesshmulti-set so that the subtract is no longer a movable (magic_knights func_801B15E8).&D[row][idx]gives(sym+noff)+rowoffwith separate givs,(T *)((u8 *)D + (idx * 0x18 + row * 0x600))givesaddu a3,s1,symfrom the combined giv shared with the field accesses (magic_debaria func_801B036C: 378 differing lines down to 58);for (i = 0; ...)in place of a separatei = 0;givesbeqzwhere the other form givesblez. - To swap the preheader inits of two givs make the OTHER biv's first increment come first
in insn order: a dead pair
list += 10; list -= 10;right beforepk += 0x28makes loop.c discover the list biv before the pk biv (in-dLthe possible-biv listiv_listis the reverse of discovery) and the inits come out in the game's order (magic_knights func_801B15E8, 2 words to 0); increments written in the cull paths instead break thergiv. When the loop pointer is the list biv itself (list += 8withlist[8..10],*(u32 *)(list + 4)), loop.c makes one giv whose init lands after the guard, a separaterpointer gives an extra giv with its init before the guard.gte_use(va); gte_use(vb); gte_use(vc);at the top of a loop lifts va above a mask constant in priority keeping the order vc, vb, va; a literal0x08000000in the store instead of au32 tgvariable lets the compiler temp be hoisted (a user variable set once is a possible biv with life 1 and is not hoisted). - A list pointer used at offset 0 stops loop.c from eliminating its biv:
((T *)(arg5 - 14))->uv2ismem (reg biv), so the biv stays in a stack slot and an extra givarg5 - 2appears; keepinglistas the biv with positive offsets (list[3],*(u32 *)(list + 4),list[8..10]) makes the single giv of the game. A user variable set inside an inner loop (yy = j * 0x40 + 6;) is hoisted to the inner loop's preheader as a non-replaceable giv, and loop.c reduces it only if the outer biv is eliminable (! v->replaceable && ! bl->eliminable && REG_USERVAR_Psubtracts copy_cost from the benefit: -6572 against 118): reg_dead_after_loop scans straight-line code after the loop for a conditional jump, so the counter must be set right after the loop (a deadj = 0;there), and the giv then lives in the frame as in the game; the game's spill slots with higher regnos than the user variables are loop.c pseudos, so the source uses natural index expressions. The hoist threshold in numbers:2 * (1 + n_non_fixed_regs)(58), minus 3 per movable already moved, and force_movables doubles the savings of a chain's first insn: four dead chained sets in the loop body (n = t2 + 5; id = n + n; col = id + id; w = (u8 *)(col + col);) took the move count to 18 so that at2*2 + t2chain stayed in the loop; the sinks must be variables used elsewhere (cse deletes dead sets of unused variables). A constant that loop.c would hoist twice (c != -1) stays in the loop if it is assigned in two places (m1 = -1; if (c != m1 ...)before each test). A(plus reg symbol)source of a struct copy is merged by combine into the movstrsi address (lui at/addiu/adduper word): a pseudo set at the top of the function (bp = D_801D1324;) that is live across a loop using all of s0..s8 gets no register, reload rematerialiseslui t3; addiu t3and combine no longer merges. Arrays instead of scalars for globals the game addresses through one hoisted register (extern s16 D_x[];) gives0 = &symbol. - A constant held in a variable gives the game's order for
y + (row * 0x12 + k): withk = 0x23;the constant is added to the product first and then the base (fold and combine otherwise move the constant outermost and loop.c builds a derived giv);i * 0x40 + ((anim << 3) + ka)makes themove s1,zerogiv init come after the guard where a runningoff += 0x40did not;q = &cursor[1].col;assigned after the call that readscursor[2].rowlets cse express it asaddiu s5,v1,-19from that address;s2 << 2in an increment arm givesaddiu v1,s0,1; move s2,v1wheres2 * 4did not. A register-normalised aligned diff tunes the structure independently of the allocation (cnfgmenu 144 to 18 lines), and a sandbox compile of a small C file with a target's flags answers 'which form keeps this move' questions in seconds.
- Try the plain code first; if the frame is still too small, an unused local
(
s32 pad;,u8 pad[8]) makes it bigger. Reading a field twice instead of through a local temporary can shrink it. - An unused 8 bytes usually come from a local variable, not a pad: try adding or removing
a temporary first.
u8 pad[4]andu8 pad[8]both add 8 bytes,s32 pad[1]nothing. - Sibling functions sharing one set of locals (club1's 3 SVECTOR, 2 MATRIX, 1 VECTOR): declare the unused ones in their slots to rebuild the frame.
- An
s16local kept across calls (even a copy) adds 8 bytes; ans32local tested as(s16)w < 0does not. A 4-byte struct or array local takes an 8-byte slot; two scalaru16locals do not. - A function-level
u8 pad[]lands below the address-taken scalars, one declared in a later nested block above them. A value spilled at0x10(sp)and reloaded in a loop, with a frame 8 bytes bigger, is a local array holding it (s32 sp[4]; sp[0] = ot;); several deads16stores to one local survive only into an array (s16 r[4]). s16/u8locals live across calls each take a slot;u8 pad[8]is one slot. Spilled locals take slots in declaration order. Halfwords spilled at a 4-byte stride (sh/lhuat sp+0x10, 0x14, 0x18, 0x1C) are two localMgSVecof which onlyvxandvzare used. A union of au32and a bitfield struct kept in a register can give a 40-byte frame with no pad.- Each
for (i = 0; i < n; i++)with a variablenleaves a dead compare temp that keeps an 8-byte stack slot (if (n) do {} whileloses it): frames of functions with many such loops need them. Locals sit in declaration order from the lowest address: an unusedu8 pad[8/16/24]before or after a local moves it to the game's slot, and two locals' order decides which sits at sp+0x10. - A frame 8 bytes short (also a leaf with
addiu sp, sp, -8) takes au8 pad[8], after the last array local or first; a larger pad (u8 pad[0x20],u8 pad[88]) before a local moves it to the game's slot. A halfword read into a local and thenD[i]++is merged by CSE into one load whose dead pseudo adds 8 bytes; a store to another global between them keeps both loads and the frame. Slots of address-taken locals follow the first&:s32 v[2]for two out-parameters. - Frame size steps:
u8 pad[4]andu8 pad[8]both give 64 where no pad gives 56,pad[9..16]72. A function-levelu8 pad[0x38]first in the declarations rebuilt scratchpad spawners' 0x50/0x58 frames;u8 pad[8]; MgSVec v; u8 pad2[0x20];placesvx/vzat sp+0x18/0x1C. m2c-stylevoid *templocals add 8 bytes; a struct arrayD[i].fn/.a/.binstead ofs32 D[i * 6]removed 24 bytes of dead locals (main func_80045D18); a cast-offset address*((u8 *)D + 1 + i * 0xB9C)can spill to an otherwise unused 8-byte slot where the typedD[i].gdoes not. MgMat m; u8 pad[8];(pad after the matrix) gives a 0x40 frame withmat sp+0x10; the pad first movesm(iyashi func_801B082C).u8 pad[0x28]beforerot(nadare func_801B19CC) andu8 pad[0x40](nadare func_801B1C54; iyashi func_801B0A74 for its 0x68 frame) rebuild larger frames.- An
s16local copy of a field used in a compare and in later arithmetic (s16 t = p->unk2;, ors16 k; k = 8; if (p->unk2 >= N) k = M - p->unk2;) giveslh v0; move v1,v0; sltiand 8 more bytes of frame; ans32gives one register (rakuseki func_801B0520, rocket func_801B0A34). - A local copy of a rodata table as a byte struct (
typedef struct { u8 b[24]; } T; tbl = D_x;), read as*(s16 *)&tbl.b[i * 2], withu8 pad[0x20]before it to rebuild the frame (reazer func_801B17F8). MgSVec unused; s32 flag;rather thanMgVecfixed a frame (hyper func_801B07A0); pads:u8 pad[8]after the last matrix (hyper func_801B1EA4),u8 pad[0x30](triangle func_801B0DC4);rotdeclared last putsmat sp+0x10 (lasboss func_801B1C60). Aggregates sit lowest in declaration order, address-taken scalars above them.s32 f(void)falling off its end keeps thebnez; noploop tail and passesv0on to a caller that returns it (hyper func_801B1160, func_801B254C).- Frame pads:
u8 pad[0x20]before an 8-byte struct local andu8 pad2[8]after it rebuilt a 0x60 frame (bushin2 func_801B0A30);u8 pad[0x40]before anMgSVec(func_801B0D34);u8 pad[8]after anMgVec(func_801B02F0);u16 w[4]plusu8 pad[8]reproduce stack halfwordssp18/sp1Cand a 0x40 frame (blaster func_801B12C8); ans16local copy of a halfword limit gavemove a0,v1and 8 bytes of frame (gaisei func_801B2128). - Three adjacent stack locals as
s32 tmp[3]withf(&tmp[0], &tmp[1]); tmp[2] = ..gave the game's frame andlhureloads each iteration (nanntoka func_801B0240). s32 t = p->unk2instead of ans16copy saved 8 bytes of frame (mrain func_801B1608); sibling functions with frames of 0x58 or 0x40 needu8 pad[0x38]oru8 pad[8].- The permuter's score ignores the frame size: its "score 0" on death func_801B2E14 was 8 bytes of frame off; check a permuter result with dd.py before trusting it.
- With quad-centroid loops, declaring
cntbeforelswaps their spill slots 0x10/0x18 (brizag2 func_801B123C). - A
forloop with a variable bound gives the 8-byte dead compare slot, so a 0x58 frame needs no pad (tupon func_801B57A8, func_801B4E00);s32 flag[3]as an out-parameter local adds a missing 8 bytes whereu8 pad[8]movedflaginstead (vahamut0 func_801B3E0C);u8 pad[8]again for kujata func_801B731C, func_801B521C, func_801B42B8.extern volatile s16 D_80162084;restores the position of a leafaddiu sp,-8and an emptybnezdelay slot (odin1 func_801B5088). - Five knights functions have a frame 8 bytes bigger than their locals (func_801B9834,
func_801B9408, func_801BAF80, func_801BCB04, func_801B56D4);
u8 pad[8]matched func_801BAF80 and func_801BCB04. A pad is not an "unused variable" in the style rule's sense: say so in agent prompts, as one agent left both out. The pointer form(&D_80162978[i])->fadds an 8-byte spill slot, and the permuter's score ignores the frame size, so check the frame of a score-0 result (hades func_801BA75C). - The frame's local size (
vars=) shows in the.frameline of a-dgdump (work/spells19/dump.py): compare it with the game's prologue before looking for a pad. Pads bigger than 8 bytes happen:u8 pad[0x38](lasboss func_801B22EC),u8 pad[0x30](lasboss2 func_801B1024); a second read of the sames16member (c = p->unk14++) adds 8 bytes; an out-parameter arrays32 flag[2]gave 0x18 missing bytes (satan func_801B3AD4). - Besides the unfolded loop guard, a folded range test also adds 8 bytes of frame (hades
func_801B7594): when the frame is 8 bytes short, look for an extra pseudo the game's
source had before reaching for
u8 pad[8]. - When a function is the last of its file, check where the file ends: BATRES.X ends right
after the last
jr ra, its delay-slotnopis not stored, so the C (which always emits it) is one word longer than the image (batres func_801B17CC needs a build change first). - Declaration order alone fixed the slots of two large functions: swapping the
declarations of
x0andciswapped their slots 0x40/0x48 (main func_80020B68), and huft_build matched once its locals were declaredc,r,u,v,x, with a separates32 mfor the zeroing loop (main func_80015D64). x[i] = x[i] | cagainstx[i] |= cchanged a frame by 8 bytes with no stack temporaries (magic_odin2 func_801B33DC; work/spells92/frame.py deletes each statement in turn and prints the frame size). Au8 pad[8]that moves the argument spill slots instead of adding space after them means the game has one more spilled pseudo (statmenu func_801D14E0). A permuter score of 0 does not check the frame: runwork.py diffon its result.- A
u8destination forx * y / 100gives an unsignedmult; mfhi; srl, and each such site adds 8 bytes to the frame (vars=in cc1's.frameline); three or more uses of one inline(s16)idx * 8in a block added 8 more; a second address name inside a table with a one-struct view (D_8012C5FE[idx].g) instead of casts of theu8array removed 8 bytes and matched condor func_800A698C. work/big1/dump.py WORKFILE NAME TARGET OUTDIR keeps the.frameand allocation dumps. - Stores to separate locals whose address is never taken (m2c's
sp22,sp24,sp26besidesp20) are deleted as dead: they are one array or struct (u16 rc[4], passed asrc).u8 pad[16]gives a frame its unused space (magic_zenbaku func_801B02A4). - A 4-word BIOS-call stub can sit right before a C function inside one splat function
(main func_80042DC8, printf, followed by sprintf at 0x80042DD8): a
type:funcsymbol in config/symbols.us..txt andtools/build.py <target> --splitseparate them. - A frame 8 bytes too big came from
(D_80162978 + D_8015169C)->unk0 = -1;:D_80162978[D_8015169C].unk0 = -1;gives the right frame (cc1 -dg showed a dead pseudo for the address that got a stack slot; magic_joker1 func_801B10B4). - A loop guard of the form
if (i < n)adds a dead-compare 8-byte slot in the frame that lands after the spills, whereu8 pad[8]puts those slots in the wrong place (field func_800B2DD4, magic_lgirl func_801B0270). Spill slot order is pseudo number order: declare the spilled locals in the game's slot order (n, i, sh, e). A macro with a "memory" clobber (gte_rtpsm) makes GCC reload a global pointer after the second rtps where the game does. A work file that redeclares globals with other types than decls.h (u8forD_801E8ECC, an array forD_801E8ED4) makes put refuse: use casts and decls.h's own declarations. - Where a frame full of dead slots comes from (battle func_800DA380: 208 bytes, 18 slots
of which two are read): a dead 8-byte slot is a pseudo with refs and no insn left. It
appears when combine merges a symbol set, an add of
idx * 0x50and a plain store and the symbol pseudo is shared by a second address chain, which happens when cse recomputes the index after a QImode store or a call invalidated the cached load of a global index. Reproduce it without changing the code by writing a byte pair as two accesses through ONE symbol, the second with+ 1(*(u8 *)((u8 *)&D_800F51A0 + idx * 0x50)and the same with+ 1) and by writing the f18/f17/f14 stores of a second window sprite in the same arm (f14 as a struct cast); halfword pairs (x/y, w/h) do not create dead slots (struct-member stores keep the cached index; plain pointers cost 6 or more insns). A battle func_800BCB1C extra 8-byte slot was the same thing: two stores through ONE symbol pseudo (D_80151850andD_80151850 + 1), removed by writing the second as a separate array symbolD_80151851[idx * 0xE] = 0;. Slot order: a declared local that is spilled takes the first slots after the locals (declaration order), a local struct sits below all spills, temps and dead pseudos follow in register order;u8 pad[128]makes the size but puts the spill slots above it (wrong offsets), a struct local holding the slot at 0x18 (typedef struct { s16 f18; u8 pad[0x56]; } BtlLoc;) pluss32 sp70;as a spilled user pseudo plus exactly six dead pseudos gives the slot at 0x70 and the game's frame.
- GCC 2.6.3's first scheduler works backward: loads sink toward their use, and free
instructions (constants, address set-ups,
i = 0) go into stall slots, the highest LUID first. Moving a statement after an earlier call changes where it lands and its live length, and with it the allocation priorityfloor_log2(refs) * refs / len. Compile with-dS -dR(or-dLfor loop hoisting,-dl -dgfor priorities) from a helper callingpsyq.assembly(..., cflags=...), run in a work folder: the dumps (gccdump.sched...) show the decisions. - Registers and operand order follow pseudo creation order: user variables get lower
pseudos than expression temps, ties break by declaration order. Order the temps and
statements the way the registers should come (
s32 b, x; x = T[a]; b = G; R = b + x;), declare a pointer before an index forbase + i. A variable set in two blocks is allocated like a global, after the block-locals (2.7.2 even within one block:n = s / 10; ... n = s % 10;givesmfhi a2where two temps givea1): repeat the expression or use one variable per block or loop. A named variable shared by blocks sums their priority and takesv0first. - What a store lets pass: a plain-symbol store does not stop a pointer load, a store
through a scalar pointer stops symbol and pointer loads, a struct-field store stops
only pointer loads, and struct member loads (alias-free) float above global stores
where raw casts do not. So a global declared as a one-field struct
(
extern struct { s16 v; } D_x; D_x.v = ..., orq = &D_x; q->v = ...) stores like a struct field;M2C_SFIELD(q, s32 **, 0) = ...keeps later loads after a pointer store; a template or vector written as fields of a struct global keeps its loads in source order. A store written before a call stays before it. - To stop a constant being hoisted out of a loop, set it in a local just before (shorter life), or give the loop more instructions.
- cho_kyu func_801B1B3C: reorg rewrites the first
sllof a loop index chain from the copy ina0tos0(the post-reload RTL and-fno-delayed-branchboth give the game'sa0); about 60 variants did not move it. - A volatile byte read stored into a
u16field keeps a redundantandi 0xFF; volatile globals were needed to keep a loop's load/store alternation (sflea func_801B1938, near miss). - Scheduler priority (ifleet func_801B3BB0,
-dSdump): anandiof a call result whose destination pseudo is set only once gets priority0x7f000001, sits right before the branch, and the later argument'slui; addiulands above it. One multi-setufor three values (u = t + 0x1388/u = t - 0x1388in the two arms, thenu = f() & 0x100) removes the bump. - The unfolded loop guard (vahamut2, spells 71): the compare reaches combine unfolded
with its constant set in the same block, and combine simplifies it with
nonzero_bits:n = ((t << 7) & 0xFF) + 0x80; while (n >= 0x100)givesbeqz v0and a 0x28 frame (vahamut2 func_801B5A48), and the game'sori s1,0x100; beqz s1is the same rule for(ge s1 0x100)withnonzero_bits0x100. The extra 8 bytes of frame are the dead compare pseudo: classST_REGS, no hard register and a stale ref count, so it gets a stack slot.-fno-rerun-cse-after-loopkeeps the guard but changes the preheader; an identical-arm dead test survives cse1 and cse2 folds it once the arms merge. - A load of a scalar global is hoisted above a store through a struct member or array
element, where a load of a struct-member global stays below it as in the game:
q[8] = D_801DCCC8.vy + 0x800;instead of the scalarD_801DCCCA(odin2 func_801B447C);D_801EC310.{x,z,w}for D_801EC310/314/316 took erave func_801B1AD0 from 37 to 29 words; three scalarsD_8009A000/4/8as one struct fixed ali 0x28; shposition, andD_801EEB68as a field of theD_801EEB60view (withD_801EEB6A/6Cleft scalar) fixed ap->unk8load (dia func_801B16DC). do { } while (0)around statements weights their references by loop depth in register priority without any loop.c rewrite, which rotates saved registers (sdust func_801B1ADC:pfroms3tos5); wrapping a whole goto loop switches loop.c on and breaks it (sdust keptagain: do { .. } while (0); if (..) goto again;). Around the firstif (p->unk2 == 0)body it flipped erave func_801B1074'sq/kpriority.- Local allocation gives an output pseudo the register of an input that dies in the same
instruction (
slt s0,s0,s2,mflo s2); a pseudo set in two blocks is global and escapes that tie: merging conf'sninto a two-blockkgave the game'sslt v0,s0,s2(conf func_801B0F00). - work/spells19/dump.py with
-dS -dRprints each insn's priority and the "ready list at T-n" lines. GCC 2.6.3 schedules a block backwards, so its first insns are picked last; ties among priority-1 insns go to the higher INSN_LUID (the later one in source order), and the producers of the last-picked insn get a boost (printed 7f000001). work/spells84/rtlsum.py prints one line per insn of a dump, work/spells84/s1order.sh the sched1/sched2 start order. - The prologue stores (
addiu sp,sw ra,sw s0) are scheduled like other instructions and float intomultor load stalls (death func_801B0858 hasaddiu spafter its firstmult); reazer func_801B1D54 and goblinp func_801B0D14 still differ there (the game hasla a0, lh, li, sw s0, la s0). - sched1's
adjust_prioritygives an insn that sets a single-set pseudo LAUNCH_PRIORITY (7f000001) when its consumer is scheduled, so single-set temps land right before their consumer. The boost applies only to a plain pseudo: ans16/u16user variable is set through asubregand is not boosted, ans32one is, and an in-place update (t += 0x240;) is not.s32 w = *h % 2;moved anaddiubefore the% 2chain as in the game (ho_den func_801B0148);t += 0x240;put anaddiuin themultshadow before the constant'sori(seald func_801B0D4C). - sched1 sinks a free insn that sets a single-set pseudo live across a call into the
first stall slot before its use; pinning its statement with
do { } while (0);and hoisting the call's argument load above it keeps it before the call, where reorg puts it in thejalslot as in the game (t = D_80062FC4; do { D_80062F24 = p + 0x24; } while (0); y2 = arg1 + arg3; func_80046794(t, p);, main func_800285AC, func_80027B84). - In
-dSdumps, ties at scheduler priority 1 are decided by "greater potential hazard", then by luid: a store picked before anlithat way does not move with the source order (snobo2 func_800B1248, battle func_800E368C, both still off). v->vx >> 2on ans16field right after its store giveslhu; sll 16; sra 18where the game haslh; sra 2: expand emits two shifts and an arithmetic shift, and combine merges the last two before it can form thelh(magic_kujata func_801B4D10). Ajalslot right after a global store (lui at+sw) staysnop(main func_80041D28).
- Calls: a function the game calls before its definition was unprototyped,
((void (*)())f)(args)(plainlwarguments); one called with other argument counts is declaredM2C_UNK f();or defined with bare parameter names; a call that takes nothing may leave a constant set before it ina0. A wrapper setting one argument isvoid f(s32 a, s32 b) { g(a, b, 1); }; the same value passed twice isv = D * 0x10; f(0, v, v); an uninitialised local passed as a fifth argument givessw sN, 0x10(sp); stack arguments read lazily come from a by-value struct parameter. Ans32 f(s16)prototype addssll/sraon the argument. - Constants: materialised in source order of first use;
c = 0x80;before a run of stores keeps it for a later0x80 - (...); a colour local given 0x80 isu8;x - C + f()folds C onto the call result unlessk = C;comes first;f(x, c ? A : B)puts thelifirst;(x << 5) | 0x10after an earlierx << 5is CSE'd where((x << 1) | 1) << 4is not;sll 16; srl 12is(u32)(n << 16) >> 12. - Narrowing:
q->f = (u16)q->f - 0x64 + f() % 200reassociates and folds; write single-def locals, one per statement. A byte or halfword store of a sum or shift ofs16fields narrows their loads tolbu/lhuunless they go throughs32locals first;(u8)D_xreads a halfword global aslbu;b--on au8givesaddiu -1whereb -= 1givesaddiu 255. - Copies: a 0x48-byte template copy is a struct assignment from an extern
typedef struct { s32 v[18]; }; eight word assignments give unscheduledlw/nop/swpairs where a struct assignment groups them; a 29-word copy isfor (i = 0x1C; i != -1; i--) *d++ = *s++; three words copied one at a time need a struct pointer parameter and struct globals; a copy that must survive asmoveis made through a cast (c = (u8)t;). GCC deletes the first of two stores to one stack local unless it is*(volatile s32 *)&d.x = p;;*(volatile s32 *)&sym = vgivesla; sw 0(reg)and stays out of a call's delay slot. - Addresses:
s32 off = 0x12674; *(s8 *)(p + off) = 0;stops&sym + offsetfolding;o = (i * 2 + j) << 3;keeps one register where* 8makes a copy;*(s32 *)(u8 *)&D_xkeeps an address in a register without redeclaringD_x. - Control and loops:
if (--p->f == 0)uses the register wherep->f--; if (...)reloads (and++p->f == Nkeeps the value across later stores); separatecase 2:andcase 3:bodies keep a beq chain wherecase 2: case 3:makes a range test;D_x = 0x10; break;in each case keeps separate blocks; for cases 1 and 2 only, an emptycase 0: break;givesbeq 1; slti 2; beq 2; a ternary used directly as a stack argument lays its arms out reversed;while (1) { if (!(mask & bit)) break; ... }avoids loop inversion; a goto search loop with the found block first keeps it inline;for (i...)leaves the increment for a delay slot wheredo { ... i++; ... } whileputs it before;for (...; i++, p += size)putsi++first. - Arithmetic:
t = A; t &= B;loads early wheret = A & Bloads last; in-place accumulation (s = A - s; s += B;) keeps one register;q = s - q * 10reuses the quotient; a remainder may want%ori - i / n * n, try both; uninitialised unused locals reproduce asubuof garbage registers; packed colour words assigned field by field through a bitfield struct give theand/orinsertion chain. - More arithmetic:
s16field % 12is computed in HImode and sign-extended again; read it into ans32first (t = p->unk2; t = t % 12;). A signed% 1024whose expansion copy must come before other shifts: write it by hand (m = r; if (m < 0) m += 0x3FF; w = r - ((m >> 10) << 10)).q->f = p->vx + (rand() % 100 - 0x32)giveslhu; addiu -50; adduwherep->vx - 0x32 + rand() % 100folds the constant;(s32)((c & 0xF) * 8) - 0x80givesaddiu -128where the plain form givesaddiu 128; au16field decrement isli 0xFFFF; adduunless it goes through ans32temporary. - More addresses:
t = idx * 4 + 0x801B0000;as its own statement keeps the constant address in a register;*(u16 *)((u8 *)0x801B0000 + idx * 2)giveslui at; addu at, v0, at; lhu 0(at);extern s32 D_1F800028;giveslui at; swfor a scratchpad word, a pointer local assigned the scratchpad address keeps it in a register inside a loop;&D_801B0000of anextern M2C_UNK(a code address) givesaddiu a0, a0, 0.D_x[a][b]with 8-byte rows givesla; addu a*8; addu b. - Strings and copies: two literals in reverse order: an unused
char *m = "second";at the top puts it first in rodata; a pair of$Id:strings is one literal with an embedded\0. An unaligned 8-byte copy (lwl/lwr):typedef struct { u8 b[8]; } T; *(T *)&q->f = *(T *)&p->f;. - The permuter can report "closer" with an unreachable statement before a case label:
check its output with
work.py diff. Itsinline_fncandidates only compile inside its harness. It ignores stack offsets unless run with--stack-diffs, and its score ignores the frame size. - Search helpers that worked when hand edits stalled: every ordering of a block of
statements, every declaration order, and wrapping each statement in turn in
do { } while (0);, each scored by a difflib alignment of the instruction lists (work.py diffcompares by position, so one extra instruction shifts every later word).cc1 -dg -dldumps show the order pseudos are allocated in and the register each gets. - More arithmetic:
x % 2 * 64on ans16field givessll 16; sra 10,(x % 2) << 6a plainsll 6;-p->f << 9givesnegu; sll 9,p->f * -0x200sll; negu;k = (s16)t - 0x2D(u16 t, s16 k) givesaddiu -45,k = t - 0x2Dli 0xFFD3; addu;u16 a, b; s16 d = a - b;is narrowed to HImode and not CSE'd with ana - b >= 0test; `x- C + f() % n` folds C onto the remainder (one single-def local per call). A magic multiplier is a division by a constant: 0x5D9F7391 with shift 7 is /350, 0x7482296B with shift 10 /2250.
- More addresses:
*(u32 *)((u8 *)tbl + ((i - 1) << 2))keeps the -1 out of the displacement; a pointer from one plain symbol (p8 = &D_8015138F; ... (u16 *)(p8 - 0x25)) gives one sharedlawith negative offsets; a local table of byte-aligned structs indexed as*(u8 *)(&t.b[2] + i * 6)(t.b[i * 6 + 2]hoistssp+16). - Calls into C already in the file: a callee called without arguments is defined
void f(arg0)and declaredvoid f();in the work file; a callback is passed as(M2C_UNK *)func_Xand defined with bare parameter names. A work file's extern replaces decls.h's (never declare a symbol with another type than decls.h's), andputprints only cc1's last stderr line. - More search helpers: a hill-climb over statement order with dependency constraints
(work/snobo9/hc3.py, work/spells19/hc.py) solved functions plain permutation could not;
the first scheduler's dump (
-dS) gives each insn a priority, its depth in its dependency chain. - Narrowing, more:
rot.vy = p->f << 6giveslhu,p->f * 0x40lh,-p->f * 0x40negu; sll;t = p->f; v = t << 6;keepslh;t = D[0] - 8; t += (p->f % 2) << 4; D[0] = t;givessll 16; sra 12where the one-liner stays HImode;s32 t = G - 6; G = t; if ((s16)t == 0)givesaddiu -6; sll 16; bnez;a = D_x + 8; D_x = a;through ans32givesaddiuwhereD_x -= 8on au16givesli 0xFFF8; addu;y = D;giveslhuwhereif (D >= 0xE1) y = 0xE0; else y = D;giveslhand amove;p->f += 0xCC; g(p->f)reloads wheres16 t = p->f + 0xCC; p->f = t; g(t)forwards. - Folding, more:
(p->e - (q->f + 0x320)) / 20folds the constant,k = q->f + 0x320; (p->e - k) / 20keeps theaddiu;(s16)D->vx - 0x12C + rand() % 600keepsaddiu -300on the field,D->vy + (rand() % 600 - 0x12C)gives the other fold;(x - K + n) % ngivesaddiu v, n, -K; addu v, x, v,x + (n - K)addiu v, x, -K; addu v, v, n;rand() % (w / 2 * 2) - w / 2matched written inline each time; in-place `d <<= 10; d= 12;
keeps one register whered << 10 >> 12` takes a temporary. - Search helpers, more: comparing a sibling function's cc1 output with the draft's
(work/spells19/dump.py on its source) found a missing
do { } while (0);; work/spells24/search.py replaces a snippet by each line of a variants file and scores the results; constraining the game's relative order of a few lines (A::Bin work/spells19/hc.py) found matches where unconstrained hill-climbs stalled. - Arithmetic order, more:
x + (w.y - 0x800)is reassociated to(x - 0x800) + w.y(single-def locals keep the game's form);(t * 0x258 >> 12) + 0x258 + (k * 0xC8 >> 12)keeps the add order where nesting folds the constant;(u16)t >> 1on0x80 - x * 16folds toandi 0xFFF0; srl 1,(u32)(t << 16) >> 17keeps it;(i << 16) >> 9givessll 16; sra 9wherei << 7givessll 7;v *= 3; v >>= 1;givesaddu a0, a0, v0. - A function whose first instructions the scheduler moved above
addiu spcan be cut by splat into a rodata symbol (the moved words) and a function at theaddiu sp: highway's code starts at its entry 0x800A00D0, seven words before the function splat had found. tools/work.py cannot parse multi-line K&R definitions with typed parameters. tools/work.py diffcompares by position, so one extra instruction shifts every later word: score with an aligned diff after normalising branch targets (work/main8/norm.py and score.py, work/spells10/diffi.py). work/spells31/magic2.py HEX SHIFT recovers a divisor from GCC's magic multiplier. The permuter'sinline_fnisinline s16 inline_fn(u16 x) { return (s16)x; }(a distinct HImode pseudo per use): plain code may not reproduce it.putdrops a work file's declaration of a function already defined in C, so a callee definedvoid f(void)that new code calls with an argument has to becomevoid f(arg0)in the source first. A function that matches only with code GCC inlined (an inlined helper is a scheduling barrier no block ordo { } while (0)replaces) takes the helper as astatic inlinefunction before it in the work file:putplaces it right before the function, once per file (reito func_801B1158).- A ring-buffer quad drawn by func_8003BD7C with the colour word per quad:
*(u32 *)(q + 4) = *(u32 *)(q + 0xC) = col(iyashi func_801B0624). - work/main10/mk34FC8n.py brute-forces where a few independent stores sit around a fixed chain (under 350 compiles for main func_80034FC8); work/spells34/decl_perm.py tries declaration orders.
- More magic multipliers: 0x64D319FF with shift 8 is /650; 0x57619F1 is /750 (shift 4) and /24000 (shift 9); 0x1A6D01A7 is /620 and /19840; 0x1B4E81B5 is /600 and /19200.
- work/spells38/declperm.py tries every order of a block of declarations;
work/spells19/hc.py with two
A::Bconstraints placed a store group in 2 iterations (reazer func_801B17F8). A helper namedtypes.pyin a work folder shadows the stdlib module for every script run from there: give helpers distinctive names. - More magic multipliers: 0x88888889 with shift 10 is /1920, 0x78787879 with shift 5 is /68, 0x66666667 with shift 3 is /20.
- tools/work.py tidies a target's decls.h whenever it uses the target (
show,diff,put), dropping declarations main/decls.h already has: another spell's decls.h changing during a batch is expected and right. - Magic multipliers:
0x10624DD3withsra 6is/ 1000(sra 7is/ 2000),0x68DB8BADwithsra 9is/ 1250,0x2AAAAAABwithsra 1is/ 12. - Frame descriptor:
D[0] = v; M2C_SFIELD(&D_x[-5], s32 *, 0) = (s32)ptr; f(&D_x[-5], ..)givessw -0xA(s0)plusaddiu s2,s0,-0xAand keeps a later global load below the store (cosmo func_801B070C). The last argument written `D_801517C0 + 0x70 + (w->z-
- 4
puts the table pointer inv0` (antlion func_801B3708).
- 4
-
(u32)((t << 12) / 40) >> 8givesdivthensrl 8(gospel func_801B2418).- ASPSX 2.34:
*(volatile s16 *)&p->unk0 = arg0giveslui; addiu; addu; sh 0(reg)(antlion func_801B3B24). t <<= 7; t = -t; if (t < 0) t += 7; c = (t >> 3) - 0x80;keeps the game's in-place division chain (hvshot func_801B0680).- The night/lgirl ring-push helper matched unchanged under GCC 2.7.2 (wep3 func_801B048C).
- Open forms (near misses): an unfolded loop guard
ori s1,0x400; slti v0,s1,0x100; bnezwith an 8-byte bigger frame (vahamut func_801B2810, func_801B2238, the family of h_blow func_801B0640 and gospel func_801B2F00); the/3quotient copiessubu v1,v1,v0; .. move s0,v1that combine merges (brizag2 func_801B0F78, func_801B1524); `(p->unk0 - 1)- 16
folded into the table offset where the game keepsaddiu -1; sll 4(odin2 func_801B3F54); a hoisted tablela` sunk after a call (sldfang func_801B2D80).
- 16
- A literal
(t << 12) / 0compiles to the game'sdivwith itsbreak 7/break 6checks (kujata func_801B6034, func_801B6CE0). - Open forms (spells 67-72): the unfolded loop guard with an 8-byte bigger frame now
covers siva func_801B3408, vahamut0 func_801B38D0 and func_801B42F0 (an unfolded entry
guard before the kept loop guard), vahamut2 func_801B3804 and func_801B712C (about 25
source forms tried); a quotient that lands in
v0where the game keeps it in place inv1(tupon func_801B2460, 1 word); anandi; beqzonv1where the game hasv0(kujata func_801B88A4, 2 words). - A constant in a variable stops a fold:
v = 0xA00; .. (p->unk2 * 20 - v)keeps `A - (B- C)
apart,k = 0x190; q->f + k - rand() % 800keeps theaddiuon the field, and inside a loop the variable must be set in the body or it is hoisted into a register (sdust, beam, wep4, jammer2, spells 77);x = -0x3E8; f = x - *(u16 *)pkeepsaddiu -1000where-0x3E8 - *(u16 *)pgivesori 0xFC18(knights func_801B7C84);(t + 4) - n
stays unfolded only through a tempw = t + 4(tifa func_801BADB8);a = (u8 *)&D; D2 = a + 0x9000;keepsori 0x9000; addu(tifa func_801BCD98);rr = rand(); r = a / 3; u = rr % 1194 - 0x100; ang = r + u;keeps- 0x100` out of the quotient (alex func_801B53B0).
- C)
- Shifts and narrowing:
/ 4 >> 3givesaddiu 3plussrl 5where/ 32givesaddiu 31(knights func_801BA964);q->f = (q->s16field << 10) >> 16giveslh; sra 6where>> 6giveslhu; sll 16; sra 22(knights func_801B440C);(i + D_x) & 0xFFFnarrows the global'slwtolhu, and ans32tempu = (D + 1) & 0xFF; D = u;keeps thelwwhere au16temp does not (sdust func_801B1424);(u32)((u16)p->unk2 - 0x30) >= 0x12Ugivessltiu;m[1][1] = m[2][2] = 0x200storesm[2][2]first. - wep4 is GCC 2.7.2 code (
mfhi/mflointo$t0for each division, as beam and garyu): its six functions in C matched under both compilers, and under 2.7.2 func_801B164C and the old near miss func_801B0074 matched. A scan of the asm still in asm formfhi/mflointo$tregisters found no other such spell. - Open forms (spells 68, 73-77): the unfolded loop guard now also covers phoenix
func_801B2F34 and func_801B3210 (fixed-point spawn accumulators; their twin
func_801B1978 with a variable start
((unk2 * 0xC0) & 0xFF) + 0xC0matched) and knights func_801B9408; twenty option sets (-O1, -O3, -funroll-loops, several -fno-*) kept none of the guards (work/spells68/flags.py). One-word near misses: hades func_801B7594 (amove v1,v0afterlh; beqz), knights func_801B3DB0 and func_801B9834, jammer2 and daionpa func_801B06E4 (sll v1,s0,1where the game hasa0). 0x51EB851Fwithsra 6is/200(sra 5is/100) (odin1 func_801B5D14).- Permuter results that matched near misses, each a small change:
v = q->unk12 = f() % 0x1000 + 0x800;(altema func_801B0BBC);do { f(&m); g(&m); } while (0);around a call pair (queir func_801B237C);w = p->unk6; m1.t[1] = w;with temps reused in the else arm (tifa func_801BADB8);base = (s32)D_801D3FE8; base = D_801D3FE0 + base;as two statements keeps a hoistedaddu(reito func_801B1684); a deadsp = (MgB8 *)D_80151A4C[i];with the copy source written out again fixed anaddu/luiorder (erave func_801B1AD0). - Check multiplication chains first: a draft's
* 0x5DCwas the game's* 1000(sll 5; subu; sll 2; addu; sll 3) (alex func_801B4CD4). One shared multi-setrfor two division chains keeps the quotient inv1and the product inv0, and a remainder into a dead variable (a = j % 8; .. a = 8 - a;) givesa0(tupon func_801B3464). - Colour bytes as elements of an
extern s8 D_x[]with the table load first into a temp (c = D[..][..]; D_x[0] = D_x[1] = D_x[2] = n * 0x10; D_y = c;) sink thesbstores below the load (kakusan func_801B075C); two scratchpad word stores written((s32 *)p)[0x10] = ..; ((s32 *)p)[0x12] = ..;keep the game's order where*(s32 *)&p->f = ..does not, and a K&R call with one argument fewer fixed a prologue (snobo2 func_800A738C). u = (vv >> 6 & 3) << 6keepsuderived fromvvwherevv & 0xC0folds;(x << 16) | (u16)sygives thesllfirst without hoisting it;s32 h = p[i]; ((h & 0xFFF) << 2)keepslh; andiwhere(p[i] & 0xFFF)narrows tolhu(snobo func_800A5E80, snobo2 func_800A2EF0); a volatile scratchpad struct pointer reproduces reloads right after stores (snobo func_800A212C).- work/mini3/asm_of.py FILE.c prints cc1's assembly of a small C file in under a second (psyq.py with snobo's options): the quickest way to test one form.
m = 1 << a; if (act & m)givessllvwith 1 in a register whereact & (1 << a)folds tosrav; andi;acc |= 1 << x; acc &= ~bit;stay two statements (akao func_800308D4).- main's text3.c is built with -ffixed-25 (only func_80018834 needs it: its loop keeps a
constant the full register set would hoist), and func_8001AEE4 uses
$t9: text3.c is split there, and text3b.c, built without the flag, holds func_8001AEE4 and the rest. To find which functions need a file option, compile the file without it (patch psyq.FILE_OPTIONS in memory, work/split3/nofixed.py) and list those that stop matching. k = 0xC;as a variable keeps GCC from foldingcy - ((h >> 1) - 0xC)into `(cy + 12)- (h >> 1)
;off = lo | ((hi & 0xF0) << 4);andt = arg1 - base + 0xFEE;as their own statements keep a constant from being folded (main func_80034BB0); a call through ans32 (*)(void)cast drops an extraandi 0xffff.e->f8 = (yy = D_801ECF86.y - 0x96) + func_80042DA8() % 300;gives the right registers and theaddiu(preexpand_calls evaluates the call first, so the lhu comes after it);e = (T )(j * 24 + (s32)base);givesaddu s0,v0,s3where(s16 *)(off + base)givesaddu v0,s3,a0. Chained storesp->u0 = p->u2 = c; p->u1 = p->u3 = c2;gave the game's store order and madec' = c + shifted` land in the shifted value's register (magic_odin1 func_801B0E60, func_801B11C8).
- (h >> 1)
- A frame that is 4 mod 8 (chocobo func_800AE534 and its copies in field, highway and
world:
addiu sp,sp,-60, 24 bytes of locals and arguments plus 9 saved words) cannot be produced: cc1 2.6.3 and 2.7.2 round the frame to a multiple of 8 whatever the locals, arguments or variadics (56 or 64 in every test) and no C function of the repository has such a frame (all 319 elfs scanned): such a function is not matchable with the current toolchain. When a function is followed by data words in .text that splat folded into its asm (main func_80034CAC and the save area D_80034CF0..), give the first data word a symbol (func_80034CF0 = 0x80034CF0; // type:func),INCLUDE_ASMit right after the function and rebuild with--split. - Volatile array elements (
D_8009D25C[3],D_8009D3EA[0]) give thela reg; lw/sb 0(reg)form even for a single use where plain arrays fold back to theluiform; au8 b = s6[0]local at the inner-loop site giveslbu s0; andi s0,s0,0xff, andb = s6[0]; c = b;keepscset twice so loop.c does not hoist the address constant (main func_80011C1C). Wrapping the whole finalif (s0 != NULL) do { } whileloop indo { } while (0)raised the node pseudo's refs from 121 to 141 against 120 for the record and flipped the s0/s1 order (about 80 lines of diff, world func_800A71E8); repeating the bound expression inline in both the loop and the post-test makes thread_jumps send the top test straight to the else branch. Extra frame bytes above an argument spill slot come from reload slots, not user locals (u8 pad[]sits below the slot). Greedy and iterated wrapall rounds (work/big21/wrapk.py, wrapn.py, work/big22/perm.py) took magic_tifa func_801B5C74 from 163 to 74 and then 38 differing words but not to zero. - A work file's
externreplaces decls.h's type for every function of the file when it is put:extern BtlC440 D_8009D898[]andextern s32 D_80062F24each broke other functions,putthen reports that functions of the file no longer match or that the file does not compile (tools/work.py put prints no detail: run work/gte15/wf.py TARGET WORK NAME and read work/gte15/wf_stderr.txt for the lines that are not warnings). Keep decls.h's type and cast at the use (*(T6 *)D_8009D898[arg0].b,(s32 *)&D_80062F24,((SbBlock16 *)&D_800DDE98)->v[0]).putalso cannot change the prototype of a main function that overlays call through casts (eqipmenu, namemenu, savemenu, shopmenu use main's decls.h): place such a function by hand, replacing its INCLUDE_ASM in the source file and changing the prototype in decls.h, then run the full build (main func_8002708C, whose third parameter is s32 and whose caller still matches). A twin that tools/twins.py reports at 1.00 may still differ in constants and in the base symbol of a table (snobo2 func_800A5F00 against snobo func_800A4D38:li a0,0x20for 0x40 and the array at D_800B85CC for D_800C0000). - Of the 20 smallest GTE functions that had no earlier attempt, 16 were real hand-written
assembly (jet, highway, world, battle: t0 to t9 as ALU scratch, trapping add/addi/sub,
rtps right after lwc2 without nops,
sbfollowed byswto the same place, OT insertion expanded by hand, a register read that nothing set; in submar the libgte RotMatrix-style routines): they stay asm. But theHandwrittenflag and a note about t registers can be wrong: battle func_800BACEC was plain compiler output (its t registers are GCC's block-copy temps), so read the asm before giving up. A GTE function with a matched twin or sibling is a port (snobo func_800A50B4 and snobo2 func_800A627C from func_800A4D38, field func_800B0618 and world func_800C5CD4 as one C, highway func_800A2ADC from three siblings). cse keeps a global pointer across a plain gte_SetRotMatrix (an asm with a clobber list but no memory clobber): gte_SetRotMatrix_mm adds the clobber and forces the re-read; a macro operand written as an expression (gte_ldv0w_m((u8 *)D_x + 0x14)) avoids a reused local becoming a saved register;u32 w = v[1]; D_a = w >> 16; D_b = w;giveslw; srlwherev[1] >> 16becomes anlh. A packet as a u32 array whose OT link is((*ot << 8) >> 8) | 0x06000000gives the game'ssll/srl;pp = &D_x;read through*ppgiveslui s1; addiu s1andlw x,0(s1). - In the spell overlays a
Handwrittenheader on a GTE function is often wrong: of the 8 shatter-family and model-draw functions read in the last batches 7 were plain compiler output and matched (magic_satan, magic_debaria, magic_queig, magic_queir, magic_lasboss3, magic_sting), so read the asm. A small one can be a part of a big matched function (magic_phoenix func_801B122C was the first two loops of magic_alex func_801B1124, 688 insns; magic_sting func_801B165C a prep loop plus the G3 and G4 loops of func_801B0080) and tools/twins.py misses those because the sizes differ: grep the matched C of other overlays for the same macro sequence. Overlay pairs with the same code (magic_gesui and magic_otsunami) take the same C with the symbols renamed. - Model-draw GTE functions of the spell overlays (FT3, FT4, G3, G4 loops over a model:
knights, lasboss3, sting, titan, odin2, brizag2, vahamut2) are one family: start from
the nearest matched one, with its loop structure and allocation tricks (magic_titan
func_801B0068 matched with the t7-clobber macro variants gte_ldv3_mk / gte_stflg_mk and
the colour word written as
w = a | x | c; brizag2 func_801B29DC was the G4 variant of func_801B2548 and func_801B200C). The clobber macros of include/gte.h (gte_clob_a2, t01, t2, t3, v0, v1, a0, t7, s012, va, tmp, t123_89, t0123_89; gte_use, gte_copy) are the levers for register order once the structure matches. - A call through a cast of a function pointer with other parameter types drops the
sll/sra 16an s16 prototype adds;q->u0 = q->u2 = 0x80stores u2 first (the chain order is the store order); the unused bytes between the locals and the saved registers needu8 pad[N]. Menu functions over 800 insns can be written from scratch (limtmenu func_801D042C, 861 insns, frame 160, two jump tables with no split needed): m2c's draft of the nested draw loops gives the structure, the levers above (counter roles, dead sets, constants held apart, arrays for globals) give the registers; eqipmenu func_801D0BD0 (m2c cannot draft it) was written by hand from the asm and compiled to 1019 against 1007 insns at the first try. - Menu functions over 800 insns can be written from scratch or by hand from the asm when
m2c cannot draft them: limtmenu func_801D042C (861 insns), eqipmenu func_801D0BD0 (1007)
and savemenu func_801D06B0 (1089, 1073 words) matched in three consecutive batches with
the levers above (single-symbol aliases, constants held in variables, counter roles,
dead sets, a permuter run of 10 minutes at the end when the aligned diff is under ~40:
it found the last change of eqipmenu); savemenu func_801D3AB0 (1122 insns) was a port of
its twin with a different pre-switch part and case 7. GTE model-draw spell functions
port between overlays: the C of magic_sting func_801B0080 / magic_tupon / magic_vahamut2
compiled almost as-is for magic_odin2 func_801B114C (plus a uv offset and
tpage + ...instead of|) and magic_sting func_801B0B40 is that port with the FT3/FT4 V-flipspk[0xD] = 0xFE - pk[0xD]: run tools/twins.py scan after each batch. - Twins and parts: tools/twins.py scan --ops finds candidates by operation similarity even
when the sizes differ: magic_alex func_801B1F7C (730 insns, 0.96 alike to the 688-insn
model-draw family) was func_801B1124 plus a min-of-three-
vyblock afterrtpt(short mholds the minimum,if (m != 0),gte_mv12(m >> 2)feeds IR0; a deadk1 = 0x24000000;before the first loop keeps theluiin thebeqzslot); magic_brizag func_801B03C0 was queig's shatter front end plus the draw part of func_801B116C; eqipmenu func_801D1D5C and shopmenu func_801D0340 have the same asm (port withtools/twins.py portand put: it matched at once); main func_8003DE9C and func_8003DFD4 followed the matched func_8003E100. Five medium menu functions (statmenu func_801D14E0, eqipmenu func_801D1D5C, shopmenu func_801D0340, func_801D1868, func_801D11A4) and cnfgmenu func_801D080C (1189 insns) matched in two batches with the levers of rounds 31 to 33. The permuter is useless on 1189-insn functions (4 iterations in several minutes): finish by hand with a register-normalised aligned diff. Forput's whole-file check on cnfgmenu the cursor table isextern struct { u32 w[3]; CnCursor c[4]; } D_801D24C0(cursors at +0xC from the lower symbol) so thatD_801D24CCkeeps decls.h'su8[]type for another function, andfunc_80028030is declared unprototyped because text.c calls it with one argument. - When
tools/work.py diffsays OK butputrefuses because the game reads a global as a plain scalar while decls.h declares it as a struct or an array that another function of the file uses (a struct read shares one address register inside an extended block,((S *)&T)->topand*(short *)&Tdo too, only a scalar gives separatelui/lhpairs, and a block-scope extern is a conflicting-types error), add an ALIAS SYMBOL: a lineD_801DF658_s = 0x801DF658;in config/symbols.us.TARGET.txt andextern s16 D_801DF658_s;in the work file: the linker resolves the alias to the same address, the compiler sees a scalar and the struct accesses elsewhere stay untouched (eqipmenu func_801D54B0; a constant-address cast*(s16 *)0x801DF658was one instruction off, and changing decls.h to a scalar with a cast struct view grew another function by 4 bytes). Splitting the file at the function is no way out for this: a split inside one game file loses the 8-byte pads between jump tables (text.o's rodata ended at 0xCC instead of 0xD0 because the linker script does not align input sections: the pad has to be inside an object). - eqipmenu is complete (every function of the target in C: func_801D0BD0, func_801D1D5C, func_801D54B0, func_801D5BD0 and func_801D6C2C of 456 to 1260 insns matched in five batches); the last of the menus with big functions are itemmenu func_801D0E80 (1837 insns: rewritten from the asm to the game's word count in one batch, aligned diff 67 + 108 after it), shopmenu func_801D1CC4 and mgicmenu func_801D0490. The workflow that worked: write the C from the asm section by section (m2c's draft is only a start and for the largest functions m2c cannot draft them), compile after each section, match with the register-normalised aligned diff first and the real diff last, then apply the per-arm variables, the single-symbol aliases, the dead sets and the clobber macros of rounds 27 to 35; work/*/mini.py style sandboxes answer 'which form keeps this' in a second.
- The five largest menu functions were matched without any m2c draft or with a draft that
did not compile, in two to four batches each, by writing the C from the asm section by
section: eqipmenu (func_801D0BD0, func_801D54B0, func_801D5BD0, func_801D6C2C), itemmenu
func_801D0E80 (1837 insns), mgicmenu func_801D0490 (2342 words), savemenu func_801D06B0
and cnfgmenu func_801D080C: the eqipmenu, itemmenu, mgicmenu, savemenu, cnfgmenu,
limtmenu and statmenu targets are complete. The method: head and first cases from the
asm, compile early, align with the register-normalised diff first (shape before
registers), then the levers of rounds 27 to 37 in the order the diff suggests: per-arm
variables, function-level variables with
gte_use10for priorities, held constants, alias symbols, dead pseudos for the frame; a permuter run only at the end and only below ~1000 insns; a sandbox that compiles a 20-line C file with the target's flags answers 'which form keeps this' in a second. - Every big menu function of the game is now in C: eqipmenu, itemmenu, mgicmenu, savemenu, cnfgmenu, limtmenu, statmenu and shopmenu (func_801D1CC4, 2297 words, the last: m2c could not draft it and it took five batches from a 175-word start: head and cases from the asm, then 3706 to 312 to 183 to 102 to 10 to 0 aligned lines): patymenu func_801D0250 (259 insns) is the last menu function left. For such functions a diff run takes about a second, so a batch can try many variants in a row; the permuter is useless above ~1000 insns.
- The menus group is 100% in C (243 of 243 functions, all the code bytes): the last functions were patymenu func_801D0250 and shopmenu func_801D1CC4. The first big non-menu function written in full was battle func_800B1D48 (825 words, two batches: write the whole function from the asm and m2c's draft first, shape lines before register lines, then the levers of rounds 27 to 39). The code that is left is concentrated in about 40 functions of 850 to 5765 insns (battle, condor, chocobo, world, field, jet, main) and the GTE families that the four copies of chocobo/field/highway/world share.
putdrops the work file's prototypes for symbols that are already defined in C: a function declared withs16/u16parameters in the target file's own declaration block gets sign extensions in the in-file build that the standalone check (work-file prototypes) does not have:matches alone, but not in its file: call it through a cast of an address-alias data symbol (((FnT)D_8001EB2C)(a, b)withextern u8 D_8001EB2C[]: a directjaland no function declaration; main func_80023AD4). Big functions matched since round 38: battle func_800B1D48 (825 words) and func_800A8E84 (872 insns, 36 cases) and condor func_800BDA24 (854 insns; m2c's draft was almost the source: compile it as it is and look at the diff before writing anything) and main func_80023AD4 (972 insns, the menu state machine) each in one or two batches by writing the whole function from the asm and m2c's draft first and fixing the register lines afterwards.- Big functions are matched in two to four batches: first draft written from the asm with
every case (the m2c draft may not compile: duplicate
default:labels,saved_reg_s0artifacts: fix it first), then the register-normalised aligned diff (shape before registers), then the levers above. battle func_800DC0CC (931 insns) took three batches; world func_800B9B2C (850 of 899 insns: frame 88 against 64, seven function-level variables s2 to s8 in the game) and chocobo func_800A8AE8 (17 raw lines) and func_800A9D94 are the open ones of this round. Bash heredocs with long text that contains quotes can fail withunexpected EOF: write such scripts with the Write tool. - Big functions of the battle script interpreters (func_800BEA38 1048, func_800BCB1C 1632:
26 and 33 opcode arms, most arms twins of each other) took two batches each once the
alias symbols existed: copy the matched arm forms of the first function into the second
(
tools/twins.py diff/port), then fix the arms that differ. A function that is 1024nopwords andjr ra; nop(battle func_800D1530, called as a delay by func_800D0B4C and func_800D0C80) is not C: it staysINCLUDE_ASM.
Some functions were assembly in the original and stay INCLUDE_ASM: the GTE (cop2) and
BIOS-call functions of the libraries (lib.c … lib5.c; also stack swaps through
addu v0, sp, zero, busy loops on t6-t9, explicit $at use, and leaf copies
interleaved through t0-t3 the way no compiler schedules), and helpers that take arguments in t0-t2 or return
through jr $at (battle's func_800D32B4, func_800D8304, func_800D29D4). splat marks most of
these "Handwritten function", not all (highway's func_800B4114 is pure GTE unmarked).
The game's own GTE code is not hand-written: it is C with PSY-Q's inline GTE macros
(gte_ldv0, gte_rtps, ...), each an asm volatile whose text is the instructions, with
the operand in a register GCC picks. It can be written the same way: include/gte.h
(included by common.h) holds one macro per sequence of the game, with the instructions
word for word (one per line, \n\t between them: maspsx cannot read ;), %0 for the
operand, the scratch registers ($12 to $15) as clobbers and "memory" for stores; a GTE
command is gte_cmd(imm) (the two nops and cop2 imm, imm = the instruction word &
0x1FFFFFF). The macros are written in the order the game executes them and the C around
is fixed as for any function (battle func_800D84F8 matched at the first try; the order of
three negations decided the loads' order). Only the PSY-Q library's own assembly
(lib.c and its neighbours) and BIOS stubs stay asm.
A file's assembler can change partway: NAMEMENU's code folds %lo into a load with a
register index (ASPSX 2.30 and later) from func_801D14E8 on, and not before. Counting
the unfolded addiu $at, %lo against the folded %lo(sym)($at) per function finds such
a boundary; split the file there and give the new part its options in tools/psyq.py.
The PSY-Q libraries were split so: libcd and libgpu have the unfolded form (ASPSX 2.21,
lib2.c and lib4.c), the other libraries the folded one; the $Id: strings in rodata
(bios.c, sys.c, intr.c) show where library files begin.
- Permuter results that matched since spells 85:
src = &D_801D71F4[p->unk2 % 8]; val = *src; D_801D71E8 = 0x28; D_801D71E4[0] = val;moved a load above a store (tbreath func_801B0A2C); a dead identical-arm testif (D != 0) { A } else { A }around one arm fixed two saved registers (knights func_801B8A00, alex func_801B2D94);do { f(..); ang += step; } while (0);got tifa func_801B1DB0 to 2 words. - Of the 348 functions splat marks handwritten that no batch had tried, 343 use GTE instructions (written with include/gte.h macros since 2026-11-25, except the PSY-Q library's own assembly); the other five are BIOS-call stubs and library assembly: they stay asm.
- How a GTE macro is written (include/gte.h, about 75 macros now): one
asm volatileper sequence of the game, the instructions one per line (\n\t; maspsx cannot read;), operands%0.. with "r" or "=r" constraints (GCC 2.6.3 rejects "+r": a macro that changes its operand uses"=r"(a) : "0"(a)), scratch registers ($12 to $15, or what the asm uses) as clobbers, "memory" for stores; branches and numeric labels (1:) inside a macro work (maspsx already emits.set noreorder),.set reorderinside one makes gas add nops. work.py drops#definelines of a work file, so new macros go into include/gte.h. When the game computes pointers in C between itsmove t4..t6instructions, each move is its ownasm volatile(gte_ldv3_m, gte_stsxy3_m, gte_stsz3_m), and three equal constants sharing one register need a single-operand macro (gte_SetBackColorN). - What decides a GTE function's match is the C around the macros: scratchpad accesses
(
lui reg; sh x,6(reg)) come from assigning the constant pointersc = (T *)0x1F800000;before the loop or label (in one straight block CSE foldsp + 6to a constant address and giveslui at; sh ..(at); two macro uses of the same literal address in a block share one register where the game reloads it, and an in/out operand or a symbol at that address stops the sharing, each with another side effect); a loop pointer written as struct-array indexing (b[i].x) givesmove v1,a0andaddiu v1,v1,12in the delay slot whereq += 6on ans16 *splits the givs; a running offset written asbase + j * nis a giv of the counter; noif (cnt != 0)guard before afor; counters at function level, temps block-local per loop;for (i = 0; i < n; i++, dst += N, src += M)gives the game's order of the increments; the loop's pointer base is the last memory access in source order (p->codelast givesp+7); raw casts for a packet's stores (*(s32 *)((u8 *)p + 0x38) = ..) instead of struct fields stop the scheduler hoisting the tag-word load (magic_wep4); a colour word asu32 w = col << 16; u32 x = (col << 8) | 0x24000000; *(u32 *)(p + 4) = w | x | col;gives the game's instruction order (magic_frog func_801B0A50 went from 435 to 243 differing lines). - The loop guard decides the allocator's order of i, e and the mask:
if (i < n)(blez) orif ((u32)i < (u32)n)(beqz with anlhucount) leavesione more reference thann != 0orn > 0and gives the game's registers (magic_hades func_801B0480 and func_801B1144, hatena, faiga2). A value that must be allocated like a global has to be set in both arms of anif(matra and reazerk). A function with GTE code that is really hand-written (trappingadd/sub/addi, hand-filled delay slots,rtptright afterlwc2without nops, an OT insertion expanded withlui $at, leaf routines on v0/v1, t0 to t7 used as ALU scratch) stays asm: wrapping its body in fixed-register macros matches but is only INCLUDE_ASM moved into a header (battle func_800D3418, func_800D3474, func_800D34C8 were reverted).
The work has been done in batches by Claude Code subagents, each given about 30 of the
smallest functions of one target still in asm, this document, and these rules: one work
folder each, only tools/work.py put changes the repository, no git, no
tools/build.py, give up on a function after about 20 tries without getting closer,
and report what was put, what was not (with what still differs) and any finding. Two
to eight agents ran at once at first; now one at a time, the maintainer's limit (each
permuter run with --jobs 2). An agent stopped by a usage limit keeps its context:
stop its leftover permuter processes, build everything, commit what it put, and resume
it later with a message. On Windows, agents must never run python3/python (the
Microsoft Store aliases) or any Python reading stdin (python -, the venv's Python with
- or with no script): such processes hang at 100% CPU and outlive their command;
scripts are written to a file and run with the venv's Python. Agents still type
.venv/Scripts/python - now and then: say it in every prompt and check for hung
processes after each batch. Agents never
delete files (rm, Remove-Item...): Claude Code asks the user about every deletion
even when it may run everything else, so an unattended batch stalls; they overwrite
files or use new names instead (work/ is ignored by git).
After each batch: tools/build.py --skip-main <target>, commit, push.
Before committing a batch, check the style of what was put: a permuter result put as it
came (2-space indent, braces on their own lines, several statements on one line) has
slipped through more than once, and put cannot replace a function already in C, so it
is tidied by hand and rebuilt. Commit only the batch's own files: a put landing while
another change is being committed goes into the wrong commit. Permuter results can
change what the code does (batch 81 rejected several): compare one with the draft
before using it. tools/permute.py needs bash, so agents start it from Git Bash, not
PowerShell. For the order of a few blocks of statements, work/spells19/hc.py with
A::B constraints (A before B) found the game's order in under 60 iterations where a
full permutation would take thousands. From functions of about 500 instructions up, a
batch matches a third or less of its functions. Batches retrying the near misses, with
the forms found since, did better: spells batches 82 to 85 matched 8 of 15 functions 1
or 2 words off, 11 of 18 at 3 or 4 words, 14 of 18 at 5 or 6 (nine of them one pattern
solved in the batch before) and 7 of 18 at 6 to 10. Such a batch starts each function
from its best draft with one 10-minute permuter run, which found about a third of the
matches within minutes. Batches 86 and 87 (1 to 28 words off) matched 9 of 18 (and a
twin) and 8 of 18. The model matters: two batches on a smaller model (Haiku 5.5) matched 1 of 27, where
Sonnet 5.5 then matched 4 of the same 12 minigame functions and 2 of 12 new ones; a
permuter-only batch (two 9-minute runs per near miss, no hand work) matched 1 of 14.
Back on Sonnet 5.5, batches of 8 or 9 untried functions of 250 to 480 instructions
(main's own code, the AKAO driver, minigames, battle) matched 2 to 4 each (13 of 41),
and a second retry of 11 near misses 1 to 10 words off matched 2. Functions of 450 to 490
instructions fill an agent's context after two to four functions (two battle batches
matched 1 of 16). Old near misses that the first batches of a target left with a one-word
note ("near miss", "registers") did better when retried with today's forms: 5 and 6 of
16 in the spells (batches 1 to 27), and 2 to 6 of 18 to 22 per batch in battle, the
minigames, field and main, where near misses that spells batches 50 to 77 had already
worked matched 1 of 16. Start such a retry from the closest old draft, scored with
work.py diff (permuter variants and _best.c files included).
The spells repeat many functions across their files (and snobo2 repeats snobo): a batch
of one representative per group of identical functions, largest groups first, then
tools/propagate.py, which copies each match to its twins (the first two batches of 58
representatives became about 700 functions). Propagate compares shapes with the asm of
functions already in C, which build.py --split writes to asm/us/<target>/matchings/.
When a target's small functions all fail the same way, check its options before
grinding: counting the folded %lo(x)($at) forms against the unfolded addiu $at, %lo
ones per file found ASPSX 2.30+ in batini, batres, brom, chocobo, snobo, snobo2 and five
spells, which tools/psyq.py had as 2.21.
Batches 88 to 98 and old1 to old14 (spells and every other target) matched 0 to 6
functions each, most of them 1 or 2. Near misses that a batch already took to 1 to 6 words
with about 20 tries rarely fall to a second batch soon after (nearmiss3: 0 of 22); large
untried functions (450 to 510 instructions) fill an agent's context (big1 to big3: 1 of
11); never-attempted functions and do { } while (0) wraps gave the recent matches.
work/wrapall/candidates.py SKIP OUT scores the best old draft of every near miss with
work.py diff, and work/wrapall/sweep.py CANDS MAXDIFF JOBS runs wrapall.py, unattended,
on the drafts that have the game's instruction count, smallest first: over 101 drafts
within 60 differing lines it matched magic_vahamut2 func_801B6C18. Before retrying an old
near miss, run a plain work.py diff on its old drafts: one in work/batres1/brom/ already
matched (brom func_800A01A0). Work-file names that differ only in case (_a.c, _A.c)
are one file on Windows. work/split3/optcheck.py TARGET FILE KEY=VALUE... compiles a file
with other options and lists the C functions that stop matching (under ASPSX 2.34 every C
function of main text4.c breaks, so func_8001C0EC is not a 2.34 function).
Batches 99 to 103 and old15 to old16, big4 to big12, lib1 to lib2 and focus1 to focus3
(2026-11-14 to 16): never-attempted spell functions of 244 to 400 instructions matched 9,
5 and 8 of 10 (spells99-101); never-drafted functions of 478 to 677 instructions matched 1
of 3 or 4 per batch at best (big4, big11) and none in five batches; small near misses one
register swap off resisted every retry (main14 0 of 18). What paid off: focus batches of 2
or 3 drafts already at the game's length or frame (1 of 3 each), 45 to 60-minute permuter
runs started by hand from an agent's best draft (night 180 to 120, then matched; eqipmenu
to the game's length), and option checks: work/optsweep/optsweep.py CANDS OUT compiles
each draft under every GCC build and ASPSX version, and work/optsweep/filecheck.py TARGET
FILE compiles each C function of a file on its own under each option value (optcheck.py's
whole-file check fails for every function of a file whose layout depends on the option):
they found that lib3.c holds a 2.21 part (func_80040CA8) and a 2.34 part (the CdRead
functions, now lib3a.c). Agents still type python -, leave permuter workers running
after reporting none, and arm wait loops that match their own command line: forbid wait
loops in the prompt and check the process list after every batch.
Batches big14 to big17 and focus8 and focus9 (2026-11-16) matched none of the large or
near-miss functions they were given: each ended 1 to 20 instructions or registers off,
with the same kind of register or delay-slot detail. What worked (2026-11-16 to 25, 33
functions): porting from twins. tools/twins.py scan ranks every function still in asm by
its most similar functions in C (instruction streams with symbols masked; --ops masks
registers and immediates as well: 0.92 and above means the same operations, other
registers or constants); twins.py diff SRC DST prints where two functions differ and how
their symbols pair (propagate.py's normalized form); twins.py port SRC DST OUT.c writes
a work file from the twin's C with its symbols renamed (--skip-dst/--skip-src drop
unpaired symbols so the rest pair up). Twins at 0.87 to 1.00 matched after edits to
constants, a case more or less, an early exit, a field offset, one operand, a nested call;
the camera-script interpreter alone gave twelve functions (hades, satan, siva, odin1,
alex, debucho, vahamut0, antlion, sting, deadsef, lamu, choco0). A matched function is a
new twin: rescan after every batch. tools/permute.py needs --stack-diffs for a function
whose only difference is a stack offset (the permuter ignores them and scores 0 at once),
and a permuter hit has to be rewritten in the repository's style (tools/tidy_style.py does
the whitespace and braces) and checked with work.py diff before put. A whole-project build
(tools/build.py) after a batch that changed main/decls.h catches clashes with overlay
declarations.
Retrying old near misses with the newest facts paid off: of 22 functions that earlier
batches had left 1 to 6 words off, near1 and near3 matched 9 (battle func_800A72C8,
magic_vahamut, odin1, alex, gospel, beast, garyu, spark, hades) and focus10 4 of 7; the
facts in this section from 2026-11-24 on are the ones that did it. GTE functions
(include/gte.h) gave about 80 more functions in a day (gte2 to gte7): batches of 15 to 36
small ones with siblings in other overlays work best, a family of large copies (frog 452
and 650, vahamut2 688, eight overlays each) is worth the most but cost a full batch
without a match; tools/permute.py cannot parse asm statements, so wrapall.py and forms are
the tools there. Up to three agents ran at once from 2026-11-25; each one has its own work
folder and put takes a lock; macros in include/gte.h are added with the Edit tool on its
last line.