-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.c
2335 lines (2144 loc) · 70.9 KB
/
generator.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
#include "boncc.h"
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static FILE *ostream;
static const char *reg_args[][6] = {{NULL},
{"dil", "sil", "dl", "cl", "r8b", "r9b"},
{"di", "si", "dx", "cx", "r8w", "r9w"},
{NULL},
{"edi", "esi", "edx", "ecx", "r8d", "r9d"},
{NULL},
{NULL},
{NULL},
{"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
static const char *reg_ax[] = {NULL, "al", "ax", NULL, "eax",
NULL, NULL, NULL, "rax"};
static const char *reg_dx[] = {NULL, "dl", "dx", NULL, "edx",
NULL, NULL, NULL, "rdx"};
static const char *reg_r10[] = {NULL, "r10b", "r10w", NULL, "r10d",
NULL, NULL, NULL, "r10"};
// Check the rsp alignment by the variable rsp_shift.
// In the AST traversal, rsp_shift follows the push and pop operations.
// In any single expression and any statement,
// "push" and "pop" instructions are always balanced and rsp remains aligned.
// We need to care about the rsp alignment when multiple expressions are
// combined, e.g "f() + g()".
// Before evaluating "f()", rsp is aligned to 16byte.
// After "f()", rsp remains aligned.
// Then the result of "f()" is pushed to the stack (rsp is shifted 8byte).
// Before "g()" is called, rsp is not aligned to 16byte.
// Therefore rsp is adjusted by 8byte, "g()" is evaluated, and then rsp
// adjustment is reverted by 8byte. Next, the result of "f()" is popped to a
// register (rsp is shifted 8byte) and "add" instruction is processed.
// After that, rsp is aligned to 16byte.
static int rsp_shift = 0;
typedef struct FloatLiteral FloatLiteral;
struct FloatLiteral {
int index;
Number *num;
};
static int float_literal_index = 0;
static Vector *float_literals = NULL; // FloatValue*
// node.c -->
bool is_constant_number(Node *node);
Variable *is_const_var_addr(Node *node);
Number *eval(Node *node);
// <-- node.c
void gen(Node *node);
__attribute__((format(printf, 1, 2))) void writeline(char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(ostream, fmt, ap);
fprintf(ostream, "\n");
}
__attribute__((format(printf, 2, 3))) void comment(Token *tok, char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
fprintf(ostream, " # ");
vfprintf(ostream, fmt, ap);
if (tok)
fprintf(ostream, " %s:%d:%d", tok->pos.file_name, tok->pos.line_number,
tok->pos.column_number);
fprintf(ostream, "\n");
}
static void push(const char *reg) {
assert(rsp_shift >= 0);
writeline(" push %s", reg);
rsp_shift += 8; // push only 8 byte register
}
static void pop(const char *reg) {
writeline(" pop %s", reg);
rsp_shift -= 8; // pop only 8 byte register
assert(rsp_shift >= 0);
}
static void push_xmm(int n, TypeKind kind) {
assert(rsp_shift >= 0);
switch (kind) {
case TYPE_FLOAT: // align to 8 even if size is 4
writeline(" sub rsp, 8 # push %s", type_text(kind));
writeline(" movss [rsp], xmm%d # push %s", n, type_text(kind));
rsp_shift += 8;
break;
case TYPE_DOUBLE:
writeline(" sub rsp, 8 # push %s", type_text(kind));
writeline(" movsd [rsp], xmm%d # push %s", n, type_text(kind));
rsp_shift += 8;
break;
case TYPE_LDOUBLE:
error(NULL, "long double is currently not supported");
rsp_shift += 16;
break;
default:
assert(false);
}
}
static void pop_xmm(int n, TypeKind kind) {
switch (kind) {
case TYPE_FLOAT: // align to 8 even if size is 4
writeline(" movss xmm%d, [rsp] # pop %s", n, type_text(kind));
writeline(" add rsp, 8 # pop %s", type_text(kind));
rsp_shift -= 8;
break;
case TYPE_DOUBLE:
writeline(" movsd xmm%d, [rsp] # pop %s", n, type_text(kind));
writeline(" add rsp, 8 # pop %s", type_text(kind));
rsp_shift -= 8;
break;
case TYPE_LDOUBLE:
error(NULL, "long double is currently not supported");
rsp_shift -= 16;
break;
default:
assert(false);
}
assert(rsp_shift >= 0);
}
void gen_constexpr(Node *node) {
assert(node->num);
assert(node->is_constant_expr);
if (is_float(node->type)) {
FloatLiteral *f = calloc(1, sizeof(FloatLiteral));
f->num = node->num;
f->index = float_literal_index++;
vector_push(float_literals, &f);
if (node->type->kind == TYPE_FLOAT)
writeline(" movss xmm0, .float%d[rip] # const expr", f->index);
else if (node->type->kind == TYPE_DOUBLE)
writeline(" movsd xmm0, .float%d[rip] # const expr", f->index);
else if (node->type->kind == TYPE_LDOUBLE)
error(NULL, "long double is currently not supported");
else
assert(false);
return;
}
switch (node->type->kind) {
case TYPE_LONG:
writeline(" mov rax, %lld # const expr", number2long(node->num));
break;
case TYPE_ULONG:
case TYPE_PTR:
writeline(" mov rax, %llu # const expr", number2ulong(node->num));
break;
case TYPE_INT:
case TYPE_ENUM:
writeline(" mov rax, %d # const expr", number2int(node->num));
break;
case TYPE_UINT:
writeline(" mov rax, %u # const expr", number2uint(node->num));
break;
case TYPE_SHORT:
writeline(" mov rax, %d # const expr", number2short(node->num));
break;
case TYPE_USHORT:
writeline(" mov rax, %u # const expr", number2ushort(node->num));
break;
case TYPE_CHAR:
writeline(" mov rax, %d # const expr", number2char(node->num));
break;
case TYPE_UCHAR:
writeline(" mov rax, %u # const expr", number2uchar(node->num));
break;
case TYPE_BOOL:
writeline(" mov rax, %d # const expr", number2bool(node->num));
break;
case TYPE_VOID:
break;
default:
assert(false);
}
}
void gen_address(Node *node) {
// write address to rax
switch (node->kind) {
case ND_DEREF:
comment(NULL, "gen_address ND_DEREF");
gen(node->lhs);
return;
case ND_VAR:
if (node->variable->kind == OBJ_LVAR) {
if (node->variable->is_static) {
comment(NULL, "gen_address ND_VAR static-local: %.*s",
node->variable->ident->len, node->variable->ident->str);
writeline(" lea rax, %.*s[rip]", node->variable->internal_ident->len,
node->variable->internal_ident->str);
} else if (node->variable->is_extern) {
comment(NULL, "gen_address ND_VAR extern-local: %.*s",
node->variable->ident->len, node->variable->ident->str);
writeline(" lea rax, %.*s[rip]", node->variable->ident->len,
node->variable->ident->str);
} else {
comment(NULL, "gen_address ND_VAR local: %.*s",
node->variable->ident->len, node->variable->ident->str);
writeline(" lea rax, [rbp-%d]", node->variable->offset);
}
} else if (node->variable->kind == OBJ_GVAR) {
comment(NULL, "gen_address ND_VAR global: %.*s",
node->variable->ident->len, node->variable->ident->str);
writeline(" lea rax, %.*s[rip]", node->variable->ident->len,
node->variable->ident->str);
} else if (node->variable->kind == OBJ_STRLIT) {
comment(NULL, "gen_address ND_VAR strlit: \"%s\"",
node->variable->string_literal);
writeline(" lea rax, %.*s[rip]", node->variable->ident->len,
node->variable->ident->str);
} else if (node->variable->kind == OBJ_FUNC) {
comment(NULL, "gen_address ND_VAR function: %.*s",
node->variable->ident->len, node->variable->ident->str);
writeline(" lea rax, %.*s[rip]", node->variable->ident->len,
node->variable->ident->str);
} else
assert(false);
return;
case ND_MEMBER:
comment(NULL, "gen_address ND_MEMBER %.*s", node->member->ident->len,
node->member->ident->str);
gen_address(node->lhs);
writeline(" add rax, %d", node->member->offset);
return;
default:
error(&node->token->pos, "failed to generate address");
}
}
bool use_xmm(Type *type, int begin, int end) {
if (is_scalar(type))
return is_float(type);
if (type->kind == TYPE_ARRAY) {
int cur = 0;
for (int i = 0; i < type->array_size && cur < end;
++i, cur += type->base->size) {
if (cur < begin)
continue;
if (!use_xmm(type->base, 0, end - cur))
return false;
}
return true;
}
if (type->kind == TYPE_STRUCT || type->kind == TYPE_UNION) {
for (Member *m = type->member; m && m->offset < end; m = m->next) {
if (m->offset >= begin) {
if (!use_xmm(m->type, 0, end - m->offset))
return false;
} else if (m->offset + m->type->size > begin) {
if (!use_xmm(m->type, begin - m->offset, end - m->offset))
return false;
}
}
return true;
}
assert(false);
return true;
}
void load(Type *type) {
// src : the address where rax is pointing to
// dest : rax or xmm0
comment(NULL, "load %s (size:%d)", type_text(type->kind), type->size);
if (type->kind == TYPE_ARRAY || pass_on_memory(type))
return; // nothing to do
if (is_struct_union(type)) {
writeline(" mov r10, rax");
int xmm_index = 0;
const char **reg = reg_ax;
for (int b = 0; b < type->size; b += 8) {
// put 8byte onto register
if (use_xmm(type, b, b + 8)) {
writeline(" movs%c xmm%d, [r10+%d]", type->size == b + 4 ? 's' : 'd',
xmm_index++, b);
} else {
writeline(" mov %s, [r10+%d]",
reg[type->size - b > 8 ? 8 : type->size - b], b);
reg = reg_dx;
}
}
return;
}
if (is_float(type)) {
if (type->kind == TYPE_FLOAT)
writeline(" movss xmm0, [rax]");
else if (type->kind == TYPE_DOUBLE)
writeline(" movsd xmm0, [rax]");
else if (type->kind == TYPE_LDOUBLE)
error(NULL, "long double is currently not supported");
else
assert(false);
return;
}
if (type->size == 1)
writeline(" mov%cx rax, byte ptr [rax]", is_unsigned(type) ? 'z' : 's');
else if (type->size == 2)
writeline(" mov%cx rax, word ptr [rax]", is_unsigned(type) ? 'z' : 's');
else if (type->size == 4)
writeline(" movsxd rax, dword ptr [rax]");
else if (type->size == 8)
writeline(" mov rax, [rax]");
else
assert(false);
}
void store(Type *type) {
// src : rax or xmm0
// dest : the address popped from stack
comment(NULL, "store %s", type_text(type->kind));
pop("r10");
if (is_struct_union(type)) {
if (pass_on_memory(type)) {
// src : the struct/union that rax is pointing to
// dest : the address popped from stack
for (int i = 0; i < type->size; i++) {
// copy each bytes like memcpy
writeline(" mov r11b, [rax+%d]", i);
writeline(" mov [r10+%d], r11b", i);
}
return;
}
// src : the struct/union on registers
// dest : the struct/union that the address popped from stack is pointing
// to
int xmm_index = 0;
const char **reg = reg_ax;
for (int b = 0; b < type->size; b += 8) {
// copy 8byte from register
if (use_xmm(type, b, b + 8)) {
writeline(" movs%c [r10+%d], xmm%d", type->size == b + 4 ? 's' : 'd',
b, xmm_index++);
} else {
writeline(" mov [r10+%d], %s", b,
reg[type->size - b > 8 ? 8 : type->size - b]);
reg = reg_dx;
}
}
return;
}
if (is_float(type)) {
if (type->kind == TYPE_FLOAT)
writeline(" movss [r10], xmm0");
else if (type->kind == TYPE_DOUBLE)
writeline(" movsd [r10], xmm0");
else if (type->kind == TYPE_LDOUBLE)
error(NULL, "long double is currently not supported");
else
assert(false);
return;
}
writeline(" mov [r10], %s", reg_ax[type->size]);
}
static void push_struct_union(Type *type) {
// push the struct/union loaded by load()
assert(is_struct_union(type));
int shift = iceil(type->size, 8);
writeline(" sub rsp, %d", shift);
rsp_shift += shift;
push("rsp"); // popped by store()
store(type);
}
void gen_if(Node *node) {
assert(node->condition->type->kind == TYPE_BOOL);
gen(node->condition);
writeline(" cmp al, 0");
if (node->else_) {
writeline(" je .Lelse%d", node->label_index);
if (node->body)
gen(node->body);
writeline(" jmp .Lend%d", node->label_index);
writeline(".Lelse%d:", node->label_index);
gen(node->else_);
writeline(".Lend%d:", node->label_index);
} else {
writeline(" je .Lend%d", node->label_index);
if (node->body)
gen(node->body);
writeline(".Lend%d:", node->label_index);
}
}
void gen_do(Node *node) {
assert(node->condition->type->kind == TYPE_BOOL);
writeline(".Ldo%d:", node->label_index);
if (node->body)
gen(node->body);
writeline(".Lcontinue%d:", node->label_index);
gen(node->condition);
writeline(" cmp al, 0");
writeline(" jne .Ldo%d", node->label_index);
writeline(".Lend%d:", node->label_index);
}
void gen_while(Node *node) {
assert(node->condition->type->kind == TYPE_BOOL);
writeline(".Lcontinue%d:", node->label_index);
gen(node->condition);
writeline(" cmp al, 0");
writeline(" je .Lend%d", node->label_index);
if (node->body)
gen(node->body);
writeline(" jmp .Lcontinue%d", node->label_index);
writeline(".Lend%d:", node->label_index);
}
void gen_for(Node *node) {
assert(node->condition->type->kind == TYPE_BOOL);
if (node->init)
gen(node->init);
writeline(".Lfor%d:", node->label_index);
if (node->condition) {
gen(node->condition);
writeline(" cmp al, 0");
writeline(" je .Lend%d", node->label_index);
}
if (node->body)
gen(node->body);
writeline(".Lcontinue%d:", node->label_index);
if (node->update)
gen(node->update);
writeline(" jmp .Lfor%d", node->label_index);
writeline(".Lend%d:", node->label_index);
}
void gen_switch(Node *node) {
assert(is_integer(node->condition->type));
gen(node->condition);
Node *c = node->next_case;
while (c) {
assert(c->condition);
assert(c->condition->kind == ND_NUM);
assert(is_integer(c->condition->type));
if (is_signed(c->condition->type))
writeline(" cmp rax, %lld", number2long(c->condition->num));
else
writeline(" cmp rax, %llu", number2ulong(c->condition->num));
writeline(" je .Lcase%d", c->label_index);
c = c->next_case;
}
if (node->default_)
writeline(" jmp .Ldefault%d", node->default_->label_index);
else
writeline(" jmp .Lend%d", node->label_index);
gen(node->body);
writeline(".Lend%d:", node->label_index);
}
void gen_block(Node *node) {
int sz = node->blk_stmts->size;
for (int i = 0; i < sz; ++i) {
Node *d = *(Node **)vector_get(node->blk_stmts, i);
gen(d);
}
}
void gen_builtin_va_arg_gp(Node *node, int label_index) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_gp");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" mov rdi, rax"); // rdi = &gp_offset
writeline(" mov r10d, [rdi]"); // r10 = gp_offset
writeline(" cmp r10d, 48");
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov rax, [rdi+16]"); // rax = reg_save_area
writeline(" add rax, r10"); // rax = reg_save_area + gp_offset
writeline(" lea rdx, [r10+8]"); // rdx = gp_offset + 8
writeline(" mov [rdi], edx"); // gp_offset = rdx
writeline(" jmp .L_va_arg_end%d", label_index);
writeline(".L_va_arg_stack%d:", label_index);
writeline(" mov rax, [rdi+8]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+8]"); // rdx = overflow_arg_area + 8
writeline(" mov [rdi+8], rdx"); // overflow_arg_area = rdx
writeline(".L_va_arg_end%d:", label_index);
}
void gen_builtin_va_arg_fp(Node *node, int label_index) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_fp");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" lea rdi, [rax+4]"); // rdi = &fp_offset
writeline(" mov r10d, [rdi]"); // r10 = fp_offset
writeline(" cmp r10d, %d", 48 + 16 * 8);
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov rax, [rdi+12]"); // rax = reg_save_area
writeline(" add rax, r10"); // rax = reg_save_area + fp_offset
writeline(" lea rdx, [r10+16]"); // rdx = fp_offset + 16
writeline(" mov [rdi], edx"); // fp_offset = rdx
writeline(" jmp .L_va_arg_end%d", label_index);
writeline(".L_va_arg_stack%d:", label_index);
writeline(" mov rax, [rdi+4]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+8]"); // rdx = overflow_arg_area + 8
writeline(" mov [rdi+4], rdx"); // overflow_arg_area = rdx
writeline(".L_va_arg_end%d:", label_index);
}
void gen_builtin_va_arg_struct_gp2(Node *node, int label_index) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_struct_gp2");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" mov rdi, rax"); // rdi = &gp_offset
writeline(" mov r10d, [rdi]"); // r10 = gp_offset
writeline(" cmp r10d, 40");
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov rax, [rdi+16]"); // rax = reg_save_area
writeline(" add rax, r10"); // rax = reg_save_area + gp_offset
writeline(" lea rdx, [r10+16]"); // rdx = gp_offset + 16
writeline(" mov [rdi], edx"); // gp_offset = rdx
writeline(" jmp .L_va_arg_end%d", label_index);
writeline(".L_va_arg_stack%d:", label_index);
writeline(" mov rax, [rdi+8]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+16]"); // rdx = overflow_arg_area + 16
writeline(" mov [rdi+8], rdx"); // overflow_arg_area = rdx
writeline(".L_va_arg_end%d:", label_index);
}
void gen_builtin_va_arg_struct_fp2(Node *node, int label_index) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_struct_fp2");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" lea rdi, [rax+4]"); // rdi = &fp_offset
writeline(" mov r10d, [rdi]"); // r10 = fp_offset
writeline(" cmp r10d, %d", 48 + 16 * 7);
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov rsi, [rdi+12]"); // rsi = reg_save_area
writeline(" lea rax, [rsi+176]"); // rax = (hidden 16byte buffer address)
writeline(" add rsi, r10"); // rsi = reg_save_area + fp_offset
writeline(" mov r11, [rsi]"); // r11 = *(reg_save_area + fp_offset)
writeline(" mov [rax], r11"); // *rax = r11
writeline(" mov r11, [rsi+16]"); // r11 = *(reg_save_area + fp_offset + 16)
writeline(" mov [rax+8], r11"); // *(rax+8) = r11
writeline(" lea rdx, [r10+32]"); // rdx = fp_offset + 32
writeline(" mov [rdi], edx"); // fp_offset = rdx
writeline(" jmp .L_va_arg_end%d", label_index);
writeline(".L_va_arg_stack%d:", label_index);
writeline(" mov rax, [rdi+4]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+16]"); // rdx = overflow_arg_area + 16
writeline(" mov [rdi+4], rdx"); // overflow_arg_area = rdx
writeline(".L_va_arg_end%d:", label_index);
}
void gen_builtin_va_arg_struct_gpfp(Node *node, int label_index,
bool fp_first) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_struct_gpfp");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" mov rdi, rax"); // rdi = &gp_offset
writeline(" lea rcx, [rax+4]"); // rcx = &fp_offset
writeline(" mov r10d, [rdi]"); // r10 = gp_offset
writeline(" cmp r10d, 48");
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov r11d, [rcx]"); // r11 = fp_offset
writeline(" cmp r11d, %d", 48 + 16 * 8);
writeline(" jae .L_va_arg_stack%d", label_index);
writeline(" mov rsi, [rdi+16]"); // rsi = reg_save_area
writeline(" lea rax, [rsi+176]"); // rax = (hidden 16byte buffer address)
if (fp_first) {
writeline(" add rsi, r11"); // rsi = reg_save_area + fp_offset
writeline(" mov r8, [rsi]"); // r8 = *(reg_save_area + fp_offset)
writeline(" mov [rax], r8"); // *rax = r8
writeline(" mov rsi, [rdi+16]"); // rsi = reg_save_area
writeline(" add rsi, r10"); // rsi = reg_save_area + gp_offset
writeline(" mov r8, [rsi]"); // r8 = *(reg_save_area + gp_offset)
writeline(" mov [rax+8], r8"); // *(rax+8) = r8
} else {
writeline(" add rsi, r10"); // rsi = reg_save_area + gp_offset
writeline(" mov r8, [rsi]"); // r8 = *(reg_save_area + gp_offset)
writeline(" mov [rax], r8"); // *(rax+8) = r8
//
writeline(" mov rsi, [rdi+16]"); // rsi = reg_save_area
//
writeline(" add rsi, r11"); // rsi = reg_save_area + fp_offset
writeline(" mov r8, [rsi]"); // r8 = *(reg_save_area + fp_offset)
writeline(" mov [rax+8], r8"); // *rax = r8
}
writeline(" lea rdx, [r10+8]"); // rdx = gp_offset + 8
writeline(" mov [rdi], edx"); // gp_offset = rdx
writeline(" lea rdx, [r11+16]"); // rdx = fp_offset + 16
writeline(" mov [rcx], edx"); // fp_offset = rdx
writeline(" jmp .L_va_arg_end%d", label_index);
writeline(".L_va_arg_stack%d:", label_index);
writeline(" mov rax, [rdi+8]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+16]"); // rdx = overflow_arg_area + 16
writeline(" mov [rdi+8], rdx"); // overflow_arg_area = rdx
writeline(".L_va_arg_end%d:", label_index);
}
void gen_builtin_va_arg_stack(Node *node, int size) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg_stack");
Node *ap = *(Node **)vector_get(node->args, 0);
gen(ap); // rax = &va_list
writeline(" lea rdi, [rax+8]"); // rdi = &overflow_arg_area
writeline(" mov rax, [rdi]"); // rax = overflow_arg_area
writeline(" lea rdx, [rax+%d]",
iceil(size, 8)); // rdx = overflow_arg_area + iceil(size,8)
writeline(" mov [rdi], rdx"); // overflow_arg_area = rdx
comment(NULL, "end builtin_va_arg_stack");
}
void gen_builtin_va_arg(Node *node) {
assert(node->args->size == 2);
comment(NULL, "builtin_va_arg");
Node *atype = *(Node **)vector_get(node->args, 1);
// the second argument is automatically casted to (void*) by parser.c
assert(atype->kind == ND_CAST);
assert(atype->type->kind == TYPE_PTR);
assert(atype->type->base->kind == TYPE_VOID);
Type *type =
(atype->lhs->kind == ND_CAST && atype->lhs->type->kind == TYPE_PTR)
? atype->lhs->type->base
: base_type(TYPE_VOID);
static int label_index = -1;
label_index++;
if (is_integer(type) || type->kind == TYPE_PTR) {
gen_builtin_va_arg_gp(node, label_index);
} else if (is_float(type)) {
gen_builtin_va_arg_fp(node, label_index);
} else if (pass_on_memory(type)) {
gen_builtin_va_arg_stack(node, type->size);
} else if (is_struct_union(type)) {
if (type->size <= 8) {
if (use_xmm(type, 0, 8))
gen_builtin_va_arg_fp(node, label_index);
else
gen_builtin_va_arg_gp(node, label_index);
} else if (type->size <= 16) {
bool fp1 = use_xmm(type, 0, 8);
bool fp2 = use_xmm(type, 8, 16);
if (fp1 && fp2)
gen_builtin_va_arg_struct_fp2(node, label_index);
else if (!fp1 && !fp2)
gen_builtin_va_arg_struct_gp2(node, label_index);
else if (fp1 && !fp2)
gen_builtin_va_arg_struct_gpfp(node, label_index, true);
else
gen_builtin_va_arg_struct_gpfp(node, label_index, false);
} else {
assert(false);
}
} else {
error(node->token ? &node->token->pos : NULL,
"unsupported type specified for va_arg");
}
}
void gen_call(Node *node) {
assert(is_funcptr(node->lhs->type));
if (node->lhs->kind == ND_VAR && node->lhs->variable->kind == OBJ_FUNC &&
same_string_nt(node->lhs->variable->ident, "__builtin_va_arg")) {
gen_builtin_va_arg(node);
return;
}
int n_fp = 0;
int alignment = 0;
int shift_by_args = 0;
// put arguments into registers or the stack
{
int sz = node->args->size;
int count_gp = pass_on_memory(node->type);
int count_fp = 0;
Vector *args_on_register = new_vector(0, sizeof(Node *));
Vector *args_on_stack = new_vector(0, sizeof(Node *));
// scan args to see where to place them
for (int i = 0; i < sz; ++i) {
Node *d = *(Node **)vector_get(node->args, i);
if (is_float(d->type)) {
if (count_fp == 8) {
vector_push(args_on_stack, &d);
shift_by_args += iceil(d->type->size, 8);
} else {
vector_push(args_on_register, &d);
count_fp++;
}
} else if (is_integer(d->type) || d->type->kind == TYPE_PTR) {
if (count_gp == 6) {
vector_push(args_on_stack, &d);
shift_by_args += iceil(d->type->size, 8);
} else {
vector_push(args_on_register, &d);
count_gp++;
}
} else if (is_struct_union(d->type)) {
if (pass_on_memory(d->type)) {
vector_push(args_on_stack, &d);
shift_by_args += iceil(d->type->size, 8);
} else {
int required_fp =
use_xmm(d->type, 0, 8) +
(d->type->size > 8 && use_xmm(d->type, 8, 16) ? 1 : 0);
int required_gp = (d->type->size > 8 ? 2 : 1) - required_fp;
if (count_gp + required_gp > 6 || count_fp + required_fp > 8) {
vector_push(args_on_stack, &d);
shift_by_args += iceil(d->type->size, 8);
} else {
vector_push(args_on_register, &d);
count_gp += required_gp;
count_fp += required_fp;
}
}
} else {
assert(false);
}
}
assert(count_gp <= 6);
assert(count_fp <= 8);
// Align rsp before evaluating the arguments.
// After this alignment, args_on_stack are evaluated and pushed to the
// stack. Then args_on_register are evaluated, pushed to the stack, and
// popped to registers. The stack operations for args_on_register are
// balanced and do not affect the rsp. Here, rsp must be aligned
// considering the shift by args_on_stack and the current rsp_shift.
alignment = (rsp_shift + shift_by_args) % 16;
if (alignment) {
// shift 8byte because rps is alywas aligned to 8byte
assert(alignment % 8 == 0);
writeline(" sub rsp, 8 # alignment");
rsp_shift += 8;
}
n_fp = count_fp;
if (args_on_stack->size > 0) {
comment(NULL, "push arguments that will be passed by stack memory");
int before = rsp_shift;
for (int i = args_on_stack->size - 1; i >= 0; --i) {
Node *d = *(Node **)vector_get(args_on_stack, i);
gen(d);
if (is_float(d->type)) {
push_xmm(0, d->type->kind);
} else if (is_integer(d->type) || d->type->kind == TYPE_PTR) {
push("rax");
} else if (is_struct_union(d->type)) {
push_struct_union(d->type);
} else {
assert(false);
}
}
assert(rsp_shift == before + shift_by_args);
}
int before = rsp_shift;
if (args_on_register->size > 0) {
comment(NULL, "push arguments that will be passed by registers");
for (int i = 0; i < args_on_register->size; ++i) {
Node *d = *(Node **)vector_get(args_on_register, i);
gen(d);
if (is_float(d->type)) {
push_xmm(0, d->type->kind);
} else if (is_integer(d->type) || d->type->kind == TYPE_PTR) {
push("rax");
} else if (is_struct_union(d->type)) {
push_struct_union(d->type);
} else {
assert(false);
}
}
comment(NULL, "pop arguments to registers");
for (int i = args_on_register->size - 1; i >= 0; --i) {
Node *d = *(Node **)vector_get(args_on_register, i);
if (is_float(d->type)) {
assert(count_fp > 0);
pop_xmm(--count_fp, d->type->kind);
} else if (is_integer(d->type) || d->type->kind == TYPE_PTR) {
assert(count_gp > 0);
pop(reg_args[8][--count_gp]);
} else if (is_struct_union(d->type)) {
assert(d->type->size <= 16);
int required_fp =
use_xmm(d->type, 0, 8) +
(d->type->size > 8 && use_xmm(d->type, 8, 16) ? 1 : 0);
int required_gp = (d->type->size > 8 ? 2 : 1) - required_fp;
int xmm_index = count_fp - required_fp;
int reg_index = count_gp - required_gp;
assert(xmm_index >= 0);
assert(reg_index >= 0);
for (int b = 0; b < d->type->size; b += 8) {
if (use_xmm(d->type, b, b + 8))
writeline(" movs%c xmm%d, [rsp]",
d->type->size == b + 4 ? 's' : 'd', xmm_index++);
else
writeline(" mov %s, [rsp]", reg_args[8][reg_index++]);
writeline(" add rsp, 8");
rsp_shift -= 8;
assert(xmm_index <= 8);
assert(reg_index <= 6);
}
count_gp -= required_gp;
count_fp -= required_fp;
assert(count_gp >= 0);
assert(count_fp >= 0);
} else {
assert(false);
}
}
}
assert(rsp_shift == before);
if (pass_on_memory(node->type)) {
// hidden argument to pass return_buffer address
assert(count_gp-- == 1);
writeline(" mov rdi, rbp # hidden argument of return buffer address");
writeline(" sub rdi, %d # hidden argument of return buffer address",
node->caller->return_buffer_offset);
}
assert(count_gp == 0);
assert(count_fp == 0);
}
if (node->lhs->kind == ND_VAR && node->lhs->variable->kind == OBJ_FUNC) {
writeline(" mov al, %d", n_fp);
writeline(" call %.*s", node->lhs->variable->ident->len,
node->lhs->variable->ident->str);
} else {
gen(node->lhs); // calculate function address
writeline(" mov r10, rax");
writeline(" mov al, %d", n_fp);
writeline(" call r10");
}
if (alignment || shift_by_args) {
// undo the 16byte alignment and the shift by arguments pushed to stack
int shift = alignment + shift_by_args;
writeline(" add rsp, %d", shift);
rsp_shift -= shift;
}
if (!pass_on_memory(node->type) && is_integer(node->type) &&
node->type->size < 8) {
// Extend the returned integer to 64bit.
// This compiler treats all integers on registers as 64bit integers.
// This extension is required when the callee function is compiled by
// another compiler.
if (node->type->kind == TYPE_INT || node->type->kind == TYPE_ENUM)
writeline(" movsxd rax, eax # extend the returned integer to 64bit");
else if (node->type->kind == TYPE_UINT)
writeline(" mov eax, eax # extend the returned integer to 64bit");
else if (node->type->kind == TYPE_BOOL)
writeline(" movzx rax, al # extend the returned integer to 64bit");
else if (is_unsigned(node->type))
writeline(" movzx rax, %s # extend the returned integer to 64bit",
reg_ax[node->type->size]);
else if (is_signed(node->type))
writeline(" movsx rax, %s # extend the returned integer to 64bit",
reg_ax[node->type->size]);
else
assert(false);
}
}
void gen_global_init(VariableInit *init, Type *type);
void gen_global_array_init(VariableInit *init, Type *type);
void gen_global_struct_init(VariableInit *init, Type *type);
void gen_global_union_init(VariableInit *init, Type *type);
void gen_global_pointer_init(VariableInit *init, Type *type);
void gen_global_integer_init(VariableInit *init, Type *type);
void gen_global_float_init(VariableInit *init, Type *type);
void gen_global_array_init(VariableInit *init, Type *type) {
assert(type->kind == TYPE_ARRAY);
if (init->expr) {
if (type->base->kind == TYPE_CHAR && init->expr->kind == ND_VAR &&
init->expr->variable->kind == OBJ_STRLIT) {
// initilize the array as a string
Variable *lit = init->expr->variable;
if (type->array_size != lit->type->array_size)
error(&init->expr->token->pos,
"miss-match between array-size and string-length");
writeline(" .ascii \"%s\\0\"", lit->string_literal);
return;
}
// When init->expr is given for an array,
// only the first element will be initialized.
Type *ty = type;
while (ty->kind == TYPE_ARRAY)
ty = ty->base;
gen_global_init(init, ty);
writeline(" .zero %d", type->size - ty->size);
return;
}
assert(init->vec);
assert(init->vec->size > 0);
if (init->nested) {
// init arrays recursively
int zero_size = type->size;
int len = type->array_size;
if (len > init->vec->size)
len = init->vec->size;
for (int i = 0; i < len; i++) {
zero_size -= type->base->size;
gen_global_init(*(VariableInit **)vector_get(init->vec, i), type->base);
}
if (zero_size)
writeline(" .zero %d", zero_size);
return;
}
// init as a one-dimensional array
Type *base = type;
while (base->kind == TYPE_ARRAY)
base = base->base;
int len = type->size / base->size;
if (len > init->vec->size)
len = init->vec->size;
for (int i = 0; i < len; i++)
gen_global_init(*(VariableInit **)vector_get(init->vec, i), base);
int zero_size = type->size - (base->size * len);
if (zero_size)
writeline(" .zero %d", zero_size);
}
void gen_global_struct_init(VariableInit *init, Type *type) {
assert(type->kind == TYPE_STRUCT);
if (init->vec) {
// init struct members recursively
Node *node = calloc(1, sizeof(Node));
node->kind = ND_BLOCK;
node->blk_stmts = new_vector(0, sizeof(Node *));
int zero_size = type->size;
Member *m = type->member;
for (int i = 0; i < init->vec->size && m; i++, m = m->next) {
gen_global_init(*(VariableInit **)vector_get(init->vec, i), m->type);
if (m->padding)
writeline(" .zero %d", m->padding);
zero_size -= m->type->size + m->padding;
}
if (zero_size)
writeline(" .zero %d", zero_size);
return;
}
assert(init->expr);
// init first member only
gen_global_init(init, type->member->type);
int zero_size = type->size - type->member->type->size;
if (zero_size)
writeline(" .zero %d", zero_size);
}
void gen_global_union_init(VariableInit *init, Type *type) {
assert(type->kind == TYPE_UNION);
// init first member only
while (init->vec)
init = *(VariableInit **)vector_get(init->vec, 0);
assert(init->expr);
gen_global_init(init, type->member->type);