-
Notifications
You must be signed in to change notification settings - Fork 0
/
c4x86.c
1636 lines (1411 loc) · 59.1 KB
/
c4x86.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
// c4.c - C in four functions
// char, int, and pointer types
// if, while, return, and expression statements
// just enough features to allow self-compilation and a bit more
// Written by Robert Swierczek
// + x86 JIT compiler by Dmytro Sirenko
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#ifndef _WIN32
#include <sys/mman.h>
#include <dlfcn.h>
#else
#include "mman32.h"
#include "dlfcn32.h"
#define CHAR TYCHAR
#define INT TYINT
#endif
char *p, *lp, // current position in source code
*jitmem, // executable memory for JIT-compiled native code
*data, // data/bss pointer
**linemap; // maps a line number into its source position
int *e, *le, *text, // current position in emitted code
*id, // currently parsed indentifier
*sym, // symbol table (simple list of identifiers)
tk, // current token
ival, // current token value
ty, // current expression type
loc, // local variable offset
line, // current line number
*srcmap, // maps a bytecode into its corresponding source line number
src; // print source, c4 assembly and JIT addresses
enum Token {
Num = 128, Fun, Sys, Glo, Loc, Id,
Char, Else, Enum, If, Int, Return, Sizeof, While,
Assign, Cond, Lor, Lan, Or, Xor, And, Eq, Ne, Lt, Gt, Le, Ge, Shl, Shr, Add, Sub, Mul, Div, Mod, Inc, Dec, Brak
};
enum Opcode {
LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH ,
OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,DIV ,MOD ,
OPEN,READ,CLOS,PRTF,MALC,MSET,MCMP,MCPY,MMAP,DOPN,DSYM,QSRT,EXIT
};
enum Ty { CHAR, INT, PTR };
// identifier offsets (since we can't create an ident struct)
// Symbol table entry's field indexes, except for `Idsz`.
// `Hash`: Symbol name's hash value.
// `Name`: Symbol name's string address.
// `Class`: Symbol type:
// - Num: Enum name.
// - Fun: Function name.
// - Sys: System call name.
// - Glo: Global variable name.
// - Loc: Local variable name.
// `Type`: Associated value type. e.g. `CHAR`, `INT`.
// `Val`: Associated value.
// `HClass`: Backup field for `Class` field.
// `HType`: Backup field for `Type` field.
// `HVal`: Backup field for `Val` field.
// `Idsz`: Symbol table entry size.
enum Identifier { Tk, Hash, Name, Class, Type, Val, HClass, HType, HVal, Idsz };
// Read token.
void next()
{
char *pp;
// Get current character.
// While current character is not `\0`.
// The source code has been read into source code buffer and ended with `\0`.
while (tk = *p) {
// Point to next character.
++p;
// If current character is newline.
if (tk == '\n') {
// If switch for printing source code line and corresponding instructions
// is on.
if (src) {
// Store the mapping from line number to source code buffer location.
linemap[line] = lp;
// While have instruction.
// Store the mapping from instruction index to line number.
while (le < e) { srcmap[le - text] = line; le++; };
}
// Point `lp` to the last newline.
lp = p;
// Increment line number.
++line;
}
// If current character is `#`, it is preprocessing directive.
// Preprocessing directive is ignored.
else if (tk == '#') {
// While current character is not `\0` and current character is not
// newline.
// Skip current character.
while (*p != 0 && *p != '\n') ++p;
}
// If current character is letter or underscore, it is identifier.
else if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') || tk == '_') {
// Point `pp` to the first character.
pp = p - 1;
// While current character is letter, digit, or underscore.
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_')
// Use current character to compute hash value.
tk = tk * 147 + *p++;
// Combine the hash value with string length.
tk = (tk << 6) + (p - pp);
// Point `id` to symbol table.
id = sym;
// While current symbol table entry is in use.
while (id[Tk]) {
// If current symbol table entry's hash is equal and name is equal, it
// means the name has been seen before.
// Set token type be the entry's token type.
if (tk == id[Hash] && !memcmp((char *)id[Name], pp, p - pp)) { tk = id[Tk]; return; }
// Point to next table entry.
id = id + Idsz;
}
// At this point, existing symbol name is not found.
// `id` is pointing to the first unused symbol table entry.
// Store the name's string address.
id[Name] = (int)pp;
// Store the name's hash value.
id[Hash] = tk;
// Set token type.
tk = id[Tk] = Id;
return;
}
// If current character is digit, it is number constant.
else if (tk >= '0' && tk <= '9') {
// If current character is not `0`, it is decimal notation.
// Convert decimal notation to value.
if (ival = tk - '0') { while (*p >= '0' && *p <= '9') ival = ival * 10 + *p++ - '0'; }
// If current character is `0` and following character is `x` or
// `X`, it is hexadecimal notation.
else if (*p == 'x' || *p == 'X') {
// Convert hexadecimal notation to value.
while ((tk = *++p) && ((tk >= '0' && tk <= '9') || (tk >= 'a' && tk <= 'f') || (tk >= 'A' && tk <= 'F')))
ival = ival * 16 + (tk & 15) + (tk >= 'A' ? 9 : 0);
}
// If current character is `0` and following character is not `x` or
// `X`, it is octal notation.
// Convert octal notation to value.
else { while (*p >= '0' && *p <= '7') ival = ival * 8 + *p++ - '0'; }
// Set token type.
tk = Num;
return;
}
// If current character is `/`, it is comments or division operator.
else if (tk == '/') {
// If following character is `/`, it is comments.
if (*p == '/') {
// Point to next character.
++p;
// While current character is not `\0` and current character is not
// newline.
// Skip current character.
while (*p != 0 && *p != '\n') ++p;
}
// If following character is not `/`, it is division operator.
else {
// Set token type.
tk = Div;
return;
}
}
// If current character is `'` or `"`, it is character constant or string
// constant.
else if (tk == '\'' || tk == '"') {
// Store data buffer's current location.
pp = data;
// While current character is not `\0` and current character is not the
// quote character.
while (*p != 0 && *p != tk) {
// If current character is `\`, it is escape notation or simply `\`
// character.
if ((ival = *p++) == '\\') {
// If following character is `n`, it is newline escape,
if ((ival = *p++) == 'n') ival = '\n';
}
// If it is string constant, copy current character to data buffer.
if (tk == '"') *data++ = ival;
}
// Point to next character.
++p;
// If it is string constant, use the string's address as the token's
// associated value. The token type is `"`.
// If it is character constant, use the character's value as the token's
// associated value. Set token type be number constant.
if (tk == '"') ival = (int)pp; else tk = Num;
return;
}
else if (tk == '=') { if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return; }
else if (tk == '+') { if (*p == '+') { ++p; tk = Inc; } else tk = Add; return; }
else if (tk == '-') { if (*p == '-') { ++p; tk = Dec; } else tk = Sub; return; }
else if (tk == '!') { if (*p == '=') { ++p; tk = Ne; } return; }
else if (tk == '<') { if (*p == '=') { ++p; tk = Le; } else if (*p == '<') { ++p; tk = Shl; } else tk = Lt; return; }
else if (tk == '>') { if (*p == '=') { ++p; tk = Ge; } else if (*p == '>') { ++p; tk = Shr; } else tk = Gt; return; }
else if (tk == '|') { if (*p == '|') { ++p; tk = Lor; } else tk = Or; return; }
else if (tk == '&') { if (*p == '&') { ++p; tk = Lan; } else tk = And; return; }
else if (tk == '^') { tk = Xor; return; }
else if (tk == '%') { tk = Mod; return; }
else if (tk == '*') { tk = Mul; return; }
else if (tk == '[') { tk = Brak; return; }
else if (tk == '?') { tk = Cond; return; }
else if (tk == '~' || tk == ';' || tk == '{' || tk == '}' || tk == '(' || tk == ')' || tk == ']' || tk == ',' || tk == ':') return;
}
}
// Parse expression.
// `lev`: Current operator precedence. Greater value means higher precedence.
// Operator precedence (lower first):
// Assign =
// Cond ?
// Lor ||
// Lan &&
// Or |
// Xor ^
// And &
// Eq ==
// Ne !=
// Lt <
// Gt >
// Le <=
// Ge >=
// Shl <<
// Shr >>
// Add +
// Sub -
// Mul *
// Div /
// Mod %
// Inc ++
// Dec --
// Brak [
void expr(int lev)
{
int t, *d;
// If current token is input end, print error and exit program.
if (!tk) { printf("%d: unexpected eof in expression\n", line); exit(-1); }
// If current token is number constant.
// Add `IMM` instruction to load the number's value to register.
// Set result value type be `INT`.
else if (tk == Num) { *++e = IMM; *++e = ival; next(); ty = INT; }
// If current token is string constant.
else if (tk == '"') {
// Add `IMM` instruction to load the string's address to register.
// Read token.
*++e = IMM; *++e = ival; next();
// While current token is string constant, it is adjacent string
// constants, e.g. "abc" "def".
// In `next`, the string's characters have been copied to data buffer.
// This implements concatenation of adjacent string constants.
// Read token.
while (tk == '"') next();
// Point `data` to next int-aligned address.
// E.g. `-sizeof(int)` is -4, i.e. 0b11111100.
// This guarantees to leave at least one '\0' after the string.
//
// Set result value type be char pointer.
// CHAR + PTR = PTR because CHAR is 0.
data = (char *)((int)data + sizeof(int) & -sizeof(int)); ty = PTR;
}
// If current token is `sizeof` operator.
else if (tk == Sizeof) {
// Read token.
// If current token is `(`, read token, else print error and exit
// program.
next(); if (tk == '(') next(); else { printf("%d: open paren expected in sizeof\n", line); exit(-1); }
// Set operand value type be `INT`.
// If current token is `int`, read token.
// If current token is `char`, read token, set operand value type be
// `CHAR`.
ty = INT; if (tk == Int) next(); else if (tk == Char) { next(); ty = CHAR; }
// While current token is `*`, it is pointer type.
// Add `PTR` to the operand value type.
while (tk == Mul) { next(); ty = ty + PTR; }
// If current token is `)`, read token, else print error and exit program.
if (tk == ')') next(); else { printf("%d: close paren expected in sizeof\n", line); exit(-1); }
// Add `IMM` instruction to load the operand value's size to register.
*++e = IMM; *++e = (ty == CHAR) ? sizeof(char) : sizeof(int);
// Set result value type be `INT`.
ty = INT;
}
// If current token is identifier.
else if (tk == Id) {
// Store the identifier's symbol table entry pointer.
// Read token.
d = id; next();
// If current token is `(`, it is function call.
if (tk == '(') {
// Read token.
next();
// Arguments count.
t = 0;
// While current token is not `)`.
// Parse argument expression.
// Add `PSH` instruction to push the argument to stack.
// Increment arguments count.
// If current token is `,`, skip.
while (tk != ')') { expr(Assign); *++e = PSH; ++t; if (tk == ',') next(); }
// Skip `)`
next();
// If it is system call,
// add the system call's opcode to instruction buffer.
if (d[Class] == Sys) *++e = d[Val];
// If it is function call,
// add `JSR` opcode and the function address to instruction buffer.
else if (d[Class] == Fun) { *++e = JSR; *++e = d[Val]; }
// Else print error message and exit program.
else { printf("%d: bad function call\n", line); exit(-1); }
// If have arguments.
// Add `ADJ` instruction and arguments count to instruction buffer to
// pop arguments off stack after returning from function call.
if (t) { *++e = ADJ; *++e = t; }
// Set result value type be the system call or function's return type.
ty = d[Type];
}
// If it is enum name.
// Add `IMM` instruction to load the enum value to register.
// Set result value type be `INT`.
else if (d[Class] == Num) { *++e = IMM; *++e = d[Val]; ty = INT; }
// If it is none of above, assume it is a variable name.
else {
// 6S71X
// If it is local variable, add `LEA` opcode and the local variable's
// offset to instruction buffer to load the local variable's address to
// register.
if (d[Class] == Loc) { *++e = LEA; *++e = loc - d[Val]; }
// If it is global variable, add `IMM` instruction to load the global
// variable's address to register.
else if (d[Class] == Glo) { *++e = IMM; *++e = d[Val]; }
// Else print error message and exit program.
else { printf("%d: undefined variable\n", line); exit(-1); }
// 2WQE9
// Add `LC`/`LI` instruction to load the value on the address in register
// to register.
*++e = ((ty = d[Type]) == CHAR) ? LC : LI;
}
}
// If current token is `(`, it is cast or expression in parentheses.
else if (tk == '(') {
// Read token.
next();
// If current token is `int` or `char`, it is cast.
if (tk == Int || tk == Char) {
// Get the cast's base data type.
// Read token.
t = (tk == Int) ? INT : CHAR; next();
// While current token is `*`, it is pointer type.
// Add `PTR` to the cast's data type.
while (tk == Mul) { next(); t = t + PTR; }
// If current token is not `)`, print error and exit program.
if (tk == ')') next(); else { printf("%d: bad cast\n", line); exit(-1); }
// Parse casted expression.
// Use `Inc` to allow only `++`, `--`, `[]` operators in the expression.
expr(Inc);
// Set result value type be the cast's data type.
ty = t;
}
// If current token is not `int` or `char`, it is expression in
// parentheses.
else {
// Parse expression.
expr(Assign);
// If current token is not `)`, print error and exit program.
if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); }
}
}
// If current token is `*`, it is dereference operator.
else if (tk == Mul) {
// Read token.
// Parse operand expression.
// Use `Inc` to allow only `++`, `--`, `[]` operators in the expression.
next(); expr(Inc);
// If operand value type is not pointer, print error and exit program.
if (ty > INT) ty = ty - PTR; else { printf("%d: bad dereference\n", line); exit(-1); }
// Add `LC`/`LI` instruction to load the value on the address in register
// to register.
*++e = (ty == CHAR) ? LC : LI;
}
// If current token is `&`, it is address-of operator.
else if (tk == And) {
// Read token.
// Parse operand expression.
// Use `Inc` to allow only `++`, `--`, `[]` operators in the expression.
next(); expr(Inc);
// The operand of the address-of operator should be a variable.
// The instructions to get the variable's address has been added at 6S71X.
// Only need to remove the `LC`/`LI` instruction added at 2WQE9.
// If current instruction is `LC`/`LI`, remove it, else print error and
// exit program.
if (*e == LC || *e == LI) --e; else { printf("%d: bad address-of\n", line); exit(-1); }
// Set result value type be pointer to current value type.
ty = ty + PTR;
}
// If current token is `!`, it is boolean negation operator.
// Add instructions to compute `x == 0` because `!x` is equivalent to
// `x == 0`.
// Set result value type be `INT`.
else if (tk == '!') { next(); expr(Inc); *++e = PSH; *++e = IMM; *++e = 0; *++e = EQ; ty = INT; }
// If current token is `~`, it is bitwise inversion operator.
// Add instructions to compute `x ^ -1` because `~x` is equivalent to
// `x ^ -1`.
// Set result value type be `INT`.
else if (tk == '~') { next(); expr(Inc); *++e = PSH; *++e = IMM; *++e = -1; *++e = XOR; ty = INT; }
// If current token is `+`, it is unary addition operator.
// Read token.
// Parse operand expression.
// Set result value type be `INT`.
else if (tk == Add) { next(); expr(Inc); ty = INT; }
// If current token is `-`, it is unary subtraction operator.
else if (tk == Sub) {
// Read token.
// Add `IMM` instruction to load number constant's negated value or `-1`
// to register.
next(); *++e = IMM;
// If operand is number constant, add negated value to instruction buffer.
// If operand is not number constant, add `-1` to instruction buffer. Add
// `PSH` instruction to push `-1` in register to stack. Parse operand
// expression. Add `MUL` instruction to multiply `-1` on stack by the
// operand value in register.
if (tk == Num) { *++e = -ival; next(); } else { *++e = -1; *++e = PSH; expr(Inc); *++e = MUL; }
// Set result value type be `INT`.
ty = INT;
}
// If current token is prefix increment or decrement operator.
else if (tk == Inc || tk == Dec) {
// Store current token type.
// Read token.
// Parse operand expression.
t = tk; next(); expr(Inc);
// If current instruction is `LC`, insert a `PSH` instruction before `LC`
// to push variable address in register to stack for use by the `SC`
// instruction added below.
if (*e == LC) { *e = PSH; *++e = LC; }
// If current instruction is `LI`, insert a `PSH` instruction before `LI`
// to push variable address in register to stack for use by the `SI`
// instruction added below.
else if (*e == LI) { *e = PSH; *++e = LI; }
// Else print error and exit program.
else { printf("%d: bad lvalue in pre-increment\n", line); exit(-1); }
// Add `PSH` instruction to push operand value in register to stack
// for use by the `ADD`/`SUB` instruction added below.
*++e = PSH;
// Add `IMM` instruction to load increment/decrement value to register.
*++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char);
// Add `ADD`/`SUB` instruction to compute result value.
*++e = (t == Inc) ? ADD : SUB;
// Add `SC`/`SI` instruction to save result value in register to address
// held on stack.
*++e = (ty == CHAR) ? SC : SI;
}
// Else print error and exit program.
else { printf("%d: bad expression\n", line); exit(-1); }
// While current token type is >= current operator precedence,
// it is an operator that should be handled here.
while (tk >= lev) { // "precedence climbing" or "Top Down Operator Precedence" method
// Store current value type.
t = ty;
// If current token is assignment operator.
if (tk == Assign) {
// Read token.
next();
// If current instruction is `LC`/`LI`, current value in register is
// variable address, replace current instruction with `PSH` instruction
// to push the variable address to stack for use by the `SC`/`SI`
// instruction added below.
// If current instruction is not `LC`/`LI`, current value in register is
// not variable address, print error and exit program.
if (*e == LC || *e == LI) *e = PSH; else { printf("%d: bad lvalue in assignment\n", line); exit(-1); }
// Parse RHS expression.
// Add `SC`/`SI` instruction to save value in register to variable
// address held on stack.
expr(Assign); *++e = ((ty = t) == CHAR) ? SC : SI;
}
// If current token is conditional operator.
else if (tk == Cond) {
// Read token.
next();
// Add jump-if-zero instruction `BZ` to jump to false branch.
// Point `d` to the jump address field to be patched later.
*++e = BZ; d = ++e;
// Parse true branch expression.
expr(Assign);
// If current token is not `:`, print error and exit program.
if (tk == ':') next(); else { printf("%d: conditional missing colon\n", line); exit(-1); }
// Patch the jump address field pointed to by `d` to hold the address of
// false branch.
// `+ 3` counts the `JMP` instruction added below.
//
// Add `JMP` instruction after the true branch to jump over the false
// branch.
// Point `d` to the jump address field to be patched later.
*d = (int)(e + 3); *++e = JMP; d = ++e;
// Parse false branch expression.
expr(Cond);
// Patch the jump address field pointed to by `d` to hold the address
// past the false branch.
*d = (int)(e + 1);
}
// If current token is logical OR operator.
// Read token.
// Add jump-if-nonzero instruction `BNZ` to implement short circuit.
// Point `d` to the jump address field to be patched later.
// Parse RHS expression.
// Patch the jump address field pointed to by `d` to hold the address past
// the RHS expression.
// Set result value type be `INT`.
else if (tk == Lor) { next(); *++e = BNZ; d = ++e; expr(Lan); *d = (int)(e + 1); ty = INT; }
// If current token is logical AND operator.
// Read token.
// Add jump-if-zero instruction `BZ` to implement short circuit.
// Point `d` to the jump address field to be patched later.
// Parse RHS expression.
// Patch the jump address field pointed to by `d` to hold the address past
// the RHS expression.
// Set result value type be `INT`.
else if (tk == Lan) { next(); *++e = BZ; d = ++e; expr(Or); *d = (int)(e + 1); ty = INT; }
// If current token is bitwise OR operator.
// Read token.
// Add `PSH` instruction to push LHS value in register to stack.
// Parse RHS expression.
// Add `OR` instruction to compute the result.
// Set result value type be `INT`.
// The following operators are similar.
else if (tk == Or) { next(); *++e = PSH; expr(Xor); *++e = OR; ty = INT; }
else if (tk == Xor) { next(); *++e = PSH; expr(And); *++e = XOR; ty = INT; }
else if (tk == And) { next(); *++e = PSH; expr(Eq); *++e = AND; ty = INT; }
else if (tk == Eq) { next(); *++e = PSH; expr(Lt); *++e = EQ; ty = INT; }
else if (tk == Ne) { next(); *++e = PSH; expr(Lt); *++e = NE; ty = INT; }
else if (tk == Lt) { next(); *++e = PSH; expr(Shl); *++e = LT; ty = INT; }
else if (tk == Gt) { next(); *++e = PSH; expr(Shl); *++e = GT; ty = INT; }
else if (tk == Le) { next(); *++e = PSH; expr(Shl); *++e = LE; ty = INT; }
else if (tk == Ge) { next(); *++e = PSH; expr(Shl); *++e = GE; ty = INT; }
else if (tk == Shl) { next(); *++e = PSH; expr(Add); *++e = SHL; ty = INT; }
else if (tk == Shr) { next(); *++e = PSH; expr(Add); *++e = SHR; ty = INT; }
// If current token is addition operator.
else if (tk == Add) {
// Read token.
// Add `PSH` instruction to push LHS value in register to stack.
// Parse RHS expression.
next(); *++e = PSH; expr(Mul);
// If LHS value type is pointer,
// the RHS value should be multiplied by int size to get address offset.
// Add `PSH` instruction to push RHS value in register to stack.
// Add `IMM` instruction to load int size to register.
// Add `MUL` instruction to multiply RHS value on stack by int size in
// register to get the address offset.
if ((ty = t) > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; }
// Add addition instruction to add LHS value on stack to RHS value in
// register.
*++e = ADD;
}
// If current token is subtraction operator.
else if (tk == Sub) {
// Read token.
// Add `PSH` instruction to push LHS value in register to stack.
// Parse RHS expression.
next(); *++e = PSH; expr(Mul);
// If LHS value type is pointer, the RHS value should be multiplied by
// int size to get address offset.
// Add `PSH` instruction to push LHS value in register to stack.
// Add `IMM` instruction to load int size to register.
// Add `MUL` instruction to multiply RHS value on stack by int size in
// register to get the address offset.
if ((ty = t) > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; }
// Add `SUB` instruction to subtract LHS value on stack by RHS value in
// register.
*++e = SUB;
}
// If current token is multiplication operator.
// Add `PSH` instruction to push LHS value in register to stack.
// Parse RHS expression.
// Add `MUL` instruction to multiply LHS value on stack by RHS value in
// register.
// Set result value type be `INT`.
// The following operators are similar.
else if (tk == Mul) { next(); *++e = PSH; expr(Inc); *++e = MUL; ty = INT; }
else if (tk == Div) { next(); *++e = PSH; expr(Inc); *++e = DIV; ty = INT; }
else if (tk == Mod) { next(); *++e = PSH; expr(Inc); *++e = MOD; ty = INT; }
// If current token is postfix increment or decrement operator.
else if (tk == Inc || tk == Dec) {
// If current instruction is `LC`, insert a `PSH` instruction before `LC`
// to push variable address in register to stack for use by the `SC`
// instruction added below.
if (*e == LC) { *e = PSH; *++e = LC; }
// If current instruction is `LI`, insert a `PSH` instruction before `LI`
// to push variable address in register to stack for use by the `SI`
// instruction added below.
else if (*e == LI) { *e = PSH; *++e = LI; }
// Else print error and exit program.
else { printf("%d: bad lvalue in post-increment\n", line); exit(-1); }
// Add `PSH` instruction to push operand value in register to stack.
// Add `IMM` instruction to load increment/decrement size to register.
*++e = PSH; *++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char);
// Add `ADD`/`SUB` instruction to compute the post value.
*++e = (tk == Inc) ? ADD : SUB;
// Add `SC`/`SI` instruction to save the post value in register to
// variable.
*++e = (ty == CHAR) ? SC : SI;
// Add `PSH` instruction to push the post value in register to stack.
// Add `IMM` instruction to load increment/decrement size to register.
*++e = PSH; *++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char);
// Add `SUB`/`ADD` instruction to compute the old value.
// This implements postfix semantics.
*++e = (tk == Inc) ? SUB : ADD;
// Read token.
next();
}
// If current token is `[`, it is array subscript.
else if (tk == Brak) {
// Read token.
// Add `PSH` instruction to push the base address in register to stack.
// Parse subscript expression.
next(); *++e = PSH; expr(Assign);
// If current token is not `]`, print error and exit program.
if (tk == ']') next(); else { printf("%d: close bracket expected\n", line); exit(-1); }
// If base address's value type is int pointer or pointer to pointer,
// the subscript value should be multiplied by int size to get address
// offset. `t == PTR` is char pointer `char*`, which needs not doing so.
// Add `PSH` instruction to push subscript value in register to stack.
// Add `IMM` instruction to load int size to register.
// Add `MUL` instruction to compute address offset.
if (t > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; }
// If base address's value type is not pointer, print error and exit
// program.
else if (t < PTR) { printf("%d: pointer type expected\n", line); exit(-1); }
// Add `ADD` instruction to add the address offset to the base address.
*++e = ADD;
// Add `LC`/`LI` instruction to load the value on the address in register
// to register.
*++e = ((ty = t - PTR) == CHAR) ? LC : LI;
}
// If current token is not a known operator, print error and exit program.
else { printf("%d: compiler error tk=%d\n", line, tk); exit(-1); }
}
}
// Parse statement.
void stmt()
{
int *a, *b;
// If current token is `if`.
if (tk == If) {
// Read token.
next();
// If current token is not `(`, print error and exit program.
if (tk == '(') next(); else { printf("%d: open paren expected\n", line); exit(-1); }
// Parse test expression.
expr(Assign);
// If current token is not `)`, print error and exit program.
if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); }
// Add jump-if-zero instruction `BZ` to jump over the true branch.
// Point `b` to the jump address field to be patched later.
*++e = BZ; b = ++e;
// Parse true branch's statement.
stmt();
// If current token is `else`.
if (tk == Else) {
// Patch the jump address field pointed to by `b` to hold the address of
// else branch.
// `e + 3` excludes the `JMP` instruction added below.
//
// Add `JMP` instruction after the true branch to jump over the else
// branch.
//
// Point `b` to the jump address field to be patched later.
*b = (int)(e + 3); *++e = JMP; b = ++e;
// Read token.
next();
// Parse else branch's statement.
stmt();
}
// Patch the jump address field pointed to by `b` to hold the address past
// the if-else structure.
*b = (int)(e + 1);
}
// If current token is `while`.
else if (tk == While) {
// Read token.
next();
// Point `a` to the loop's test expression's address.
a = e + 1;
// If current token is not `(`, print error and exit program.
if (tk == '(') next(); else { printf("%d: open paren expected\n", line); exit(-1); }
// Parse test expression.
expr(Assign);
// If current token is not `)`, print error and exit program.
if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); }
// Add jump-if-zero instruction `BZ` to jump over loop body.
// Point `b` to the jump address field to be patched later.
*++e = BZ; b = ++e;
// Parse loop body's statement.
stmt();
// Add `JMP` instruction to jump to test expression.
*++e = JMP; *++e = (int)a;
// Patch the jump address field pointed to by `b` to hold the address past
// the loop structure.
*b = (int)(e + 1);
}
// If current token is `return`.
else if (tk == Return) {
// Read token.
next();
// If current token is not `;`, it is return expression.
// Parse return expression.
if (tk != ';') expr(Assign);
// Add `LEV` instruction to leave the function.
*++e = LEV;
// If current token is `;`, read token, else print error and exit program.
if (tk == ';') next(); else { printf("%d: semicolon expected\n", line); exit(-1); }
}
// If current token is `{`, it is block.
else if (tk == '{') {
// Read token.
next();
// While current token is not `}`.
// Parse statement.
while (tk != '}') stmt();
// Read token.
next();
}
// If current token is `;`, it is statement end.
else if (tk == ';') {
// Read token.
next();
}
// If current token is none of above, assume it is expression.
else {
// Parse expression.
expr(Assign);
// If current token is `;`, read token, else print error and exit program.
if (tk == ';') next(); else { printf("%d: semicolon expected\n", line); exit(-1); }
}
}
int main(int argc, char **argv)
{
int fd, bt, ty, poolsz, *idmain;
int *pc;
int i, tmp; // temps
void *dl;
int (*jitmain)();
char *je, // current position in emitted native code
**jitmap; // maps c4 bytecode index into native code position
// Decrement `argc` to get the number of command line arguments.
// Increment `argv` to point to the first command line argument.
--argc; ++argv;
// If command line argument `-s` is given,
// turn on switch for printing source code line and corresponding
// instructions.
if (argc > 0 && **argv == '-' && (*argv)[1] == 's') { src = 1; --argc; ++argv; }
// If command line argument `-d` is given,
// turn on debug switch.
if (argc > 0 && **argv == '-' && (*argv)[1] == 'd') { debug = 1; --argc; ++argv; }
// If source code file path is not given, print program usage and exit
// program.
if (argc < 1) { printf("usage: c4x86 [-s] file ...\n"); return -1; }
// Open source code file.
// If failed, print error and exit program.
if ((fd = open(*argv, 0)) < 0) { printf("could not open(%s)\n", *argv); return -1; }
// Set buffer size.
poolsz = 256*1024; // arbitrary size
// Allocate symbol table.
// If failed, print error and exit program.
if (!(sym = malloc(poolsz))) { printf("could not malloc(%d) symbol area\n", poolsz); return -1; }
// Allocate instruction buffer.
// If failed, print error and exit program.
if (!(text = le = e = malloc(poolsz))) { printf("could not malloc(%d) text area\n", poolsz); return -1; }
// Allocate data buffer.
// If failed, print error and exit program.
if (!(data = malloc(poolsz))) { printf("could not malloc(%d) data area\n", poolsz); return -1; }
// Allocate stack.
// If failed, print error and exit program.
if (!(sp = malloc(poolsz))) { printf("could not malloc(%d) stack area\n", poolsz); return -1; }
// Clear the buffers.
memset(sym, 0, poolsz);
memset(e, 0, poolsz);
memset(data, 0, poolsz);
// Keywords and system call names.
p = "char else enum if int return sizeof while "
"open read close printf malloc memset memcmp memcpy mmap dlopen dlsym qsort exit void main";
// For each keyword from `char` to `while`,
// call `next` to create symbol table entry,
// store the keyword's token type in the symbol table entry's `Tk` field.
i = Char; while (i <= While) { next(); id[Tk] = i++; } // add keywords to symbol table
// For each system call name from `open` to `exit`,
// call `next` to create symbol table entry,
// set the symbol table entry's symbol type field be `Sys`,
// set the symbol table entry's associated value type field be the system
// call's return type,
// set the symbol table entry's associated value field be the system call's
// opcode.
i = OPEN; while (i <= EXIT) { next(); id[Class] = Sys; id[Type] = INT; id[Val] = i++; } // add library to symbol table
// Create symbol table entry for `void`.
next(); id[Tk] = Char; // handle void type
// Create symbol table entry for `main`.
// Point `idmain` to the symbol table entry.
next(); idmain = id; // keep track of main
// Allocate source code buffer.
// If failed, print error and exit program.
if (!(lp = p = malloc(poolsz))) { printf("could not malloc(%d) source area\n", poolsz); return -1; }
// Read source code from source code file into source code buffer.
// If failed, print error and exit program.
if ((i = read(fd, p, poolsz-1)) <= 0) { printf("read() returned %d\n", i); return -1; }
// Close source code file.
close(fd);
// Add end maker `\0` after the source code in source code buffer.
p[i] = 0;
// If switch for printing source code line and corresponding instructions is
// on.
if (src) {
// Set `linemap`'s address be next 16-aligned address in the source code
// buffer.
linemap = (char **)(((int)(p + i + 1) & 0xffffff00) + 0x100);
// Set `srcmap`'s address.
srcmap = text + (poolsz / 8);
}
// parse declarations
line = 1;
// Read token.
next();
// While current token is not input end.
while (tk) {
// Set result value type.
bt = INT; // basetype
// If current token is `int`, read token.
if (tk == Int) next();
// If current token is `char`, read token, set result value type be `CHAR`.
else if (tk == Char) { next(); bt = CHAR; }
// If current token is `enum`, it is enum definition.
else if (tk == Enum) {
// Read token.
next();
// If current token is not `{`, it means having enum type name.
// Skip the enum type name.
if (tk != '{') next();
// If current token is `{`.
if (tk == '{') {
// Read token.
next();
// Enum value starts from 0.
i = 0;
// While current token is not `}`
while (tk != '}') {
// Current token should be enum name.
// If current token is not identifier, print error and exit program.
if (tk != Id) { printf("%d: bad enum identifier %d\n", line, tk); return -1; }
// Read token.
next();
// If current token is assignment operator.
if (tk == Assign) {
// Read token.
next();