aboutsummaryrefslogtreecommitdiff
path: root/src/ARMeilleure/Translation/EmitterContext.cs
blob: 88bfe1335adeda92df4798d827827bdce5b0b48c (plain) (blame)
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
using ARMeilleure.Diagnostics;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.State;
using System;
using System.Collections.Generic;
using System.Reflection;
using static ARMeilleure.IntermediateRepresentation.Operand.Factory;

namespace ARMeilleure.Translation
{
    class EmitterContext
    {
        private int _localsCount;

        private readonly Dictionary<Operand, BasicBlock> _irLabels;
        private readonly IntrusiveList<BasicBlock> _irBlocks;

        private BasicBlock _irBlock;
        private BasicBlock _ifBlock;

        private bool _needsNewBlock;
        private BasicBlockFrequency _nextBlockFreq;

        public EmitterContext()
        {
            _localsCount = 0;

            _irLabels = new Dictionary<Operand, BasicBlock>();
            _irBlocks = new IntrusiveList<BasicBlock>();

            _needsNewBlock = true;
            _nextBlockFreq = BasicBlockFrequency.Default;
        }

        public Operand AllocateLocal(OperandType type)
        {
            Operand local = Local(type);

            local.NumberLocal(++_localsCount);

            return local;
        }

        public Operand Add(Operand op1, Operand op2)
        {
            return Add(Instruction.Add, Local(op1.Type), op1, op2);
        }

        public Operand BitwiseAnd(Operand op1, Operand op2)
        {
            return Add(Instruction.BitwiseAnd, Local(op1.Type), op1, op2);
        }

        public Operand BitwiseExclusiveOr(Operand op1, Operand op2)
        {
            return Add(Instruction.BitwiseExclusiveOr, Local(op1.Type), op1, op2);
        }

        public Operand BitwiseNot(Operand op1)
        {
            return Add(Instruction.BitwiseNot, Local(op1.Type), op1);
        }

        public Operand BitwiseOr(Operand op1, Operand op2)
        {
            return Add(Instruction.BitwiseOr, Local(op1.Type), op1, op2);
        }

        public void Branch(Operand label)
        {
            NewNextBlockIfNeeded();

            BranchToLabel(label, uncond: true, BasicBlockFrequency.Default);
        }

        public void BranchIf(Operand label, Operand op1, Operand op2, Comparison comp, BasicBlockFrequency falseFreq = default)
        {
            Add(Instruction.BranchIf, default, op1, op2, Const((int)comp));

            BranchToLabel(label, uncond: false, falseFreq);
        }

        public void BranchIfFalse(Operand label, Operand op1, BasicBlockFrequency falseFreq = default)
        {
            BranchIf(label, op1, Const(op1.Type, 0), Comparison.Equal, falseFreq);
        }

        public void BranchIfTrue(Operand label, Operand op1, BasicBlockFrequency falseFreq = default)
        {
            BranchIf(label, op1, Const(op1.Type, 0), Comparison.NotEqual, falseFreq);
        }

        public Operand ByteSwap(Operand op1)
        {
            return Add(Instruction.ByteSwap, Local(op1.Type), op1);
        }

        public virtual Operand Call(MethodInfo info, params Operand[] callArgs)
        {
            IntPtr funcPtr = Delegates.GetDelegateFuncPtr(info);

            OperandType returnType = GetOperandType(info.ReturnType);

            Symbols.Add((ulong)funcPtr.ToInt64(), info.Name);

            return Call(Const(funcPtr.ToInt64()), returnType, callArgs);
        }

        protected static OperandType GetOperandType(Type type)
        {
            if (type == typeof(bool) || type == typeof(byte) ||
                type == typeof(char) || type == typeof(short) ||
                type == typeof(int) || type == typeof(sbyte) ||
                type == typeof(ushort) || type == typeof(uint))
            {
                return OperandType.I32;
            }
            else if (type == typeof(long) || type == typeof(ulong))
            {
                return OperandType.I64;
            }
            else if (type == typeof(double))
            {
                return OperandType.FP64;
            }
            else if (type == typeof(float))
            {
                return OperandType.FP32;
            }
            else if (type == typeof(V128))
            {
                return OperandType.V128;
            }
            else if (type == typeof(void))
            {
                return OperandType.None;
            }
            else
            {
                throw new ArgumentException($"Invalid type \"{type.Name}\".");
            }
        }

        public Operand Call(Operand address, OperandType returnType, params Operand[] callArgs)
        {
            Operand[] args = new Operand[callArgs.Length + 1];

            args[0] = address;

            Array.Copy(callArgs, 0, args, 1, callArgs.Length);

            if (returnType != OperandType.None)
            {
                return Add(Instruction.Call, Local(returnType), args);
            }
            else
            {
                return Add(Instruction.Call, default, args);
            }
        }

        public void Tailcall(Operand address, params Operand[] callArgs)
        {
            Operand[] args = new Operand[callArgs.Length + 1];

            args[0] = address;

            Array.Copy(callArgs, 0, args, 1, callArgs.Length);

            Add(Instruction.Tailcall, default, args);

            _needsNewBlock = true;
        }

        public Operand CompareAndSwap(Operand address, Operand expected, Operand desired)
        {
            return Add(Instruction.CompareAndSwap, Local(desired.Type), address, expected, desired);
        }

        public Operand CompareAndSwap16(Operand address, Operand expected, Operand desired)
        {
            return Add(Instruction.CompareAndSwap16, Local(OperandType.I32), address, expected, desired);
        }

        public Operand CompareAndSwap8(Operand address, Operand expected, Operand desired)
        {
            return Add(Instruction.CompareAndSwap8, Local(OperandType.I32), address, expected, desired);
        }

        public Operand ConditionalSelect(Operand op1, Operand op2, Operand op3)
        {
            return Add(Instruction.ConditionalSelect, Local(op2.Type), op1, op2, op3);
        }

        public Operand ConvertI64ToI32(Operand op1)
        {
            if (op1.Type != OperandType.I64)
            {
                throw new ArgumentException($"Invalid operand type \"{op1.Type}\".");
            }

            return Add(Instruction.ConvertI64ToI32, Local(OperandType.I32), op1);
        }

        public Operand ConvertToFP(OperandType type, Operand op1)
        {
            return Add(Instruction.ConvertToFP, Local(type), op1);
        }

        public Operand ConvertToFPUI(OperandType type, Operand op1)
        {
            return Add(Instruction.ConvertToFPUI, Local(type), op1);
        }

        public Operand Copy(Operand op1)
        {
            return Add(Instruction.Copy, Local(op1.Type), op1);
        }

        public Operand Copy(Operand dest, Operand op1)
        {
            if (dest.Kind != OperandKind.Register &&
                (dest.Kind != OperandKind.LocalVariable || dest.GetLocalNumber() == 0))
            {
                throw new ArgumentException($"Destination operand must be a Register or a numbered LocalVariable.");
            }

            return Add(Instruction.Copy, dest, op1);
        }

        public Operand CountLeadingZeros(Operand op1)
        {
            return Add(Instruction.CountLeadingZeros, Local(op1.Type), op1);
        }

        public Operand Divide(Operand op1, Operand op2)
        {
            return Add(Instruction.Divide, Local(op1.Type), op1, op2);
        }

        public Operand DivideUI(Operand op1, Operand op2)
        {
            return Add(Instruction.DivideUI, Local(op1.Type), op1, op2);
        }

        public Operand ICompare(Operand op1, Operand op2, Comparison comp)
        {
            return Add(Instruction.Compare, Local(OperandType.I32), op1, op2, Const((int)comp));
        }

        public Operand ICompareEqual(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.Equal);
        }

        public Operand ICompareGreater(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.Greater);
        }

        public Operand ICompareGreaterOrEqual(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.GreaterOrEqual);
        }

        public Operand ICompareGreaterOrEqualUI(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.GreaterOrEqualUI);
        }

        public Operand ICompareGreaterUI(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.GreaterUI);
        }

        public Operand ICompareLess(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.Less);
        }

        public Operand ICompareLessOrEqual(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.LessOrEqual);
        }

        public Operand ICompareLessOrEqualUI(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.LessOrEqualUI);
        }

        public Operand ICompareLessUI(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.LessUI);
        }

        public Operand ICompareNotEqual(Operand op1, Operand op2)
        {
            return ICompare(op1, op2, Comparison.NotEqual);
        }

        public Operand Load(OperandType type, Operand address)
        {
            return Add(Instruction.Load, Local(type), address);
        }

        public Operand Load16(Operand address)
        {
            return Add(Instruction.Load16, Local(OperandType.I32), address);
        }

        public Operand Load8(Operand address)
        {
            return Add(Instruction.Load8, Local(OperandType.I32), address);
        }

        public Operand LoadArgument(OperandType type, int index)
        {
            return Add(Instruction.LoadArgument, Local(type), Const(index));
        }

        public void LoadFromContext()
        {
            _needsNewBlock = true;

            Add(Instruction.LoadFromContext);
        }

        public void MemoryBarrier()
        {
            Add(Instruction.MemoryBarrier);
        }

        public Operand Multiply(Operand op1, Operand op2)
        {
            return Add(Instruction.Multiply, Local(op1.Type), op1, op2);
        }

        public Operand Multiply64HighSI(Operand op1, Operand op2)
        {
            return Add(Instruction.Multiply64HighSI, Local(OperandType.I64), op1, op2);
        }

        public Operand Multiply64HighUI(Operand op1, Operand op2)
        {
            return Add(Instruction.Multiply64HighUI, Local(OperandType.I64), op1, op2);
        }

        public Operand Negate(Operand op1)
        {
            return Add(Instruction.Negate, Local(op1.Type), op1);
        }

        public void Return()
        {
            Add(Instruction.Return);

            _needsNewBlock = true;
        }

        public void Return(Operand op1)
        {
            Add(Instruction.Return, default, op1);

            _needsNewBlock = true;
        }

        public Operand RotateRight(Operand op1, Operand op2)
        {
            return Add(Instruction.RotateRight, Local(op1.Type), op1, op2);
        }

        public Operand ShiftLeft(Operand op1, Operand op2)
        {
            return Add(Instruction.ShiftLeft, Local(op1.Type), op1, op2);
        }

        public Operand ShiftRightSI(Operand op1, Operand op2)
        {
            return Add(Instruction.ShiftRightSI, Local(op1.Type), op1, op2);
        }

        public Operand ShiftRightUI(Operand op1, Operand op2)
        {
            return Add(Instruction.ShiftRightUI, Local(op1.Type), op1, op2);
        }

        public Operand SignExtend16(OperandType type, Operand op1)
        {
            return Add(Instruction.SignExtend16, Local(type), op1);
        }

        public Operand SignExtend32(OperandType type, Operand op1)
        {
            return Add(Instruction.SignExtend32, Local(type), op1);
        }

        public Operand SignExtend8(OperandType type, Operand op1)
        {
            return Add(Instruction.SignExtend8, Local(type), op1);
        }

        public void Store(Operand address, Operand value)
        {
            Add(Instruction.Store, default, address, value);
        }

        public void Store16(Operand address, Operand value)
        {
            Add(Instruction.Store16, default, address, value);
        }

        public void Store8(Operand address, Operand value)
        {
            Add(Instruction.Store8, default, address, value);
        }

        public void StoreToContext()
        {
            Add(Instruction.StoreToContext);

            _needsNewBlock = true;
        }

        public Operand Subtract(Operand op1, Operand op2)
        {
            return Add(Instruction.Subtract, Local(op1.Type), op1, op2);
        }

        public Operand VectorCreateScalar(Operand value)
        {
            return Add(Instruction.VectorCreateScalar, Local(OperandType.V128), value);
        }

        public Operand VectorExtract(OperandType type, Operand vector, int index)
        {
            return Add(Instruction.VectorExtract, Local(type), vector, Const(index));
        }

        public Operand VectorExtract16(Operand vector, int index)
        {
            return Add(Instruction.VectorExtract16, Local(OperandType.I32), vector, Const(index));
        }

        public Operand VectorExtract8(Operand vector, int index)
        {
            return Add(Instruction.VectorExtract8, Local(OperandType.I32), vector, Const(index));
        }

        public Operand VectorInsert(Operand vector, Operand value, int index)
        {
            return Add(Instruction.VectorInsert, Local(OperandType.V128), vector, value, Const(index));
        }

        public Operand VectorInsert16(Operand vector, Operand value, int index)
        {
            return Add(Instruction.VectorInsert16, Local(OperandType.V128), vector, value, Const(index));
        }

        public Operand VectorInsert8(Operand vector, Operand value, int index)
        {
            return Add(Instruction.VectorInsert8, Local(OperandType.V128), vector, value, Const(index));
        }

        public Operand VectorOne()
        {
            return Add(Instruction.VectorOne, Local(OperandType.V128));
        }

        public Operand VectorZero()
        {
            return Add(Instruction.VectorZero, Local(OperandType.V128));
        }

        public Operand VectorZeroUpper64(Operand vector)
        {
            return Add(Instruction.VectorZeroUpper64, Local(OperandType.V128), vector);
        }

        public Operand VectorZeroUpper96(Operand vector)
        {
            return Add(Instruction.VectorZeroUpper96, Local(OperandType.V128), vector);
        }

        public Operand ZeroExtend16(OperandType type, Operand op1)
        {
            return Add(Instruction.ZeroExtend16, Local(type), op1);
        }

        public Operand ZeroExtend32(OperandType type, Operand op1)
        {
            return Add(Instruction.ZeroExtend32, Local(type), op1);
        }

        public Operand ZeroExtend8(OperandType type, Operand op1)
        {
            return Add(Instruction.ZeroExtend8, Local(type), op1);
        }

        private void NewNextBlockIfNeeded()
        {
            if (_needsNewBlock)
            {
                NewNextBlock();
            }
        }

        private Operand Add(Instruction inst, Operand dest = default)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(inst, dest);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        private Operand Add(Instruction inst, Operand dest, Operand[] sources)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(inst, dest, sources);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        private Operand Add(Instruction inst, Operand dest, Operand source0)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(inst, dest, source0);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        private Operand Add(Instruction inst, Operand dest, Operand source0, Operand source1)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(inst, dest, source0, source1);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        private Operand Add(Instruction inst, Operand dest, Operand source0, Operand source1, Operand source2)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(inst, dest, source0, source1, source2);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        public Operand AddIntrinsic(Intrinsic intrin, params Operand[] args)
        {
            return Add(intrin, Local(OperandType.V128), args);
        }

        public Operand AddIntrinsicInt(Intrinsic intrin, params Operand[] args)
        {
            return Add(intrin, Local(OperandType.I32), args);
        }

        public Operand AddIntrinsicLong(Intrinsic intrin, params Operand[] args)
        {
            return Add(intrin, Local(OperandType.I64), args);
        }

        public void AddIntrinsicNoRet(Intrinsic intrin, params Operand[] args)
        {
            Add(intrin, default, args);
        }

        private Operand Add(Intrinsic intrin, Operand dest, params Operand[] sources)
        {
            NewNextBlockIfNeeded();

            Operation operation = Operation.Factory.Operation(intrin, dest, sources);

            _irBlock.Operations.AddLast(operation);

            return dest;
        }

        private void BranchToLabel(Operand label, bool uncond, BasicBlockFrequency nextFreq)
        {
            if (!_irLabels.TryGetValue(label, out BasicBlock branchBlock))
            {
                branchBlock = new BasicBlock();

                _irLabels.Add(label, branchBlock);
            }

            if (uncond)
            {
                _irBlock.AddSuccessor(branchBlock);
            }
            else
            {
                // Defer registration of successor to _irBlock so that the order of successors is correct.
                _ifBlock = branchBlock;
            }

            _needsNewBlock = true;
            _nextBlockFreq = nextFreq;
        }

        public void MarkLabel(Operand label, BasicBlockFrequency nextFreq = default)
        {
            _nextBlockFreq = nextFreq;

            if (_irLabels.TryGetValue(label, out BasicBlock nextBlock))
            {
                nextBlock.Index = _irBlocks.Count;

                _irBlocks.AddLast(nextBlock);

                NextBlock(nextBlock);
            }
            else
            {
                NewNextBlock();

                _irLabels.Add(label, _irBlock);
            }
        }

        private void NewNextBlock()
        {
            BasicBlock block = new(_irBlocks.Count);

            _irBlocks.AddLast(block);

            NextBlock(block);
        }

        private void NextBlock(BasicBlock nextBlock)
        {
            if (_irBlock?.SuccessorsCount == 0 && !EndsWithUnconditional(_irBlock))
            {
                _irBlock.AddSuccessor(nextBlock);

                if (_ifBlock != null)
                {
                    _irBlock.AddSuccessor(_ifBlock);

                    _ifBlock = null;
                }
            }

            _irBlock = nextBlock;
            _irBlock.Frequency = _nextBlockFreq;

            _needsNewBlock = false;
            _nextBlockFreq = BasicBlockFrequency.Default;
        }

        private static bool EndsWithUnconditional(BasicBlock block)
        {
            Operation last = block.Operations.Last;

            return last != default &&
               (last.Instruction == Instruction.Return ||
                last.Instruction == Instruction.Tailcall);
        }

        public ControlFlowGraph GetControlFlowGraph()
        {
            return new ControlFlowGraph(_irBlocks.First, _irBlocks, _localsCount);
        }
    }
}