@@ -880,11 +880,10 @@ internal class AsmGen(private val program: Program,
880880 }
881881
882882 out (" ; variables" )
883- for ((name, addr) in sub.asmGenInfo.extraVarsZP) {
884- out (" $name = $addr " )
885- }
886- for ((dt, name) in sub.asmGenInfo.extraVars) {
887- when (dt) {
883+ for ((dt, name, addr) in sub.asmGenInfo.extraVars) {
884+ if (addr!= null )
885+ out (" $name = $addr " )
886+ else when (dt) {
888887 DataType .UBYTE -> out (" $name .byte 0" )
889888 DataType .UWORD -> out (" $name .word 0" )
890889 else -> throw AssemblyError (" weird dt" )
@@ -1069,33 +1068,40 @@ $repeatLabel lda $counterVar
10691068 }
10701069
10711070 private fun createRepeatCounterVar (dt : DataType , constIterations : Int? , stmt : RepeatLoop ): String {
1072- // TODO share counter variables between subroutines or even between repeat loops as long as they're not nested
1073- // var parent = stmt.parent
1074- // while(parent !is ParentSentinel) {
1075- // if(parent is RepeatLoop)
1076- // break
1077- // parent = parent.parent
1078- // }
1079- // val isNested = parent is RepeatLoop
1080- val counterVar = makeLabel(" repeatcounter" )
10811071 val asmInfo = stmt.definingSubroutine()!! .asmGenInfo
1072+ var parent = stmt.parent
1073+ while (parent !is ParentSentinel ) {
1074+ if (parent is RepeatLoop )
1075+ break
1076+ parent = parent.parent
1077+ }
1078+ val isNested = parent is RepeatLoop
1079+
1080+ if (! isNested) {
1081+ // we can re-use a counter var from the subroutine if it already has one for that datatype
1082+ val existingVar = asmInfo.extraVars.firstOrNull { it.first== dt }
1083+ if (existingVar!= null )
1084+ return existingVar.second
1085+ }
1086+
1087+ val counterVar = makeLabel(" repeatcounter" )
10821088 when (dt) {
10831089 DataType .UBYTE -> {
10841090 if (constIterations!= null && constIterations>= 16 && zeropage.hasByteAvailable()) {
10851091 // allocate count var on ZP
10861092 val zpAddr = zeropage.allocate(counterVar, DataType .UBYTE , stmt.position, errors)
1087- asmInfo.extraVarsZP .add(Pair ( counterVar, zpAddr))
1093+ asmInfo.extraVars .add(Triple ( DataType . UBYTE , counterVar, zpAddr))
10881094 } else {
1089- asmInfo.extraVars.add(Pair (DataType .UBYTE , counterVar))
1095+ asmInfo.extraVars.add(Triple (DataType .UBYTE , counterVar, null ))
10901096 }
10911097 }
10921098 DataType .UWORD -> {
10931099 if (constIterations!= null && constIterations>= 16 && zeropage.hasWordAvailable()) {
10941100 // allocate count var on ZP
10951101 val zpAddr = zeropage.allocate(counterVar, DataType .UWORD , stmt.position, errors)
1096- asmInfo.extraVarsZP .add(Pair ( counterVar, zpAddr))
1102+ asmInfo.extraVars .add(Triple ( DataType . UWORD , counterVar, zpAddr))
10971103 } else {
1098- asmInfo.extraVars.add(Pair (DataType .UWORD , counterVar))
1104+ asmInfo.extraVars.add(Triple (DataType .UWORD , counterVar, null ))
10991105 }
11001106 }
11011107 else -> throw AssemblyError (" invalidt dt" )
0 commit comments