-
Notifications
You must be signed in to change notification settings - Fork 745
/
gen.c
1523 lines (1406 loc) · 40.6 KB
/
gen.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
// Copyright 2012 Rui Ueyama. Released under the MIT license.
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "8cc.h"
bool dumpstack = false;
bool dumpsource = true;
static char *REGS[] = {"rdi", "rsi", "rdx", "rcx", "r8", "r9"};
static char *SREGS[] = {"dil", "sil", "dl", "cl", "r8b", "r9b"};
static char *MREGS[] = {"edi", "esi", "edx", "ecx", "r8d", "r9d"};
static int TAB = 8;
static Vector *functions = &EMPTY_VECTOR;
static int stackpos;
static int numgp;
static int numfp;
static FILE *outputfp;
static Map *source_files = &EMPTY_MAP;
static Map *source_lines = &EMPTY_MAP;
static char *last_loc = "";
static void emit_addr(Node *node);
static void emit_expr(Node *node);
static void emit_decl_init(Vector *inits, int off, int totalsize);
static void do_emit_data(Vector *inits, int size, int off, int depth);
static void emit_data(Node *v, int off, int depth);
#define REGAREA_SIZE 176
#define emit(...) emitf(__LINE__, "\t" __VA_ARGS__)
#define emit_noindent(...) emitf(__LINE__, __VA_ARGS__)
#ifdef __GNUC__
#define SAVE \
int save_hook __attribute__((unused, cleanup(pop_function))); \
if (dumpstack) \
vec_push(functions, (void *)__func__);
static void pop_function(void *ignore) {
if (dumpstack)
vec_pop(functions);
}
#else
#define SAVE
#endif
static char *get_caller_list() {
Buffer *b = make_buffer();
for (int i = 0; i < vec_len(functions); i++) {
if (i > 0)
buf_printf(b, " -> ");
buf_printf(b, "%s", vec_get(functions, i));
}
buf_write(b, '\0');
return buf_body(b);
}
void set_output_file(FILE *fp) {
outputfp = fp;
}
void close_output_file() {
fclose(outputfp);
}
static void emitf(int line, char *fmt, ...) {
// Replace "#" with "%%" so that vfprintf prints out "#" as "%".
char buf[256];
int i = 0;
for (char *p = fmt; *p; p++) {
assert(i < sizeof(buf) - 3);
if (*p == '#') {
buf[i++] = '%';
buf[i++] = '%';
} else {
buf[i++] = *p;
}
}
buf[i] = '\0';
va_list args;
va_start(args, fmt);
int col = vfprintf(outputfp, buf, args);
va_end(args);
if (dumpstack) {
for (char *p = fmt; *p; p++)
if (*p == '\t')
col += TAB - 1;
int space = (28 - col) > 0 ? (30 - col) : 2;
fprintf(outputfp, "%*c %s:%d", space, '#', get_caller_list(), line);
}
fprintf(outputfp, "\n");
}
static void emit_nostack(char *fmt, ...) {
fprintf(outputfp, "\t");
va_list args;
va_start(args, fmt);
vfprintf(outputfp, fmt, args);
va_end(args);
fprintf(outputfp, "\n");
}
static char *get_int_reg(Type *ty, char r) {
assert(r == 'a' || r == 'c');
switch (ty->size) {
case 1: return (r == 'a') ? "al" : "cl";
case 2: return (r == 'a') ? "ax" : "cx";
case 4: return (r == 'a') ? "eax" : "ecx";
case 8: return (r == 'a') ? "rax" : "rcx";
default:
error("Unknown data size: %s: %d", ty2s(ty), ty->size);
}
}
static char *get_load_inst(Type *ty) {
switch (ty->size) {
case 1: return "movsbq";
case 2: return "movswq";
case 4: return "movslq";
case 8: return "mov";
default:
error("Unknown data size: %s: %d", ty2s(ty), ty->size);
}
}
static int align(int n, int m) {
int rem = n % m;
return (rem == 0) ? n : n - rem + m;
}
static void push_xmm(int reg) {
SAVE;
emit("sub $8, #rsp");
emit("movsd #xmm%d, (#rsp)", reg);
stackpos += 8;
}
static void pop_xmm(int reg) {
SAVE;
emit("movsd (#rsp), #xmm%d", reg);
emit("add $8, #rsp");
stackpos -= 8;
assert(stackpos >= 0);
}
static void push(char *reg) {
SAVE;
emit("push #%s", reg);
stackpos += 8;
}
static void pop(char *reg) {
SAVE;
emit("pop #%s", reg);
stackpos -= 8;
assert(stackpos >= 0);
}
static int push_struct(int size) {
SAVE;
int aligned = align(size, 8);
emit("sub $%d, #rsp", aligned);
emit("mov #rcx, -8(#rsp)");
emit("mov #r11, -16(#rsp)");
emit("mov #rax, #rcx");
int i = 0;
for (; i < size; i += 8) {
emit("movq %d(#rcx), #r11", i);
emit("mov #r11, %d(#rsp)", i);
}
for (; i < size; i += 4) {
emit("movl %d(#rcx), #r11", i);
emit("movl #r11d, %d(#rsp)", i);
}
for (; i < size; i++) {
emit("movb %d(#rcx), #r11", i);
emit("movb #r11b, %d(#rsp)", i);
}
emit("mov -8(#rsp), #rcx");
emit("mov -16(#rsp), #r11");
stackpos += aligned;
return aligned;
}
static void maybe_emit_bitshift_load(Type *ty) {
SAVE;
if (ty->bitsize <= 0)
return;
emit("shr $%d, #rax", ty->bitoff);
push("rcx");
emit("mov $0x%lx, #rcx", (1 << (long)ty->bitsize) - 1);
emit("and #rcx, #rax");
pop("rcx");
}
static void maybe_emit_bitshift_save(Type *ty, char *addr) {
SAVE;
if (ty->bitsize <= 0)
return;
push("rcx");
push("rdi");
emit("mov $0x%lx, #rdi", (1 << (long)ty->bitsize) - 1);
emit("and #rdi, #rax");
emit("shl $%d, #rax", ty->bitoff);
emit("mov %s, #%s", addr, get_int_reg(ty, 'c'));
emit("mov $0x%lx, #rdi", ~(((1 << (long)ty->bitsize) - 1) << ty->bitoff));
emit("and #rdi, #rcx");
emit("or #rcx, #rax");
pop("rdi");
pop("rcx");
}
static void emit_gload(Type *ty, char *label, int off) {
SAVE;
if (ty->kind == KIND_ARRAY) {
if (off)
emit("lea %s+%d(#rip), #rax", label, off);
else
emit("lea %s(#rip), #rax", label);
return;
}
char *inst = get_load_inst(ty);
emit("%s %s+%d(#rip), #rax", inst, label, off);
maybe_emit_bitshift_load(ty);
}
static void emit_intcast(Type *ty) {
switch(ty->kind) {
case KIND_BOOL:
case KIND_CHAR:
ty->usig ? emit("movzbq #al, #rax") : emit("movsbq #al, #rax");
return;
case KIND_SHORT:
ty->usig ? emit("movzwq #ax, #rax") : emit("movswq #ax, #rax");
return;
case KIND_INT:
ty->usig ? emit("mov #eax, #eax") : emit("cltq");
return;
case KIND_LONG:
case KIND_LLONG:
return;
}
}
static void emit_toint(Type *ty) {
SAVE;
if (ty->kind == KIND_FLOAT)
emit("cvttss2si #xmm0, #eax");
else if (ty->kind == KIND_DOUBLE)
emit("cvttsd2si #xmm0, #eax");
}
static void emit_lload(Type *ty, char *base, int off) {
SAVE;
if (ty->kind == KIND_ARRAY) {
emit("lea %d(#%s), #rax", off, base);
} else if (ty->kind == KIND_FLOAT) {
emit("movss %d(#%s), #xmm0", off, base);
} else if (ty->kind == KIND_DOUBLE || ty->kind == KIND_LDOUBLE) {
emit("movsd %d(#%s), #xmm0", off, base);
} else {
char *inst = get_load_inst(ty);
emit("%s %d(#%s), #rax", inst, off, base);
maybe_emit_bitshift_load(ty);
}
}
static void maybe_convert_bool(Type *ty) {
if (ty->kind == KIND_BOOL) {
emit("test #rax, #rax");
emit("setne #al");
}
}
static void emit_gsave(char *varname, Type *ty, int off) {
SAVE;
assert(ty->kind != KIND_ARRAY);
maybe_convert_bool(ty);
char *reg = get_int_reg(ty, 'a');
char *addr = format("%s+%d(%%rip)", varname, off);
maybe_emit_bitshift_save(ty, addr);
emit("mov #%s, %s", reg, addr);
}
static void emit_lsave(Type *ty, int off) {
SAVE;
if (ty->kind == KIND_FLOAT) {
emit("movss #xmm0, %d(#rbp)", off);
} else if (ty->kind == KIND_DOUBLE) {
emit("movsd #xmm0, %d(#rbp)", off);
} else {
maybe_convert_bool(ty);
char *reg = get_int_reg(ty, 'a');
char *addr = format("%d(%%rbp)", off);
maybe_emit_bitshift_save(ty, addr);
emit("mov #%s, %s", reg, addr);
}
}
static void do_emit_assign_deref(Type *ty, int off) {
SAVE;
emit("mov (#rsp), #rcx");
char *reg = get_int_reg(ty, 'c');
if (off)
emit("mov #%s, %d(#rax)", reg, off);
else
emit("mov #%s, (#rax)", reg);
pop("rax");
}
static void emit_assign_deref(Node *var) {
SAVE;
push("rax");
emit_expr(var->operand);
do_emit_assign_deref(var->operand->ty->ptr, 0);
}
static void emit_pointer_arith(char kind, Node *left, Node *right) {
SAVE;
emit_expr(left);
push("rcx");
push("rax");
emit_expr(right);
int size = left->ty->ptr->size;
if (size > 1)
emit("imul $%d, #rax", size);
emit("mov #rax, #rcx");
pop("rax");
switch (kind) {
case '+': emit("add #rcx, #rax"); break;
case '-': emit("sub #rcx, #rax"); break;
default: error("invalid operator '%d'", kind);
}
pop("rcx");
}
static void emit_zero_filler(int start, int end) {
SAVE;
for (; start <= end - 4; start += 4)
emit("movl $0, %d(#rbp)", start);
for (; start < end; start++)
emit("movb $0, %d(#rbp)", start);
}
static void ensure_lvar_init(Node *node) {
SAVE;
assert(node->kind == AST_LVAR);
if (node->lvarinit)
emit_decl_init(node->lvarinit, node->loff, node->ty->size);
node->lvarinit = NULL;
}
static void emit_assign_struct_ref(Node *struc, Type *field, int off) {
SAVE;
switch (struc->kind) {
case AST_LVAR:
ensure_lvar_init(struc);
emit_lsave(field, struc->loff + field->offset + off);
break;
case AST_GVAR:
emit_gsave(struc->glabel, field, field->offset + off);
break;
case AST_STRUCT_REF:
emit_assign_struct_ref(struc->struc, field, off + struc->ty->offset);
break;
case AST_DEREF:
push("rax");
emit_expr(struc->operand);
do_emit_assign_deref(field, field->offset + off);
break;
default:
error("internal error: %s", node2s(struc));
}
}
static void emit_load_struct_ref(Node *struc, Type *field, int off) {
SAVE;
switch (struc->kind) {
case AST_LVAR:
ensure_lvar_init(struc);
emit_lload(field, "rbp", struc->loff + field->offset + off);
break;
case AST_GVAR:
emit_gload(field, struc->glabel, field->offset + off);
break;
case AST_STRUCT_REF:
emit_load_struct_ref(struc->struc, field, struc->ty->offset + off);
break;
case AST_DEREF:
emit_expr(struc->operand);
emit_lload(field, "rax", field->offset + off);
break;
default:
error("internal error: %s", node2s(struc));
}
}
static void emit_store(Node *var) {
SAVE;
switch (var->kind) {
case AST_DEREF: emit_assign_deref(var); break;
case AST_STRUCT_REF: emit_assign_struct_ref(var->struc, var->ty, 0); break;
case AST_LVAR:
ensure_lvar_init(var);
emit_lsave(var->ty, var->loff);
break;
case AST_GVAR: emit_gsave(var->glabel, var->ty, 0); break;
default: error("internal error");
}
}
static void emit_to_bool(Type *ty) {
SAVE;
if (is_flotype(ty)) {
push_xmm(1);
emit("xorpd #xmm1, #xmm1");
emit("%s #xmm1, #xmm0", (ty->kind == KIND_FLOAT) ? "ucomiss" : "ucomisd");
emit("setne #al");
pop_xmm(1);
} else {
emit("cmp $0, #rax");
emit("setne #al");
}
emit("movzb #al, #eax");
}
static void emit_comp(char *inst, char *usiginst, Node *node) {
SAVE;
if (is_flotype(node->left->ty)) {
emit_expr(node->left);
push_xmm(0);
emit_expr(node->right);
pop_xmm(1);
if (node->left->ty->kind == KIND_FLOAT)
emit("ucomiss #xmm0, #xmm1");
else
emit("ucomisd #xmm0, #xmm1");
} else {
emit_expr(node->left);
push("rax");
emit_expr(node->right);
pop("rcx");
int kind = node->left->ty->kind;
if (kind == KIND_LONG || kind == KIND_LLONG)
emit("cmp #rax, #rcx");
else
emit("cmp #eax, #ecx");
}
if (is_flotype(node->left->ty) || node->left->ty->usig)
emit("%s #al", usiginst);
else
emit("%s #al", inst);
emit("movzb #al, #eax");
}
static void emit_binop_int_arith(Node *node) {
SAVE;
char *op = NULL;
switch (node->kind) {
case '+': op = "add"; break;
case '-': op = "sub"; break;
case '*': op = "imul"; break;
case '^': op = "xor"; break;
case OP_SAL: op = "sal"; break;
case OP_SAR: op = "sar"; break;
case OP_SHR: op = "shr"; break;
case '/': case '%': break;
default: error("invalid operator '%d'", node->kind);
}
emit_expr(node->left);
push("rax");
emit_expr(node->right);
emit("mov #rax, #rcx");
pop("rax");
if (node->kind == '/' || node->kind == '%') {
if (node->ty->usig) {
emit("xor #edx, #edx");
emit("div #rcx");
} else {
emit("cqto");
emit("idiv #rcx");
}
if (node->kind == '%')
emit("mov #edx, #eax");
} else if (node->kind == OP_SAL || node->kind == OP_SAR || node->kind == OP_SHR) {
emit("%s #cl, #%s", op, get_int_reg(node->left->ty, 'a'));
} else {
emit("%s #rcx, #rax", op);
}
}
static void emit_binop_float_arith(Node *node) {
SAVE;
char *op;
bool isdouble = (node->ty->kind == KIND_DOUBLE);
switch (node->kind) {
case '+': op = (isdouble ? "addsd" : "addss"); break;
case '-': op = (isdouble ? "subsd" : "subss"); break;
case '*': op = (isdouble ? "mulsd" : "mulss"); break;
case '/': op = (isdouble ? "divsd" : "divss"); break;
default: error("invalid operator '%d'", node->kind);
}
emit_expr(node->left);
push_xmm(0);
emit_expr(node->right);
emit("%s #xmm0, #xmm1", (isdouble ? "movsd" : "movss"));
pop_xmm(0);
emit("%s #xmm1, #xmm0", op);
}
static void emit_load_convert(Type *to, Type *from) {
SAVE;
if (is_inttype(from) && to->kind == KIND_FLOAT)
emit("cvtsi2ss #eax, #xmm0");
else if (is_inttype(from) && to->kind == KIND_DOUBLE)
emit("cvtsi2sd #eax, #xmm0");
else if (from->kind == KIND_FLOAT && to->kind == KIND_DOUBLE)
emit("cvtps2pd #xmm0, #xmm0");
else if ((from->kind == KIND_DOUBLE || from->kind == KIND_LDOUBLE) && to->kind == KIND_FLOAT)
emit("cvtpd2ps #xmm0, #xmm0");
else if (to->kind == KIND_BOOL)
emit_to_bool(from);
else if (is_inttype(from) && is_inttype(to))
emit_intcast(from);
else if (is_inttype(to))
emit_toint(from);
}
static void emit_ret() {
SAVE;
emit("leave");
emit("ret");
}
static void emit_binop(Node *node) {
SAVE;
if (node->ty->kind == KIND_PTR) {
emit_pointer_arith(node->kind, node->left, node->right);
return;
}
switch (node->kind) {
case '<': emit_comp("setl", "setb", node); return;
case OP_EQ: emit_comp("sete", "sete", node); return;
case OP_LE: emit_comp("setle", "setna", node); return;
case OP_NE: emit_comp("setne", "setne", node); return;
}
if (is_inttype(node->ty))
emit_binop_int_arith(node);
else if (is_flotype(node->ty))
emit_binop_float_arith(node);
else
error("internal error: %s", node2s(node));
}
static void emit_save_literal(Node *node, Type *totype, int off) {
switch (totype->kind) {
case KIND_BOOL: emit("movb $%d, %d(#rbp)", !!node->ival, off); break;
case KIND_CHAR: emit("movb $%d, %d(#rbp)", node->ival, off); break;
case KIND_SHORT: emit("movw $%d, %d(#rbp)", node->ival, off); break;
case KIND_INT: emit("movl $%d, %d(#rbp)", node->ival, off); break;
case KIND_LONG:
case KIND_LLONG:
case KIND_PTR: {
emit("movl $%lu, %d(#rbp)", ((uint64_t)node->ival) & ((1L << 32) - 1), off);
emit("movl $%lu, %d(#rbp)", ((uint64_t)node->ival) >> 32, off + 4);
break;
}
case KIND_FLOAT: {
float fval = node->fval;
emit("movl $%u, %d(#rbp)", *(uint32_t *)&fval, off);
break;
}
case KIND_DOUBLE:
case KIND_LDOUBLE: {
emit("movl $%lu, %d(#rbp)", *(uint64_t *)&node->fval & ((1L << 32) - 1), off);
emit("movl $%lu, %d(#rbp)", *(uint64_t *)&node->fval >> 32, off + 4);
break;
}
default:
error("internal error: <%s> <%s> <%d>", node2s(node), ty2s(totype), off);
}
}
static void emit_addr(Node *node) {
switch (node->kind) {
case AST_LVAR:
ensure_lvar_init(node);
emit("lea %d(#rbp), #rax", node->loff);
break;
case AST_GVAR:
emit("lea %s(#rip), #rax", node->glabel);
break;
case AST_DEREF:
emit_expr(node->operand);
break;
case AST_STRUCT_REF:
emit_addr(node->struc);
emit("add $%d, #rax", node->ty->offset);
break;
case AST_FUNCDESG:
emit("lea %s(#rip), #rax", node->fname);
break;
default:
error("internal error: %s", node2s(node));
}
}
static void emit_copy_struct(Node *left, Node *right) {
push("rcx");
push("r11");
emit_addr(right);
emit("mov #rax, #rcx");
emit_addr(left);
int i = 0;
for (; i < left->ty->size; i += 8) {
emit("movq %d(#rcx), #r11", i);
emit("movq #r11, %d(#rax)", i);
}
for (; i < left->ty->size; i += 4) {
emit("movl %d(#rcx), #r11", i);
emit("movl #r11, %d(#rax)", i);
}
for (; i < left->ty->size; i++) {
emit("movb %d(#rcx), #r11", i);
emit("movb #r11, %d(#rax)", i);
}
pop("r11");
pop("rcx");
}
static int cmpinit(const void *x, const void *y) {
Node *a = *(Node **)x;
Node *b = *(Node **)y;
return a->initoff - b->initoff;
}
static void emit_fill_holes(Vector *inits, int off, int totalsize) {
// If at least one of the fields in a variable are initialized,
// unspecified fields has to be initialized with 0.
int len = vec_len(inits);
Node **buf = malloc(len * sizeof(Node *));
for (int i = 0; i < len; i++)
buf[i] = vec_get(inits, i);
qsort(buf, len, sizeof(Node *), cmpinit);
int lastend = 0;
for (int i = 0; i < len; i++) {
Node *node = buf[i];
if (lastend < node->initoff)
emit_zero_filler(lastend + off, node->initoff + off);
lastend = node->initoff + node->totype->size;
}
emit_zero_filler(lastend + off, totalsize + off);
}
static void emit_decl_init(Vector *inits, int off, int totalsize) {
emit_fill_holes(inits, off, totalsize);
for (int i = 0; i < vec_len(inits); i++) {
Node *node = vec_get(inits, i);
assert(node->kind == AST_INIT);
bool isbitfield = (node->totype->bitsize > 0);
if (node->initval->kind == AST_LITERAL && !isbitfield) {
emit_save_literal(node->initval, node->totype, node->initoff + off);
} else {
emit_expr(node->initval);
emit_lsave(node->totype, node->initoff + off);
}
}
}
static void emit_pre_inc_dec(Node *node, char *op) {
emit_expr(node->operand);
emit("%s $%d, #rax", op, node->ty->ptr ? node->ty->ptr->size : 1);
emit_store(node->operand);
}
static void emit_post_inc_dec(Node *node, char *op) {
SAVE;
emit_expr(node->operand);
push("rax");
emit("%s $%d, #rax", op, node->ty->ptr ? node->ty->ptr->size : 1);
emit_store(node->operand);
pop("rax");
}
static void set_reg_nums(Vector *args) {
numgp = numfp = 0;
for (int i = 0; i < vec_len(args); i++) {
Node *arg = vec_get(args, i);
if (is_flotype(arg->ty))
numfp++;
else
numgp++;
}
}
static void emit_je(char *label) {
emit("test #rax, #rax");
emit("je %s", label);
}
static void emit_label(char *label) {
emit("%s:", label);
}
static void emit_jmp(char *label) {
emit("jmp %s", label);
}
static void emit_literal(Node *node) {
SAVE;
switch (node->ty->kind) {
case KIND_BOOL:
case KIND_CHAR:
case KIND_SHORT:
emit("mov $%u, #rax", node->ival);
break;
case KIND_INT:
emit("mov $%u, #rax", node->ival);
break;
case KIND_LONG:
case KIND_LLONG: {
emit("mov $%lu, #rax", node->ival);
break;
}
case KIND_FLOAT: {
if (!node->flabel) {
node->flabel = make_label();
float fval = node->fval;
emit_noindent(".data");
emit_label(node->flabel);
emit(".long %d", *(uint32_t *)&fval);
emit_noindent(".text");
}
emit("movss %s(#rip), #xmm0", node->flabel);
break;
}
case KIND_DOUBLE:
case KIND_LDOUBLE: {
if (!node->flabel) {
node->flabel = make_label();
emit_noindent(".data");
emit_label(node->flabel);
emit(".quad %lu", *(uint64_t *)&node->fval);
emit_noindent(".text");
}
emit("movsd %s(#rip), #xmm0", node->flabel);
break;
}
case KIND_ARRAY: {
if (!node->slabel) {
node->slabel = make_label();
emit_noindent(".data");
emit_label(node->slabel);
emit(".string \"%s\"", quote_cstring_len(node->sval, node->ty->size - 1));
emit_noindent(".text");
}
emit("lea %s(#rip), #rax", node->slabel);
break;
}
default:
error("internal error");
}
}
static char **split(char *buf) {
char *p = buf;
int len = 1;
while (*p) {
if (p[0] == '\r' && p[1] == '\n') {
len++;
p += 2;
continue;
}
if (p[0] == '\r' || p[0] == '\n')
len++;
p++;
}
p = buf;
char **r = malloc(sizeof(char *) * len + 1);
int i = 0;
while (*p) {
if (p[0] == '\r' && p[1] == '\n') {
p[0] = '\0';
p += 2;
r[i++] = p;
continue;
}
if (p[0] == '\r' || p[0] == '\n') {
p[0] = '\0';
r[i++] = p + 1;
}
p++;
}
r[i] = NULL;
return r;
}
static char **read_source_file(char *file) {
FILE *fp = fopen(file, "r");
if (!fp)
return NULL;
struct stat st;
fstat(fileno(fp), &st);
char *buf = malloc(st.st_size + 1);
if (fread(buf, 1, st.st_size, fp) != st.st_size) {
fclose(fp);
return NULL;
}
fclose(fp);
buf[st.st_size] = '\0';
return split(buf);
}
static void maybe_print_source_line(char *file, int line) {
if (!dumpsource)
return;
char **lines = map_get(source_lines, file);
if (!lines) {
lines = read_source_file(file);
if (!lines)
return;
map_put(source_lines, file, lines);
}
int len = 0;
for (char **p = lines; *p; p++)
len++;
emit_nostack("# %s", lines[line - 1]);
}
static void maybe_print_source_loc(Node *node) {
if (!node->sourceLoc)
return;
char *file = node->sourceLoc->file;
long fileno = (long)map_get(source_files, file);
if (!fileno) {
fileno = map_len(source_files) + 1;
map_put(source_files, file, (void *)fileno);
emit(".file %ld \"%s\"", fileno, quote_cstring(file));
}
char *loc = format(".loc %ld %d 0", fileno, node->sourceLoc->line);
if (strcmp(loc, last_loc)) {
emit("%s", loc);
maybe_print_source_line(file, node->sourceLoc->line);
}
last_loc = loc;
}
static void emit_lvar(Node *node) {
SAVE;
ensure_lvar_init(node);
emit_lload(node->ty, "rbp", node->loff);
}
static void emit_gvar(Node *node) {
SAVE;
emit_gload(node->ty, node->glabel, 0);
}
static void emit_builtin_return_address(Node *node) {
push("r11");
assert(vec_len(node->args) == 1);
emit_expr(vec_head(node->args));
char *loop = make_label();
char *end = make_label();
emit("mov #rbp, #r11");
emit_label(loop);
emit("test #rax, #rax");
emit("jz %s", end);
emit("mov (#r11), #r11");
emit("sub $1, #rax");
emit_jmp(loop);
emit_label(end);
emit("mov 8(#r11), #rax");
pop("r11");
}
// Set the register class for parameter passing to RAX.
// 0 is INTEGER, 1 is SSE, 2 is MEMORY.
static void emit_builtin_reg_class(Node *node) {
Node *arg = vec_get(node->args, 0);
assert(arg->ty->kind == KIND_PTR);
Type *ty = arg->ty->ptr;
if (ty->kind == KIND_STRUCT)
emit("mov $2, #eax");
else if (is_flotype(ty))
emit("mov $1, #eax");
else
emit("mov $0, #eax");
}
static void emit_builtin_va_start(Node *node) {
SAVE;
assert(vec_len(node->args) == 1);
emit_expr(vec_head(node->args));
push("rcx");
emit("movl $%d, (#rax)", numgp * 8);
emit("movl $%d, 4(#rax)", 48 + numfp * 16);
emit("lea %d(#rbp), #rcx", -REGAREA_SIZE);
emit("mov #rcx, 16(#rax)");
pop("rcx");
}
static bool maybe_emit_builtin(Node *node) {
SAVE;
if (!strcmp("__builtin_return_address", node->fname)) {
emit_builtin_return_address(node);
return true;
}
if (!strcmp("__builtin_reg_class", node->fname)) {
emit_builtin_reg_class(node);
return true;
}
if (!strcmp("__builtin_va_start", node->fname)) {
emit_builtin_va_start(node);
return true;
}
return false;
}
static void classify_args(Vector *ints, Vector *floats, Vector *rest, Vector *args) {
SAVE;
int ireg = 0, xreg = 0;
int imax = 6, xmax = 8;
for (int i = 0; i < vec_len(args); i++) {
Node *v = vec_get(args, i);
if (v->ty->kind == KIND_STRUCT)
vec_push(rest, v);
else if (is_flotype(v->ty))
vec_push((xreg++ < xmax) ? floats : rest, v);
else
vec_push((ireg++ < imax) ? ints : rest, v);
}
}
static void save_arg_regs(int nints, int nfloats) {
SAVE;
assert(nints <= 6);
assert(nfloats <= 8);
for (int i = 0; i < nints; i++)
push(REGS[i]);
for (int i = 1; i < nfloats; i++)
push_xmm(i);
}
static void restore_arg_regs(int nints, int nfloats) {
SAVE;
for (int i = nfloats - 1; i > 0; i--)
pop_xmm(i);
for (int i = nints - 1; i >= 0; i--)
pop(REGS[i]);
}
static int emit_args(Vector *vals) {
SAVE;
int r = 0;
for (int i = 0; i < vec_len(vals); i++) {
Node *v = vec_get(vals, i);
if (v->ty->kind == KIND_STRUCT) {
emit_addr(v);
r += push_struct(v->ty->size);
} else if (is_flotype(v->ty)) {
emit_expr(v);
push_xmm(0);
r += 8;
} else {
emit_expr(v);
push("rax");
r += 8;
}
}
return r;
}
static void pop_int_args(int nints) {
SAVE;
for (int i = nints - 1; i >= 0; i--)
pop(REGS[i]);
}
static void pop_float_args(int nfloats) {
SAVE;
for (int i = nfloats - 1; i >= 0; i--)
pop_xmm(i);
}
static void maybe_booleanize_retval(Type *ty) {
if (ty->kind == KIND_BOOL) {
emit("movzx #al, #rax");
}
}
static void emit_func_call(Node *node) {