-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.c
2504 lines (2087 loc) · 103 KB
/
backend.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
/*
Working notes
Function calls, 'set_return'
How do we indicate which sets of keys we want to use as registers?
Reordering the way in which those keys are initialized might permit us to do
better register allocation. Do we want to bother with getting that working?
It seems like an optimization which would be rather complicated, but it
could potentially remove multiple extra instructions in certain cases.
'my_function(x, y << z)' is one such case:
x must be in RCX, as dictated by calling convention,
but z must be in CL for us to compute the shift.
'copy' and 'clear'
Optimizing these into efficient sequences of instructions must happen
during 'end_function', after register allocation, because we only then
know what the alignment of keys will be on the stack.
I can't remember whether I allready did some work towards this goal...
Temporary places for executing unwieldy instructions
Currently, there are a bunch of 'unimplemented' cases here, where we havent
thought out what to do when we run out of free registers.
* Knowing how this should work is tricky, because it has to interact with
register allocation
* ...but, I think we want to make sure this works before we do smart register
allocation, because that will allow us to more easily test some of the
pathological cases which we want to make sure we handle.
There are two cases we want to solve:
1. We need to flush a specific register so we can use it directly. Here, we can either
flush the register to another register, or flush it to the stack. (In practice,
we are probably never going to flush to a register, because if there are free
registers the register allocator has done a bad job. This is an argument
for working on this part before we do register allocation)
2. We need any register, because we generated a memory/immediate operand in a place
where we can only use a register operand. Here we can use any register, but we
might have to flush one.
Should the register allocator also have something to say here? Maybe it doesn't
matter: If there are no free registers, the allocator has failed and we are in
the worst case anyways.
Using x64 addressing modes
I think we can do this through approximately the same code pahts as those we will use
to infer that a key has a constant value.
Register allocation
* We have some initial hard constraints on which registers we can allocate, based on which instructions
we use a key in (e.g. RHS of a shift must be an immediate or CL)
* Certain keys will have to be in different registers at different times, if there are multiple
hard constraints on a single key
* Because of our previous work regarding fixing up instructions, hard constraints are not actually
hard, but we still want to do our best to acomodate them
Floating point
This is, as far as I can think, not a major concern, as the SSE instruction set is a lot
more uniform than amd64 in general. Casting will be a bit nasty. Negating a float is also
a bit tricky, as it requires referncing a memory location (PXOR with '-0.0', where '-0.0'
must be in memory as there are no immediates operand variants for PXOR).
*/
#include "common.c"
#include "backend.h"
typedef enum Reg {
REG_NONE = 0,
RIP, // Only used for addresses
RSP, RBP, // Kept outside main range so they don't get allocated
RAX, RCX, RDX, RBX,
/*RSP, RBP*/ RSI, RDI,
R8, R9, R10, R11,
R12, R13, R14, R15,
XMM0, XMM1, XMM2, XMM3,
XMM4, XMM5, XMM6, XMM7,
XMM8, XMM9, XMM10, XMM11,
XMM12, XMM13, XMM14, XMM15,
REG_COUNT
} Reg;
void print_reg(Reg reg, u8 size);
// This keeps track of which sub-register (AL, AX, EAX or RAX) of a specific
// register we are currently using, so we can allocate the minimal amount of
// stack space needed when flushing a register to the stack
typedef u64 Reg_Sizes;
u8 get_reg_size(Reg_Sizes sizes, Reg reg) {
assert(reg >= RAX && reg <= XMM15);
u8 size_index = (sizes >> ((reg - RAX)*2)) & 3;
return 1 << size_index;
}
Reg_Sizes set_reg_size(Reg_Sizes sizes, Reg reg, u8 size) {
u8 size_index;
switch (size) {
case 1: size_index = 0; break;
case 2: size_index = 1; break;
case 4: size_index = 2; break;
case 8: size_index = 3; break;
default: assert(false);
}
assert(reg >= RAX && reg <= XMM15);
u8 offset = (reg - RAX)*2;
sizes &= ~(3 << offset);
sizes |= size_index << offset;
return sizes;
}
typedef enum Reg_Kind {
REG_KIND_INVALID = 0,
REG_KIND_GPR,
REG_KIND_XMM,
} Reg_Kind;
Reg_Kind reg_kind(Reg reg) {
if ((reg >= RAX && reg <= R15) || reg == RSP || reg == RBP) return REG_KIND_GPR;
if (reg >= XMM0 && reg <= XMM15) return REG_KIND_GPR;
assert(false);
return 0;
}
typedef struct Address {
u8 base, index; // Reg
u8 scale; // Must be 1, 2, 4 or 8
i32 offset;
} Address;
bool address_uses_reg(Address *address, Reg reg) {
return address->base == reg || address->index == reg;
}
void replace_regs_in_address(Address *address, Reg old, Reg new) {
if (address->base == old) address->base = new;
if (address->index == old) address->index = new;
}
enum Key_Flags {
KEY_FLAG_ADDRESSABLE = 2,
};
// NB defined in header
struct Key {
u64 index;
u32 flags;
u32 alignment;
u32 size;
Key_Kind kind;
};
// NB defined in header
struct Place {
enum {
PLACE_NONE,
PLACE_KEY,
PLACE_KEY_ADDRESS,
PLACE_REG,
PLACE_MEM,
} kind;
u32 size;
union {
Key *key;
Reg reg;
Address address;
};
};
void print_place(Place *place);
u64 place_get_used_regs(Place place) {
if (place.kind == PLACE_REG) {
return 1 << place.reg;
} else if (place.kind == PLACE_MEM) {
return (1 << place.address.base) | (1 << place.address.index);
} else {
return 0;
}
}
typedef enum Inst_Kind {
INST_INVALID = 0,
INST_CALL,
INST_JMP,
INST_RET,
INST_INT3,
INST_NOP,
INST_CBW, // sign extend al into ah
INST_CWD, // sign extend ax into dx
INST_CDQ, // sign extend eax into edx
INST_CQO, // sign extend rax into rdx
INST_REP_STOSB,
INST_REP_STOSW,
INST_REP_STOSD,
INST_REP_STOSQ,
INST_REP_MOVSB,
INST_REP_MOVSW,
INST_REP_MOVSD,
INST_REP_MOVSQ,
INST_XOR_AH_AH,
INST_MOV,
INST_LEA,
INST_XCHG,
INST_ADD,
INST_SUB,
INST_AND,
INST_OR,
INST_XOR,
INST_CMP,
INST_SHL,
INST_SHR,
INST_SAR,
INST_INC,
INST_DEC,
INST_MUL,
INST_IMUL,
INST_DIV,
INST_IDIV,
INST_NEG,
INST_NOT,
INST_JE, // ZF = 1
INST_JNE, // ZF = 0
INST_JP, // PF = 1
INST_JNP, // PF = 0
INST_JA, // CF = 0 && ZF = 0
INST_JAE, // CF = 0
INST_JB, // CF = 1
INST_JBE, // CF = 0 || ZF = 0
INST_JL, // SF != OF
INST_JLE, // ZF = 1 || ZF != OF
INST_JG, // ZF = 0 && ZF == OF
INST_JGE, // SF == OF
#define INST_JCC_FIRST INST_JE
#define INST_JCC_LAST INST_JGE
INST_SETE, // ZF = 1
INST_SETNE, // ZF = 0
INST_SETP, // PF = 1
INST_SETNP, // PF = 0
INST_SETA, // CF = 0 && ZF = 0
INST_SETAE, // CF = 0
INST_SETB, // CF = 1
INST_SETBE, // CF = 0 || ZF = 0
INST_SETL, // SF != OF
INST_SETLE, // ZF = 1 || ZF != OF
INST_SETG, // ZF = 0 && ZF == OF
INST_SETGE, // SF == OF
// TODO SSE
INST_COUNT,
} Inst_Kind;
u8 *INST_NAMES[INST_COUNT] = {
[INST_CALL] = "call",
[INST_JMP] = "jmp",
[INST_RET] = "ret",
[INST_INT3] = "int 3",
[INST_NOP] = "nop",
[INST_CBW] = "cbw",
[INST_CWD] = "cwd",
[INST_CDQ] = "cdq",
[INST_CQO] = "cqo",
[INST_REP_STOSB] = "rep stosb",
[INST_REP_STOSW] = "rep stosw",
[INST_REP_STOSD] = "rep stosd",
[INST_REP_STOSQ] = "rep stosq",
[INST_REP_MOVSB] = "rep movsb",
[INST_REP_MOVSW] = "rep movsw",
[INST_REP_MOVSD] = "rep movsd",
[INST_REP_MOVSQ] = "rep movsq",
[INST_XOR_AH_AH] = "xor ah, ah",
[INST_JE] = "je",
[INST_JNE] = "jne",
[INST_JP] = "jp",
[INST_JNP] = "jnp",
[INST_JA] = "ja",
[INST_JAE] = "jae",
[INST_JB] = "jb",
[INST_JBE] = "jbe",
[INST_JL] = "jl",
[INST_JLE] = "jle",
[INST_JG] = "jg",
[INST_JGE] = "jge",
[INST_SETE] = "sete",
[INST_SETNE] = "setne",
[INST_SETP] = "setp",
[INST_SETNP] = "setnp",
[INST_SETA] = "seta",
[INST_SETAE] = "setae",
[INST_SETB] = "setb",
[INST_SETBE] = "setbe",
[INST_SETL] = "setl",
[INST_SETLE] = "setle",
[INST_SETG] = "setg",
[INST_SETGE] = "setge",
[INST_MOV] = "mov",
[INST_LEA] = "lea",
[INST_XCHG] = "xchg",
[INST_ADD] = "add",
[INST_SUB] = "sub",
[INST_AND] = "and",
[INST_OR] = "or",
[INST_XOR] = "xor",
[INST_CMP] = "cmp",
[INST_SHL] = "shl",
[INST_SHR] = "shr",
[INST_SAR] = "sar",
[INST_INC] = "inc",
[INST_DEC] = "dec",
[INST_MUL] = "mul",
[INST_IMUL] = "imul",
[INST_DIV] = "div",
[INST_IDIV] = "idiv",
[INST_NEG] = "neg",
[INST_NOT] = "not",
};
typedef struct Imm {
u8 size;
u64 value;
} Imm;
typedef struct Inst {
Inst_Kind kind;
Place places[2];
Imm imm;
u16 index;
} Inst;
void print_inst(Inst *inst);
u32 inst_get_used_regs(Inst *inst) {
return place_get_used_regs(inst->places[0]) | place_get_used_regs(inst->places[1]);
}
Inst_Kind JMP_FOR_CONDITION[CONDITION_COUNT] = {
[CONDITION_NONE] = INST_JMP,
[CONDITION_E] = INST_JE,
[CONDITION_NE] = INST_JNE,
[CONDITION_P] = INST_JP,
[CONDITION_NP] = INST_JNP,
[CONDITION_A] = INST_JA,
[CONDITION_AE] = INST_JAE,
[CONDITION_B] = INST_JB,
[CONDITION_BE] = INST_JBE,
[CONDITION_L] = INST_JL,
[CONDITION_LE] = INST_JLE,
[CONDITION_G] = INST_JG,
[CONDITION_GE] = INST_JGE,
};
typedef struct Inst_Block Inst_Block;
// typedefed in header
struct Jump_To {
u8 *debug_name;
Inst_Block *block;
u64 relative_bytecode_pos;
};
struct Jump_From {
Jump_To *jump_to;
Inst_Block *block;
};
enum { DEFAULT_INST_BLOCK_CAPACITY = 16 };
struct Inst_Block {
u16 length, capacity;
Inst_Block *next;
Jump_To *jump_to; // refers to label at start of block, if any
Jump_From *jump_from; // refers to INST_JMP at end of block, if any
Inst insts[];
};
enum { LINK_LIST_BLOCK_CAPACITY = 16 };
typedef struct Link_List Link_List; // A linked list of jump links
struct Link_List {
u32 length;
Link_List *next;
struct {
Jump_From *from;
Jump_To *to;
} links[LINK_LIST_BLOCK_CAPACITY];
};
typedef struct Inst_Block_Group {
u16 next_inst_index;
Inst_Block *start, *head;
} Inst_Block_Group;
// NB defined in header
typedef struct Code_Builder {
Arena *arena, *stack;
u64 next_key_index;
Link_List *link_list_start, *link_list_head; // for jumps
Inst_Block_Group inst_blocks;
} Code_Builder;
// NB defined in header
Code_Builder *new_code_builder(Arena *arena, Arena *stack) {
Code_Builder *builder = arena_new(arena, Code_Builder);
builder->arena = arena;
builder->stack = stack;
return builder;
}
void inst_block_group_concat(Inst_Block_Group *start, Inst_Block_Group *end) {
assert(start->head != null && start->head->next == null);
assert(end->start != null && end->head != null);
start->head->next = end->start;
start->head = end->head;
}
void inst_block_group_start_new_block(Code_Builder *builder, Inst_Block_Group *group, u16 capacity) {
Inst_Block *new = (Inst_Block*) arena_alloc(builder->arena, sizeof(Inst_Block) + capacity*sizeof(Inst));
new->capacity = capacity;
group->head = group->start == null? (group->start = new) : (group->head->next = new);
}
void inst_block_group_add_inst(Code_Builder *builder, Inst_Block_Group *group, Inst inst) {
if (
group->head == null ||
group->head->length >= group->head->capacity ||
group->head->jump_from != null
) {
inst_block_group_start_new_block(builder, group, DEFAULT_INST_BLOCK_CAPACITY);
}
assert(group->next_inst_index + 1 > group->next_inst_index);
group->next_inst_index += 1;
inst.index = group->next_inst_index;
group->head->insts[group->head->length] = inst;
group->head->length += 1;
}
void code_builder_insert_insts(
Code_Builder *builder, Inst_Block *block, u16 index,
Inst prefixes[], u8 prefix_length,
Inst postfixes[], u8 postfix_length
) {
if (prefix_length + postfix_length == 0) return;
assert(index < block->length);
u16 symbolic_inst_index = block->insts[index].index;
i32 spill_count = (prefix_length + postfix_length) - (block->capacity - block->length);
if (spill_count > 0) {
u16 capacity = max(spill_count, DEFAULT_INST_BLOCK_CAPACITY);
Inst_Block *new = (Inst_Block*) arena_alloc(builder->arena, sizeof(Inst_Block) + capacity*sizeof(Inst));
new->length = spill_count;
new->capacity = capacity;
new->jump_from = block->jump_from;
block->jump_from = null;
new->next = block->next;
block->next = new;
if (new->next == null) {
builder->inst_blocks.head = new;
}
}
// Move instructions after the current instruction into their right spot
{
Inst_Block *old_block = block;
Inst_Block *new_block = spill_count > 0? block->next : block;
u16 old_end = old_block->length - 1;
u16 new_end = spill_count > 0? new_block->length - 1 : old_end + prefix_length + postfix_length;
for (u16 i = index + 1; i < block->length; i += 1) {
new_block->insts[new_end] = old_block->insts[old_end];
old_end -= 1;
if (new_end == 0) {
assert(spill_count > 0);
new_block = old_block;
new_end = old_block->capacity - 1;
} else {
new_end -= 1;
}
}
}
if (spill_count > 0) {
block->length = block->capacity;
} else {
block->length += prefix_length + postfix_length;
}
assert(block->length <= block->capacity);
// Move the current instruction into the right place
Inst_Block *new_inst_block = block;
u16 new_inst_index = index + prefix_length;
if (new_inst_index >= new_inst_block->length) {
new_inst_index -= new_inst_block->length;
new_inst_block = new_inst_block->next;
}
new_inst_block->insts[new_inst_index] = block->insts[index];
// Copy in prefixes
{
Inst_Block *target_block = block;
u16 target_index = index;
for (u32 i = 0; i < prefix_length; i += 1) {
if (target_index >= target_block->length) {
target_index -= target_block->length;
target_block = target_block->next;
}
target_block->insts[target_index] = prefixes[i];
target_block->insts[target_index].index = symbolic_inst_index;
target_index += 1;
}
}
// Copy in postfixes
{
Inst_Block *target_block = block;
u16 target_index = index + prefix_length + 1;
for (u32 i = 0; i < postfix_length; i += 1) {
if (target_index >= target_block->length) {
target_index -= target_block->length;
target_block = target_block->next;
}
target_block->insts[target_index] = postfixes[i];
target_block->insts[target_index].index = symbolic_inst_index;
target_index += 1;
}
}
}
// NB defined in header
Key *new_key(Code_Builder *builder, int kind, u32 size, u32 alignment) {
if (kind == KEY_INTEGER) {
assert(size == 1 || size == 2 || size == 4 || size == 8);
assert(alignment == size);
} else if (kind == KEY_FLOAT) {
assert(size == 4 || size == 8);
assert(alignment == size);
} else if (kind == KEY_COMPOUND) {
assert(alignment == 1 || alignment == 2 || alignment == 4 || alignment == 8);
} else {
assert(false);
}
Key *key = arena_new(builder->arena, Key);
key->index = builder->next_key_index;
builder->next_key_index += 1;
key->size = size;
key->alignment = alignment;
key->kind = kind;
builder->next_key_index;
return key;
}
// NB all of these functions are also defined in header
#define GEN_NEW_INT_FUNCTION(name, type) \
Key *name(Code_Builder *builder, type value) { \
Key *key = new_key(builder, KEY_INTEGER, sizeof(type), sizeof(type)); \
Inst inst = { INST_MOV, { { PLACE_KEY, sizeof(type), .key = key } }, { sizeof(type), .value = (u64) value } }; \
inst_block_group_add_inst(builder, &builder->inst_blocks, inst); \
return key; \
}
GEN_NEW_INT_FUNCTION(new_i8, i8)
GEN_NEW_INT_FUNCTION(new_i16, i16)
GEN_NEW_INT_FUNCTION(new_i32, i32)
GEN_NEW_INT_FUNCTION(new_i64, i64)
GEN_NEW_INT_FUNCTION(new_u8, u8)
GEN_NEW_INT_FUNCTION(new_u16, u16)
GEN_NEW_INT_FUNCTION(new_u32, u32)
GEN_NEW_INT_FUNCTION(new_u64, u64)
GEN_NEW_INT_FUNCTION(new_pointer, u64)
#undef GEN_NEW_INT_FUNCTION
// NB defined in header
Place key_deref(Key *key, u32 size) {
assert(key->kind == KEY_INTEGER && key->size == POINTER_SIZE);
return (Place) { PLACE_KEY_ADDRESS, size, .key = key };
}
// NB defined in header
Place key_direct(Key *key) {
return (Place) { PLACE_KEY, key->size, .key = key };
}
// NB defined in header
Jump_To *add_label(Code_Builder *builder, u8 *debug_name) {
Jump_To *result = arena_new(builder->arena, Jump_To);
result->relative_bytecode_pos = U64_MAX;
result->debug_name = debug_name;
if (builder->inst_blocks.head == null || builder->inst_blocks.head->length > 0 || builder->inst_blocks.head->jump_to != null) {
inst_block_group_start_new_block(builder, &builder->inst_blocks, DEFAULT_INST_BLOCK_CAPACITY);
}
assert(builder->inst_blocks.head->jump_to == null);
builder->inst_blocks.head->jump_to = result;
result->block = builder->inst_blocks.head;
return result;
}
// NB defined in header
Jump_From *add_jump(Code_Builder *builder, Condition condition) {
Jump_From *result = arena_new(builder->arena, Jump_From);
if (builder->inst_blocks.head == null || builder->inst_blocks.head->jump_from != null) {
// We have to start a new block after the jump we insert, so we just need a single slot in this block.
inst_block_group_start_new_block(builder, &builder->inst_blocks, 1);
}
Inst inst = { JMP_FOR_CONDITION[condition] };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
assert(builder->inst_blocks.head->jump_from == null);
builder->inst_blocks.head->jump_from = result;
result->block = builder->inst_blocks.head;
return result;
}
// NB defined in header
void link_jump(Code_Builder *builder, Jump_From *from, Jump_To *to) {
assert(from->jump_to == null);
from->jump_to = to;
if (builder->link_list_start == null) {
builder->link_list_start = arena_new(builder->arena, Link_List);
builder->link_list_head = builder->link_list_start;
}
if (builder->link_list_head->length >= LINK_LIST_BLOCK_CAPACITY) {
Link_List *new = arena_new(builder->arena, Link_List);
builder->link_list_head->next = new;
builder->link_list_head = new;
}
builder->link_list_head->links[builder->link_list_head->length].from = from;
builder->link_list_head->links[builder->link_list_head->length].to = to;
builder->link_list_head->length += 1;
}
// NB defined in header
void clear(Code_Builder *builder, Place place) {
assert(place.kind == PLACE_KEY || place.kind == PLACE_KEY_ADDRESS);
if (place.size == 1 || place.size == 2 || place.size == 4 || place.size == 8) {
Inst inst = { INST_MOV, { place }, { place.size, .value = 0 } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
} else {
// TODO Unroll this into a sequence of movs in some cases
// What heuristic should we use for that? Unroll when the unrolled version
// produces less bytes of instructions, or unroll when the unrolled version
// causes less register pressure?
// For the second option, we would have to do the unrolling at a later stage
// in the pipeline, when we know whether using RAX, RCX and RDI would cause us
// to have to spill many registers.
// TODO Also, what about alignment concerns. Is that really not an issue anymore
// on modern processors?
// NB When we fix this, also fix 'copy', see below
u32 size = place.size;
Inst inst = { INST_REP_STOSB, { place }, { 4, place.size } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
}
}
// NB defined in header
void copy(Code_Builder *builder, Place source, Place destination) {
assert(source.kind == PLACE_KEY || source.kind == PLACE_KEY_ADDRESS);
assert(destination.kind == PLACE_KEY || destination.kind == PLACE_KEY_ADDRESS);
assert(source.size == destination.size);
u32 size = source.size;
if (size == 1 || size == 2 || size == 4 || size == 8) {
Inst inst = { INST_MOV, { destination, source } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
} else {
// TODO The same general concerns as in 'void clear' above also apply here
Inst inst = { INST_REP_MOVSB, { destination, source }, { 4, size } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
}
}
// NB defined in header
void set_return(Code_Builder *builder, Key_Kind kind, Place place) {
// TODO This function is to simplistic. We would preferably couple it with
// how we generate the 'ret' instruction, or alternatively with how we
// handle register allocation, so we can verify that the generated 'mov rax, ...'
// is allways followed by the epilog or a direct 'ret'
//assert(place.kind == PLACE_KEY || place.kind == PLACE_KEY_ADDRESS); TODO TODO TODO reenable
if (place.kind == PLACE_KEY) {
assert(place.key->kind == kind);
}
if (kind == KEY_INTEGER) {
Inst inst = { INST_MOV, { { PLACE_REG, place.size, .reg = RAX }, place } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
} else {
assert(false);
}
}
void binary(Code_Builder *builder, Key_Kind kind, Binary_Kind binary, Place left, Place right) {
assert(left.size == right.size);
if (left.kind == PLACE_KEY) {
assert(left.key->kind == kind);
} else if (left.kind == PLACE_KEY_ADDRESS) {
assert(left.key->size == POINTER_SIZE && left.key->kind == KEY_INTEGER);
} else {
//assert(false); TODO TODO TODO TODO reenable
}
if (right.kind == PLACE_KEY) {
assert(right.key->kind == kind);
} else if (right.kind == PLACE_KEY_ADDRESS) {
assert(right.key->size == POINTER_SIZE && right.key->kind == KEY_INTEGER);
} else {
//assert(false); TODO TODO TODO TODO reenable
}
Inst_Kind inst_kind;
if (kind == KEY_INTEGER) {
switch (binary) {
case BINARY_MOV: inst_kind = INST_MOV; break;
case BINARY_ADD: inst_kind = INST_ADD; break;
case BINARY_SUB: inst_kind = INST_SUB; break;
case BINARY_MUL: inst_kind = INST_MUL; break;
case BINARY_DIV: inst_kind = INST_DIV; break;
case BINARY_IMUL: inst_kind = INST_IMUL; break;
case BINARY_IDIV: inst_kind = INST_IDIV; break;
case BINARY_AND: inst_kind = INST_AND; break;
case BINARY_OR: inst_kind = INST_OR; break;
case BINARY_XOR: inst_kind = INST_XOR; break;
case BINARY_CMP: inst_kind = INST_CMP; break;
case BINARY_SHL: inst_kind = INST_SHL; break;
case BINARY_SHR: inst_kind = INST_SHR; break;
case BINARY_SAR: inst_kind = INST_SAR; break;
default: assert(false);
}
} else if (kind == KEY_FLOAT) {
unimplemented();
} else {
assert(false);
}
Inst inst = { inst_kind, { left, right } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
}
// NB defined in header
void unary(Code_Builder *builder, Key_Kind kind, Unary_Kind unary, Place place) {
if (place.kind == PLACE_KEY) {
assert(place.key->kind == kind);
} else if (place.kind == PLACE_KEY_ADDRESS) {
assert(place.key->size == POINTER_SIZE && place.key->kind == KEY_INTEGER);
} else {
assert(false);
}
Inst_Kind inst_kind;
if (kind == KEY_INTEGER) {
switch (unary) {
case UNARY_NEG: inst_kind = INST_NEG; break;
case UNARY_NOT: inst_kind = INST_NOT; break;
case UNARY_INC: inst_kind = INST_INC; break;
case UNARY_DEC: inst_kind = INST_DEC; break;
default: assert(false);
}
} else if (kind == KEY_FLOAT) {
unimplemented();
} else {
assert(false);
}
Inst inst = { inst_kind, { place } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
}
// Produces a new key, which contains the pointer to the given value
// This generates a lea instruction
// NB defined in header
Key *address_of(Code_Builder *builder, Key *value) {
value->flags |= KEY_FLAG_ADDRESSABLE;
Key *address = new_key(builder, KEY_INTEGER, POINTER_SIZE, POINTER_SIZE);
Inst inst = { INST_LEA, { { PLACE_KEY, POINTER_SIZE, .key = address }, { PLACE_KEY, POINTER_SIZE, .key = value } } };
inst_block_group_add_inst(builder, &builder->inst_blocks, inst);
return address;
}
typedef struct Allocator {
Reg_Sizes reg_sizes;
Reg next_gpr;
i32 next_stack_offset;
i32 *max_stack_offset;
} Allocator;
i32 alloc_stack_space(Allocator *allocator, i32 size, i32 align) {
if (size == 0) return 0;
assert(align == 1 || align == 2 || align == 4 || align == 8);
i32 place = allocator->next_stack_offset;
place = (i32) round_to_next((i32) place, align);
allocator->next_stack_offset = place + size;
*allocator->max_stack_offset = max(allocator->next_stack_offset, *allocator->max_stack_offset);
assert(place <= I32_MAX);
return place;
}
Reg alloc_gpr(Allocator *allocator, u32 size) {
if (allocator->next_gpr == REG_NONE) {
allocator->next_gpr = RAX;
}
if (allocator->next_gpr > R15) {
return REG_NONE;
} else {
Reg result = allocator->next_gpr;
allocator->next_gpr += 1;
allocator->reg_sizes = set_reg_size(allocator->reg_sizes, result, size);
return result;
}
}
bool allocator_reg_is_allocated(Allocator *allocator, Reg reg) {
return allocator->next_gpr > reg;
}
typedef struct Flush_Info {
bool did_flush;
Inst push, pop;
Place place;
} Flush_Info;
Flush_Info allocator_temp_flush_reg(Allocator *allocator, Reg reg) {
assert(reg_kind(reg) == REG_KIND_GPR); // TODO also allow flushing XMM registers
Flush_Info result = {0};
if (!allocator_reg_is_allocated(allocator, reg)) return result;
u32 flush_size = get_reg_size(allocator->reg_sizes, reg);
Reg flush_reg = alloc_gpr(allocator, flush_size);
if (flush_reg != REG_NONE) {
result.place = (Place) { PLACE_REG, flush_size, .reg = flush_reg };
} else {
i32 stack_offset = alloc_stack_space(allocator, flush_size, flush_size);
Address address = { RSP, REG_NONE, 0, stack_offset };
result.place = (Place) { PLACE_MEM, flush_size, .address = address };
}
Place source_place = { PLACE_REG, flush_size, .reg = reg };
result.push = (Inst) { INST_MOV, { result.place, source_place } };
result.pop = (Inst) { INST_MOV, { source_place, result.place } };
result.did_flush = true;
return result;
}
// NB defined in header
void end_function(Code_Builder *builder) {
arena_stack_push(builder->stack);
u64 key_count = builder->next_key_index;
Place *key_places = (Place*) arena_alloc(builder->stack, key_count * sizeof(Place));
mem_clear((u8*) key_places, key_count * sizeof(Place));
i32 max_stack_offset = 0;
Allocator allocator = { .max_stack_offset = &max_stack_offset };
for (Inst_Block *block = builder->inst_blocks.start; block != null; block = block->next) {
for (u16 i = 0; i < block->length; i += 1) {
Inst *inst = &block->insts[i];
for (u8 j = 0; j < 2; j += 1) {
if (!(inst->places[j].kind == PLACE_KEY || inst->places[j].kind == PLACE_KEY_ADDRESS)) {
continue;
}
Key *key = inst->places[j].key;
Place *assigned_place = &key_places[key->index];
if (assigned_place->kind == PLACE_NONE) {
if (key->kind == KEY_COMPOUND || (key->flags & KEY_FLAG_ADDRESSABLE)) {
i32 stack_offset = alloc_stack_space(&allocator, key->size, key->alignment);
Address address = { RSP, REG_NONE, 0, stack_offset };
*assigned_place = (Place) { PLACE_MEM, key->size, .address = address };
} else if (key->kind == KEY_INTEGER) {
Reg reg = alloc_gpr(&allocator, key->size);
assert(reg != REG_NONE); // TODO
*assigned_place = (Place) { PLACE_REG, key->size, .reg = reg };
} else if (key->kind == KEY_FLOAT) {
unimplemented(); // TODO allocate a xmm register
} else {
assert(false);
}
}
}
}
}
// Generate instructions
Inst_Block **previous_block_slot = &builder->inst_blocks.start;
u32 skip_insts = 0;
for (Inst_Block *block = builder->inst_blocks.start; block != null; block = block->next) {
for (u16 i = 0; i < block->length; i += 1) {
if (skip_insts > 0) {
skip_insts -= 1;
continue;
}
Allocator temp_allocator = allocator;
enum { MAX_PREFIXES = 10, MAX_POSTFIXES = 10 };
Inst prefix_array[MAX_PREFIXES] = {0}, postfix_array[MAX_POSTFIXES] = {0};
u8 prefix_index = 0, postfix_index = MAX_POSTFIXES;
Inst *inst = &block->insts[i];
bool remove_inst = false;
for (u8 j = 0; j < 2; j += 1) {
Place *place_slot = &inst->places[j];
if (place_slot->kind == PLACE_KEY) {
Key *key = place_slot->key;
*place_slot = key_places[key->index];
} else if (inst->places[j].kind == PLACE_KEY_ADDRESS) {
Key *key = place_slot->key;
Place *place = &key_places[key->index];
Reg pointer_reg = REG_NONE;
if (place->kind == PLACE_MEM) {
pointer_reg = alloc_gpr(&temp_allocator, POINTER_SIZE);
if (pointer_reg == REG_NONE) {
unimplemented(); // TODO (2) We need a register, flush something
}
prefix_array[prefix_index++] = (Inst) { INST_MOV, { { PLACE_REG, POINTER_SIZE, .reg = pointer_reg }, *place } };
} else if (place->kind == PLACE_REG) {
pointer_reg = place->reg;
} else {
assert(false);