forked from totalspectrum/spin2cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutbc.c
More file actions
3566 lines (3235 loc) · 137 KB
/
outbc.c
File metadata and controls
3566 lines (3235 loc) · 137 KB
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
//
// Bytecode compiler for spin2cpp
//
// Copyright 2021-2025 Ada Gottensträter, Total Spectrum Software Inc.,
// and contributors
// see the file COPYING for conditions of redistribution
//
#include "outbc.h"
#include "bcbuffers.h"
#include "bcir.h"
#include <stdlib.h>
#include "becommon.h"
#include <inttypes.h>
const BCContext nullcontext = {.hiddenVariables = 0};
static int getFuncIDForKnownFunc(Module *M,Function *F); // forward declaration
static void BCAddStaticReference(Module *P, AST *obj);
static AST *BCAllocaExpr(AST *siz) {
if (gl_interp_kind != INTERP_KIND_P1ROM) {
ERROR(siz, "Interpreter does not support __builtin_alloca");
return siz;
}
AST *tmp = AstIdentifier("OUTB");
AST *dcurr = AstIdentifier("__interp_dcurr");
AST *assign = AstAssign(tmp, dcurr);
AST *expr = AstOperator('+', siz, AstInteger(3));
expr = AstOperator('&', expr, AstInteger(0xfffffffc));
expr = FoldIfConst(expr);
expr = AstOpAssign('+', dcurr, expr);
expr = NewAST(AST_SEQUENCE, assign, expr);
expr = NewAST(AST_SEQUENCE, expr, tmp);
return expr;
}
static int BCGetNumResultsByType(AST *funcType) {
int n = FuncNumResults(funcType);
return (n<=1) ? 1 : n;
}
static int BCGetNumResults(Function *F) {
int n = F->numresults;
return (n<=1) ? 1 : n;
}
static int BCLocalSize(Function *F) {
return FuncLocalSize(F); // F->numlocals*LONG_SIZE;
}
static int BCGetOBJSize(Module *P,AST *ast) {
if (ast->kind == AST_LISTHOLDER) ast = ast->right;
if (ast->kind == AST_DECLARE_VAR) {
Module *mod = GetClassPtr(ast->left);
if (!mod) {
ERROR(ast,"Can't get Module in BCGetOBJSize");
return 0;
}
return mod->varsize;
} else if (ast->kind == AST_OBJECT) {
// static reference has no size
return 0;
} else ERROR(ast,"Unhandled AST Kind %d in BCGetOBJSize\n",ast->kind);
return 0;
}
static int BCGetOBJOffset(Module *P,AST *ast) {
Symbol *sym = NULL;
if (ast->kind == AST_LISTHOLDER) ast = ast->right;
if (ast->kind == AST_DECLARE_VAR) {
// FIXME this seems kindof wrong?
AST *ident = ast->right->left;
if (ident->kind == AST_ARRAYDECL) ident = ident->left;
if (ident->kind == AST_ARRAYREF) ident = ident->left;
if (ident->kind != AST_IDENTIFIER) {
ERROR(ident,"Not an identifier");
return 0;
}
const char *name = ident->d.string;
if(name) sym = LookupSymbolInTable(&P->objsyms,name);
} else if (ast->kind == AST_IDENTIFIER) {
sym = LookupAstSymbol(ast,NULL);
} else if (ast->kind == AST_OBJECT) {
// Static reference to type, must have zero offset
return 0;
} else ERROR(ast,"Unhandled AST Kind %d in BCGetOBJOffset\n",ast->kind);
if (!sym) {
ERROR(ast,"Can't find symbol for an OBJ");
return -1;
}
//printf("In BCGetOBJOffset: ");
//printf("got symbol with name %s, kind %d, offset %d\n",sym->our_name,sym->kind,sym->offset);
return sym->offset;
}
// Get offset from PBASE to DAT start
int BCgetDAToffset(Module *P, bool absolute, AST *errloc, bool printErrors) {
if (gl_output != OUTPUT_BYTECODE) {
if (printErrors) ERROR(errloc,"BCgetDAToffset called, but not in bytecode mode");
return -1;
}
if (!P->bedata) {
if (printErrors) ERROR(errloc,"BCgetDAToffset: bedata for module %s uninitialized",P->classname);
return -1;
}
int pbase_offset = -1;
switch(gl_interp_kind) {
case INTERP_KIND_P1ROM: pbase_offset = 4*(ModData(P)->pub_cnt+ModData(P)->pri_cnt+ModData(P)->obj_cnt+1); break;
default:
if (printErrors) ERROR(errloc,"Unknown interpreter kind");
return -1;
}
if (absolute) {
int compiledAddress = ModData(P)->compiledAddress;
if (compiledAddress < 0) {
if (printErrors) ERROR(errloc,"Internal error, Taking address of uncompiled module");
return -1;
}
return pbase_offset + compiledAddress;
} else return pbase_offset;
}
struct bcheaderspans {
OutputSpan *pbase,*vbase,*dbase,*pcurr,*dcurr;
};
static struct bcheaderspans
OutputSpinBCHeader(ByteOutputBuffer *bob, Module *P)
{
unsigned int clkfreq;
unsigned int clkmodeval;
struct bcheaderspans spans = {0};
if (!GetClkFreq(P, &clkfreq, &clkmodeval)) {
// use defaults
clkfreq = 80000000;
clkmodeval = 0x6f;
}
BOB_PushLong(bob, clkfreq, "CLKFREQ"); // offset 0
BOB_PushByte(bob, clkmodeval, "CLKMODE"); // offset 4
BOB_PushByte(bob, 0,"Placeholder for checksum"); // checksum
spans.pbase = BOB_PushWord(bob, 0x0010,"PBASE"); // PBASE
spans.vbase = BOB_PushWord(bob, 0x7fe8,"VBASE"); // VBASE offset 8
spans.dbase = BOB_PushWord(bob, 0x7ff0,"DBASE"); // DBASE
spans.pcurr = BOB_PushWord(bob, 0x0018,"PCURR"); // PCURR offset 12
spans.dcurr = BOB_PushWord(bob, 0x7ff8,"DCURR"); // DCURR
return spans;
}
// get HW register for extra return values
static int
HWRegRetval(int n) {
if (gl_interp_kind == INTERP_KIND_P1ROM) {
static const int reg_addr[] = { 0x1f5, 0x1f7, 0x1f3 };
if (n < 1 || n > 3) {
ERROR(NULL, "Return value index %d is out of range", n);
return 0;
}
// return index for OUTB, DIRB, INB
// these are $1f5, $1f7, $1f3 respectively
return reg_addr[n-1] - 0x1e0;
}
ERROR(NULL, "Internal error, interpreter does not need return registers");
return 0;
}
static int
HWRegVBase() {
switch(gl_interp_kind) {
case INTERP_KIND_P1ROM: {
return 0x1EC - 0x1E0;
} break;
default:
ERROR(NULL,"Unknown interpreter kind");
return 0;
}
}
static int
HWReg2Index(HwReg *reg) {
switch(gl_interp_kind) {
case INTERP_KIND_P1ROM: {
int index = reg->addr - 0x1E0;
if (index < 0 || index >= 32) {
ERROR(NULL,"Register index %d for %s out of range",index,reg->name);
return 0;
}
return index;
} break;
default:
ERROR(NULL,"Unknown interpreter kind");
return 0;
}
}
// Get math op for AST operator token
// Returns 0 if it is not a simple binary operator
static enum MathOpKind
Optoken2MathOpKind(int token,bool *unaryOut,bool *needsAbsOut) {
bool unary = false;
bool needsAbs = false;
enum MathOpKind mok = MOK_MOD_UNDEFINED;
//printf("In Optoken2MathOpKind, optoken %03X\n",token);
switch (token) {
default: return mok;
case '^': mok = MOK_BITXOR; break;
case '|': mok = MOK_BITOR; break;
case '&': mok = MOK_BITAND; break;
case '+': mok = MOK_ADD; break;
case '-': mok = MOK_SUB; break;
case '*': mok = MOK_MULLOW; break;
case K_HIGHMULT: mok = MOK_MULHIGH; break;
case '/': mok = MOK_DIVIDE; break;
case K_MODULUS: mok = MOK_REMAINDER; break;
case K_LIMITMAX: mok = MOK_MAX; break;
case K_LIMITMIN: mok = MOK_MIN; break;
case '<': mok = MOK_CMP_B; needsAbs = true; break;
case '>': mok = MOK_CMP_A; needsAbs = true; break;
case K_LE: mok = MOK_CMP_BE; needsAbs = true; break;
case K_GE: mok = MOK_CMP_AE; needsAbs = true; break;
case K_EQ: mok = MOK_CMP_E; needsAbs = true; break;
case K_NE: mok = MOK_CMP_NE; needsAbs = true; break;
case K_SHL: mok = MOK_SHL; break;
case K_SHR: mok = MOK_SHR; break;
case K_SAR: mok = MOK_SAR; break;
case K_ROTL: mok = MOK_ROL; break;
case K_ROTR: mok = MOK_ROR; break;
case K_REV: mok = MOK_REV; break;
case K_LOGIC_AND: mok = MOK_LOGICAND; break;
case K_LOGIC_OR: mok = MOK_LOGICOR; break;
case K_BOOL_NOT: mok = MOK_BOOLNOT; unary=true; break;
case K_NEGATE: mok = MOK_NEG; unary = true; break;
case K_ABS: mok = MOK_ABS; unary = true; break;
case K_SQRT: mok = MOK_SQRT; unary = true; break;
case K_DECODE: mok = MOK_DECODE; unary = true; break;
case K_ENCODE: mok = MOK_ENCODE; unary = true; break;
case K_BIT_NOT: mok = MOK_BITNOT; unary = true; break;
}
if (unaryOut) *unaryOut = unary;
if (needsAbsOut) {
needsAbs = needsAbs && curfunc && LangBoolIsOne(curfunc->language);
*needsAbsOut = needsAbs;
}
return mok;
}
ByteOpIR BCBuildString(AST *expr, int prefixLen) {
ByteOpIR ir = {0};
ir.kind = BOK_FUNDATA_STRING;
Flexbuf fb;
flexbuf_init(&fb, 32);
StringBuildBuffer(&fb, expr, prefixLen);
ir.attr.stringLength = flexbuf_curlen(&fb);
ir.data.stringPtr = flexbuf_get(&fb);
return ir;
}
#ifdef NEED_ORIG_DEBUG
static void
printASTInfo(AST *node) {
if (node) {
printf("node is %d, ",node->kind);
if (node->left) printf("left is %d, ",node->left->kind);
else printf("left empty, ");
if (node->right) printf("right is %d\n",node->right->kind);
else printf("right empty\n");
} else printf("null node");
}
#else
#define printASTInfo(node) DumpAST(node)
#endif
static void BCCompileExpression(BCIRBuffer *irbuf,AST *node,BCContext context,bool asStatement); // forward decl;
static void BCCompileStatement(BCIRBuffer *irbuf,AST *node, BCContext context); // forward decl;
static ByteOpIR*
BCNewOrphanLabel(BCContext context) {
ByteOpIR *lbl = (ByteOpIR *)calloc(sizeof(ByteOpIR),1);
lbl->kind = BOK_LABEL;
lbl->attr.labelHiddenVars = context.hiddenVariables;
return lbl;
}
static ByteOpIR*
BCPushLabel(BCIRBuffer *irbuf,BCContext context) {
ByteOpIR lbl = {.kind = BOK_LABEL,.attr.labelHiddenVars = context.hiddenVariables};
return BIRB_PushCopy(irbuf,&lbl);
}
static ByteOpIR*
BCNewNamedLabelRef(BCContext context,const char *name) {
ByteOpIR *lbl = (ByteOpIR*)calloc(sizeof(ByteOpIR),1);
lbl->kind = BOK_NAMEDLABEL;
lbl->attr.labelHiddenVars = context.hiddenVariables;
lbl->data.stringPtr = name;
return lbl;
}
static void
BCCompileInteger(BCIRBuffer *irbuf,int32_t ival) {
ByteOpIR opc = {0};
opc.kind = BOK_CONSTANT;
opc.data.int32 = ival;
BIRB_PushCopy(irbuf,&opc);
}
static void
BCCompilePushModuleFuncRef(BCIRBuffer *irbuf,Module *M,int32_t funcid)
{
ByteOpIR opc = {0};
opc.kind = BOK_CONSTANT_FUNCREF;
opc.attr.funcval.modref = M;
opc.data.int32 = funcid;
BIRB_PushCopy(irbuf,&opc);
}
static void
BCCompilePushModuleDatRef(BCIRBuffer *irbuf,Module *M,int32_t offset)
{
ByteOpIR opc = {0};
opc.kind = BOK_CONSTANT_DATREF;
opc.attr.datval.modref = M;
opc.data.int32 = offset;
BIRB_PushCopy(irbuf,&opc);
}
static void
BCCompileDatModuleFuncRef(uint8_t *where,Module *M,int32_t funcid)
{
ERROR(NULL, "Unable to put data reloc");
}
static void BCCompilePopN(BCIRBuffer *irbuf,int popcount) {
if (popcount < 0) ERROR(NULL,"Internal Error: negative pop count");
else if (popcount > 0) {
BCCompileInteger(irbuf,popcount*4);
ByteOpIR popOp = {.kind = BOK_POP};
BIRB_PushCopy(irbuf,&popOp);
}
}
static void
BCCompileJumpEx(BCIRBuffer *irbuf, ByteOpIR *label, enum ByteOpKind kind, BCContext context, int stackoffset, bool logicallyTerminal) {
int stackdiff = context.hiddenVariables - label->attr.labelHiddenVars + stackoffset; // Will be zero if we got an AST_NAMEDLABEL
if (stackdiff > 0) {
// emit pop to get rid of hidden vars
if (kind != BOK_JUMP) ERROR(NULL,"Internal Error: Compiling conditional jump to label with less hidden vars than current context");
else BCCompilePopN(irbuf,stackdiff);
} else if (stackdiff < 0) {
ERROR(NULL,"Internal Error: Compiling jump to label with more hidden vars than current context");
}
ByteOpIR condjmp = {0};
condjmp.kind = kind;
condjmp.jumpTo = label;
condjmp.attr.condjump.logicallyTerminal = logicallyTerminal;
BIRB_PushCopy(irbuf,&condjmp);
}
static void
BCCompileJump(BCIRBuffer *irbuf, ByteOpIR *label, BCContext context) {
BCCompileJumpEx(irbuf,label,BOK_JUMP,context,0,false);
}
static void
BCCompileConditionalJump(BCIRBuffer *irbuf,AST *condition, bool ifNotZero, ByteOpIR *label, BCContext context) {
ByteOpIR condjmp = {0};
condjmp.jumpTo = label;
int stackdiff = context.hiddenVariables - label->attr.labelHiddenVars;
if (stackdiff) ERROR(condition,"Conditional jump to label with unequal hidden var count");
if (condition && condition->kind == AST_EXPECT) condition = condition->left;
if (!condition) {
ERROR(NULL,"Null condition!");
return;
} else if (IsConstExpr(condition)) {
int ival = EvalConstExpr(condition);
if (!!ival == !!ifNotZero) {
condjmp.kind = BOK_JUMP; // Unconditional jump
} else return; // Impossible jump
} else if (condition->kind == AST_OPERATOR) {
int optoken = condition->d.ival;
AST *left = condition->left, *right = condition->right;
bool extrasmall = curfunc->optimize_flags & OPT_EXTRASMALL;
OptimizeOperator(&optoken,&left,&right);
if (optoken == K_BOOL_NOT) {
// Inverted jump
BCCompileConditionalJump(irbuf,right,!ifNotZero,label,context);
return;
} else if ((optoken == K_EQ || optoken == K_NE )
&& ( IsConstZero(left) || IsConstZero(right))) {
// Slightly complex condition, I know
// optimize conditions like x == 0 and x<>0
BCCompileConditionalJump(irbuf,IsConstZero(left) ? right : left,!!ifNotZero != !!(optoken == K_EQ),label,context);
return;
} else if ((optoken == K_BOOL_AND || optoken == K_BOOL_OR) && extrasmall && !ExprHasSideEffects(right)) {
goto normal_condjump; // using an AND/OR operator is smaller but slower
} else if (optoken == K_BOOL_AND && !ifNotZero) {
// like in "IF L AND R"
BCCompileConditionalJump(irbuf,left,false,label,context);
BCCompileConditionalJump(irbuf,right,false,label,context);
return;
} else if (optoken == K_BOOL_AND && ifNotZero) {
// like in "IFNOT L AND R"
ByteOpIR *skipLabel = BCNewOrphanLabel(context);
BCCompileConditionalJump(irbuf,left,false,skipLabel,context);
BCCompileConditionalJump(irbuf,right,true,label,context);
BIRB_Push(irbuf,skipLabel);
return;
} else if (optoken == K_BOOL_OR && !ifNotZero) {
// like in "IF L OR R"
ByteOpIR *skipLabel = BCNewOrphanLabel(context);
BCCompileConditionalJump(irbuf,left,true,skipLabel,context);
BCCompileConditionalJump(irbuf,right,false,label,context);
BIRB_Push(irbuf,skipLabel);
return;
} else if (optoken == K_BOOL_OR && ifNotZero) {
// like in "IFNOT L OR R"
BCCompileConditionalJump(irbuf,left,true,label,context);
BCCompileConditionalJump(irbuf,right,true,label,context);
return;
}
goto normal_condjump;
} else {
normal_condjump:
// Just normal
BCCompileExpression(irbuf,condition,context,false);
condjmp.kind = ifNotZero ? BOK_JUMP_IF_NZ : BOK_JUMP_IF_Z;
}
BIRB_PushCopy(irbuf,&condjmp);
}
enum MemOpTargetKind {
MOT_UNDEFINED,MOT_MEM,MOT_REG,MOT_REGBIT,MOT_REGBITRANGE,MOT_REGIDX
};
static void
BCCompileMemOpExEx(BCIRBuffer *irbuf,AST *node,BCContext context, enum MemOpKind kind,
enum MathOpKind modifyMathKind, bool modifyReverseMath, bool pushModifyResult, ByteOpIR *jumpTo, bool repeatPopStep) {
enum MemOpTargetKind targetKind = MOT_UNDEFINED;
if (jumpTo != NULL) {
if (kind != MEMOP_MODIFY || modifyMathKind != MOK_MOD_REPEATSTEP) ERROR(node,"Trying to compile memop with jumpTo that is not a jumping kind");
int stackdiff = context.hiddenVariables - jumpTo->attr.labelHiddenVars;
if (stackdiff) ERROR(node,"Modify jump to label with unequal hidden var count");
}
ByteOpIR memOp = {0};
memOp.mathKind = modifyMathKind;
memOp.attr.memop.modifyReverseMath = modifyReverseMath;
memOp.attr.memop.pushModifyResult = pushModifyResult;
memOp.attr.memop.repeatPopStep=repeatPopStep;
memOp.jumpTo=jumpTo;
AST *type = ExprType(node);
AST *typeoverride = NULL;
Symbol *sym = NULL;
HwReg *hwreg;
AST *baseExpr = NULL;
AST *indexExpr = NULL;
AST *typeAfterIndex = NULL;
AST *bitExpr1 = NULL;
AST *bitExpr2 = NULL;
AST *ident;
int memberOffset = 0;
int pushMultiple = 0;
if (node->kind == AST_METHODREF) {
AST *selector = node->right;
Module *P = GetClassPtr(ExprType(node->left));
if (!P) {
// check for a namespace reference
sym = LookupMethodRef(node, NULL, NULL);
if (sym) {
ident = node->right;
goto found_symbol;
}
ERROR(node,"Unable to find object");
return;
}
if (!IsIdentifier(selector)) {
ERROR(node,"Expected identifier after `.'");
return;
}
const char *memberName = GetUserIdentifierName(selector);
node = node->left;
sym = LookupSymbolInTable(&P->objsyms, memberName);
if (!sym) {
ERROR(node,"Unable to find member %s in class %s", memberName, P->classname);
return;
}
switch(sym->kind) {
case SYM_VARIABLE:
memberOffset += sym->offset;
type = (AST *)sym->v.ptr;
if (!type) type = ast_type_long;
break;
case SYM_FUNCTION:
if (kind == MEMOP_ADDRESS) {
Function *F = (Function *)sym->v.ptr;
Module *M = F->module;
if (M->bedata == NULL) {
ERROR(node, "Cannot find address for function %s (no module info)", sym->user_name);
return;
}
int32_t addr = ModData(M)->compiledAddress;
int id = getFuncIDForKnownFunc(M, F);
if (addr < 0) {
//WARNING(node, "Need to patch address later");
BCCompilePushModuleFuncRef(irbuf, M, id);
} else {
uint32_t val = (id<<16) | addr;
BCCompileInteger(irbuf, val);
}
return;
}
ERROR(node, "Unhandled memory operation on function");
break;
case SYM_LABEL:
{
Module *M = (Module *)sym->module;
if (!M) {
ERROR(node,"Method reference for unknown module");
return;
}
if (M->bedata == NULL) {
ERROR(node, "Cannot find address for field %s (no module info)", sym->user_name);
return;
}
Label *lab = (Label *)sym->v.ptr;
BCCompilePushModuleDatRef(irbuf, M, lab->hubval);
switch (kind) {
case MEMOP_ADDRESS: break; /* nothing more to do */
case MEMOP_READ:
case MEMOP_WRITE:
break;
type = lab->type;
typeoverride = BaseType(type);
targetKind = MOT_MEM;
memOp.attr.memop.base = MEMOP_BASE_POP;
baseExpr = NULL;
memberOffset = 0;
goto nosymbol_memref;
default:
ERROR(node, "Unsupported operation on object DAT field");
break;
}
return;
}
default:
ERROR(node,"Wrong kind of symbol (%d) in method reference", sym->kind);
break;
}
}
if (node->kind == AST_ARRAYREF) {
ident = node->left;
indexExpr = node->right;
typeAfterIndex = BaseType(ExprType(ident));
} else ident = node;
try_ident_again:
if (IsIdentifier(ident) || ident->kind == AST_SYMBOL) sym = LookupAstSymbol(ident,NULL);
else if (ident->kind == AST_RESULT) {
if (curfunc && curfunc->resultexpr && IsIdentifier(curfunc->resultexpr)) {
sym = LookupAstSymbol(curfunc->resultexpr, NULL);
} else {
sym = LookupSymbol("result");
if (!sym) {
WARNING(node, "unable to find result variable");
sym = (Symbol *)calloc(sizeof(*sym), 1);
sym->kind = SYM_RESULT;
}
}
} else if (ident->kind == AST_MEMREF) {
if (!typeoverride && ident->right->kind == AST_ADDROF &&
ident->right->left && ident->right->left->kind == AST_ARRAYREF && IsConstZero(ident->right->left->right)) {
// Handle weird AST representation of "var.byte[x]""
DEBUG(node,"handling size override kind 1...");
typeoverride = ident->left;
ident = ident->right->left->left;
goto try_ident_again;
} else if (!typeoverride && ident->right->kind == AST_ADDROF && IsIdentifier(ident->right->left)) {
DEBUG(node,"handling size override kind 2...");
typeoverride = ident->left;
ident = ident->right->left;
goto try_ident_again;
} else {
// normal raw memory access
memOp.attr.memop.base = MEMOP_BASE_POP;
targetKind = MOT_MEM;
if (type) typeoverride = type;
type = ident->left;
baseExpr = ident->right;
if (memberOffset) {
baseExpr = AstOperator('+', baseExpr, AstInteger(memberOffset));
memberOffset = 0;
}
goto nosymbol_memref;
}
} else if (ident->kind == AST_HWREG) {
targetKind = MOT_REG;
hwreg = (HwReg *)ident->d.ptr;
memOp.data.int32 = HWReg2Index(hwreg);
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
goto after_typeinfer;
} else if (ident->kind == AST_SPRREF) {
targetKind = MOT_REGIDX;
baseExpr = ident->left; // Perhaps a bit odd to use baseExpr instead of indexExpr
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
// AST for SPR[n] somewhat rightfully is (n|496).
// The Spin1 interpreter does this internally
if (gl_interp_kind == INTERP_KIND_P1ROM) {
if (baseExpr->kind == AST_OPERATOR && baseExpr->d.ival == '|' && IsConstEqual(baseExpr->right,496)) baseExpr = baseExpr->left;
}
goto after_typeinfer;
} else if (ident->kind == AST_RANGEREF) {
ASSERT_AST_KIND(ident->left,AST_HWREG,return;);
ASSERT_AST_KIND(ident->right,AST_RANGE,return;);
hwreg = (HwReg *)ident->left->d.ptr;
memOp.data.int32 = HWReg2Index(hwreg);
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
bitExpr1 = ident->right->left;
bitExpr2 = ident->right->right;
targetKind = bitExpr2 ? MOT_REGBITRANGE : MOT_REGBIT;
goto after_typeinfer;
}
found_symbol:
if (!sym) {
if (node->kind == AST_ARRAYREF && indexExpr && !baseExpr) {
memOp.attr.memop.base = MEMOP_BASE_POP;
targetKind = MOT_MEM;
baseExpr = ident;
goto nosymbol_memref;
}
ERROR(ident,"Can't get symbol");
return;
} else {
//printf("got symbol with name %s and kind %d\n",sym->our_name,sym->kind);
if (!type) type = ExprType(ident);
switch (sym->kind) {
case SYM_LABEL: {
memOp.attr.memop.base = MEMOP_BASE_PBASE;
targetKind = MOT_MEM;
Label *lab = (Label *)sym->v.ptr;
uint32_t labelval = lab->hubval;
// Add header offset
if (sym->module == current || sym->module == 0) {
labelval += BCgetDAToffset(current,false,node,true);
memOp.data.int32 = labelval;
} else {
WARNING(ident, "bytecode may not always support cross-module label references");
labelval += BCgetDAToffset((Module *)sym->module, true,node,true);
memOp.attr.memop.base = MEMOP_BASE_POP;
if (baseExpr) ERROR(node,"baseExpr already set?!?!");
else baseExpr = AstInteger(labelval);
}
} break;
case SYM_VARIABLE: {
if (sym->flags & SYMF_GLOBAL) {
DEBUG(node,"Got special symbol %s with offset %d",sym->our_name,sym->offset);
memOp.attr.memop.base = MEMOP_BASE_POP;
targetKind = MOT_MEM;
if (baseExpr) ERROR(node,"baseExpr already set?!?!");
else baseExpr = AstInteger(sym->offset);
} else {
memOp.attr.memop.base = MEMOP_BASE_VBASE;
targetKind = MOT_MEM;
memOp.data.int32 = sym->offset;
}
} break;
case SYM_CLOSURE:{
BCAddStaticReference(current, (AST *)sym->v.ptr);
memOp.attr.memop.base = MEMOP_BASE_VBASE;
targetKind = MOT_MEM;
memOp.data.int32 = 0;
} break;
case SYM_LOCALVAR: {
memOp.attr.memop.base = (curfunc->closure) ? MEMOP_BASE_VBASE : MEMOP_BASE_DBASE;
targetKind = MOT_MEM;
memOp.data.int32 = sym->offset;
} break;
case SYM_PARAMETER: {
memOp.attr.memop.base = (curfunc->closure) ? MEMOP_BASE_VBASE : MEMOP_BASE_DBASE;
targetKind = MOT_MEM;
memOp.data.int32 = sym->offset;
} break;
case SYM_TEMPVAR: {
memOp.attr.memop.base = MEMOP_BASE_DBASE;
targetKind = MOT_MEM;
memOp.data.int32 = sym->offset;
} break;
case SYM_RESERVED: {
if (!strcmp(sym->our_name,"result")) {
goto do_result;
} else {
ERROR(node,"Unhandled reserved word %s in assignment",sym->our_name);
}
}
do_result:
case SYM_RESULT: {
memOp.attr.memop.base = MEMOP_BASE_DBASE;
targetKind = MOT_MEM;
memOp.data.int32 = sym->offset;
} break;
case SYM_HWREG: {
targetKind = MOT_REG;
hwreg = (HwReg *)sym->v.ptr;
memOp.data.int32 = HWReg2Index(hwreg);
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
goto after_typeinfer;
} break;
case SYM_BUILTIN: {
if (!strcmp(sym->our_name,"_cogid")) {
if (kind != MEMOP_READ) WARNING(node,"Writing COGID register, bad idea");
Symbol *cogid_sym = LookupSymbolInTable(&spinCommonReservedWords,"__interp_cogid");
if (!cogid_sym || cogid_sym->kind != SYM_HWREG) {
ERROR(node,"Internal Error: Failed to get cogid register");
return;
}
targetKind = MOT_REG;
hwreg = (HwReg *)cogid_sym->v.ptr;
memOp.data.int32 = HWReg2Index(hwreg);
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
goto after_typeinfer;
} else {
ERROR(node,"Unhandled symbol identifier %s in memop",sym->our_name);
return;
}
} break;
case SYM_LOCALLABEL: {
if (kind == MEMOP_ADDRESS) {
if (indexExpr || baseExpr) {
ERROR(node,"Unable to offset label");
}
ByteOpIR *labelRef = BCNewNamedLabelRef(context,sym->our_name);
ByteOpIR pushOp = {.kind = BOK_FUNDATA_PUSHADDRESS, .jumpTo = labelRef, .attr.pushaddress.addPbase = true};
BIRB_PushCopy(irbuf, &pushOp);
return;
}
ERROR(node,"Unhandled memory operation on local label");
} break;
case SYM_FUNCTION: {
if (kind == MEMOP_ADDRESS) {
Function *F = (Function *)sym->v.ptr;
Module *M = F->module;
if (M->bedata == NULL) {
ERROR(node, "Cannot find address for function (no module info)");
return;
}
int32_t addr = ModData(M)->compiledAddress;
int id = getFuncIDForKnownFunc(M, F);
if (addr < 0) {
//WARNING(node, "Need to patch address later");
BCCompilePushModuleFuncRef(irbuf, M, id);
} else {
uint32_t val = (id<<16) | (addr);
BCCompileInteger(irbuf, val);
}
return;
}
ERROR(node, "Unhandled memory operation on function");
} break;
case SYM_ALIAS: {
AST *expr = (AST *)sym->v.ptr;
AST *typ = NULL;
if (expr->kind == AST_CAST) {
typ = expr->left;
expr = expr->right;
}
if (typ) typeoverride = type;
if (expr && expr->kind == AST_ARRAYREF) {
expr = expr->left;
}
if (IsIdentifier(expr) || expr->kind == AST_MEMREF) {
ident = expr;
goto try_ident_again;
}
ERROR(ident,"DECLARE ALIAS %s not handled yet in bytecode", sym->user_name);
return;
}
default:
ERROR(ident,"Unhandled Symbol type %d in memop",sym->kind);
return;
}
}
nosymbol_memref:
if (typeoverride) type = typeoverride;
if (IsPointerType(type))
type = ast_type_long;
else type = RemoveTypeModifiers(BaseType(type));
if (!type) type = ast_type_long;
switch (type->kind) {
case AST_GENERICTYPE:
case AST_UNSIGNEDTYPE: {
int size = type->left->d.ival;
switch (size) {
case 1: memOp.attr.memop.memSize = MEMOP_SIZE_BYTE; break;
case 2: memOp.attr.memop.memSize = MEMOP_SIZE_WORD; break;
// Technically treated as signed, but all the unsigned operators are seperate, anyways, so I guess it's fine?
case 4: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; break;
case 8: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; pushMultiple = 2; break;
default: ERROR(node,"Can't handle unsigned type with size %d",size); break;
}
} break;
case AST_INTTYPE:
case AST_SIGNED_BOOLTYPE:
case AST_UNS_BOOLTYPE: {
int size = type->left->d.ival;
switch (size) {
// sign-extend is generated for these
case 1: if (kind == MEMOP_WRITE || kind == MEMOP_READ) memOp.attr.memop.memSize = MEMOP_SIZE_BYTE; else goto signed_todo; break;
case 2: if (kind == MEMOP_WRITE || kind == MEMOP_READ) memOp.attr.memop.memSize = MEMOP_SIZE_WORD; else goto signed_todo; break;
case 4: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; break;
case 8: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; pushMultiple = 2; break;
signed_todo:
default: ERROR(node,"Can't handle signed type with size %d",size); break;
}
} break;
case AST_FLOATTYPE: {
int size = type->left->d.ival;
switch (size) {
case 4: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; break;
case 8: memOp.attr.memop.memSize = MEMOP_SIZE_LONG; pushMultiple = 2; break;
default: ERROR(node,"Can't handle float type with size %d",size); break;
}
} break;
case AST_PTRTYPE:
case AST_FUNCTYPE: {
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
} break;
case AST_OBJECT: {
int size = TypeSize(type);
if (size == 4) {
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
} else if (kind == MEMOP_ADDRESS) {
// we're creating a pointer, need to offset appropriately
if (indexExpr) {
indexExpr = AstOperator('*', indexExpr, AstInteger(size / LONG_SIZE));
}
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
} else {
// need to push multiple values here
memOp.attr.memop.memSize = MEMOP_SIZE_LONG;
pushMultiple = size / 4;
}
} break;
default:
ERROR(node,"Unhandled type kind %d",type->kind);
}
after_typeinfer:
memOp.attr.memop.modSize = memOp.attr.memop.memSize; // Let's just assume these are the same
if (indexExpr && TypeSize(typeAfterIndex) != TypeSize(type)) {
indexExpr = AstOperator('*', indexExpr, AstInteger(TypeSize(typeAfterIndex) / TypeSize(type)));
type = typeAfterIndex;
}
switch(targetKind) {
case MOT_MEM: {
if (memberOffset) {
memOp.data.int32 += memberOffset;
if (memOp.attr.memop.base == MEMOP_BASE_POP) ERROR(node,"Internal Error: memberOffset on POP base");
}
// transform long[a+b] to long[a][b/4]
if (baseExpr && (!indexExpr || IsConstZero(indexExpr)) && baseExpr->kind == AST_OPERATOR && baseExpr->d.ival == '+') {
if (memOp.attr.memop.memSize == MEMOP_SIZE_BYTE) {
// Can always do this transform for bytes
indexExpr = baseExpr->right;
baseExpr = baseExpr->left;
} else {
int typeShift = memOp.attr.memop.memSize == MEMOP_SIZE_WORD ? 1 : 2;
int typeMask = memOp.attr.memop.memSize == MEMOP_SIZE_WORD ? 1 : 3;
if (IsConstExpr(baseExpr->right) && (EvalConstExpr(baseExpr->right) & typeMask) == 0) {
indexExpr = AstInteger(EvalConstExpr(baseExpr->right) >> typeShift);
baseExpr = baseExpr->left;
} else if (IsConstExpr(baseExpr->left) && (EvalConstExpr(baseExpr->left) & typeMask) == 0) {
indexExpr = AstInteger(EvalConstExpr(baseExpr->left) >> typeShift);
baseExpr = baseExpr->right;
}
}
}
//if (!!baseExpr != !!(memOp.attr.memop.base == MEMOP_BASE_POP)) ERROR(node,"Internal Error: baseExpr condition mismatch");
if (bitExpr1) ERROR(node,"Bit1 expression on memory op!");
if (bitExpr2) ERROR(node,"Bit2 expression on memory op!");
if (baseExpr) {
if (baseExpr->kind == AST_METHODREF) {
baseExpr = NewAST(AST_ADDROF, baseExpr, NULL);
}
BCCompileExpression(irbuf,baseExpr,context,false);
}
// handle index
if (indexExpr) {
bool indexConst = IsConstExpr(indexExpr);
int constIndexVal;
if (indexConst) constIndexVal = EvalConstExpr(indexExpr);
if (baseExpr && indexConst && constIndexVal == 0) {
// In this case, do nothing
} else if (!baseExpr && indexConst) {
// Just add index onto base
if (memOp.attr.memop.memSize == MEMOP_SIZE_BYTE) memOp.data.int32 += constIndexVal;
else if (memOp.attr.memop.memSize == MEMOP_SIZE_WORD) memOp.data.int32 += constIndexVal << 1;
else if (memOp.attr.memop.memSize == MEMOP_SIZE_LONG) memOp.data.int32 += constIndexVal << 2;
} else if (baseExpr && pushMultiple) {
ERROR(indexExpr, "Cannot handle indices with large values");
} else {
// dynamic index
memOp.attr.memop.popIndex = true;
BCCompileExpression(irbuf,indexExpr,context,false);
}
}
switch (kind) {
case MEMOP_READ: memOp.kind = BOK_MEM_READ; break;
case MEMOP_WRITE: memOp.kind = BOK_MEM_WRITE; break;
case MEMOP_MODIFY: memOp.kind = BOK_MEM_MODIFY; break;
case MEMOP_ADDRESS: memOp.kind = BOK_MEM_ADDRESS; break;
default: ERROR(node,"Unknown memop kind %d",kind); break;
}
} break;
case MOT_REG: {
if (baseExpr) ERROR(node,"Base expression on plain register op!");
if (indexExpr) ERROR(node,"Index expression on plain register op!");
if (bitExpr1) ERROR(node,"Bit1 expression on plain register op!");
if (bitExpr2) ERROR(node,"Bit2 expression on plain register op!");
if (memOp.attr.memop.memSize != MEMOP_SIZE_LONG) ERROR(node,"Non-long size on plain register op!");
switch (kind) {
case MEMOP_READ: memOp.kind = BOK_REG_READ; break;
case MEMOP_WRITE: memOp.kind = BOK_REG_WRITE; break;
case MEMOP_MODIFY: memOp.kind = BOK_REG_MODIFY; break;
case MEMOP_ADDRESS: ERROR(node,"Trying to get address of register"); break;
default: ERROR(node,"Unknown memop kind %d",kind); break;
}
} break;
case MOT_REGBIT: {
if (baseExpr) ERROR(node,"Base expression on register bit op!");
if (indexExpr) ERROR(node,"Index expression on register bit op!");
if (bitExpr2) ERROR(node,"Bit2 expression on register bit op!");
if (memOp.attr.memop.memSize != MEMOP_SIZE_LONG) ERROR(node,"Non-long size on register bit op!");
memOp.attr.memop.modSize = MEMOP_SIZE_BIT; // I guess?
BCCompileExpression(irbuf,bitExpr1,context,false);
switch (kind) {
case MEMOP_READ: memOp.kind = BOK_REGBIT_READ; break;
case MEMOP_WRITE: memOp.kind = BOK_REGBIT_WRITE; break;
case MEMOP_MODIFY: memOp.kind = BOK_REGBIT_MODIFY; break;
case MEMOP_ADDRESS: ERROR(node,"Trying to get address of register"); break;
default: ERROR(node,"Unknown memop kind %d",kind); break;
}
} break;
case MOT_REGBITRANGE: {
if (baseExpr) ERROR(node,"Base expression on register range op!");
if (indexExpr) ERROR(node,"Index expression on register range op!");
if (memOp.attr.memop.memSize != MEMOP_SIZE_LONG) ERROR(node,"Non-long size on register range op!");
memOp.attr.memop.modSize = MEMOP_SIZE_BIT; // I guess?
BCCompileExpression(irbuf,bitExpr1,context,false);
BCCompileExpression(irbuf,bitExpr2,context,false);
switch (kind) {
case MEMOP_READ: memOp.kind = BOK_REGBITRANGE_READ; break;
case MEMOP_WRITE: memOp.kind = BOK_REGBITRANGE_WRITE; break;