"""SSA6: structured for loops, conditional CFG and batched exact PHI construction. Isolated algorithmic research; host schedules correct typed AST, resident tensors reserve loop-header values and patch backedges. Restricted unsigned i32 subset. No early returns, break/continue, memory, unsupported casts or templates. """ import argparse,json,time,hashlib,random,re,ctypes,tempfile,subprocess from pathlib import Path from collections import defaultdict,Counter import torch from torch import nn import ssa_tensor_experiment as old from ssa_tensor_experiment import K,O,U,MASK,PIN,f,VOCAB,sem,ASTBridge,SignatureTable,SSAAdapter,candidates,literal_batch,oracle,label # Event codes, value encoding: nonnegative SSA IDs; immediate -(value+2); -1 unknown. ENTER,MERGE,PHI,PARAM,CONST,READ,WRITE,ARITH,CMP,BR,JMP,RET=range(1,13) LOOPPHI,PATCH=13,14 OPS={'+':0,'-':1,'*':2,'^':3,'&':4,'<<':5,'>>':6,'>':7,'<':8,'==':9} IR=['add','sub','mul','xor','and','shl','lshr','icmp ugt','icmp ult','icmp eq'] def generate(count=32): r=random.Random(6606);out=[] for g in ('loop_fixed','loop_dynamic','loop_nested','loop_branch','loop_shadow','loop_sequential','loop_zero','loop_long','unsupported_loop_two_immediate_phi','unsupported_condition_side_effect'): for i in range(count if not g.startswith('unsupported') else 8): c=r.randrange(1,8);d=r.randrange(1,64);op=r.choice(['+','*','^','-']);base='unsigned int x=a; unsigned int y=b;' if g=='loop_fixed':body=base+f'for(unsigned int i=0u;i<{c}u;++i) x=x {op} (i+{d}u); return x+y;' elif g=='loop_dynamic':body=base+f'unsigned int n=b&7u; for(unsigned int i=0u;iy) x=x-y; else y=y+{d}u; x=x+i;}} return x+y;' elif g=='loop_shadow':body=base+f'for(unsigned int i=0u;i<{c}u;++i) {{unsigned int x=i+{d}u; y=y {op} x; {{unsigned int y=x+a; x=x^y;}} y=y+x;}} return x+y;' elif g=='loop_sequential':body=base+f'for(unsigned int i=0u;i<{c}u;++i) x=x {op} y; for(unsigned int j=0u;j<3u;++j) y=y+x; return x+y;' elif g=='loop_zero':body=base+f'for(unsigned int i=0u;i<0u;++i) x=x+{d}u; return x+y;' elif g=='loop_long':body=base+f'for(unsigned int i=0u;i<{16+i%17}u;++i) {{x=x {op} y; y=y+i;}} return x+y;' elif g=='unsupported_loop_two_immediate_phi':body=base+'unsigned int z=3u; for(unsigned int i=0u;i<3u;++i) z=4u; return z+x;' else:body=base+'for(unsigned int i=0u;++i<3u;++i) x=x+y; return x+y;' src='extern "C" unsigned int kernel('+(' '*(i+1))+'const unsigned int *__restrict p, unsigned int *__restrict q, unsigned int a, unsigned int b) {'+body+'}\n';h=hashlib.sha256(src.encode()).hexdigest();out.append(dict(id=h[:16],sha256=h,group=g,source=src)) return out class Plan: """Host-only structural scheduling, no reference SSA or runtime values.""" def __init__(self,p,s): self.k=p['kind'].tolist();self.o=p['opcode'].tolist();self.ty=p['type'].tolist();self.cast=p['cast'].tolist();self.decl=p['decl'].tolist();self.ch=[[q for q in r if q>=0] for r in p['children'].tolist()];self.literal=f.bytes_int64(p['literal']).tolist();self.events=[];self.blocks=0;self.block=-1;self.visible=set();self.s=s def emit(self,tag,a=0,b=0,c=0): self.events.append([tag,self.block,a,b,c]);return len(self.events)-1 def newblock(self,pre=-1,second=-1): self.block=self.blocks;self.blocks+=1;self.emit(ENTER,pre,second);return self.block def kind(self,j):return VOCAB['kind'][self.k[j]] def op(self,j):return VOCAB['opcode'][self.o[j]] def need(self,test,msg): if not test:raise ValueError(msg) def expr(self,j,condition=False): k=self.kind(j);ch=self.ch[j];self.need(self.ty[j]==(2 if condition else U),'unsupported expression type') if k=='ParenExpr':return self.expr(ch[0],condition) if k=='ImplicitCastExpr': self.need(not condition and self.cast[j]==3 and len(ch)==1,'unsupported cast');return self.expr(ch[0]) if k=='DeclRefExpr': d=self.decl[j];self.need(d in self.visible and not condition,'unbound reference');return self.emit(READ,d) if k=='IntegerLiteral':self.need(not condition and 0<=self.literal[j]<=MASK,'unsupported literal');return self.emit(CONST,self.literal[j]) self.need(k=='BinaryOperator' and len(ch)==2,'unsupported expression') op=self.op(j);self.need(op in OPS and (op in ('>','<','=='))==condition,'unsupported operator') a=self.expr(ch[0]);b=self.expr(ch[1]);return self.emit(CMP if condition else ARITH,OPS[op],a,b) def stmt(self,j): k=self.kind(j);ch=self.ch[j] if k=='CompoundStmt': prev=self.visible.copy() for c in ch:self.stmt(c) self.visible=prev elif k=='DeclStmt': for d in ch: self.need(self.kind(d)=='VarDecl' and self.ty[d]==U and len(self.ch[d])==1,'unsupported declaration');v=self.expr(self.ch[d][0]);self.emit(WRITE,d,v);self.visible.add(d) elif k=='BinaryOperator' and self.op(j)=='=': self.need(len(ch)==2 and self.kind(ch[0])=='DeclRefExpr' and self.decl[ch[0]] in self.visible and self.ty[j]==U,'unsupported assignment');self.emit(WRITE,self.decl[ch[0]],self.expr(ch[1])) elif k=='UnaryOperator' and self.op(j)=='++': self.need(len(ch)==1 and self.kind(ch[0])=='DeclRefExpr' and self.ty[j]==U and self.decl[ch[0]] in self.visible,'unsupported increment') d=self.decl[ch[0]];v=self.emit(READ,d);one=self.emit(CONST,1);self.emit(WRITE,d,self.emit(ARITH,OPS['+'],v,one)) elif k=='ForStmt': self.need(len(ch)==5 and self.kind(ch[1])=='Unknown' and not self.ch[ch[1]],'unsupported for shape');outer=self.visible.copy() self.stmt(ch[0]);vis=self.visible.copy();pre=self.block;pj=self.emit(JMP,-1);header=self.newblock(pre);self.events[pj][2]=header # Only visible declarations actually written by the body or increment need loop PHIs. written=set();todo=[ch[3],ch[4]] while todo: t=todo.pop();cc=self.ch[t];todo.extend(cc) if self.kind(t) in ('BinaryOperator','UnaryOperator') and self.op(t) in ('=','++') and cc and self.kind(cc[0])=='DeclRefExpr':written.add(self.decl[cc[0]]) phis=[(d,self.emit(LOOPPHI,d,pre,-1)) for d in sorted(vis&written)] # Existing vocabulary lacks icmp ult i32 {v},{i}. Invert i < C to i > C-1; # for C=0, use i==i and invert. All expressions in this subset are pure. cond=ch[2];inv=False while self.kind(cond)=='ParenExpr':cond=self.ch[cond][0] cc=self.ch[cond] if self.kind(cond)=='BinaryOperator' and self.op(cond)=='<' and len(cc)==2 and self.kind(cc[1])=='IntegerLiteral': self.need(self.ty[cond]==2 and self.ty[cc[1]]==U,'condition type');v=self.expr(cc[0]);bound=self.literal[cc[1]];self.need(0<=bound<=MASK,'unsupported literal');inv=True test=self.emit(CMP,OPS['>'],v,self.emit(CONST,bound-1)) if bound else self.emit(CMP,OPS['=='],v,v) else:test=self.expr(cond,True) br=self.emit(BR,test,-1,-1);body=self.newblock(header);self.stmt(ch[4]);self.visible=vis.copy();self.stmt(ch[3]);latch=self.block;self.emit(JMP,header) for d,e in phis:self.events[e][4]=latch;self.emit(PATCH,e,latch,d) exit=self.newblock(header);self.events[br][3:5]=[exit,body] if inv else [body,exit];self.visible=outer elif k=='IfStmt': self.need(len(ch) in (2,3),'unsupported if initializer/arity');vis=self.visible.copy();cond=self.expr(ch[0],True);entry=self.block;br=self.emit(BR,cond,-1,-1) then=self.newblock(entry);self.stmt(ch[1]);te=self.block;tjump=self.emit(JMP,-1);self.visible=vis.copy() if len(ch)==3: other=self.newblock(entry);self.stmt(ch[2]);fe=self.block;fjump=self.emit(JMP,-1);self.visible=vis.copy() else:other=None;fe=entry;fjump=None merge=self.newblock(te,fe);self.events[br][3:5]=[then,other if other is not None else merge];self.events[tjump][2]=merge if fjump is not None:self.events[fjump][2]=merge for d in sorted(vis):self.emit(PHI,d,te,fe) else:raise ValueError('unsupported statement '+k) def build(self): ch=self.ch[0];self.need(self.kind(0)=='FunctionDecl' and self.ty[0]==8 and len(ch)==5 and self.kind(ch[-1])=='CompoundStmt','signature');self.newblock() for i,j in enumerate(ch[:4]): self.need(self.kind(j)=='ParmVarDecl','parameter'); if i>=2:self.need(self.ty[j]==U,'scalar parameter type');self.emit(PARAM,j,i);self.visible.add(j) body=self.ch[ch[-1]];self.need(bool(body) and self.kind(body[-1])=='ReturnStmt','final return') for j in body[:-1]:self.stmt(j) self.need(len(self.ch[body[-1]])==1,'return arity');self.emit(RET,self.expr(self.ch[body[-1]][0]));self.need(self.blocks<=self.s['B'],'block capacity');return self.events def prepare(p,s): valid=sem.validate_packet(p).cpu().tolist();p={k:v.cpu() for k,v in p.items()};plans=[];errors=[] for i,v in enumerate(valid): try: if not v:raise ValueError('invalid AST packet') plan=Plan({k:x[i] for k,x in p.items()},s).build();plans.append(plan);errors.append(None) except (ValueError,IndexError,KeyError,RecursionError) as e:plans.append([]);errors.append(str(e)) E=max(1,max(map(len,plans)));ev=torch.zeros(len(plans),E,5,dtype=torch.long) for i,plan in enumerate(plans): if plan:ev[i,:len(plan)]=torch.tensor(plan) return ev,torch.tensor([x is None for x in errors]),errors class LoopSSA(nn.Module): def __init__(self,s,device): super().__init__();self.s=s;self.meta=f.ssa_metadata(s,device);lookup=lambda x:s['templates'].index(x) if x in s['templates'] else 0 self.table=torch.tensor([[lookup(f'def {op} i32 '+form) for form in ('{v}, {v}','{v}, {i}','{i}, {v}','{i}, {i}')] for op in IR],device=device);self.phi=torch.tensor([lookup('def phi i32 [ {v}, {b} ], [ {v}, {b} ]'),lookup('def phi i32 [ {v}, {b} ], [ {i}, {b} ]'),lookup('def phi i32 [ {i}, {b} ], [ {v}, {b} ]'),0],device=device);self.br=lookup('br i1 {v}, label {b}, label {b}');self.jmp=lookup('br label {b}');self.ret=lookup('ret i32 {v}');self.sig=SignatureTable(VOCAB['type'],device) @torch.inference_mode() def forward(self,ev,valid): B,E,_=ev.shape;dev=ev.device;T,M,P=self.s['T'],self.s['B'],self.s['P'];i=torch.arange(B,device=dev);env=torch.full((B,M,512),-1,dtype=torch.long,device=dev);vals=torch.full((B,E),-1,dtype=torch.long,device=dev);tmpl=torch.zeros(B,T+1,dtype=torch.long,device=dev);blk=tmpl.clone();oper=torch.zeros(B,T+1,P,dtype=torch.long,device=dev);n=torch.zeros(B,dtype=torch.long,device=dev);valid=valid.clone() for t in range(E): tag,block,a,b,c=ev[:,t].unbind(-1);block=block.clamp(0,M-1);aidx=a.clamp(0,511);isenter=tag.eq(ENTER);loopphi=tag.eq(LOOPPHI);patch=tag.eq(PATCH);isphi=tag.eq(PHI)|loopphi;ar=tag.eq(ARITH)|tag.eq(CMP);iswrite=tag.eq(WRITE)|tag.eq(PARAM);read=tag.eq(READ) incoming=env[i,a.clamp(0,M-1)];env[i,block]=torch.where((isenter&a.ge(0))[:,None],incoming,env[i,block]); x=vals[i,b.clamp(0,E-1)];y=vals[i,c.clamp(0,E-1)];u=vals[i,a.clamp(0,E-1)];x=torch.where(isphi,env[i,b.clamp(0,M-1),aidx],x);y=torch.where(isphi,env[i,c.clamp(0,M-1),aidx],y);y=torch.where(loopphi,n+4,y) # commutation, and relational reversal when an immediate is on the left. op=a.clamp(0,len(IR)-1);swap=ar&x.lt(-1)&y.ge(0)&((op==0)|(op==2)|(op==3)|(op==4)|(op==9)|(op==7)|(op==8));x,y=torch.where(swap,y,x),torch.where(swap,x,y);op=torch.where(swap&op.eq(7),8,torch.where(swap&op.eq(8),7,op));form=2*x.lt(-1).long()+y.lt(-1).long();atid=self.table[op,form];ptid=self.phi[form];different=loopphi|(isphi&x.ne(y));emit=ar|different|tag.eq(BR)|tag.eq(JMP)|tag.eq(RET);tid=torch.where(ar,atid,torch.where(different,ptid,torch.where(tag.eq(BR),self.br,torch.where(tag.eq(JMP),self.jmp,torch.where(tag.eq(RET),self.ret,0))))) valid &= (~(ar|isphi)|(x.ne(-1)&y.ne(-1)))&(~emit|(tid.gt(0)&n.lt(T)))&(~(tag.eq(BR)|tag.eq(RET))|u.ge(0))&(~read|env[i,block,aidx].ne(-1))&(~(ar&((op==5)|(op==6)))|(y.lt(-1)&(-y-2).lt(32))) dst=torch.where(emit&n.lt(T),n,T);tmpl[i,dst]=tid;blk[i,dst]=block;decode=lambda v:torch.where(v.lt(-1),-v-2,v) op0=torch.where(ar|isphi,decode(x),torch.where(tag.eq(JMP),a,u));op1=torch.where(isphi,b,torch.where(tag.eq(BR),b,decode(y)));op2=torch.where(isphi,decode(y),c);op3=c oper[i,dst,:4]=torch.stack([op0,op1,op2,op3],-1) value=torch.where(ar|different,n+4,torch.where(isphi,x,torch.where(tag.eq(CONST),-a-2,torch.where(read,env[i,block,aidx],-1))));vals[:,t]=value upd=torch.where(tag.eq(PARAM),b,torch.where(isphi,value,x));env[i,block,aidx]=torch.where(iswrite|isphi,upd,env[i,block,aidx]); # Backedge values can be defined after the header. Patch reserved row only. row=(vals[i,a.clamp(0,E-1)]-4);safe=row.clamp(0,T);first=oper[i,safe,0];firstimm=self.meta[0][tmpl[i,safe],0].eq(3);back=env[i,b.clamp(0,M-1),c.clamp(0,511)];pf=2*firstimm.long()+back.lt(-1).long();patched=self.phi[pf];valid &= (~patch|(row.ge(0)&row.lt(n)&back.ne(-1)&patched.gt(0))) pdst=torch.where(patch&row.ge(0)&row.lt(T),row,T);tmpl[i,pdst]=torch.where(patch,patched,tmpl[i,pdst]);oper[i,pdst,2]=torch.where(patch,decode(back),oper[i,pdst,2]);n+=emit.long() tmpl=tmpl[:,:T];blk=blk[:,:T];role=self.meta[0][tmpl];mask=tmpl.ne(0);oper=oper[:,:T].masked_fill(role.eq(0),0);z=dict(template=tmpl,block=blk,role=role,operands=oper,mask=mask,routing_valid=valid);z['valid']=f.ssa_tensor_valid(z,self.s,self.meta);z.update(self.sig(torch.full((B,),8,device=dev,dtype=torch.long)));z['valid'] &= z['signature_valid']; for k in ('template','block','role','operands','mask'):z[k]=z[k].masked_fill(~z['valid'].reshape(B,*([1]*(z[k].ndim-1))),0) return z def interpret(rows,a,b,trace=None): """Independent CFG interpreter: simultaneous PHIs, branch selection, uint32 arithmetic.""" blocks=defaultdict(list) for j,r in enumerate(rows):blocks[r['block']].append((j+4,r)) v={2:a,3:b};block=0;pred=-1 for _ in range(1024): pending={};jump=None for id,r in blocks[block]: t=r['template'];p=r['operands'];roles=re.findall(r'\{([vbi])\}',t);get=lambda j:v[p[j]] if roles[j]=='v' else p[j] if t.startswith('def phi i32 '): ix=[j for j in range(0,len(p),2) if p[j+1]==pred] if len(ix)!=1:raise ValueError('phi predecessor'); pending[id]=get(ix[0]);continue v.update(pending);pending={} if t=='br label {b}':jump=p[0];break if t=='br i1 {v}, label {b}, label {b}': jump=p[1] if get(0) else p[2] if trace is not None:trace.add((block,jump)) break if t=='ret i32 {v}':return get(0) m=re.fullmatch(r'def (add|sub|mul|xor|and|shl|lshr|icmp ugt|icmp ult|icmp eq) i32 \{[vi]\}, \{[vi]\}',t) if not m:raise ValueError('unsupported interpreter template') x,y=get(0)&MASK,get(1)&MASK;op=m[1] if op in ('shl','lshr') and y>=32:raise ValueError('shift') v[id]=int({'add':lambda:x+y,'sub':lambda:x-y,'mul':lambda:x*y,'xor':lambda:x^y,'and':lambda:x&y,'shl':lambda:x<>y,'icmp ugt':lambda:x>y,'icmp ult':lambda:x