-
Notifications
You must be signed in to change notification settings - Fork 15
/
exe.c
2100 lines (1777 loc) · 62.2 KB
/
exe.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
// common part of machine code generators
const int word_size;
void generate_exe();
// 1MB heap
#define RT_HEAP_SIZE 104857600
#define MAX_CODE_SIZE 500000
int code[MAX_CODE_SIZE];
int code_alloc = 0;
void emit_i8(int a) {
if (code_alloc >= MAX_CODE_SIZE) {
fatal_error("code buffer overflow");
}
code[code_alloc] = (a & 0xff);
code_alloc += 1;
}
void emit_2_i8(int a, int b) {
emit_i8(a);
emit_i8(b);
}
void emit_4_i8(int a, int b, int c, int d) {
emit_2_i8(a, b);
emit_2_i8(c, d);
}
void emit_i32_le(int n) {
emit_4_i8(n, n >> 8, n >> 16, n >> 24);
}
void emit_i64_le(int n) {
emit_i32_le(n);
// Sign extend to 64 bits. Arithmetic shift by 31 gives -1 for negative numbers and 0 for positive numbers.
emit_i32_le(n >> 31);
}
void emit_word_le(int n) {
if (word_size == 4) {
emit_i32_le(n);
} else if (word_size == 8) {
emit_i64_le(n);
} else {
fatal_error("emit_word_le: unknown word size");
}
}
void write_i8(int n) {
putchar(n & 0xff);
}
void write_2_i8(int a, int b) {
write_i8(a);
write_i8(b);
}
void write_4_i8(int a, int b, int c, int d) {
write_2_i8(a, b);
write_2_i8(c, d);
}
void write_i32_le(int n) {
write_4_i8(n, n >> 8, n >> 16, n >> 24);
}
// If the main function returns a value
bool main_returns = false;
// Environment tracking
#include "env.c"
void grow_fs(int words) {
cgc_fs += words;
}
const int char_width = 1;
const int reg_X;
const int reg_Y;
const int reg_Z;
const int reg_SP;
const int reg_glo;
void mov_reg_imm(int dst, int imm);
void mov_reg_reg(int dst, int src);
void mov_mem_reg(int base, int offset, int src);
void mov_mem8_reg(int base, int offset, int src);
void mov_reg_mem(int dst, int base, int offset);
void mov_reg_mem8(int dst, int base, int offset);
void add_reg_imm(int dst, int imm);
void add_reg_reg(int dst, int src);
void or_reg_reg (int dst, int src);
void and_reg_reg(int dst, int src);
void sub_reg_reg(int dst, int src);
void xor_reg_reg(int dst, int src);
void mul_reg_reg(int dst, int src);
void div_reg_reg(int dst, int src);
void rem_reg_reg(int dst, int src);
void shl_reg_reg(int dst, int src);
void sar_reg_reg(int dst, int src);
void push_reg(int src);
void pop_reg (int dst);
void jump(int lbl);
void jump_rel(int offset);
void call(int lbl);
void ret();
void dup(int reg) {
pop_reg(reg);
push_reg(reg);
push_reg(reg);
grow_fs(1);
}
void load_mem_location(int dst, int base, int offset, int width) {
if (width == 1) {
mov_reg_mem8(dst, base, offset);
} else if (width == word_size) {
mov_reg_mem(dst, base, offset);
} else {
fatal_error("load_mem_location: unknown width");
}
}
// Write a value from a register to a memory location
void write_mem_location(int base, int offset, int src, int width) {
if (width == 1) {
mov_mem8_reg(base, offset, src);
} else if (width == word_size) {
mov_mem_reg(base, offset, src);
} else {
fatal_error("write_mem_location: unknown width");
}
}
void copy_obj(int dst_base, int dst_offset, int src_base, int src_offset, int width) {
int i;
// move the words
for (i = 0; i < width / word_size; i += 1) {
mov_reg_mem(reg_Z, src_base, src_offset + i * word_size);
mov_mem_reg(dst_base, dst_offset + i * word_size, reg_Z);
}
// then move the remaining bytes
for (i = width - width % word_size; i < width; i += 1) {
mov_reg_mem8(reg_Z, src_base, src_offset + i);
mov_mem8_reg(dst_base, dst_offset + i, reg_Z);
}
}
int is_power_of_2(int n) {
return n != 0 && (n & (n - 1)) == 0;
}
int power_of_2_log(int n) {
int i = 0;
while (n > 1) {
n /= 2;
i += 1;
}
return i;
}
void mul_for_pointer_arith(int reg, int type_width) {
int other_reg = reg == reg_X ? reg_Y : reg_X;
if (type_width == 1) return;
if (is_power_of_2(type_width)) {
while (type_width > 1) {
type_width /= 2;
add_reg_reg(reg, reg);
}
} else {
push_reg(other_reg);
mov_reg_imm(other_reg, type_width);
mul_reg_reg(reg, other_reg);
pop_reg(other_reg);
}
}
void div_for_pointer_arith(int reg, int type_width) {
int reg_start = reg;
if (type_width == 1) return;
if (is_power_of_2(type_width)) {
// sar_reg_reg does not work with reg_Y, so we need to shift the value to reg_X
if (reg_start != reg_X) {
push_reg(reg_X); // Save reg_X
mov_reg_reg(reg_X, reg_start); // Move the value to reg_X
reg = reg_X;
} else {
push_reg(reg_Y); // Otherwise we still clobber reg_Y so save it
}
// At this point, reg is always reg_X, and reg_Y is free
mov_reg_imm(reg_Y, power_of_2_log(type_width));
sar_reg_reg(reg_X, reg_Y);
// Now reg_X contains the result, and we move it back in reg_start if needed
if (reg_start != reg_X) {
mov_reg_reg(reg_start, reg_X);
pop_reg(reg_X);
} else {
pop_reg(reg_Y); // Otherwise, we still need to restore reg_Y
}
} else {
// div_reg_reg only works with reg_X on certain architectures, so we need to save it
if (reg_start != reg_X) {
push_reg(reg_X);
reg = reg_X;
} else {
push_reg(reg_Y);
}
mov_reg_imm(reg_Y, type_width);
div_reg_reg(reg_X, reg_Y);
if (reg_start != reg_X) {
mov_reg_reg(reg_start, reg_X);
pop_reg(reg_X);
} else {
pop_reg(reg_Y);
}
}
}
const int EQ; // x == y
const int NE; // x != y
const int LT; // x < y
const int GE; // x >= y
const int LE; // x <= y
const int GT; // x > y
void jump_cond_reg_reg(int cond, int lbl, int reg1, int reg2);
void os_getchar();
void os_putchar();
void os_exit();
void os_fopen();
void os_fclose();
void os_fgetc();
void os_allocate_memory(int size);
void os_read();
void os_write();
void os_open();
void os_close();
void setup_proc_args(int global_vars_size);
#define cgc int
int setup_lbl;
int init_start_lbl;
int init_next_lbl;
int main_lbl;
int exit_lbl;
int getchar_lbl;
int putchar_lbl;
int fopen_lbl;
int fclose_lbl;
int fgetc_lbl;
int malloc_lbl;
int free_lbl;
int printf_lbl; // Stub
int read_lbl;
int write_lbl;
int open_lbl;
int close_lbl;
int round_up_to_word_size(int n) {
return (n + word_size - 1) / word_size * word_size;
}
void grow_stack(int words) {
add_reg_imm(reg_SP, -words * word_size);
}
// Like grow_stack, but takes bytes instead of words.
// To maintain alignment, the stack is grown by a multiple of word_size (rounded
// up from the number of bytes).
void grow_stack_bytes(int bytes) {
add_reg_imm(reg_SP, -round_up_to_word_size(bytes));
}
// Label definition
enum {
GENERIC_LABEL,
GOTO_LABEL,
};
int alloc_label() {
int lbl = alloc_obj(2);
heap[lbl] = GENERIC_LABEL;
heap[lbl + 1] = 0; // Address of label
return lbl;
}
int alloc_goto_label() {
int lbl = alloc_obj(3);
heap[lbl] = GOTO_LABEL;
heap[lbl + 1] = 0; // Address of label
heap[lbl + 2] = 0; // cgc-fs of label
return lbl;
}
void use_label(int lbl) {
int addr = heap[lbl + 1];
if (heap[lbl] != GENERIC_LABEL) fatal_error("use_label expects generic label");
if (addr < 0) {
// label address is currently known
addr = -addr - (code_alloc + 4); // compute relative address
emit_i32_le(addr);
} else {
// label address is not yet known
emit_i32_le(0); // 32 bit placeholder for distance
code[code_alloc-1] = addr; // chain with previous patch address
heap[lbl + 1] = code_alloc;
}
}
void def_label(int lbl) {
int addr = heap[lbl + 1];
int label_addr = code_alloc;
int next;
if (heap[lbl] != GENERIC_LABEL) fatal_error("def_label expects generic label");
if (addr < 0) {
fatal_error("label defined more than once");
} else {
heap[lbl + 1] = -label_addr; // define label's address
while (addr != 0) {
next = code[addr-1]; // get pointer to next patch address
code_alloc = addr;
addr = label_addr - addr; // compute relative address
code_alloc -= 4;
emit_i32_le(addr);
addr = next;
}
code_alloc = label_addr;
}
}
// Similar to use_label, but for gotos.
// The main difference is that it adjusts the stack and jumps, as opposed to
// simply emitting the address.
void jump_to_goto_label(int lbl) {
int addr = heap[lbl + 1];
int lbl_fs = heap[lbl + 2];
int start_code_alloc = code_alloc;
if (heap[lbl] != GOTO_LABEL) fatal_error("jump_to_goto_label expects goto label");
if (addr < 0) {
// label address is currently known
grow_stack(lbl_fs - cgc_fs);
start_code_alloc = code_alloc;
jump_rel(0); // Generate dummy jump instruction to get instruction length
addr = -addr - code_alloc; // compute relative address
code_alloc = start_code_alloc;
jump_rel(addr);
} else {
// label address is not yet known
// placeholders for when we know the destination address and frame size
grow_stack(0);
jump_rel(0);
code[code_alloc-1] = addr; // chain with previous patch address
code[code_alloc-2] = cgc_fs; // save current frame size
code[code_alloc-3] = start_code_alloc; // track initial code alloc so we can come back
heap[lbl + 1] = code_alloc;
}
}
void def_goto_label(int lbl) {
int addr = heap[lbl + 1];
int label_addr = code_alloc;
int next;
int goto_fs;
int start_code_alloc;
if (heap[lbl] != GOTO_LABEL) fatal_error("def_goto_label expects goto label");
if (addr < 0) {
fatal_error("goto label defined more than once");
} else {
heap[lbl + 1] = -label_addr; // define label's address
heap[lbl + 2] = cgc_fs; // define label's frame size
while (addr != 0) {
next = code[addr-1]; // get pointer to next patch address
goto_fs = code[addr-2]; // get frame size at goto instruction
code_alloc = code[addr-3]; // reset code pointer to start of jump_to_goto_label instruction
grow_stack(cgc_fs - goto_fs); // adjust stack
start_code_alloc = code_alloc;
jump_rel(0); // Generate dummy jump instruction to get instruction length
addr = label_addr - code_alloc; // compute relative address
code_alloc = start_code_alloc;
jump_rel(addr);
addr = next;
}
code_alloc = label_addr;
}
}
// Type, structure and union handling
int type_width_ast(ast type, bool array_value, bool word_align);
int struct_union_size(ast struct_type);
// A pointer type is either an array type or a type with at least one star
bool is_pointer_type(ast type) {
bool op = get_op(type);
bool stars = get_val(type);
return op == '[' || stars > 0;
}
bool is_struct_or_union_type(ast type) {
int op = get_op(type);
return op == STRUCT_KW || op == UNION_KW;
}
// An aggregate type is either an array type or a struct/union type (that's not a reference)
bool is_aggregate_type(ast type) {
if ((is_struct_or_union_type(type) && get_val(type) == 0) || get_op(type) == '[') {
return true;
} else {
return false;
}
}
bool is_type(ast type) {
switch (get_op(type)) {
case INT_KW:
case CHAR_KW:
case VOID_KW:
case STRUCT_KW:
case UNION_KW:
case ENUM_KW:
case '[':
return true;
default:
return false;
}
}
bool is_not_pointer_type(ast type) {
return !is_pointer_type(type);
}
// Size an object of the given type would occupy in memory (in bytes).
// If array_value is true, the size of the array is returned, otherwise the
// size of the pointer is returned.
// If word_align is true, the size is rounded up to the word size.
int type_width(ast type, int stars, bool array_value, bool word_align) {
// All types have the same shape (kw, stars, ...) except for arrays so we
// handle array types separately.
if (get_op(type) == '[') {
// In certain contexts, we want to know the static size of the array (i.e.
// sizeof, in struct definitions, etc.) while in other contexts we care
// about the pointer (i.e. when passing an array to a function, etc.)
if (array_value) {
return round_up_to_word_size(get_val(get_child(type, 0)) * type_width_ast(get_child(type, 1), true, false));
} else {
return word_size; // Array is a pointer to the first element
}
} else if (stars) {
return word_size; // Pointer
}
// Basic type kw
switch (get_op(type)) {
case CHAR_KW:
return word_align ? word_size : char_width;
case STRUCT_KW:
case UNION_KW:
return struct_union_size(type);
case VOID_KW:
fatal_error("type_width_ast: void type");
return 0;
default:
return word_size;
}
}
int type_width_ast(ast type, bool array_value, bool word_align) {
return type_width(type, get_val(type), array_value, word_align);
}
// Structs, enums and unions types come in 2 variants:
// - definition: the type contains the members of the struct/enum/union
// - reference: the type reference an already declared struct/enum/union and doesn't contain the members.
//
// We mostly want to work with type definitions, and not type references so
// this function returns the type definition when passed a type reference.
ast canonicalize_type(ast type) {
ast res = type;
int binding;
if (get_op(type) == STRUCT_KW && get_child(type, 2) == 0) { // struct with empty def => reference
binding = cgc_lookup_struct(get_val(get_child(type, 1)), cgc_globals);
if (binding == 0) fatal_error("canonicalize_type: struct type not defined");
res = heap[binding+3];
if (get_val(type) != 0) { // Copy stars
res = clone_ast(res);
set_child(res, 0, get_child(type, 0));
}
} else if (get_op(type) == UNION_KW && get_child(type, 2) == 0) { // union with empty def => reference
binding = cgc_lookup_union(get_val(get_child(type, 1)), cgc_globals);
if (binding == 0) fatal_error("canonicalize_type: union type not defined");
res = heap[binding+3];
if (get_val(type) != 0) { // Copy stars
res = clone_ast(res);
set_child(res, 0, get_child(type, 0));
}
} else if (get_op(type) == ENUM_KW && get_child(type, 1) == 0) { // enum with empty def => reference
binding = cgc_lookup_enum(get_val(get_child(type, 0)), cgc_globals);
if (binding == 0) fatal_error("canonicalize_type: enum type not defined");
res = heap[binding+3];
if (get_val(type) != 0) { // Copy stars
res = clone_ast(res);
set_child(res, 0, get_child(type, 0));
}
}
return res;
}
// Size of a struct or union type, rounded up to the word size
int struct_union_size(ast type) {
ast members;
ast member_type;
int member_size;
int size = 0;
type = canonicalize_type(type);
members = get_child(type, 2);
switch (get_op(type)) {
case STRUCT_KW:
while (get_op(members) == ',') {
member_type = get_child(members, 1);
members = get_child(members, 2);
member_size = type_width_ast(member_type, true, true);
size += member_size;
}
break;
case UNION_KW:
while (get_op(members) == ',') {
member_type = get_child(members, 1);
members = get_child(members, 2);
member_size = type_width_ast(member_type, true, true);
// Union size is the max of its members
if (member_size > size) size = member_size;
}
break;
default:
fatal_error("struct_union_size: not a struct or union type");
}
return round_up_to_word_size(size);
}
// Find offset of struct member
int struct_member_offset_go(ast struct_type, ast member_ident) {
ast members = get_child(canonicalize_type(struct_type), 2);
int offset = 0;
int sub_offset;
ast ident;
while (get_op(members) == ',') {
ident = get_val(get_child(members, 0));
if (ident == 0) { // Anonymous struct member, search that struct
sub_offset = struct_member_offset_go(get_child(members, 1), member_ident);
if (sub_offset != -1) return offset + sub_offset;
} else if (get_val(member_ident) == get_val(get_child(members, 0))) {
return offset;
}
if (get_op(struct_type) == STRUCT_KW) {
// For unions, fields are always at offset 0. We must still iterate
// because the field may be in an anonymous struct.
offset += round_up_to_word_size(type_width_ast(get_child(members, 1), true, true));
}
members = get_child(members, 2);
}
return -1;
}
int struct_member_offset(ast struct_type, ast member_ident) {
int offset = struct_member_offset_go(struct_type, member_ident);
if (offset == -1) fatal_error("struct_member_offset: member not found");
return offset;
}
// Find a struct member
ast struct_member_go(ast struct_type, ast member_ident) {
ast members = get_child(canonicalize_type(struct_type), 2);
ast ident;
while (members != 0) {
ident = get_val(get_child(members, 0));
if (ident == 0) { // Anonymous struct member, search that struct
ident = struct_member_go(get_child(members, 1), member_ident);
if (ident != 0) return ident; // Found member in the anonymous struct
} else if (get_val(member_ident) == ident) {
return members;
}
members = get_child(members, 2);
}
return -1;
}
ast struct_member(ast struct_type, ast member_ident) {
ast member = struct_member_go(struct_type, member_ident);
if (member == -1) fatal_error("struct_member: member not found");
return member;
}
// Width of an object pointed to by a reference type.
int ref_type_width(ast type) {
if (get_op(type) == '[') {
return type_width_ast(get_child(type, 1), false, false); // size of inner type
} else if (get_val(type) == 1) { // pointer *
return type_width(type, 0, false, false); // size of inner type
} else {
return word_size;
}
}
ast int_type;
ast char_type;
ast string_type;
ast void_type;
ast void_star_type;
// Compute the type of an expression
ast value_type(ast node) {
int op = get_op(node);
int nb_children = get_nb_children(node);
int binding;
int ident;
ast left_type;
ast right_type;
if (nb_children == 0) {
if (op == INTEGER) {
return int_type;
} else if (op == CHARACTER) {
return char_type;
} else if (op == STRING) {
return string_type;
} else if (op == IDENTIFIER) {
ident = get_val(node);
binding = cgc_lookup_var(ident, cgc_locals);
if (binding != 0) {
return heap[binding+5];
} else {
binding = cgc_lookup_var(ident, cgc_globals);
if (binding != 0) {
return heap[binding+5];
} else {
binding = cgc_lookup_enum_value(ident, cgc_globals);
if (binding != 0) {
return int_type; // Enums are always integers
} else {
putstr("ident = ");
putstr(string_pool+get_val(ident));
putchar('\n');
fatal_error("value_type: identifier not found");
return -1;
}
}
}
} else {
putstr("op="); putint(op); putchar('\n');
fatal_error("value_type: unknown expression with nb_children == 0");
return -1;
}
} else if (nb_children == 1) {
if (op == '*') {
left_type = value_type(get_child(node, 0));
if (get_op(left_type) == '[') { // Array type
return get_child(left_type, 1);
} else if (get_val(left_type) != 0) { // Pointer type
left_type = clone_ast(left_type);
set_val(left_type, get_val(left_type) - 1); // one less indirection
return left_type;
} else {
putstr("left_type="); putint(left_type); putchar('\n');
fatal_error("pointer_width: non pointer is being dereferenced with *");
return -1;
}
} else if (op == '&') {
left_type = value_type(get_child(node, 0));
if (get_op(left_type) == '[') {
left_type = clone_ast(get_child(left_type, 1)); // Inner type
set_val(left_type, get_val(left_type) + 1); // Increment star by 2, to account for the [ we just removed
} else {
left_type = clone_ast(left_type);
set_val(left_type, get_val(left_type) + 1); // Increment star by 1
}
return left_type;
} else if (op == '+' || op == '-' || op == '~' || op == '!' || op == MINUS_MINUS || op == PLUS_PLUS || op == MINUS_MINUS_POST || op == PLUS_PLUS_POST || op == PLUS_PLUS_PRE || op == MINUS_MINUS_PRE || op == PARENS) {
// Unary operation don't change the type
return value_type(get_child(node, 0));
} else if (op == SIZEOF_KW) {
return int_type; // sizeof always returns an integer
} else {
putstr("op="); putint(op); putchar('\n');
fatal_error("value_type: unexpected operator");
return -1;
}
} else if (nb_children == 2) {
if (op == '+' || op == '-' || op == '*' || op == '/' || op == '%' || op == '&' || op == '|' || op == '^'
|| op == LSHIFT || op == RSHIFT || op == '<' || op == '>' || op == EQ_EQ || op == EXCL_EQ || op == LT_EQ || op == GT_EQ) {
left_type = value_type(get_child(node, 0));
right_type = value_type(get_child(node, 1));
if (is_pointer_type(left_type) && is_pointer_type(right_type) && op == '-') {
return int_type; // Pointer - Pointer = Integer
} else if (is_pointer_type(left_type)) {
// if left is an array or a pointer, the type is also a pointer
return left_type;
} else {
// if left is not a pointer, the type is the type of the right operand
return right_type;
}
} else if (op == ',') {
return value_type(get_child(node, 1)); // The type of the right operand
} else if (op == '[') {
left_type = value_type(get_child(node, 0));
right_type = value_type(get_child(node, 1));
if (get_op(left_type) == '[') { // Array
return get_child(left_type, 1); // array inner type
} else if (get_val(left_type) != 0) { // Pointer
left_type = clone_ast(left_type);
set_val(left_type, get_val(left_type) - 1); // one less indirection
return left_type;
} else if (get_op(right_type) == '[') { // Array, but with the operands flipped (i.e. 0[arr] instead of arr[0])
return get_child(right_type, 1); // array inner type
} else if (get_val(right_type) != 0) {
right_type = clone_ast(right_type);
set_val(right_type, get_val(right_type) - 1); // one less indirection
return right_type;
} else {
putstr("left_type="); putint(left_type); putchar('\n');
fatal_error("value_type: non pointer is being dereferenced with *");
return -1;
}
} else if (op == '=' || op == AMP_EQ || op == BAR_EQ || op == CARET_EQ || op == LSHIFT_EQ || op == MINUS_EQ || op == PERCENT_EQ || op == PLUS_EQ || op == RSHIFT_EQ || op == SLASH_EQ || op == STAR_EQ) {
return value_type(get_child(node, 0)); // Only the left side is relevant here
} else if (op == AMP_AMP || op == BAR_BAR) {
// TODO: Check that the operands have compatible types?
return value_type(get_child(node, 0));
} else if (op == '(') {
binding = cgc_lookup_fun(get_val(get_child(node, 0)), cgc_globals);
if (binding != 0) {
return heap[binding+5];
} else {
putstr("ident = ");
putstr(string_pool + get_val(get_val(get_child(node, 0))));
putchar('\n');
fatal_error("value_type: function not found");
return -1;
}
} else if (op == '.') {
left_type = value_type(get_child(node, 0));
if (is_struct_or_union_type(left_type) && get_val(left_type) == 0) {
return get_child(struct_member(left_type, get_child(node, 1)), 1); // child 1 of member is the type
} else {
fatal_error("value_type: . operator on non-struct pointer type");
return -1;
}
} else if (op == ARROW) {
// Same as '.', but left_type must be a pointer
left_type = value_type(get_child(node, 0));
if (is_struct_or_union_type(left_type) && get_val(left_type) == 1) {
return get_child(struct_member(left_type, get_child(node, 1)), 1); // child 1 of member is the type
} else {
fatal_error("value_type: -> operator on non-struct pointer type");
return -1;
}
} else if (op == CAST) {
return get_child(node, 0);
} else {
fatal_error("value_type: unknown expression with 2 children");
return -1;
}
} else if (nb_children == 3) {
if (op == '?') {
// We assume that the 2 cases have the same type.
return value_type(get_child(node, 1));
} else {
putstr("op="); putint(op); putchar('\n');
fatal_error("value_type: unknown expression with 3 children");
return -1;
}
} else {
putstr("op="); putint(op); putchar('\n');
fatal_error("value_type: unknown expression with >4 children");
return -1;
}
}
void codegen_binop(int op, ast lhs, ast rhs) {
int lbl1;
int lbl2;
int cond = -1;
ast left_type = value_type(lhs);
ast right_type = value_type(rhs);
int width;
pop_reg(reg_Y); // rhs operand
pop_reg(reg_X); // lhs operand
if (op == '<') cond = LT;
else if (op == '>') cond = GT;
else if (op == EQ_EQ) cond = EQ;
else if (op == EXCL_EQ) cond = NE;
else if (op == LT_EQ) cond = LE;
else if (op == GT_EQ) cond = GE;
if (cond != -1) {
lbl1 = alloc_label();
lbl2 = alloc_label();
jump_cond_reg_reg(cond, lbl1, reg_X, reg_Y);
xor_reg_reg(reg_X, reg_X);
jump(lbl2);
def_label(lbl1);
mov_reg_imm(reg_X, 1);
def_label(lbl2);
} else {
if (op == '+' || op == PLUS_EQ || op == PLUS_PLUS_PRE || op == PLUS_PLUS_POST) {
// Check if one of the operands is a pointer
// If so, multiply the other operand by the width of the pointer target object.
if (is_pointer_type(left_type) && is_not_pointer_type(right_type)) {
mul_for_pointer_arith(reg_Y, ref_type_width(left_type));
}
if (is_pointer_type(right_type) && is_not_pointer_type(left_type)) {
mul_for_pointer_arith(reg_X, ref_type_width(right_type));
}
add_reg_reg(reg_X, reg_Y);
}
else if (op == '-' || op == MINUS_EQ || op == MINUS_MINUS_PRE || op == MINUS_MINUS_POST) {
// Pointer subtraction is only valid if one of the operands is a pointer
// When both operands are pointers, the result is the difference between the two pointers divided by the width of the target object.
// When one operand is a pointer and the other is an integer, the result is the pointer minus the integer times the width of the target object.
if (is_pointer_type(left_type) && is_pointer_type(right_type)) {
sub_reg_reg(reg_X, reg_Y);
div_for_pointer_arith(reg_X, ref_type_width(left_type));
} else if (is_pointer_type(left_type)) {
mul_for_pointer_arith(reg_Y, ref_type_width(left_type));
sub_reg_reg(reg_X, reg_Y);
} else if (is_pointer_type(right_type)) {
mul_for_pointer_arith(reg_X, ref_type_width(right_type));
sub_reg_reg(reg_X, reg_Y);
} else {
sub_reg_reg(reg_X, reg_Y);
}
}
else if (op == '*' || op == STAR_EQ) mul_reg_reg(reg_X, reg_Y);
else if (op == '/' || op == SLASH_EQ) div_reg_reg(reg_X, reg_Y);
else if (op == '%' || op == PERCENT_EQ) rem_reg_reg(reg_X, reg_Y);
else if (op == '&' || op == AMP_EQ) and_reg_reg(reg_X, reg_Y);
else if (op == '|' || op == BAR_EQ) or_reg_reg(reg_X, reg_Y);
else if (op == '^' || op == CARET_EQ) xor_reg_reg(reg_X, reg_Y);
else if (op == LSHIFT || op == LSHIFT_EQ) shl_reg_reg(reg_X, reg_Y);
else if (op == RSHIFT || op == RSHIFT_EQ) sar_reg_reg(reg_X, reg_Y);
else if (op == ',') mov_reg_reg(reg_X, reg_Y); // Ignore lhs and keep rhs
else if (op == '[') {
// Same as pointer addition for address calculation
if (is_pointer_type(left_type) && is_not_pointer_type(right_type)) {
mul_for_pointer_arith(reg_Y, ref_type_width(left_type));
width = ref_type_width(left_type);
} else if (is_pointer_type(right_type) && is_not_pointer_type(left_type)) {
mul_for_pointer_arith(reg_X, ref_type_width(right_type));
width = ref_type_width(right_type);
} else {
fatal_error("codegen_binop: invalid array access operands");
return;
}
add_reg_reg(reg_X, reg_Y);
load_mem_location(reg_X, reg_X, 0, width);
} else {
putstr("op="); putint(op); putchar('\n');
fatal_error("codegen_binop: unknown op");
}
}
push_reg(reg_X);
}
void codegen_rvalue(ast node);
void codegen_statement(ast node);
int codegen_lvalue(ast node);
int codegen_param(ast param) {
int type = value_type(param);
int left_width;
if (is_struct_or_union_type(type) && get_val(type) == 0) {
left_width = codegen_lvalue(param);
pop_reg(reg_X);
grow_fs(-1);
grow_stack_bytes(round_up_to_word_size(left_width));
grow_fs(round_up_to_word_size(left_width) / word_size);
copy_obj(reg_SP, 0, reg_X, 0, left_width);
} else {
codegen_rvalue(param);
}
return type_width_ast(type, false, true) / word_size;
}
int codegen_params(ast params) {
int fs = 0;
if (params != 0) {
if (get_op(params) == ',') {
fs = codegen_params(get_child(params, 1));
fs += codegen_param(get_child(params, 0));
} else {
fs = codegen_param(params);
}
}
return fs;
}
void codegen_call(ast node) {
ast fun = get_child(node, 0);
ast name = get_val(fun);
ast params = get_child(node, 1);
ast nb_params = codegen_params(params);
int binding = cgc_lookup_fun(name, cgc_globals);
int lbl;
if (binding == 0) {
lbl = alloc_label();
cgc_add_global_fun(name, lbl, 0);
binding = cgc_globals;
}
call(heap[binding+4]);
grow_stack(-nb_params);
grow_fs(-nb_params);
push_reg(reg_X);
}
void codegen_goto(ast node) {
ast label_ident = get_val(node);
int binding = cgc_lookup_goto_label(label_ident, cgc_locals_fun);
int goto_lbl;
if (binding == 0) {
goto_lbl = alloc_goto_label();
cgc_add_goto_label(label_ident, goto_lbl);
binding = cgc_locals_fun;
}