-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
loops.c
1784 lines (1690 loc) · 54.9 KB
/
loops.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Spin to C/C++ converter
* Copyright 2011-2023 Total Spectrum Software Inc.
* MIT Licensed
* See the file COPYING for terms of use
*
* code for handling loops
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spinc.h"
#define LVFLAG_CONDITIONAL 0x01 /* assignment is conditional */
#define LVFLAG_NESTED 0x02 /* assignment is nested in a loop */
#define LVFLAG_LOOPDEPEND 0x04 /* assignment value is loop dependent */
#define LVFLAG_LOOPUSED 0x08 /* variable in assignment is used */
#define LVFLAG_VARYMASK 0xff /* any of these bits set means assignment depends on loop */
//
// loop value table
// this keeps track of state of various variables
// if the variable has only been assigned once, then it
// will have an entry in the table with its initial value
// if it has been assigned multiple times, then it
// will have an entry saying that; in this case, if the second
// assignment was a simple one like i := i+1 we mark the entry
//
typedef struct LoopValueEntry {
struct LoopValueEntry *next;
AST *name; // name of the variable
AST *value; // last assignment (only really useful if hits == 1)
AST *parent; // parent of the last assignment statement
unsigned flags; // info about the assignment
int hits; // number of times we see assignments to this variable
AST *loopstep; // if strength reduction is possible, do this each time through
AST *basename; // base loop induction variable that "loopstep" depends on
} LoopValueEntry;
typedef struct LoopValueSet {
LoopValueEntry *head;
LoopValueEntry *tail;
bool valid; // if false, abandon all attempts to use this LVS
} LoopValueSet;
/*
* utility functions
*/
bool AstMatchName(AST *expr, AST *name)
{
if (expr && expr->kind == AST_LOCAL_IDENTIFIER) {
expr = expr->left;
}
if (name && name->kind == AST_LOCAL_IDENTIFIER) {
name = name->left;
}
return AstMatch(expr, name);
}
bool AstUsesName(AST *expr, AST *name)
{
if (expr && expr->kind == AST_LOCAL_IDENTIFIER) {
expr = expr->left;
}
if (name && name->kind == AST_LOCAL_IDENTIFIER) {
name = name->left;
}
return AstUses(expr, name);
}
/*
* initialize a LoopValueSet
*/
static void
InitLoopValueSet(LoopValueSet *lvs)
{
lvs->head = lvs->tail = NULL;
lvs->valid = true;
}
/*
* destroy a loop value set
*/
static void
FreeLoopValueSet(LoopValueSet *lvs)
{
LoopValueEntry *entry;
LoopValueEntry *old;
entry = lvs->head;
while (entry) {
old = entry;
entry = entry->next;
free(old);
}
lvs->head = lvs->tail = NULL;
}
/*
* add a name to an LVSet
*/
static void
AddToLVS(LoopValueSet *lvs, LoopValueEntry *entry)
{
entry->next = NULL;
if (!lvs->tail) {
lvs->head = lvs->tail = entry;
return;
}
lvs->tail->next = entry;
lvs->tail = entry;
}
/*
* find a name in an LVSet
*/
static LoopValueEntry *
FindName(LoopValueSet *lvs, AST *name)
{
LoopValueEntry *entry;
for (entry = lvs->head; entry; entry = entry->next) {
if (AstMatchName(entry->name, name)) {
return entry;
}
}
return NULL;
}
/*
* Merge loop value set "l2" into "lvs", updating assignments as
* applicable and freeing duplicate entries
*/
static void
MergeAndFreeLoopValueSets(LoopValueSet *lvs, LoopValueSet *l2)
{
LoopValueEntry *e2;
LoopValueEntry *old;
LoopValueEntry *orig;
e2 = l2->head;
while(e2) {
old = e2;
e2 = e2->next;
orig = FindName(lvs, old->name);
if (orig) {
orig->value = old->value;
orig->parent = old->parent;
orig->flags |= old->flags;
orig->hits += old->hits;
free(old);
} else {
AddToLVS(lvs, old);
}
}
l2->head = NULL;
}
/*
* Add a new assignment "name = value" to a LoopValueSet
* if value is NULL then we're adding a use rather than an assignment
*/
static LoopValueEntry *
AddAssignment(LoopValueSet *lvs, AST *name, AST *value, unsigned flags, AST *parent)
{
LoopValueEntry *entry;
switch (name->kind) {
case AST_EXPRLIST:
{
// multiple assignment... punt on this for now
// pretend all of these depend on a hardware register
while (name) {
AddAssignment(lvs, name->left, NewAST(AST_HWREG, NULL, NULL), LVFLAG_VARYMASK, NULL);
name = name->right;
}
return NULL;
}
case AST_ARRAYREF:
case AST_MEMREF:
case AST_HWREG:
case AST_RANGEREF:
{
// we mostly just leave array updates out of things
return NULL;
}
case AST_IDENTIFIER:
case AST_LOCAL_IDENTIFIER:
break;
default:
// unexpected item, bail
lvs->valid = false;
return NULL;
}
entry = FindName(lvs, name);
if (entry) {
if (value) {
entry->hits++;
entry->value = value;
entry->parent = parent; // keep track of last assignment
entry->flags |= flags;
}
return entry;
}
entry = (LoopValueEntry*)calloc(sizeof(*entry), 1);
entry->hits = value ? 1 : 0;
entry->name = name;
entry->value = value;
entry->parent = parent;
entry->flags = flags;
AddToLVS(lvs, entry);
return entry;
}
/*
* check an operator for any assignments
*/
static unsigned
CheckOperatorForAssignment(LoopValueSet *lvs, AST *parent, AST *ast, unsigned flags)
{
AST *name = NULL;
AST *val = ast;
switch (ast->d.ival) {
case K_INCREMENT:
case K_DECREMENT:
case '?':
name = ast->left ? ast->left : ast->right;
AddAssignment(lvs, name, val, flags, parent);
break;
case K_BOOL_OR:
case K_BOOL_AND:
/* lhs will be unconditional, but we cannot check that here */
flags |= LVFLAG_CONDITIONAL;
break;
default:
break;
}
return flags;
}
/*
* analyze a statement list, updating the LoopValueSet with all
* assignments
*/
static void
FindAllAssignments(LoopValueSet *lvs, AST *parent, AST *ast, unsigned flags)
{
if (!ast) return;
switch (ast->kind) {
case AST_ASSIGN:
if (AddAssignment(lvs, ast->left, ast->right, flags, parent)) {
FindAllAssignments(lvs, parent, ast->right, flags);
return;
}
break;
case AST_ADDROF:
case AST_ABSADDROF:
AddAssignment(lvs, ast->left, NewAST(AST_HWREG, NULL, NULL), LVFLAG_VARYMASK, NULL);
break;
case AST_OPERATOR:
flags = CheckOperatorForAssignment(lvs, parent, ast, flags);
break;
case AST_POSTSET:
//ERROR(NULL, "Internal error, should not see POSTSET in LVS");
// bytecode generates POSTSETs, so just invalidate for now
lvs->valid = false;
break;
case AST_IF:
case AST_CASE:
case AST_LABEL:
flags |= LVFLAG_CONDITIONAL;
break;
case AST_GOTO:
/* cannot cope with this */
lvs->valid = 0;
break;
case AST_WHILE:
case AST_DOWHILE:
case AST_FOR:
case AST_FORATLEASTONCE:
flags |= LVFLAG_NESTED;
break;
#if 0
case AST_METHODREF:
case AST_CONSTREF:
// don't recurse inside these
return;
#endif
case AST_COMMENTEDNODE:
// don't update parent here
break;
case AST_STMTLIST:
parent = ast;
break;
case AST_LOCAL_IDENTIFIER:
case AST_IDENTIFIER:
// if this identifier is being used in the loop, but has not
// yet been assigned, add an entry for it
AddAssignment(lvs, ast, NULL, flags | LVFLAG_LOOPUSED, NULL);
return;
default:
parent = ast; // do we really want this?
break;
}
FindAllAssignments(lvs, parent, ast->left, flags);
FindAllAssignments(lvs, parent, ast->right, flags);
}
//
// return true if an expression is loop dependent
// be conservative about this!
//
static bool
IsLoopDependent(LoopValueSet *lvs, AST *expr)
{
if (!expr) {
return false;
}
switch (expr->kind) {
case AST_INTEGER:
return false;
case AST_LOCAL_IDENTIFIER:
case AST_IDENTIFIER:
{
Symbol *sym = LookupAstSymbol(expr, NULL);
LoopValueEntry *entry;
if (!sym) {
return true;
}
switch (sym->kind) {
case SYM_PARAMETER:
case SYM_RESULT:
case SYM_LOCALVAR:
case SYM_TEMPVAR:
entry = FindName(lvs, expr);
if (!entry || !entry->value) {
// never assigned in the loop
if (curfunc->local_address_taken) return true;
return false;
}
if ((0 == (entry->flags & LVFLAG_VARYMASK))) {
unsigned saveflag;
bool r;
// if entry->hits > 1 then variable is loop dependent
if (entry->hits > 1) return true;
// temporarily pretend the variable is dependent
// and see if that makes its assigned value dependent
// (this detects inter-variable circular dependencies)
saveflag = entry->flags;
entry->flags |= LVFLAG_LOOPDEPEND;
r = IsLoopDependent(lvs, entry->value);
entry->flags = saveflag;
return r;
}
return true;
default:
return true;
}
}
case AST_OPERATOR:
switch (expr->d.ival) {
case K_INCREMENT:
case K_DECREMENT:
return true;
default:
break;
}
return IsLoopDependent(lvs, expr->left) || IsLoopDependent(lvs, expr->right);
case AST_ARRAYREF:
return IsLoopDependent(lvs, expr->left) || IsLoopDependent(lvs, expr->right);
case AST_ADDROF:
case AST_ABSADDROF:
// addr of a variable is loop independent, even if the variable
// isn't
{
AST *ast = expr->left;
if (!ast) return false;
if (IsIdentifier(ast)) return false;
if (ast->kind == AST_ARRAYREF) {
if (ast->left) {
if (IsIdentifier(ast->left)) {
return IsLoopDependent(lvs, ast->right);
} else if (ast->left->kind == AST_MEMREF) {
return IsLoopDependent(lvs, ast->right) || IsLoopDependent(lvs, ast->left);
}
}
}
return IsLoopDependent(lvs, ast);
}
case AST_MEMREF:
// left side is type, we don't need to check that
return IsLoopDependent(lvs, expr->right);
default:
return true;
}
}
//
// given an expression "val"
// find an expression for the difference in values
// between this loop step and the next
// Sets *baseName to point to the bottom level name
// that changes between loop updates
//
static int
ElementSize(AST *typ)
{
if (!typ) {
typ = ast_type_generic;
}
typ = RemoveTypeModifiers(typ);
if (typ->kind == AST_ARRAYTYPE) {
typ = typ->left;
}
return TypeSize(typ);
}
static AST *
FindLoopStep(LoopValueSet *lvs, AST *val, AST **basename)
{
AST *loopstep;
LoopValueEntry *entry;
AST *newval;
int stepval;
if (!val) return NULL;
switch(val->kind) {
case AST_LOCAL_IDENTIFIER:
case AST_IDENTIFIER:
newval = val;
for(;;) {
entry = FindName(lvs, newval);
if (!entry) return NULL;
if (entry->hits != 1) return NULL;
newval = entry->value;
if (!newval) return NULL;
if (!IsIdentifier(newval)) break;
}
if (AstUsesName(newval, val)) {
AST *increment = NULL;
if (newval->kind == AST_OPERATOR && newval->d.ival == '+') {
if (AstMatchName(val, newval->left) && IsConstExpr(newval->right)) {
increment = newval->right;
}
} else if (newval->kind == AST_OPERATOR && newval->d.ival == '-') {
if (AstMatchName(val, newval->left) && IsConstExpr(newval->right)) {
increment = AstOperator(K_NEGATE, NULL, newval->right);
}
} else if (newval->kind == AST_OPERATOR && newval->d.ival == K_INCREMENT && (AstMatchName(val, newval->left) || AstMatchName(val, newval->right))) {
increment = AstInteger(1);
} else if (newval->kind == AST_OPERATOR && newval->d.ival == K_DECREMENT && (AstMatchName(val, newval->left) || AstMatchName(val, newval->right))) {
increment = AstOperator(K_NEGATE, NULL, AstInteger(1));
}
if (increment) {
if (*basename == NULL) {
*basename = val;
} else {
if (!AstMatchName(val, *basename)) {
return NULL;
}
}
return increment;
}
return NULL;
}
return FindLoopStep(lvs, newval, basename);
case AST_ADDROF:
val = val->left;
if (val && val->kind == AST_ARRAYREF) {
int elementsize = 4;
AST *arrayname = val->left;
Symbol *sym;
if (arrayname->kind == AST_MEMREF) {
elementsize = ElementSize(arrayname->left);
}
else if (IsIdentifier(arrayname)) {
sym = LookupAstSymbol(arrayname, NULL);
if (!sym) {
return NULL;
}
switch (sym->kind) {
case SYM_VARIABLE:
case SYM_TEMPVAR:
case SYM_LOCALVAR:
case SYM_PARAMETER:
elementsize = ElementSize((AST *)sym->v.ptr);
break;
case SYM_LABEL:
{
Label *lab = (Label *)sym->v.ptr;
elementsize = ElementSize(lab->type);
break;
}
default:
return NULL;
}
} else {
return NULL;
}
val = val->right;
if (!val) return NULL;
loopstep = FindLoopStep(lvs, val, basename);
if (!loopstep) return NULL;
if (!IsConstExpr(loopstep)) return NULL;
if (!*basename) return NULL;
stepval = elementsize * EvalConstExpr(loopstep);
if (stepval >= 0) {
return AstInteger(stepval);
} else {
return AstOperator(K_NEGATE, NULL, AstInteger(-stepval));
}
}
return NULL;
case AST_OPERATOR:
if (val->d.ival == '*') {
// CONST * index or index * CONST may be
// strength reduced to adding CONST to the index each time
AST *constval;
AST *indexval;
AST *loopstep;
int32_t stepval;
if (IsConstExpr(val->left)) {
constval = val->left;
indexval = val->right;
} else if (IsConstExpr(val->right)) {
constval = val->right;
indexval = val->left;
} else {
return NULL;
}
stepval = EvalConstExpr(constval);
loopstep = FindLoopStep(lvs, indexval, basename);
if (!loopstep || !IsConstExpr(loopstep))
return NULL;
if (!*basename) return NULL;
stepval = stepval * EvalConstExpr(loopstep);
if (stepval >= 0) {
return AstInteger(stepval);
} else {
return AstOperator(K_NEGATE, NULL, AstInteger(-stepval));
}
} else if (val->d.ival == '-' || val->d.ival == '+' ) {
if (IsConstExpr(val->right)) {
AST *loopstep = FindLoopStep(lvs, val->left, basename);
if (!loopstep || !IsConstExpr(loopstep) || !*basename) {
return NULL;
}
return loopstep;
}
// C - indexval may be strength reduced
if (IsConstExpr(val->left)) {
AST *loopstep = FindLoopStep(lvs, val->right, basename);
if (!loopstep || !IsConstExpr(loopstep) || !*basename) {
return NULL;
}
return (val->d.ival == '+') ? loopstep : AstOperator(K_NEGATE, NULL, loopstep);
}
}
return NULL;
default:
return NULL;
}
}
static bool
AstUsesMemory(AST *ast)
{
if (!ast) return false;
switch (ast->kind) {
case AST_MEMREF:
case AST_ARRAYREF:
return true;
case AST_CONSTREF:
return false;
case AST_FUNCCALL:
case AST_GOSUB:
return true;
case AST_LOCAL_IDENTIFIER:
case AST_IDENTIFIER:
{
Symbol *sym = LookupAstSymbol(ast, NULL);
if (!sym) {
return true;
}
switch (sym->kind) {
case SYM_TEMPVAR:
case SYM_PARAMETER:
case SYM_RESULT:
case SYM_LOCALVAR:
return (curfunc->local_address_taken != 0);
default:
return true;
}
}
default:
return AstUsesMemory(ast->left) || AstUsesMemory(ast->right);
}
}
static void
MarkDependencies(LoopValueSet *lvs)
{
LoopValueEntry *entry;
int change = 1;
// mark any self-dependent entries
for (entry = lvs->head; entry; entry = entry->next) {
if (!entry->value) continue;
if (AstUsesName(entry->value, entry->name)) {
entry->flags |= LVFLAG_LOOPDEPEND;
}
if (AstUsesMemory(entry->value) || AstUsesMemory(entry->name)) {
entry->flags |= LVFLAG_LOOPDEPEND;
}
}
while (change != 0) {
change = 0;
for (entry = lvs->head; entry; entry = entry->next) {
if (0 == (entry->flags & LVFLAG_VARYMASK)) {
if (IsLoopDependent(lvs, entry->value)) {
entry->flags |= LVFLAG_LOOPDEPEND;
change = 1;
}
}
}
}
// now look here for expressions that can be strength reduced
for (entry = lvs->head; entry; entry = entry->next) {
if (entry->hits == 1 && (entry->flags & LVFLAG_VARYMASK)) {
entry->basename = NULL;
entry->loopstep = FindLoopStep(lvs, entry->value, &entry->basename);
}
}
}
/*
* place an assignment statement after a parent
*/
static bool
PlaceAssignAfter(AST *parent, AST *assign)
{
AST *stmt;
if (!parent) {
return false;
}
if (parent->kind == AST_STMTLIST) {
stmt = NewAST(AST_STMTLIST, assign, NULL);
parent->left = NewAST(AST_STMTLIST, parent->left, stmt);
return true;
}
if (parent->kind == AST_SEQUENCE) {
stmt = NewAST(AST_SEQUENCE, assign, NULL);
parent->left = NewAST(AST_SEQUENCE, parent->left, stmt);
return true;
}
return false;
}
/*
* actually perform loop strength reduction on a single loop body
* "initial" is a loop value set holding potential initial values for
* loop variables
* returns a statement list of assignments which should be performed
* before the loop
* and sets *updates to a list of assignments which should be performed on each loop
* iteration
*/
static AST *
doLoopStrengthReduction(LoopValueSet *initial, AST *body, AST *condition, AST *update)
{
LoopValueSet lv;
LoopValueEntry *entry;
LoopValueEntry *initEntry;
LoopValueEntry *lastAssign;
AST *stmtlist = NULL;
AST *stmt;
AST *replace;
AST *pullvalue; // initial value for pulled out code
AST *parent;
InitLoopValueSet(&lv);
FindAllAssignments(&lv, body, body, 0);
FindAllAssignments(&lv, update, update, 0);
FindAllAssignments(&lv, NULL, condition, 0);
MarkDependencies(&lv);
if (!lv.valid) {
return NULL;
}
for (entry = lv.head; entry; entry = entry->next) {
if (entry->hits > 1) {
continue;
}
parent = entry->parent;
if (!parent) continue;
if (parent->kind == AST_STMTLIST) {
/* OK */
} else {
continue;
}
if (entry->flags & (LVFLAG_VARYMASK)) {
// if the new value is sufficiently simple,
// and we know the initial value
// maybe we can apply loop strength reduction
if (!entry->loopstep || !entry->basename) {
continue;
}
if (!IsIdentifier(entry->basename)) {
continue;
}
initEntry = FindName(initial, entry->basename);
if (!initEntry || (initEntry->flags & LVFLAG_CONDITIONAL) ) {
continue;
}
lastAssign = FindName(&lv, entry->basename);
if (!lastAssign) {
continue;
}
if (AstMatchName(entry->name, entry->basename)) {
// entry depends on itself, do not update
continue;
}
// if value is used in a non-assignment before its update, skip
if (entry->flags & LVFLAG_LOOPUSED) {
continue;
}
// if this assignment is conditional don't mess with it
if (entry->flags & LVFLAG_CONDITIONAL) {
continue;
}
pullvalue = DupASTWithReplace(entry->value, entry->basename, initEntry->value);
if (entry->loopstep->kind == AST_OPERATOR && entry->loopstep->d.ival == K_NEGATE) {
replace = AstAssign(entry->name,
AstOperator('-', entry->name, entry->loopstep->right));
} else {
replace = AstAssign(entry->name,
AstOperator('+', entry->name, entry->loopstep));
}
// we have to place the "replace" after the last
// update to "basename" (the loop variable this value
// ultimately depends on)
if (!PlaceAssignAfter(lastAssign->parent, replace)) {
continue;
}
parent->left = NULL;
} else {
pullvalue = entry->value;
parent->left = NULL; // null out original statement
}
// this statement can be pulled out
stmt = AstAssign(entry->name, pullvalue);
stmt = NewAST(AST_STMTLIST, stmt, NULL);
stmtlist = AddToList(stmtlist, stmt);
}
MergeAndFreeLoopValueSets(initial, &lv);
return stmtlist;
}
static void doLoopOptimizeList(LoopValueSet *lvs, AST *list);
//
// helper for doLoopOptimizeList()
//
static AST *
doLoopHelper(LoopValueSet *lvs, AST *initial, AST *condtest, AST *update,
AST *body)
{
LoopValueSet sub;
AST *pull;
// initial loop assignments take place before the loop
if (initial) {
FindAllAssignments(lvs, NULL, initial, 0);
}
if (!lvs->valid) {
return NULL;
}
// optimize sub-loops
InitLoopValueSet(&sub);
doLoopOptimizeList(&sub, body);
FreeLoopValueSet(&sub);
// pull out loop invariants
pull = doLoopStrengthReduction(lvs, body, condtest, update);
// and update assignments based on loop
FindAllAssignments(lvs, NULL, body, 0);
return pull;
}
//
// convert a <= b to a < b+1
// and a <= b-1 to a < b
// leave a < b alone
//
AST *GetRevisedLimit(int updateTestOp, AST *oldLimit)
{
if (IsConstExpr(oldLimit) || IsIdentifier(oldLimit)) {
// a constant expression is always good
if (updateTestOp == K_LE || updateTestOp == K_LEU) {
oldLimit = AstOperator('+', oldLimit, AstInteger(1));
}
return oldLimit;
}
if (updateTestOp != K_LE && updateTestOp != K_LEU) {
return NULL;
}
// only accept very simple expressions
if (oldLimit->kind == AST_OPERATOR && oldLimit->d.ival == '-') {
int32_t offset;
if (!IsIdentifier(oldLimit->left)) {
return NULL;
}
if (!IsConstExpr(oldLimit->right)) {
return NULL;
}
offset = EvalConstExpr(oldLimit->right);
if (offset == 1) {
return oldLimit->left;
}
oldLimit->right = AstInteger(offset - 1);
return oldLimit;
}
return NULL;
}
//
// check for a "simple" decrement loop (counting down from N to 0
//
static bool
CheckSimpleDecrementLoop(AST *stmt)
{
AST *initial;
AST *condtest;
AST *update;
AST *body;
AST *updateparent;
AST *updateVar = NULL;
AST *updateLimit = NULL;
int updateTestOp = 0;
initial = stmt->left;
condtest = stmt->right;
updateparent = condtest->right;
condtest = condtest->left;
body = updateparent->right;
update = updateparent->left;
updateVar = NULL;
(void) body;
(void) initial;
// check for a simple count down to 0
if (!condtest || condtest->kind != AST_OPERATOR) {
return false;
}
if (ExprHasSideEffects(condtest)) {
return false;
}
updateTestOp = condtest->d.ival;
if (updateTestOp == '>' || updateTestOp == K_GTU) {
int32_t ival;
updateVar = condtest->left;
if (!updateVar) {
return false;
}
if (!IsIdentifier(updateVar)) {
return false;
}
updateLimit = condtest->right;
if (!IsConstExpr(updateLimit)) {
return false;
}
ival = EvalConstExpr(updateLimit);
if (ival != 0) {
return false;
}
} else if (updateTestOp != K_NE) {
return false;
}
/* check that the update is a decrement */
while (update && update->kind == AST_SEQUENCE) {
if (update->right && AstUsesName(update->right, updateVar)) {
return false;
}
update = update->left;
}
if (!update) return false;
if (update->kind != AST_OPERATOR) {
return false;
}
if (update->d.ival == K_DECREMENT) {
if (!AstMatchName(update->left, updateVar) && !AstMatchName(update->right, updateVar)) {
return false;
}
} else {
return false;
}
if (updateTestOp == K_GTU) {
condtest->d.ival = K_NE;
return true;
}
if (condtest->d.ival != K_NE) {
return false;
}
// change AST_FOR to AST_FORATLEASTONCE here, for better performance
if (stmt->kind == AST_FOR) {
AST *newstmt = NewAST(AST_FORATLEASTONCE, NULL, NULL);
AST *skipif;
*newstmt = *stmt;
newstmt->kind = AST_FORATLEASTONCE;
newstmt->left = NULL; // initial will be performed earlier
newstmt = NewAST(AST_STMTLIST, newstmt, NULL);
newstmt = NewAST(AST_THENELSE, newstmt, NULL);
skipif = NewAST(AST_IF, DupAST(condtest), newstmt);
skipif = NewAST(AST_STMTLIST, initial,
NewAST(AST_STMTLIST, skipif, NULL));
*stmt = *skipif;
}
return true;
}
//
// check for branches
// function calls are OK, I think, because we already reject loop
// transforms that can affect variables in memory
//
static bool
doHasBranch(AST *body, bool inCase)
{
if (!body) return false;
switch (body->kind) {
case AST_GOTO:
case AST_GOSUB:
case AST_LABEL:
case AST_QUITLOOP:
return true;
case AST_ENDCASE:
return !inCase; // "break" outside of case
case AST_CASE:
return doHasBranch(body->left, inCase) || doHasBranch(body->right, true);
default:
return doHasBranch(body->left, inCase) || doHasBranch(body->right, inCase);
}
}
static bool HasBranch(AST *body) { return doHasBranch(body, false); }
//
// check for "simple" loops using increments (like "repeat i from 0 to 9") these may be further
// optimized into "repeat 10" if we discover that the loop index is not
// used inside the body -- but beware that if the variable is used after
// the loop we have to make it have the correct value
//
static void
CheckSimpleIncrementLoop(AST *stmt)
{
AST *condtest;
AST *updateparent;
AST *update;
AST *body;
AST *initial;
AST *updateVar = NULL;
AST *updateInit = NULL;
AST *updateLimit = NULL;
AST *finalValue = NULL;
AST *newInitial = NULL;
AST *ifskip = NULL;
AST *thenelseskip = NULL;
Symbol *sym;
int updateTestOp = 0;
int32_t initVal;
ASTReportInfo saveinfo;
initial = stmt->left;
condtest = stmt->right;
updateparent = condtest->right;
condtest = condtest->left;
body = updateparent->right;
update = updateparent->left;
updateVar = NULL;
/* check initial assignment */
if (!initial || initial->kind != AST_ASSIGN)
return;
updateVar = initial->left;
if (!IsIdentifier(updateVar))
return;
sym = LookupAstSymbol(updateVar, NULL);
if (!sym) return;
switch (sym->kind) {
case SYM_PARAMETER:
case SYM_RESULT: