-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.c
1432 lines (1298 loc) · 40.9 KB
/
codegen.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 "mimicc.h"
#include <stdio.h>
#include <string.h>
// TODO: Do not use "push" and "pop" when store too much arguments to stack?
// TODO: Maybe even when sizeOf(number) returns 4, it actually uses 8 bytes.
// "push" and "pop" operator implicitly uses rsp as memory address.
// Therefore, `push rax` is equal to:
// sub rsp, 8
// mov [rsp], rax
// and `pop rax` is equal to:
// mov rax, [rsp]
// add rsp, 8
//
// In addition, rsp points to the top of the stack, "push" and "pop" works as
// stack operator.
//
// Equivalents for some control statements:
// - if statement
// if (A)
// B
//
// if (A == 0)
// goto Lend;
// B
// Lend:
//
// - if-else statement
// if (A) B else C
//
// if (A == 0)
// goto Lelse;
// B
// goto Lend;
// Lelse:
// C
// Lend:
//
// - if-elseiflse statement
// if (A)
// B
// else if (C)
// D
//
// if (A == 0)
// goto Lelse;
// B
// goto Lend;
// Lelse:
// if (C == 0)
// goto Lend;
// D
// Lend:
//
// - if-elseif-else statement
// if (A)
// B
// else if (C)
// D
// else
// E
//
// if (A == 0)
// goto Lelse1;
// B
// goto Lend;
// Lelse1:
// if (C == 0)
// goto Lelse2;
// D
// goto Lend;
// Lelse2:
// E
// Lend:
//
// Stack state at the head of function:
// (When function has 8 arguments)
//
// | |
// | |
// +--------------------------------------------+
// | 8th argument |
// +--------------------------------------------+
// | 7th argument |
// +--------------------------------------------+
// | Return address of previous function |
// +--------------------------------------------+
// | Saved RBP value | <-- RBP
// +--------------------------------------------+
// | 1st argument |
// +--------------------------------------------+
// | 2nd argument |
// +--------------------------------------------+
// | |
// .
// .
// .
// | |
// +--------------------------------------------+
// | 6th argument |
// +--------------------------------------------+
// | |
// .
// . (Local variables or tmp values exprs left)
// .
typedef struct {
Obj *currentFunc;
int loopBlockID;
} DumpEnv;
static DumpEnv dumpEnv;
static void genCodeInitVarArray(const Node *n, TypeInfo *varType);
static void genCodeInitVarStruct(const Node *n, TypeInfo *varType);
static void genCodeInitVar(const Node *n, TypeInfo *varType);
static int isExprNode(const Node *n) {
// All cases in this switch uses fallthrough.
switch (n->kind) {
case NodeAdd:
case NodeSub:
case NodeMul:
case NodeDiv:
case NodeDivRem:
case NodeEq:
case NodeNeq:
case NodeLT:
case NodeLE:
case NodePreIncl:
case NodePreDecl:
case NodePostIncl:
case NodePostDecl:
case NodeMemberAccess:
case NodeAddress:
case NodeDeref:
case NodeNot:
case NodeLogicalAND:
case NodeLogicalOR:
case NodeNum:
case NodeBitwiseAND:
case NodeBitwiseOR:
case NodeBitwiseXOR:
case NodeArithShiftL:
case NodeArithShiftR:
case NodeLiteralString:
case NodeLVar:
case NodeAssign:
case NodeAssignStruct:
case NodeFCall:
case NodeExprList:
case NodeGVar:
case NodeTypeCast:
return 1;
case NodeIf:
case NodeElseif:
case NodeElse:
case NodeSwitch:
case NodeSwitchCase:
case NodeFor:
case NodeDoWhile:
case NodeBlock:
case NodeBreak:
case NodeContinue:
case NodeReturn:
case NodeFunction:
case NodeClearStack:
case NodeVaStart:
case NodeNop:
case NodeInitVar:
return 0;
case NodeConditional:
if (n->lhs->type->type == TypeVoid)
return 0;
return 1;
case NodeInitList:
errorUnreachable();
}
errorUnreachable();
return 0;
}
static void fillNodeNum(Node *n, int val) {
n->kind = NodeNum;
n->val = val;
n->type = &Types.Int;
}
static void fillNodeAdd(Node *n, Node *var, Node *shifter, TypeInfo *type) {
n->kind = NodeAdd;
n->lhs = var;
n->rhs = shifter;
n->type = type;
}
static void fillNodeInitVar(Node *n, Token *token, Node *var, Node *init) {
n->kind = NodeInitVar;
n->token = token;
n->lhs = var;
n->rhs = init;
n->type = &Types.Void;
}
// Return an integer corresponding to 1 for given type.
// In concrate explanation, return
// - sizeof(type) for "type *" and "type[]"
// - 1 for integer.
static int getAlternativeOfOneForType(const TypeInfo *ti) {
if (ti->type == TypePointer || ti->type == TypeArray) {
return sizeOf(ti->baseType);
}
return 1;
}
typedef enum {
RAX,
RDI,
RSI,
RDX,
RCX,
RBP,
RSP,
RBX,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15,
RegCount,
} RegKind;
const int Reg8 = 3;
const int Reg16 = 2;
const int Reg32 = 1;
const int Reg64 = 0;
// clang-format off
static const char *RegTable[RegCount][4] = {
{"rax", "eax", "ax", "al"},
{"rdi", "edi", "di", "dil"},
{"rsi", "esi", "si", "sil"},
{"rdx", "edx", "dx", "dl"},
{"rcx", "ecx", "cx", "cl"},
{"rbp", "ebp", "bp", "bpl"},
{"rsp", "esp", "sp", "spl"},
{"rbx", "ebx", "bx", "bl"},
{"r8", "r8d", "r8w", "r8b"},
{"r9", "r9d", "r9w", "r9b"},
{"r10", "r10d", "r10w", "r10b"},
{"r11", "r11d", "r11w", "r11b"},
{"r12", "r12d", "r12w", "r12b"},
{"r13", "r13d", "r13w", "r13b"},
{"r14", "r14d", "r14w", "r14b"},
{"r15", "r15d", "r15w", "r15b"},
};
// clang-format on
static const char *getReg(RegKind reg, int size) {
switch (size) {
case 1:
return RegTable[reg][3];
case 2:
return RegTable[reg][2];
case 4:
return RegTable[reg][1];
case 8:
return RegTable[reg][0];
}
errorUnreachable();
return "";
}
/*
static const char *argRegs[REG_ARGS_MAX_COUNT] = {
"rdi", "rsi", "rdx", "rcx", "r8", "r9"
};
*/
static const RegKind argRegs[REG_ARGS_MAX_COUNT] = {RDI, RSI, RDX, RCX, R8, R9};
static void genCodeGVarInit(GVarInit *initializer) {
for (GVarInit *elem = initializer; elem; elem = elem->next) {
if (elem->kind == GVarInitZero) {
dumpf(" .zero %d\n", elem->size);
} else if (elem->kind == GVarInitNum) {
switch (elem->size) {
case 8:
dumpf(" .quad %d\n", elem->rhs->val);
break;
case 4:
dumpf(" .long %d\n", elem->rhs->val);
break;
case 1:
dumpf(" .byte %d\n", elem->rhs->val);
break;
default:
errorUnreachable();
}
} else if (elem->kind == GVarInitString) {
dumpf(" .string \"%s\"\n", elem->rhs->token->literalStr->string);
} else if (elem->kind == GVarInitPointer) {
if (elem->rhs->kind == NodeLiteralString) {
dumpf(" .quad .LiteralString%d\n", elem->rhs->token->literalStr->id);
} else if (elem->rhs->kind == NodeGVar) {
Token *token = initializer->rhs->token;
dumpf(" .quad %.*s\n", token->len, token->str);
} else if (elem->rhs->kind == NodeLVar) {
dumpf(" .quad .StaticVar%d\n", elem->rhs->obj->staticVarID);
} else if (elem->rhs->kind == NodeNum) {
dumpf(" .long %d\n", elem->rhs->val);
} else {
errorUnreachable();
}
} else {
errorUnreachable();
}
}
}
void genCodeGlobals(void) {
if (globals.globalVars == NULL && globals.staticVars == NULL &&
globals.strings == NULL)
return;
dumps("\n.data");
if (globals.literalStringCount) {
LiteralString **strings = (LiteralString **)safeAlloc(
globals.literalStringCount * sizeof(LiteralString *));
// Reverse order.
int index = globals.literalStringCount - 1;
for (LiteralString *s = globals.strings; s; s = s->next) {
strings[index--] = s;
}
for (int i = 0; i < globals.literalStringCount; ++i) {
LiteralString *s = strings[i];
dumpf(".LiteralString%d:\n", s->id);
dumpf(" .string \"%s\"\n", s->string);
}
safeFree(strings);
}
for (GVar *gvar = globals.globalVars; gvar; gvar = gvar->next) {
Obj *v = gvar->obj;
if (v->isExtern)
continue;
if (!v->isStatic) {
dumpf(".globl %.*s\n", v->token->len, v->token->str);
}
dumpf("%.*s:\n", v->token->len, v->token->str);
genCodeGVarInit(gvar->initializer);
}
for (GVar *v = globals.staticVars; v; v = v->next) {
dumpf(".StaticVar%d:\n", v->obj->staticVarID);
genCodeGVarInit(v->initializer);
}
}
static void genCodeLVal(const Node *n) {
if (!n)
return;
if (n->kind == NodeDeref) {
genCode(n->rhs);
// Address for variable must be on the top of the stack.
return;
} else if (n->kind == NodeExprList) {
Node *expr = n->body;
if (!expr)
errorAt(n->token, "Not a lvalue");
while (expr->next)
expr = expr->next;
if (!isLvalue(expr))
errorAt(expr->token, "Not a lvalue");
genCode(n);
return;
} else if (!isLvalue(n)) {
errorAt(n->token, "Not a lvalue");
}
// Make sure the value on the top of the stack is the memory address to lhs
// variable.
// When it's local variable, calculate it on rax from the rbp(base pointer)
// and offset, then store it on the top of the stack. Calculate it on rax,
// not on rbp, because rbp must NOT be changed until exiting from a
// function.
if (n->kind == NodeGVar || (n->kind == NodeLVar && n->obj->isExtern)) {
dumpf(" lea rax, %.*s[rip]\n", n->token->len, n->token->str);
dumps(" push rax");
} else if (n->kind == NodeMemberAccess) {
Obj *m = findStructMember(n->lhs->type->structDef, n->token->str, n->token->len);
genCodeLVal(n->lhs);
dumps(" pop rax");
dumpf(" add rax, %d\n", m->offset);
dumps(" push rax");
} else if (n->kind == NodeLVar && n->obj->isStatic) {
dumpf(" lea rax, .StaticVar%d[rip]\n", n->obj->staticVarID);
dumps(" push rax");
} else if (n->obj->type->type == TypeFunction) {
dumpf(" mov rax, QWORD PTR %.*s@GOTPCREL[rip]\n", n->token->len, n->token->str);
dumps(" push rax");
} else {
dumps(" mov rax, rbp");
dumpf(" sub rax, %d\n", n->obj->offset);
dumps(" push rax");
}
}
// Generate code dereferencing variables as rvalue. If code for dereference as
// lvalue, use genCodeLVal() instead.
static void genCodeDeref(const Node *n) {
if (!n)
return;
genCodeLVal(n);
dumps(" mov rax, [rsp]");
switch (sizeOf(n->type)) {
case 8:
dumps(" mov rax, [rax]");
break;
case 4:
dumps(" mov eax, DWORD PTR [rax]");
dumps(" movsx rax, eax");
break;
case 1:
dumps(" mov al, BYTE PTR [rax]");
dumps(" movsx rax, al");
break;
default:
dumps(" lea rax, [rax]");
break;
}
dumps(" mov [rsp], rax");
}
static void genCodeAssign(const Node *n) {
if (!n)
return;
genCode(n->rhs);
genCodeLVal(n->lhs);
// Stack before assign:
// | |
// | ...... |
// +---------------------+
// | Rhs value | --> Load to RDI.
// +---------------------+
// | Lhs memory address | --> Load to RAX.
// +---------------------+
//
// Stack after assign:
// | |
// | ...... |
// +---------------------+
// | Rhs value | <-- Restore from RDI.
// +---------------------+
dumps(" pop rax");
dumps(" pop rdi");
switch (sizeOf(n->type)) {
case 8:
dumps(" mov [rax], rdi");
break;
case 4:
dumps(" mov DWORD PTR [rax], edi");
break;
case 1:
dumps(" mov BYTE PTR [rax], dil");
break;
default:
errorUnreachable();
}
dumps(" push rdi");
}
static void genCodeReturn(const Node *n) {
if (!n)
return;
if (n->lhs) {
if (!isExprNode(n->lhs))
errorAt(n->lhs->token, "Expression doesn't left value.");
genCode(n->lhs);
dumps(" pop rax");
}
dumpf(" jmp .Lreturn_%.*s\n", dumpEnv.currentFunc->token->len,
dumpEnv.currentFunc->token->str);
}
static void genCodeIf(const Node *n) {
if (!n)
return;
int elseblockCount = 0;
genCode(n->condition);
dumps(" pop rax");
dumps(" cmp rax, 0");
if (n->elseblock) {
dumpf(" je .Lelse%d_%d\n", n->blockID, elseblockCount);
} else {
dumpf(" je .Lend%d\n", n->blockID);
}
genCode(n->body);
if (isExprNode(n->body)) {
dumps(" pop rax");
}
if (n->elseblock) {
dumpf(" jmp .Lend%d\n", n->blockID);
}
if (n->elseblock) {
for (Node *e = n->elseblock; e; e = e->next) {
dumpf(".Lelse%d_%d:\n", n->blockID, elseblockCount);
++elseblockCount;
if (e->kind == NodeElseif) {
genCode(e->condition);
dumps(" pop rax");
dumps(" cmp rax, 0");
if (e->next)
dumpf(" je .Lelse%d_%d\n", n->blockID, elseblockCount);
else // Last 'else' is omitted.
dumpf(" je .Lend%d\n", n->blockID);
}
genCode(e->body);
dumpf(" jmp .Lend%d\n", n->blockID);
}
}
dumpf(".Lend%d:\n", n->blockID);
}
static void genCodeSwitch(const Node *n) {
int haveDefaultLabel = 0;
int loopBlockIDSave;
if (!n)
return;
loopBlockIDSave = dumpEnv.loopBlockID;
dumpEnv.loopBlockID = n->blockID;
genCode(n->condition);
dumps(" pop rax");
for (SwitchCase *c = n->cases; c; c = c->next) {
if (!c->node->condition) {
haveDefaultLabel = 1;
continue;
}
dumpf(" mov rdi, %d\n", c->node->condition->val);
dumps(" cmp rax, rdi");
dumpf(" je .Lswitch_case_%d_%d\n", n->blockID, c->node->condition->val);
}
if (haveDefaultLabel)
dumpf(" jmp .Lswitch_default_%d\n", n->blockID);
else
dumpf(" jmp .Lend%d\n", n->blockID);
genCode(n->body);
dumpf(".Lend%d:\n", n->blockID);
dumpEnv.loopBlockID = loopBlockIDSave;
}
static void genCodeSwitchCase(const Node *n) {
if (!n)
return;
if (n->condition)
dumpf(".Lswitch_case_%d_%d:\n", n->blockID, n->condition->val);
else
dumpf(".Lswitch_default_%d:\n", n->blockID);
}
static void genCodeFor(const Node *n) {
if (!n)
return;
int loopBlockIDSave = dumpEnv.loopBlockID;
dumpEnv.loopBlockID = n->blockID;
if (n->initializer) {
genCode(n->initializer);
// Not always initializer statement left a value on stack. E.g.
// Variable declarations won't left values on stack.
if (isExprNode(n->initializer))
dumps(" pop rax");
}
dumpf(".Lbegin%d:\n", n->blockID);
if (n->condition) {
genCode(n->condition);
} else {
dumps(" push 1");
}
dumps(" pop rax");
dumps(" cmp rax, 0");
dumpf(" je .Lend%d\n", n->blockID);
genCode(n->body);
if (n->body && isExprNode(n->body)) {
dumps(" pop rax");
}
dumpf(".Literator%d:\n", n->blockID);
if (n->iterator) {
genCode(n->iterator);
dumps(" pop rax");
}
dumpf(" jmp .Lbegin%d\n", n->blockID);
dumpf(".Lend%d:\n", n->blockID);
dumpEnv.loopBlockID = loopBlockIDSave;
}
static void genCodeDoWhile(const Node *n) {
int loopBlockIDSave = dumpEnv.loopBlockID;
if (!n)
return;
dumpEnv.loopBlockID = n->blockID;
dumpf(".Lbegin%d:\n", n->blockID);
genCode(n->body);
if (isExprNode(n->body)) {
dumps(" pop rax");
}
dumpf(".Literator%d:\n", n->blockID);
genCode(n->condition);
dumps(" pop rax");
dumps(" cmp rax, 0");
dumpf(" jne .Lbegin%d\n", n->blockID);
dumpf(".Lend%d:\n", n->blockID);
dumpEnv.loopBlockID = loopBlockIDSave;
}
static void genCodeFCall(const Node *n) {
if (!n)
return;
static int stackAlignState = -1; // RSP % 16
int stackAlignStateSave = 0;
int stackVarSize = 0; // Size of local variables on stack.
int stackArgSize = 0; // Size of arguments (passed to function) on stack.
int exCapToAlignRSP = 0; // Extra memory size to capture in order to align RSP.
int regargs = n->fcall->argsCount;
int isSimpleFuncCall =
n->body->type->type == TypeFunction; // TRUE if simple function call.
if (!isSimpleFuncCall)
genCode(n->body);
stackAlignStateSave = stackAlignState;
if (regargs > REG_ARGS_MAX_COUNT)
regargs = REG_ARGS_MAX_COUNT;
if (stackAlignState == -1) {
stackAlignState = 0;
stackVarSize = dumpEnv.currentFunc->func->capStackSize;
}
if ((n->fcall->argsCount - regargs) > 0) {
stackArgSize += (n->fcall->argsCount - regargs) * ONE_WORD_BYTES;
stackVarSize += stackArgSize;
}
if (!isSimpleFuncCall)
stackVarSize += ONE_WORD_BYTES; // Capacity for function pointer on stack
stackAlignState = (stackAlignState + stackVarSize) % 16;
if (stackAlignState)
exCapToAlignRSP = 16 - stackAlignState;
stackAlignState = 0;
if (exCapToAlignRSP)
// Align RSP to multiple of 16.
dumpf(" sub rsp, %d /* RSP alignment */\n", exCapToAlignRSP);
for (Node *c = n->fcall->args; c; c = c->next) {
genCode(c);
if (isExprNode(c))
stackAlignState += 8;
}
for (int i = 0; i < regargs; ++i)
dumpf(" pop %s\n", getReg(argRegs[i], ONE_WORD_BYTES));
// Set AL to count of float arguments in variadic arguments area. This is
// always 0 now.
dumps(" mov al, 0");
if (isSimpleFuncCall) {
dumpf(" call %.*s\n", n->fcall->len, n->fcall->name);
} else {
dumpf(" mov r10, QWORD PTR %d[rsp]\n", exCapToAlignRSP + stackArgSize);
dumps(" call r10");
dumpf(" add rsp, %d /* Throw away function pointer */\n", ONE_WORD_BYTES);
}
stackAlignState = stackAlignStateSave;
if (exCapToAlignRSP)
dumpf(" add rsp, %d /* RSP alignment */\n", exCapToAlignRSP);
// Adjust RSP value when we used stack to pass arguments.
if (stackArgSize)
dumpf(" add rsp, %d /* Pop overflow args */\n", stackArgSize);
dumps(" push rax");
}
static void genCodeVaStart(const Node *n) {
Obj *lastArg = NULL;
int offset = 0; // va_list member's offset currently watching
int argsOverflows = 0;
for (Obj *arg = n->parentFunc->func->args; arg; arg = arg->next)
if (!arg->next)
lastArg = arg;
genCodeLVal(n->fcall->args->next);
dumps(" pop rax");
if (n->parentFunc->func->argsCount < REG_ARGS_MAX_COUNT) {
dumpf(" mov DWORD PTR %d[rax], %d\n", offset,
ONE_WORD_BYTES * (REG_ARGS_MAX_COUNT + 1) - lastArg->offset);
} else {
dumpf(" mov DWORD PTR %d[rax], %d\n", offset,
ONE_WORD_BYTES * REG_ARGS_MAX_COUNT);
}
offset += sizeOf(&Types.Int);
dumpf(" mov DWORD PTR %d[rax], %d\n", offset, REG_ARGS_MAX_COUNT * ONE_WORD_BYTES);
offset += sizeOf(&Types.Int);
if (n->parentFunc->func->argsCount <= REG_ARGS_MAX_COUNT) {
dumpf(" lea rdi, %d[rbp]\n", ONE_WORD_BYTES * 2);
} else {
int overflow_reg_offset = -lastArg->offset + ONE_WORD_BYTES;
dumpf(" lea rdi, %d[rbp]\n", overflow_reg_offset);
}
dumpf(" mov %d[rax], rdi\n", offset);
offset += ONE_WORD_BYTES;
dumpf(" lea rdi, %d[rbp]\n", -n->parentFunc->func->args->offset);
dumpf(" mov %d[rax], rdi\n", offset);
}
static void genCodeFunction(const Node *n) {
int regargs = 0;
if (!n)
return;
else if (dumpEnv.currentFunc)
errorUnreachable();
dumpEnv.currentFunc = n->obj;
regargs = n->obj->func->argsCount;
if (regargs > REG_ARGS_MAX_COUNT)
regargs = REG_ARGS_MAX_COUNT;
dumpc('\n');
if (!n->obj->isStatic) {
dumpf(".globl %.*s\n", n->obj->token->len, n->obj->token->str);
}
dumpf("%.*s:\n", n->obj->token->len, n->obj->token->str);
// Prologue.
dumps(" push rbp");
dumps(" mov rbp, rsp");
if (n->obj->func->capStackSize)
dumpf(" sub rsp, %d\n", n->obj->func->capStackSize);
// Push arguments onto stacks from registers.
if (regargs) {
int count = 0;
Obj *arg = n->obj->func->args;
for (; count < regargs; ++count, arg = arg->next) {
int size = sizeOf(arg->type);
char *fmt;
switch (sizeOf(arg->type)) {
case 8:
fmt = " mov %d[rbp], %s\n";
break;
case 4:
fmt = " mov DWORD PTR %d[rbp], %s\n";
break;
case 1:
fmt = " mov BYTE PTR %d[rbp], %s\n";
break;
default:
errorUnreachable();
}
dumpf(fmt, -arg->offset, getReg(argRegs[count], size));
}
}
if (n->obj->func->haveVaArgs && regargs < REG_ARGS_MAX_COUNT) {
int offset = 0;
for (Obj *arg = n->obj->func->args; arg; arg = arg->next)
if (!arg->next)
offset = -arg->offset;
for (int i = regargs; i < REG_ARGS_MAX_COUNT; ++i) {
offset += ONE_WORD_BYTES;
dumpf(" mov %d[rbp], %s\n", offset, getReg(argRegs[i], ONE_WORD_BYTES));
}
}
genCode(n->body);
// Epilogue
if (n->obj->token->len == 4 && memcmp(n->obj->token->str, "main", 4) == 0)
dumps(" mov rax, 0");
dumpf(".Lreturn_%.*s:\n", n->obj->token->len, n->obj->token->str);
dumps(" mov rsp, rbp");
dumps(" pop rbp");
dumps(" ret");
dumpEnv.currentFunc = NULL;
}
static void genCodeIncrement(const Node *n, int prefix) {
if (!n)
return;
Node *expr = prefix ? n->rhs : n->lhs;
genCodeLVal(expr);
dumps(" pop rax");
dumps(" mov rdi, rax");
switch (sizeOf(n->type)) {
case 8:
dumps(" mov rax, [rax]");
break;
case 4:
dumps(" mov eax, DWORD PTR [rax]");
dumps(" movsx rax, eax");
break;
case 1:
dumps(" mov al, BYTE PTR [rax]");
dumps(" movsx rax, al");
break;
default:
errorUnreachable();
}
// Postfix increment operator refers the value before increment.
if (!prefix)
dumps(" push rax");
switch (sizeOf(n->type)) {
case 8:
dumpf(" add rax, %d\n", getAlternativeOfOneForType(n->type));
break;
case 4:
dumpf(" add eax, %d\n", getAlternativeOfOneForType(n->type));
dumps(" movsx rax, eax");
break;
case 1:
dumpf(" add al, %d\n", getAlternativeOfOneForType(n->type));
dumps(" movsx rax, al");
break;
default:
errorUnreachable();
}
// Prefix increment operator refers the value after increment.
if (prefix)
dumps(" push rax");
// Reflect the expression result on variable.
switch (sizeOf(n->type)) {
case 8:
dumps(" mov [rdi], rax");
break;
case 4:
dumps(" mov DWORD PTR [rdi], eax");
break;
case 1:
dumps(" mov BYTE PTR [rdi], al");
break;
default:
errorUnreachable();
}
}
static void genCodeDecrement(const Node *n, int prefix) {
if (!n)
return;
Node *expr = prefix ? n->rhs : n->lhs;
genCodeLVal(expr);
dumps(" pop rax");
dumps(" mov rdi, rax");
switch (sizeOf(n->type)) {
case 8:
dumps(" mov rax, [rax]");
break;
case 4:
dumps(" mov eax, DWORD PTR [rax]");
dumps(" movsx rax, eax");
break;
case 1:
dumps(" mov al, BYTE PTR [rax]");
dumps(" movsx rax, al");
break;
default:
errorUnreachable();
}
// Postfix decrement operator refers the value before decrement.
if (!prefix)
dumps(" push rax");
switch (sizeOf(n->type)) {
case 8:
dumpf(" sub rax, %d\n", getAlternativeOfOneForType(n->type));
break;
case 4:
dumpf(" sub eax, %d\n", getAlternativeOfOneForType(n->type));
dumps(" movsx rax, eax");
break;
case 1:
dumpf(" sub al, %d\n", getAlternativeOfOneForType(n->type));
dumps(" movsx rax, al");
break;
default:
errorUnreachable();
}
// Prefix decrement operator refers the value after decrement.
if (prefix)
dumps(" push rax");
// Reflect the expression result on variable.
switch (sizeOf(n->type)) {
case 8:
dumps(" mov [rdi], rax");
break;
case 4:
dumps(" mov DWORD PTR [rdi], eax");
break;
case 1:
dumps(" mov BYTE PTR [rdi], al");
break;
default:
errorUnreachable();
}
}
static void genCodeAdd(const Node *n) {
if (!n)
return;
int altOne = getAlternativeOfOneForType(n->type);
genCode(n->lhs);
genCode(n->rhs);
if (isWorkLikePointer(n->lhs->type) || isWorkLikePointer(n->rhs->type)) {
// Load integer to RAX and pointer to RDI in either case.
if (isWorkLikePointer(n->lhs->type)) { // ptr + num
dumps(" pop rax");
dumps(" pop rdi");
} else { // num + ptr
dumps(" pop rdi");
dumps(" pop rax");
}
dumpf(" mov rsi, %d\n", altOne);
dumps(" imul rax, rsi");
dumps(" add rax, rdi");
dumps(" push rax");
} else {
dumps(" pop rdi");
dumps(" pop rax");
switch (sizeOf(n->lhs->type)) {
case 8:
dumps(" add rax, rdi");
break;
case 4:
dumps(" add eax, edi");
dumps(" movsx rax, eax");
break;
case 1:
dumps(" add al, dil");
dumps(" movsx rax, al");
break;
default:
errorUnreachable();
}
dumps(" push rax");
}
}
static void genCodeSub(const Node *n) {
if (!n)
return;
genCode(n->lhs);
genCode(n->rhs);
dumps(" pop rdi");
dumps(" pop rax");
if (n->lhs->type->type == TypePointer) {
int altOne = getAlternativeOfOneForType(n->lhs->type);