-
Notifications
You must be signed in to change notification settings - Fork 1
/
mc.c
4259 lines (4042 loc) · 153 KB
/
mc.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
/*
* mc is capable of compiling a (subset of) C source files into GNU/Linux
* executables or running via just-in-time compilation on 32-bit ARM
* processor-based platforms. There is no preprocessor.
*
* The following options are supported:
* -s : Print source and generated intermediate representation (IR).
* -o : Create executable file and terminate normally.
*
* If -o and -s are omitted, the compiled code is executed immediately (if
* there were no compile errors) with the command line arguments passed
* after the source file parameter.
*
* All modifications as of Feb 19 2022 are by HPCguy.
* See AMaCC project repository for baseline code prior to that date.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
#define SMALL_TBL_SZ 256
#ifdef __MC__
float strtof(char *s, char **e);
#endif
#ifdef SQUINT_SO
void squint_opt(int *begin, int *end);
#endif
char *freep, *p, *lp; // current position in source code
char *freedata, *data, *_data; // data/bss pointer
int *e, *le, *text; // current position in emitted IR code
int *lastLEV; // needed to close out functions
char *idn, *idp; // decouples ids from program source code
char *idl, *idln; // storage for func scope label names
int *cas; // case statement patch-up pointer
int *def; // default statement patch-up pointer
int *brks; // break statement patch-up pointer
int *cnts; // continue statement patch-up pointer
int *rets; // single function exit model
int swtc; // !0 -> in a switch-stmt context
int brkc; // !0 -> in a break-stmt context
int cntc; // !0 -> in a continue-stmt context
int *tsize; // array (indexed by type) of type sizes
int tnew; // next available type
int tk; // current token
int sbegin; // statement begin state.
int deadzone; // don't do inlining during dead code elimination
int attq; // attribute query such as dereference or sizeof
int parg; // attq -- assume passing deref var to func means it is set
int inDecl; // declaration statement context
int pinlndef; // parsing an inline-only function
int tokloc; // 0 = global scope, 1 = function scope
// 2 = function scope, declaration in progress
union conv {
int i;
float f;
} tkv; // current token value
int ty; // current expression type
// bit 0:1 - tensor rank, eg a[4][4][4]
// 0=scalar, 1=1d, 2=2d, 3=3d
// 1d etype -- bit 0:30)
// 2d etype -- bit 0:15,16:30 [32768,65536]
// 3d etype -- bit 0:10,11:20,21:30 [1024,1024,2048]
// bit 2:9 - type
// bit 10:11 - ptr level
int compound; // manage precedence of compound assign expressions
int rtf, rtt; // return flag and return type for current function
int ld, maxld; // function frame ptr -- argument index then local var
int loc; // separating point for arg vs local variables
int line; // current line number
int src; // print source and assembly flag
int signed_char; // use `signed char` for `char`
int single_exit; // one function exit point at end
int elf; // print ELF format
int peephole; // helper for peephole optimization
int *n; // current position in emitted abstract syntax tree
// With an AST, the compiler is not limited to generate
// code on the fly with parsing.
// This capability allows function parameter code to be
// emitted and pushed on the stack in the proper
// right-to-left order.
int lds[32], ldn; // used to track scope level for duplicate local var defs
int pplev, pplevt; // preprocessor conditional level
int ppactive;
int oline, osize; // for optimization suggestion
char *oname;
int btrue = 0; // comparison "true" = ( btrue ? -1 : 1)
int ma = 1; // prevent "modify argument" in functions
// max recursive inline levels
#define INL_LEV 32
// max function arguments
#define MAX_FARG 52
// keywords and global ids grow upward in memory
// Function parameters and (nested) local id scopes grow downward
// When a local block scope terminates, it relinquishes stack space
// Carefully creating declarations with block scopes improves optimization
#define MAX_LABEL 16384
struct ident_s {
int tk; // type-id or keyword
int hash;
char *name; // name of this identifier
char *tsub; // != 0 substitutes var usage with tsub text, or func
int class; // FUNC, GLO (global var), LOC (local var), Syscall
int type; // data type such as char and int
int val; // usually, contains stack or memory address of var
int etype; // extended type info for tensors
int ftype[2]; // extended type info for funcs
int flags; // funcID: 1 = fwd decl func, 2 = func not dead code
// varID: 4 = decl initalizer, 8 = assign
// 16 = alias initializer, 32 = var was read
// retlabel IDs: holds depth of recursive inlining
int *chain; // used for forward declaration IR inst ptr
} *id, // currently parsed identifier
*sym, // symbol table (simple list of identifiers)
*symk, // tail for keywords
*symgt, // tail for global symbols
*syms, // struct/union member parsing
*symlh, // head for local symbols
*symlt, // tail for local symbols
*labt, // tail ptr for label Ids
*retlabel[INL_LEV], // label for end of inline function
lab[MAX_LABEL];
int mns; // member namespace -- 1 = member lookup in progress
int masgn; // This variable is used to skip struct substitutions
int irl; // inline label counter
char *pts[INL_LEV]; // != 0 means text substitutuion in progress
int tsline[INL_LEV]; // what line is being parsed
int numpts; // number of text substitution levels in flight
int numfspec; // number of inlinable functions
int *fspec[256]; // inline function specifications
char linespec[96]; // a string used to capture inlining context
// IR information for local vars and parameters
#define MAX_IR 256
struct ir_s {
int loc;
char *name;
} ir_var[MAX_IR];
int ir_count;
// (library) external functions
struct ef_s {
char *name;
int addr;
} **ef_cache;
int ef_count;
struct member_s {
struct member_s *next;
int hash;
char *id;
int offset;
int type;
int etype;
} **members; // array (indexed by type) of struct member lists
// tokens and classes (operators last and in precedence order)
// ( >= 128 so not to collide with ASCII-valued tokens)
enum {
Func=128, Syscall, Main, ClearCache, Fneg, Fabs, Sqrt,
Glo, Par, Loc, Keyword, Id, Load,
Enter, Num, NumF, TypeId,
Typedef, Enum, Char, Int, Float, Struct, Union,
Sizeof, Return, Goto,
Break, Continue, If, DoWhile, While, For,
Switch, Case, Default, Else, Inln, Label,
Alias, // operator :=, text substitution for simple memory address
Assign, // operator =, keep Assign as highest priority operator
OrAssign, XorAssign, AndAssign, ShlAssign, ShrAssign, // |=, ^=, &=, <<=, >>=
AddAssign, SubAssign, MulAssign, DivAssign, ModAssign, // +=, -=, *=, /=, %=
Cond, // operator: ?
Lor, Lan, Or, Xor, And, // operator: ||, &&, |, ^, &
Eq, Ne, Ge, Lt, Gt, Le, // operator: ==, !=, >=, <, >, <=
Shl, Shr, Add, Sub, Mul, Div, Mod, // operator: <<, >>, +, -, *, /, %
AddF, SubF, MulF, DivF, // float type operators (hidden)
EqF, NeF, GeF, LtF, GtF, LeF,
CastF, Inc, Dec, Dot, Arrow, Bracket, // operator: ++, --, ., ->, [
Phf // inform peephole optimizer a function call is beginning
};
// opcodes
/* The instruction set is designed for building intermediate representation.
* Expression 10 + 20 will be translated into the following instructions:
* i = 0;
* text[i++] = IMM;
* text[i++] = 10;
* text[i++] = PSH;
* text[i++] = IMM;
* text[i++] = 20;
* text[i++] = ADD;
* text[i++] = PSH;
* text[i++] = EXIT;
* pc = text;
*/
enum {
LEA , /* 0 */
/* LEA addressed the problem how to fetch arguments inside sub-function.
* Let's check out what a calling frame looks like before learning how
* to fetch arguments (Note that arguments are pushed in its calling
* order):
*
* sub_function(arg1, arg2, arg3);
*
* | .... | high address
* +---------------+
* | arg: 1 | new_bp + 4
* +---------------+
* | arg: 2 | new_bp + 3
* +---------------+
* | arg: 3 | new_bp + 2
* +---------------+
* |return address | new_bp + 1
* +---------------+
* | old BP | <- new BP
* +---------------+
* | local var 1 | new_bp - 1
* +---------------+
* | local var 2 | new_bp - 2
* +---------------+
* | .... | low address
*
* If we need to refer to arg1, we need to fetch new_bp + 4, which can not
* be achieved by restricted ADD instruction. Thus another special
* instrcution is introduced to do this: LEA <offset>.
* Together with JSR, ENT, ADJ, LEV, and LEA instruction, we are able to
* make function calls.
*/
IMM , /* 1 */
/* IMM <num> to put immediate <num> into R0 */
IMMF , /* 2 */
/* IMM <num> to put immediate <num> into S0 */
JMP , /* 3 */
/* JMP <addr> will unconditionally set the value PC register to <addr> */
JSR , /* 4 */
/* Jump to address, setting link register for return address */
BZ , /* 5 : conditional jump if R0 is zero (jump-if-zero) */
BNZ , /* 6 : conditional jump if R0 is not zero */
ENT , /* 7 */
/* ENT <size> is called when we are about to enter the function call to
* "make a new calling frame". It will store the current PC value onto
* the stack, and save some space(<size> bytes) to store the local
* variables for function.
*/
ADJ , /* 8 */
/* ADJ <size> is to adjust the stack, to "remove arguments from frame"
* The following pseudocode illustrates how ADJ works:
* if (op == ADJ) { sp += *pc++; } // add esp, <size>
*/
LEV , /* 9 */
/* LEV fetches bookkeeping info to resume previous execution.
* There is no POP instruction in our design, and the following pseudocode
* illustrates how LEV works:
* if (op == LEV) { sp = bp; bp = (int *) *sp++;
* pc = (int *) *sp++; } // restore call frame and PC
*/
PSH , /* 10 */
/* PSH pushes the value in R0 onto the stack */
PSHF , /* 11 */
/* PSH pushes the value in R0 onto the stack */
LC , /* 12 */
/* LC loads a character into R0 from a given memory
* address which is stored in R0 before execution.
*/
LI , /* 13 */
/* LI loads an integer into R0 from a given memory
* address which is stored in R0 before execution.
*/
LF , /* 14 */
/* LI loads a float into S0 from a given memory
* address which is stored in R0 before execution.
*/
SC , /* 15 */
/* SC stores the character in R0 into the memory whose
* address is stored on the top of the stack.
*/
SI , /* 16 */
/* SI stores the integer in R0 into the memory whose
* address is stored on the top of the stack.
*/
SF , /* 17 */
/* SI stores the float in S0 into the memory whose
* address is stored on the top of the stack.
*/
OR , /* 18 */ XOR , /* 19 */ AND , /* 20 */
EQ , /* 21 */ NE , /* 22 */
GE , /* 23 */ LT , /* 24 */ GT , /* 25 */ LE , /* 26 */
SHL , /* 27 */ SHR , /* 28 */
ADD , /* 29 */ SUB , /* 30 */ MUL , /* 31 */ DIV , /* 32 */ MOD, /* 33 */
ADDF, /* 34 */ SUBF, /* 35 */ MULF, /* 36 */ DIVF, /* 37 */
FTOI, /* 38 */ ITOF, /* 39 */ EQF , /* 40 */ NEF , /* 41 */
GEF , /* 42 */ LTF , /* 43 */ GTF , /* 44 */ LEF , /* 45 */
/* arithmetic instructions
* Each operator has two arguments: the first one is stored on the top
* of the stack while the second is stored in R0.
* After the calculation is done, the argument on the stack will be poped
* off and the result will be stored in R0.
*/
FNEG, /* 46 float fnegf(float); returns -arg */
FABS, /* 47 float fabsf(float); */
SQRT, /* 48 float sqrtf(float); */
SYSC, /* 49 system call */
CLCA, /* 50 clear cache, used by JIT compilation */
VENT, /* 51 Needed fo Varargs ABI, which requires 8-byte stack align */
VLEV, /* 52 */
PHD, /* 53 PeepHole Disable next assembly instruction in optimizer */
PHF, /* 54 Inform peephole optimizer a function call is beginning */
PHR0, /* 55 Inform PeepHole optimizer that R0 holds a return value */
INVALID
};
// types -- 4 scalar types, 1020 aggregate types, 4 tensor ranks, 8 ptr levels
// bits 0-1 = tensor rank, 2-11 = type id, 12-14 = ptr level
// 4 type ids are scalars: 0 = char/void, 1 = int, 2 = float, 3 = reserved
enum { CHAR = 0, INT = 4, FLOAT = 8, ATOM_TYPE = 11,
PTR = 0x1000, PTR2 = 0x2000 };
// ELF generation
char **plt_func_addr;
char *freebuf;
char *append_strtab(char **strtab, char *str)
{
char *s;
for (s = str; *s && (*s != ' '); ++s) ; /* ignore trailing space */
int nbytes = s - str + 1;
char *res = *strtab;
memcpy(res, str, nbytes);
res[s - str] = 0; // null terminator
*strtab = res + nbytes;
return res;
}
// need this complex function to trace inlining errors
char *linestr()
{
char *out = linespec;
int i, ntmp, tidx=0;
char stmp[10];
tsline[numpts] = line;
if (numpts) { strcpy(linespec, "inline:"); out += 7; }
for (i=0; i<=numpts; ++i) {
ntmp = tsline[i];
while (ntmp>0) { stmp[tidx++] = '0' + ntmp%10; ntmp /= 10; }
while (tidx > 0) *out++ = stmp[--tidx];
*out++ = ':';
}
*--out = 0;
if (out == linespec) { *out++ = '0'; *out = 0; }
return linespec;
}
void fatal(char *msg)
{
if (!numpts) printf("%d: %.*s\n", line, p - lp, lp);
printf("%s: %s\n", linestr(), msg); exit(-1);
}
void ef_add(char *name, int addr) // add external function
{
ef_cache[ef_count] = (struct ef_s *) malloc(sizeof(struct ef_s)) ;
ef_cache[ef_count]->name = (char *) malloc(strlen(name)+1);
strcpy(ef_cache[ef_count]->name, name);
ef_cache[ef_count]->addr = addr;
++ef_count;
}
int ef_getaddr(int idx) // get address external function
{
return (elf ? (int) plt_func_addr[idx] : ef_cache[idx]->addr);
}
int ef_getidx(char *name) // get cache index of external function
{
int i;
for (i = 0; i < ef_count; ++i)
if (!strcmp(ef_cache[i]->name, name))
break;
if (i == ef_count) { // add new external lib func to cache
int dladdr;
if ((dladdr = (int) dlsym(0, name))) {
ef_add(name, dladdr);
} else {
void *divmod_handle = (void *) dlopen("libgcc_s.so.1", 1);
if (!divmod_handle) fatal("failed to open libgcc_s.so.1");
dladdr = (int) dlsym(divmod_handle, name);
if (!dladdr) // fatal("bad function call");
{
void *libm_handle = (void *) dlopen("libm.so.6", 1);
if (!libm_handle) fatal("failed to open libm.so.6");
dladdr = (int) dlsym(libm_handle, name);
if (!dladdr) fatal("bad function call");
}
ef_add(name, dladdr);
}
}
return i;
}
inline void expr(int lev);
/* parse next token
* 1. store data into id and then set the id to current lexcial form
* 2. set tk to appropriate type
*/
void eol2semi(char *ss) // preprocessor support
{
char *s;
s = ss;
while(*s && *s != '\n') ++s;
if (*s) *s = ';';
}
void next()
{
char *pp;
int t;
/* using loop to ignore whitespace characters, but characters that
* cannot be recognized by the lexical analyzer are considered blank
* characters, such as '@'.
*/
text_sub:
while ((tk = *p)) {
++p;
if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') ||
(tk == '_') || (tk == '$')) {
pp = p - 1;
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') || (*p == '_') || (*p == '$'))
tk = tk * 147 + *p++;
tk = (tk << 6) + (p - pp); // hash plus symbol length
// hash value is used for fast comparison. Since it is inaccurate,
// we have to validate the memory content as well.
int nlen = p - pp;
for (id = sym; id < symk; ++id) { // check for keywords
if (tk == id->hash && id->name[nlen] == 0 &&
!memcmp(id->name, pp, nlen)) {
tk = id->tk;
return;
}
}
if (tokloc) {
for (id = symlh; id < symlt; ++id) { // local ids
if (tk == id->hash && id->name[nlen] == 0 &&
!memcmp(id->name, pp, nlen)) {
if (tokloc == 2) {
if (id->val > lds[ldn])
fatal("redefinition of var within scope");
else {
printf("%s: var %s decl hides previous decl\n",
linestr(), id->name);
goto new_block_def;
}
}
if (id->tsub && !mns) {
if (id->val & 1) { // recursive
// handle recursion
if (id->val == 3) { id->val = 1; continue; }
else id->val = 3;
}
if (numpts == INL_LEV) fatal("inline level exceeded");
tsline[numpts] = 0;
pts[numpts++] = p; p = id->tsub;
goto text_sub;
}
tk = id->tk;
return;
}
}
}
if (tokloc < 2) {
for (id = symk; id < symgt; ++id) { // global ids
if (tk == id->hash && id->name[nlen] == 0 &&
!memcmp(id->name, pp, nlen)) {
tk = id->tk;
return;
}
}
}
if (tokloc) {
for (id = lab; id < labt; ++id) { // labels
if (tk == id->hash && id->name[nlen] == 0 &&
!memcmp(id->name, pp, nlen)) {
tk = id->tk;
return;
}
}
}
// At this point, pre-existing symbol name was not found.
new_block_def:
id = tokloc ? --symlh : symgt++;
id->name = idp;
memcpy(idp, pp, nlen); idp[nlen] = 0;
idp = (char *) (((int) idp + nlen + 1 + sizeof(int)) &
(-sizeof(int)));
id->hash = tk;
tk = id->tk = Id; // token type identifier
id->class = id->val = id->type = id->etype = 0;
id->tsub = 0;
id->flags = 0;
id->chain = 0;
return;
}
/* Calculate the constant */
// first byte is a digit, and it is considered a numerical value
else if (tk >= '0' && tk <= '9') {
tk = Num; // token is char or int
tkv.i = strtoul((pp = p - 1), &p, 0); // octal, decimal, hex parsing
if (*p == '.') { // float
tkv.f = strtof(pp, &p); tk = NumF;
if (*p == 'f') ++p; // floating const has 'f' suffix
}
return;
}
switch (tk) {
case '\n':
if (lp < p && !numpts) {
if (src) printf("%d: %.*s", line, p - lp, lp);
lp = p;
}
++line;
case ' ':
case '\t':
case '\v':
case '\f':
case '\r':
break;
case '/':
if (*p == '/') { // comment
while (*p != 0 && *p != '\n') ++p;
} else if (*p == '*') { // C-style multiline comments
t = 0;
for (++p; (*p != 0) && (t == 0); ++p) {
pp = p + 1;
if (*p == '\n') ++line;
else if (*p == '*' && *pp == '/') t = 1;
}
++p;
} else {
if (*p == '=') { ++p; tk = DivAssign; }
else tk = Div; return;
}
break;
case '#': // skip include statements, and most preprocessor directives
if (!strncmp(p, "define", 6)) {
p += 6; next(); if (!ppactive) break;
if (tk == Id) {
struct ident_s *ndd = id;
int *nbase = n;
if (ndd->class != 0) fatal("can't redefine preprocessor symbol");
while (*p == ' ') ++p;
if (*p == '\n') { // no value assigned
ndd->class = Num; ndd->type = INT;
break;
}
eol2semi(p); next(); expr(Cond); *--p = '\n';
if ((nbase - n) == 2 && (*n == Num || *n == NumF)) {
ndd->class = *n; ndd->val = n[1];
ndd->type = (*n == Num) ? INT : FLOAT;
n += 2; // remove expr from AST
break;
}
else
fatal("Bad #define syntax");
}
else {
fatal("Bad #define syntax");
}
}
else if ((t = !strncmp(p, "ifdef", 5)) || !strncmp(p, "ifndef", 6)) {
p += 6; next();
if (tk != Id) fatal("No identifier");
++pplev;
if (ppactive &&
(((id->class == Num || id->class == NumF) ^ t) & 1)) {
int *nbase = n; ppactive = 0;
t = pplevt; pplevt = pplev - 1;
do next(); while (pplev != pplevt);
pplevt = t;
n = nbase; ppactive = 1;
}
}
else if (!strncmp(p, "if", 2)) {
int *nbase = n;
p += 2;
++pplev;
if (!ppactive) break;
eol2semi(p); next(); expr(Cond); *--p = '\n';
if ((nbase - n) == 2 && (*n == Num || *n == NumF)) {
t = n[1]; n += 2;
if (t == 0) { // throw away code inside of #if
t = pplevt; pplevt = pplev - 1; ppactive = 0;
do next(); while (pplev != pplevt);
pplevt = t;
n = nbase; ppactive = 1;
}
}
else
fatal("#if expression does not evaluate to const value");
}
else if(!strncmp(p, "endif", 5)) {
p += 5;
if (--pplev < 0) fatal("preprocessor context nesting error");
if (pplev == pplevt) return;
}
else if (!strncmp(p, "else", 4) || !strncmp(p, "elif", 4)) {
p += 4;
if (ppactive) fatal("#else/elif not supported in preprocessor");
}
else if (!strncmp(p, "error", 5)) {
p += 5;
if (ppactive) fatal ("#error encountered");
}
else {
while (*p && *p != '\n') ++p;
}
break;
case '\'': // quotes start with character (string)
case '"':
pp = data;
while (*p != 0 && *p != tk) {
if ((tkv.i = *p++) == '\\') {
switch (tkv.i = *p++) {
case 'n': tkv.i = '\n'; break; // new line
case 't': tkv.i = '\t'; break; // horizontal tab
case 'v': tkv.i = '\v'; break; // vertical tab
case 'f': tkv.i = '\f'; break; // form feed
case 'r': tkv.i = '\r'; break; // carriage return
case '0': tkv.i = '\0'; break; // an int with value 0
}
}
// if it is double quotes (string literal), it is considered as
// a string, copying characters to data
if (tk == '"') *data++ = tkv.i;
}
++p;
if (tk == '"') tkv.i = (int) pp; else tk = Num;
return;
case '=': if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return;
case '*': if (*p == '=') { ++p; tk = MulAssign; }
else tk = Mul; return;
case '+': if (*p == '+') { ++p; tk = Inc; }
else if (*p == '=') { ++p; tk = AddAssign; }
else tk = Add; return;
case '-': if (*p == '-') { ++p; tk = Dec; }
else if (*p == '>') { ++p; tk = Arrow; }
else if (*p == '=') { ++p; tk = SubAssign; }
else tk = Sub; return;
case '[': tk = Bracket; return;
case '&': if (*p == '&') { ++p; tk = Lan; }
else if (*p == '=') { ++p; tk = AndAssign; }
else tk = And; return;
case '!': if (*p == '=') { ++p; tk = Ne; } return;
case '<': if (*p == '=') { ++p; tk = Le; }
else if (*p == '<') {
++p; if (*p == '=') { ++p ; tk = ShlAssign; } else tk = Shl;
}
else tk = Lt; return;
case '>': if (*p == '=') { ++p; tk = Ge; }
else if (*p == '>') {
++p; if (*p == '=') { ++p ; tk = ShrAssign; } else tk = Shr;
}
else tk = Gt; return;
case '|': if (*p == '|') { ++p; tk = Lor; }
else if (*p == '=') { ++p; tk = OrAssign; }
else tk = Or; return;
case '^': if (*p == '=') { ++p; tk = XorAssign; } else tk = Xor; return;
case '%': if (*p == '=') { ++p; tk = ModAssign; }
else tk = Mod; return;
case '?': tk = Cond; return;
case '.': tk = Dot; return;
case ':': if (*p == '=') { ++p; tk = Alias; } return;
default: return;
}
}
if (numpts != 0) {
p = pts[--numpts];
if (tsline[numpts] != 0) line = tsline[numpts];
goto text_sub;
}
}
int popcount32(int ii)
{
int i;
i = ii - ((ii >> 1) & 0x55555555); // add pairs of bits
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads
i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8
return (i * 0x01010101) >> 24; // horizontal sum of bytes
}
// verify binary operations are legal
void typecheck(int op, int tl, int tr)
{
int pt = 0, it = 0, st = 0;
if (tl >= PTR) pt += 2; // is pointer?
if (tr >= PTR) pt += 1;
if (tl < FLOAT) it += 2; // is int?
if (tr < FLOAT) it += 1;
if (tl > ATOM_TYPE && tl < PTR) st += 2; // is struct/union?
if (tr > ATOM_TYPE && tr < PTR) st += 1;
if ((tl ^ tr) & (PTR | PTR2)) { // operation on different pointer levels
if (op == Add && pt != 3 && (it & ~pt)) ; // ptr + int or int + ptr ok
else if (op == Sub && pt == 2 && it == 1) ; // ptr - int ok
else if (op == Assign && pt == 2 && *n == Num && n[1] == 0) ; // ok
else if (op >= Eq && op <= Le && *n == Num && n[1] == 0) ; // ok
else fatal("bad pointer arithmetic or cast needed");
}
else if (pt == 3 && op != Assign && op != Sub &&
(op < Eq || op > Le)) // pointers to same type
fatal("bad pointer arithmetic");
if (pt == 0 && op != Assign && (it == 1 || it == 2))
fatal("cast operation needed");
if (pt == 0 && st != 0)
fatal("illegal operation with dereferenced struct");
}
void bitopcheck(int tl, int tr)
{
if (tl >= FLOAT || tr >= FLOAT)
fatal("bit operation on non-int types");
}
int tensor_size(int dim, int etype)
{
int retVal;
switch (dim) {
case 1: retVal = (etype+1);
break;
case 2: retVal = ((etype & 0xffff) + 1) * ((etype >> 16) + 1);
break;
case 3: retVal = ((etype & 0x7ff) + 1) *
(((etype >> 11) & 0x3ff) + 1) *
((etype >> 21) + 1);
break;
}
return retVal;
}
/* expression parsing
* lev represents an operator.
* because each operator `token` is arranged in order of priority,
* large `lev` indicates a high priority.
*
* Operator precedence (lower first):
* Assign =
* Cond ?
* Lor ||
* Lan &&
* Or |
* Xor ^
* And &
* Eq ==
* Ne !=
* Ge >=
* Lt <
* Gt >
* Le <=
* Shl <<
* Shr >>
* Add +
* Sub -
* Mul *
* Div /
* Mod %
* Inc ++
* Dec --
* Bracket [
*/
#define REENTRANT 0x10000
inline void stmt(int ctx);
int idchar(int n) // 6 bits wide
{
int val;
if (n < 10) val = '0' + n;
else if (n < 36) val = 'a' + n - 10;
else if (n < 62) val = 'A' + n - 36;
else val = ((n == 62) ? '_' : '$');
return val;
}
/* Drop second item on AST stack */
void swapDrop(int *b, int sz) // n is global
{
int *t, *c = b, *a = b + sz;
do {
--c; --a;
t = (int *) (*a = *c);
if (t >= n && t <= b) *a += sz; // sketchy, not guaranteed safe
} while (c != n);
n += sz;
}
int elideZero(int *aa, int *b, int bt, int op) // n and ty are global
{
// 0 = no elision, 1 = const elision, 2 = AST deletion (NOP)
int elide = 0;
if ((aa-n) == 2 && *n == Num) {
if (*b == Num) elide = 1;
else if (n[1] == 0) { n += 2; ty = bt; elide = 2; }
}
else if (aa == b && *b == Num && b[1] == 0) {
swapDrop(b, 2); elide = 2;
}
return elide;
}
int hasSideEffect(int *b, int *e) // conservative, so not strictly sketchy
{
int *s;
s = b;
while (s != e) {
if (*s == Inc || *s == Dec || *s == Assign) break;
++s;
}
return (s != e);
}
int idMatch(char *id, char *expr)
{
int retVal = 0;
int bracketLev = 0;
char *a = id, *b = expr;
while (*a && *a++ == *b++);
while (*b) {
if (*b != ' ') {
if (bracketLev == 0 && *b != '[') break;
if (*b == '[') ++bracketLev;
else if (*b == ']') --bracketLev;
}
++b;
}
if (*b && *b == ')' && b[1] == 0) retVal = !0;
return retVal;
}
void modArgCheck(int *node)
{
if (ma && node[0] == Loc && node[1] > 1)
fatal("Can't modify passed argument (compile -ma to allow)");
}
void flagWrite(int *flags, int *high, int *low)
{
*flags |= ((*flags & 4) ? 8 : 4);
if (high - low == 2 && *low != Num && *low != NumF) *flags |= 64; // not lit
}
void expr(int lev)
{
int t, tc, tt[2], nf, sz;
int *a, *b, *c;
int memsub = 0;
union conv *c1, *c2;
struct ident_s *d;
struct member_s *m;
int inln_func = 0;
switch (tk) {
case Id:
do_inln_func:
d = id; next();
if (tokloc && sbegin && tk == ':') {
if (d->class != 0 || !(d->type == 0 || d->type == -1))
fatal("invalid label");
if (d < lab || d >= labt) { // move labels to separate area
if (d != symlh || (labt - lab) == MAX_LABEL)
fatal("label problem");
memcpy(idl, d->name, t = idp - d->name); idp = d->name;
memcpy(d = labt++, symlh++, sizeof (struct ident_s));
d->name = idl; idl += t;
}
d->type = -1 ; // hack for d->class deficiency
*--n = (int) d; *--n = Label;
next(); return;
}
sbegin = 0;
// function call
if (tk == '(') {
int fidx, tsi, *saven = 0;
char *psave, *ts[52];
if (d == symlh) { // move ext func Ids to global sym table
memcpy(d = symgt++, symlh++, sizeof (struct ident_s));
}
if (d->class == Func && d->val == 0 &&
d->tsub == 0 && (d->flags & 1) == 0) { // lib func prototype
goto resolve_fnproto;
}
if (d->class < Func || d->class > Sqrt) {
if (d->class != 0) fatal("bad function call");
d->type = INT;
d->ftype[0] = d->ftype[1] = 0;
resolve_fnproto:
d->class = Syscall;
d->val = ef_getidx(d->name) ;
if (inln_func) inln_func = 0; // should I warn here?
if (d->tsub) fatal("internal compiler error");
}
while (*p == ' ' || *p == 0x0a) if (*p++ == 0x0a) ++line;
psave = p;
next();
t = 0; b = c = 0; tt[0] = tt[1] = 0; nf = 0; // FP argument count
if (!deadzone && (inln_func || d->tsub)) {
if (d->tsub) {
if (numpts == INL_LEV) {
if (d->val == 0) fatal("inline level exceeded");
}
else { fidx = ((int) d->tsub) - 1; inln_func = 1; }
}
else {
for (fidx = 0; fidx < numfspec; ++fidx)
if (!strcmp(d->name, (char *)fspec[fidx][0])) break;
}
if (fidx == numfspec || numpts == INL_LEV) inln_func = 0; // warn?
else { tsi = 0; saven = n; }
}
if (peephole && (d->class < Fneg || d->class > Sqrt) && !inln_func) {
*--n = Phf; c = n;
}
parg = 1;
while (tk != ')') {
if (inln_func && !deadzone) {
a = n; expr(Assign);
ts[tsi++] = idp;
if ((a-n == 2) && (*n == Num || *n == NumF)) { // lit const
a = (int *) idp;
*a++ = n[0]; *a++ = n[1];
idp = (char *) a;
}
else {
*idp = '(';
memcpy(idp+1, psave, p-psave-1);
idp[p-psave] = ')'; idp[p-psave+1] = 0;
idp = (char *) (((int) idp +
(p - psave) + 2 + sizeof(int)) &
(-sizeof(int)));
}
while (*p == ' ' || *p == 0x0a) if (*p++ == 0x0a) ++line;
psave = p;
}
else expr(Assign);
*--n = (int) b; b = n; ++t;
if (ty == FLOAT) { ++nf; tt[(t+11)/32] |= 1 << ((t+11) % 32); }
if (tk == ',') {
next();
if (tk == ')') fatal("unexpected comma in function call");
} else if (tk != ')') fatal("missing comma in function call");
}
if (t > MAX_FARG) fatal("maximum of 52 function parameters");
parg = 0;
tt[0] += (nf << 6) + t;