forked from mono/mono
/
BitCodeEmitter.cs
1016 lines (942 loc) · 53.5 KB
/
BitCodeEmitter.cs
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
// BitCodeEmitter.cs
//
// Author:
// Ming Zhou <zhoux738@umn.edu>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Threading;
using Mono.Compiler;
using SimpleJit.Metadata;
using SimpleJit.CIL;
using LLVMSharp;
/// <summary>
/// Emit LLVM bitcode via LLVMSharp.
/// </summary>
namespace Mono.Compiler.BigStep.LLVMBackend {
public class BitCodeEmitter : IOperationProcessor {
private static readonly LLVMBool Success = new LLVMBool (0);
private static readonly LLVMBool True = new LLVMBool (1);
private static readonly LLVMValueRef Const0 = LLVM.ConstInt (LLVM.Int32Type (), 0, false);
private static readonly LLVMValueRef Const1 = LLVM.ConstInt (LLVM.Int32Type (), 1, false);
private static readonly LLVMMCJITCompilerOptions s_options = new LLVMMCJITCompilerOptions { NoFramePointerElim = 0 };
private static int s_moduleSeq;
private static bool s_initialized;
private LLVMModuleRef module;
private LLVMBuilderRef builder;
private LLVMValueRef function;
private LLVMValueRef[] argAddrs;
private LLVMValueRef[] localAddrs;
private Dictionary<string, LLVMValueRef> temps;
private Dictionary<string, LLVMBasicBlockRef> bbs;
private LLVMBasicBlockRef currentbb;
// Provides a one-time use temp name. The values generated by this name
// should be used immediately and not preserved across lexical scopes.
private string NextTempName => "R" + Interlocked.Increment(ref tempSeq);
private int tempSeq = 0;
public bool PrintDebugInfo { get; set; }
public bool VerifyGeneratedCode { get; set; }
internal MethodInfo MethodInfo { get; }
internal IRuntimeInformation RuntimeInfo { get; }
public BitCodeEmitter (IRuntimeInformation runtimeInfo, MethodInfo method)
{
RuntimeInfo = runtimeInfo;
MethodInfo = method;
int seq = Interlocked.Increment (ref s_moduleSeq);
string modName = "llvmmodule_" + seq;
module = LLVM.ModuleCreateWithName(modName);
builder = LLVM.CreateBuilder ();
temps = new Dictionary<string, LLVMValueRef> ();
bbs = new Dictionary<string, LLVMBasicBlockRef> ();
IReadOnlyCollection<ParameterInfo> prms = method.Parameters;
LLVMTypeRef[] largs = new LLVMTypeRef[prms.Count];
int i = 0;
foreach (ParameterInfo pinfo in prms)
{
largs[i] = TranslateType (pinfo.ParameterType);
i++;
}
LLVMTypeRef rtyp = TranslateType (method.ReturnType);
var funTy = LLVM.FunctionType (rtyp, largs, false);
string funcName = modName + "_" + method.Name;
function = LLVM.AddFunction (module, funcName, funTy);
CreateFirstBasicBlock ();
IList<LocalVariableInfo> locals = method.Body.LocalVariables;
AllocateArgsAndLocals (largs, locals);
}
/// <summary>
/// Produce a native handle for the generated native code. Call this after Symbolic Executor finishes Execute().
/// </summary>
public NativeCodeHandle Yield ()
{
if (PrintDebugInfo)
LLVM.DumpModule (module);
if (!BitCodeEmitter.s_initialized)
{
lock (typeof (BitCodeEmitter))
{
if (!BitCodeEmitter.s_initialized)
{
BigStep.InitializeLLVM_OSX_AMD64 (s_options);
BitCodeEmitter.s_initialized = true;
}
}
}
try {
if (VerifyGeneratedCode)
{
if (LLVM.VerifyFunction (function, LLVMVerifierFailureAction.LLVMPrintMessageAction) != Success)
throw new Exception ($"Couldn't verify the generated code. There is likely due to bug in code generation.");
}
if (LLVM.CreateMCJITCompilerForModule(out LLVMExecutionEngineRef engine, module, s_options, out var error) != Success)
throw new Exception ($"Compilation by LLVM failed: { error }");
IntPtr fnptr = LLVM.GetPointerToGlobal (engine, function);
unsafe {
return new NativeCodeHandle((byte*)fnptr, -1);
}
} finally {
LLVM.DisposeBuilder(builder);
}
}
/// <summary>
/// Emit LLVM instruction per CIL operation.
/// </summary>
public void Process (OperationInfo opInfo)
{
int pcIndex = opInfo.Index;
if (opInfo.JumpTarget) {
// If this op is a jump target, conclude the current BB and start a new one
LLVMBasicBlockRef prevbb = currentbb;
LLVMValueRef term = prevbb.GetBasicBlockTerminator();
if (term.Equals(default(LLVMValueRef)))
{
// We don't have terminator yet. Create one.
currentbb = this.GetOrAddBasicBlock (pcIndex, false);
LLVM.BuildBr(builder, currentbb);
LLVM.PositionBuilderAtEnd (builder, currentbb);
}
else
{
currentbb = this.GetOrAddBasicBlock (pcIndex, true);
}
}
Opcode op = opInfo.Operation;
ExtendedOpcode? exop = opInfo.ExtOperation;
IOperand[] operands = opInfo.Operands;
// The result is the value pushed onto the stack by CLR at the end of instruction.
// In the translation we treat each new frame on the stack as a distinct instance
// that corresponds to a register in LLVM. If a frame is popped and pushed again it
// becomes a new instance.
//
// CLR eval-stack frame = TempOperand = LLVM temp register
//
// If the result is non-null, we must generate a new temp value and associate it
// with the temp operand's name. When a temp operand appears in the operands, it
// means a previously pushed value is being consumed by instruction. Based on the
// name of the operand we can retrieve the temp register and use that in LLVM
// operation.
string tempName = opInfo.Result?.Name;
if (exop.HasValue)
{
switch (exop.Value)
{
case ExtendedOpcode.Cgt:
// compare greater than
// tmp, tmp => result
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp;
if (this.hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
tmp = LLVM.BuildFCmp (builder, LLVMRealPredicate.LLVMRealOGT, vm.Temp0, vm.Temp1, tempName);
}
else
{
tmp = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntSGT, vm.Temp0, vm.Temp1, tempName);
}
return new NamedTempValue (tmp, tempName);
});
break;
case ExtendedOpcode.CgtUn:
// compare greater than, unsigned
// tmp, tmp => result
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp;
if (this.hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
tmp = LLVM.BuildFCmp (builder, LLVMRealPredicate.LLVMRealUGT, vm.Temp0, vm.Temp1, tempName);
}
else
{
tmp = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntUGT, vm.Temp0, vm.Temp1, tempName);
}
return new NamedTempValue (tmp, tempName);
});
break;
case ExtendedOpcode.Clt:
// compare less than
// tmp, tmp => result
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp;
if (this.hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
tmp = LLVM.BuildFCmp (builder, LLVMRealPredicate.LLVMRealOLT, vm.Temp0, vm.Temp1, tempName);
}
else
{
tmp = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntSLT, vm.Temp0, vm.Temp1, tempName);
}
return new NamedTempValue (tmp, tempName);
});
break;
case ExtendedOpcode.CltUn:
// compare less than, unsigned
// tmp, tmp => result
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp;
if (this.hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
tmp = LLVM.BuildFCmp (builder, LLVMRealPredicate.LLVMRealULT, vm.Temp0, vm.Temp1, tempName);
}
else
{
tmp = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntULT, vm.Temp0, vm.Temp1, tempName);
}
return new NamedTempValue (tmp, tempName);
});
break;
case ExtendedOpcode.Ceq:
// compare equal to
// tmp, tmp => result
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp;
if (this.hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
tmp = LLVM.BuildFCmp (builder, LLVMRealPredicate.LLVMRealOEQ, vm.Temp0, vm.Temp1, tempName);
}
else
{
tmp = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntEQ, vm.Temp0, vm.Temp1, tempName);
}
return new NamedTempValue (tmp, tempName);
});
break;
default:
throw new NotImplementedException($"Unexpected. CIL operation { exop } is not implemented yet.");
}
return;
}
switch (op) {
// Notation for comments:
// op1, op2, ... => result pushed into expr-stack
case Opcode.Nop:
break;
case Opcode.Ret:
// tmp
InvokeOperation (op, exop, operands,
vm => {
if (operands.Length > 0) {
LLVM.BuildRet (builder, vm.Temp0);
} else {
LLVM.BuildRetVoid (builder);
}
});
break;
case Opcode.Ldarg0:
case Opcode.Ldarg1:
case Opcode.Ldarg2:
case Opcode.Ldarg3:
case Opcode.LdargS:
// arg => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildLoad (builder, vm.Address0, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Stloc0:
case Opcode.Stloc1:
case Opcode.Stloc2:
case Opcode.Stloc3:
// tmp, local
InvokeOperation (op, exop, operands,
vm => {
LLVM.BuildStore (builder, vm.Temp0, vm.Address1);
});
break;
case Opcode.StargS:
// store a value in an argument slot (short offset)
// tmp, arg
InvokeOperation (op, exop, operands,
vm => {
LLVM.BuildStore (builder, vm.Temp0, vm.Address1);
});
break;
case Opcode.LdcI4:
case Opcode.LdcI4_0:
case Opcode.LdcI4_1:
case Opcode.LdcI4_2:
case Opcode.LdcI4_3:
case Opcode.LdcI4_4:
case Opcode.LdcI4_5:
case Opcode.LdcI4_6:
case Opcode.LdcI4_7:
case Opcode.LdcI4_8:
case Opcode.LdcI4M1:
case Opcode.LdcI4S:
// const => tmp
InvokeOperation (op, exop, operands,
vm => {
// LLVM doesn't allow assignment from constant to value.
// So we just pretend that the constant is a temp value.
// When it's used in an instruction it will be realized
// in the form of "ty value-literal" (e.g. "i32 42")
LLVMValueRef tmp = vm.Const0;
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Ldloc0:
case Opcode.Ldloc1:
case Opcode.Ldloc2:
case Opcode.Ldloc3:
case Opcode.LdlocS:
// local => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildLoad (builder, vm.Address0, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.LdelemI1:
// load element from array
// tmp (array), tmp (index) => tmp
InvokeOperation (op, exop, operands,
vm => {
return GetIntArrayElement (operands[0].Type, 1, tempName, vm.Temp0, vm.Temp1);
});
break;
case Opcode.LdelemI2:
// load element from array
// tmp (array), tmp (index) => tmp
InvokeOperation (op, exop, operands,
vm => {
return GetIntArrayElement (operands[0].Type, 2, tempName, vm.Temp0, vm.Temp1);
});
break;
case Opcode.LdelemI:
// ASSUME native integer = 4 bytes, may need change
// FALL THROUGH
case Opcode.LdelemI4:
// load element from array
// tmp (array), tmp (index) => tmp
InvokeOperation (op, exop, operands,
vm => {
return GetIntArrayElement(operands[0].Type, 4, tempName, vm.Temp0, vm.Temp1);
});
break;
case Opcode.LdelemI8:
// load element from array
// tmp (array), tmp (index) => tmp
InvokeOperation (op, exop, operands,
vm => {
return GetIntArrayElement (operands[0].Type, 8, tempName, vm.Temp0, vm.Temp1);
});
break;
case Opcode.StelemI1:
// store element into array
// tmp (array), tmp (index), tmp (value) => tmp
InvokeOperation (op, exop, operands,
vm => {
SetIntArrayElement (operands[0].Type, 1, vm.Temp2, vm.Temp0, vm.Temp1);
});
break;
case Opcode.StelemI2:
// store element into array
// tmp (array), tmp (index), tmp (value) => tmp
InvokeOperation (op, exop, operands,
vm => {
SetIntArrayElement (operands[0].Type, 2, vm.Temp2, vm.Temp0, vm.Temp1);
});
break;
case Opcode.StelemI:
// ASSUME native integer = 4 bytes, may need change
// FALL THROUGH
case Opcode.StelemI4:
// store element into array
// tmp (array), tmp (index), tmp (value) => tmp
InvokeOperation (op, exop, operands,
vm => {
SetIntArrayElement (operands[0].Type, 4, vm.Temp2, vm.Temp0, vm.Temp1);
});
break;
case Opcode.StelemI8:
// store element into array
// tmp (array), tmp (index), tmp (value) => tmp
InvokeOperation (op, exop, operands,
vm => {
SetIntArrayElement (operands[0].Type, 8, vm.Temp2, vm.Temp0, vm.Temp1);
});
break;
case Opcode.Ldsfld:
// const => tmp
int token = (operands[0] as Int32ConstOperand).Value;
InvokeOperation (op, exop, operands,
vm => {
// TODO: It would be nice if operand[0] just carried the fieldInfo here
FieldInfo fieldInfo = RuntimeInfo.GetFieldInfoForToken (MethodInfo, token);
LLVMValueRef fieldAddress = GetConstValue (RuntimeInfo.ComputeFieldAddress (fieldInfo));
LLVMTypeRef fieldType = LLVM.Int32Type (); /* FIXME: get from field info */
LLVMValueRef address = LLVM.ConstIntToPtr (fieldAddress, LLVM.PointerType (fieldType, 0));
LLVMValueRef tmp = LLVM.BuildLoad (builder, address, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Add:
case Opcode.AddOvf: // TODO - Handle overflow
case Opcode.AddOvfUn: // TODO - Handle overflow, unsigned
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildAdd (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Sub:
case Opcode.SubOvf: // TODO - Handle overflow
case Opcode.SubOvfUn: // TODO - Handle overflow, unsigned
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildSub (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Mul:
case Opcode.MulOvf: // TODO - Handle overflow
case Opcode.MulOvfUn: // TODO - Handle overflow, unsigned
// tmp, tmp => tmp
InvokeOperation(op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildMul (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Div:
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildFDiv (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.DivUn:
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildUDiv (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Rem:
// modulo, signed
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildSRem (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.RemUn:
// modulo, unsigned
// tmp, tmp => tmp
InvokeOperation (op, exop, operands,
vm => {
LLVMValueRef tmp = LLVM.BuildURem (builder, vm.Temp0, vm.Temp1, tempName);
return new NamedTempValue (tmp, tempName);
});
break;
case Opcode.Br:
case Opcode.BrS:
LLVM.BuildBr(builder, this.GetBranchTarget (operands[0]));
break;
case Opcode.Brtrue:
case Opcode.BrtrueS:
// branch on true (int value != 0)
// tmp, pc
InvokeOperation (op, exop, operands,
vm => {
// LLVM's conditional branch requires the 1st argument to be a boolean, but CIL
// may pop an integer. If so, convert that to a boolean (0 => false; others => true)
LLVMBasicBlockRef bbTrue = this.GetBranchTarget (operands[1]);
LLVMBasicBlockRef bbFalse = this.GetImplicitBranchTarget (pcIndex);
LLVMValueRef res = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntEQ, vm.Temp0, Const1, NextTempName);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, vm.Temp0, bbTrue, bbFalse);
});
break;
case Opcode.Brfalse:
case Opcode.BrfalseS:
// branch on false (int value = 0)
// tmp, pc
InvokeOperation (op, exop, operands,
vm => {
// LLVM's conditional branch requires the 1st argument to be a boolean, but CIL
// may pop an integer. If so, convert that to a boolean (0 => false; others => true)
LLVMBasicBlockRef bbTrue = this.GetBranchTarget (operands[1]);
LLVMBasicBlockRef bbFalse = this.GetImplicitBranchTarget (pcIndex);
LLVMValueRef res = LLVM.BuildICmp (builder, LLVMIntPredicate.LLVMIntEQ, vm.Temp0, Const0, NextTempName);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, res, bbTrue, bbFalse);
});
break;
case Opcode.Beq:
case Opcode.BeqS:
// branch on ==
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealOEQ, LLVMIntPredicate.LLVMIntEQ, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.BneUn:
case Opcode.BneUnS:
// branch on !=, unsigned
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealUNE, LLVMIntPredicate.LLVMIntNE, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.Ble:
case Opcode.BleS:
// branch on <=
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealOLE, LLVMIntPredicate.LLVMIntSLE, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.BleUn:
case Opcode.BleUnS:
// branch on <=, unsigned
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealULE, LLVMIntPredicate.LLVMIntULE, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.Blt:
case Opcode.BltS:
// branch on <
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealOLT, LLVMIntPredicate.LLVMIntSLT, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.BltUn:
case Opcode.BltUnS:
// branch on <, unsigned
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealULT, LLVMIntPredicate.LLVMIntULT, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.Bge:
case Opcode.BgeS:
// branch on >=
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealOGE, LLVMIntPredicate.LLVMIntSGE, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.BgeUn:
case Opcode.BgeUnS:
// branch on >=, unsigned
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealUGE, LLVMIntPredicate.LLVMIntUGE, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.Bgt:
case Opcode.BgtS:
// branch on >
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (LLVMRealPredicate.LLVMRealOGT, LLVMIntPredicate.LLVMIntSGT, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
case Opcode.BgtUn:
case Opcode.BgtUnS:
// branch on >, unsigned
// tmp, tmp, pc
InvokeOperation (op, exop, operands,
vm => {
var tuple = CompareAndJumpTo (
LLVMRealPredicate.LLVMRealUGT, LLVMIntPredicate.LLVMIntUGT, operands, vm, pcIndex);
LLVMValueRef tmp = LLVM.BuildCondBr (builder, tuple.Item1, tuple.Item2, tuple.Item3);
});
break;
default:
throw new NotImplementedException($"Unexpected. CIL operation { op } is not implemented yet.");
}
}
internal class ValueMappings {
internal LLVMValueRef Const0 {
get { return Values[0].Value; }
}
internal LLVMValueRef Address0 {
get { return Values[0].Value; }
}
internal LLVMValueRef Address1 {
get { return Values[1].Value; }
}
internal LLVMValueRef Temp0 {
get { return Values[0].Value; }
}
internal LLVMValueRef Temp1 {
get { return Values[1].Value; }
}
internal LLVMValueRef Temp2 {
get { return Values[2].Value; }
}
internal StorageTypedValue[] Values { get; private set; }
internal ValueMappings (int length)
{
Values = new StorageTypedValue[length];
}
}
internal enum StorageType {
Address,
Temp,
Const
}
internal class StorageTypedValue {
internal StorageType Type { get; set; }
internal LLVMValueRef Value { get; set; }
}
internal class NamedTempValue {
internal string Name { get; set; }
internal LLVMValueRef Value { get; set; }
internal NamedTempValue (LLVMValueRef value, string name = null)
{
this.Value = value;
this.Name = name;
}
}
private void AllocateArgsAndLocals (LLVMTypeRef[] args, IList<LocalVariableInfo> locals)
{
this.argAddrs = new LLVMValueRef[args.Length];
uint i = 0;
for (; i < args.Length; i++) {
LLVMValueRef vref = LLVM.GetParam (function, i);
LLVMValueRef vaddr = LLVM.BuildAlloca (builder, args[i], "A" + i);
LLVM.BuildStore (builder, vref, vaddr);
this.argAddrs[i] = vaddr;
}
i = 0;
localAddrs = new LLVMValueRef[locals.Count];
foreach (LocalVariableInfo lvi in locals) {
LLVMTypeRef ltyp = TranslateType (lvi.LocalType);
LLVMValueRef lref = LLVM.BuildAlloca (builder, ltyp, "L" + i);
this.localAddrs[i++] = lref;
}
}
private NamedTempValue GetIntArrayElement(
ClrType arrayClrType, uint elementSize, string resultValueName, LLVMValueRef arrayBaseAddr, LLVMValueRef index)
{
// Get array's base address
LLVMValueRef basePtr = GetArrayBaseAddress (arrayClrType, elementSize, arrayBaseAddr);
// Array access is translated to two LLVM operations:
// (1) get element address
// %tmpPtr = getelementptr i32, i32* %tmp0, i64 %tmp1
// (2) get element data
// %result = load i32, i32* %tmpPtr
LLVMValueRef tmpPtr = LLVM.BuildGEP (builder, basePtr, new LLVMValueRef[] { index }, this.NextTempName);
LLVMValueRef tmp = LLVM.BuildLoad (builder, tmpPtr, resultValueName);
return new NamedTempValue (tmp, resultValueName);
}
private void SetIntArrayElement(
ClrType arrayClrType, uint elementSize, LLVMValueRef valueToSet, LLVMValueRef arrayBaseAddr, LLVMValueRef index)
{
// Get array's base address
LLVMValueRef basePtr = GetArrayBaseAddress (arrayClrType, elementSize, arrayBaseAddr);
// Array access is translated to two LLVM operations:
// (1) get element address
// %tmpPtr = getelementptr i32, i32* %tmp0, i64 %tmp1
// (2) set element data
// store i32, i32* %tmpPtr
LLVMValueRef tmpPtr = LLVM.BuildGEP (builder, basePtr, new LLVMValueRef[] { index }, this.NextTempName);
LLVMValueRef tmp = LLVM.BuildStore (builder, valueToSet, tmpPtr);
}
private LLVMValueRef GetArrayBaseAddress (ClrType arrayClrType, uint elementSize, LLVMValueRef arrayBaseAddr)
{
// Get array's base address
// The trick is to treat the metadata also as array elements and use GEP to perform pointer arithmetics
LLVMValueRef offset = LLVM.ConstInt (
LLVM.Int32Type(), RuntimeInfo.GetArrayBaseOffset(arrayClrType) / elementSize, false);
LLVMValueRef basePtr = LLVM.BuildGEP (
builder, arrayBaseAddr, new LLVMValueRef[] { offset }, this.NextTempName);
return basePtr;
}
private Tuple<LLVMValueRef, LLVMBasicBlockRef, LLVMBasicBlockRef> CompareAndJumpTo (
LLVMRealPredicate rprd, LLVMIntPredicate prd, IOperand[] operands, ValueMappings vm, int pcIndex)
{
// 1) Comapre the two values and store the result in an LLVM auto temp
LLVMValueRef cmpResult;
if (hasAtLeastOneFloat(vm.Temp0, vm.Temp1))
{
cmpResult = LLVM.BuildFCmp (builder, rprd, vm.Temp0, vm.Temp1, NextTempName);
}
else
{
cmpResult = LLVM.BuildICmp (builder, prd, vm.Temp0, vm.Temp1, NextTempName);
}
// 2) True: the target
// False: next op
LLVMBasicBlockRef bbTrue = this.GetBranchTarget (operands[2]);
LLVMBasicBlockRef bbFalse = this.GetImplicitBranchTarget (pcIndex);
return new Tuple<LLVMValueRef, LLVMBasicBlockRef, LLVMBasicBlockRef>(cmpResult, bbTrue, bbFalse);
}
private bool hasAtLeastOneFloat(LLVMValueRef v1, LLVMValueRef v2)
{
LLVMTypeRef typ0 = v1.TypeOf ();
LLVMTypeRef typ1 = v2.TypeOf ();
return typ0.Equals (LLVMTypeRef.FloatType()) ||
typ1.Equals (LLVMTypeRef.FloatType()) ||
typ0.Equals (LLVMTypeRef.DoubleType()) ||
typ1.Equals (LLVMTypeRef.DoubleType());
}
/// Invoke an LLVM operation with given value mappings.
/// The operation is supposed to return a temp value to be stored.
private void InvokeOperation (Opcode op, ExtendedOpcode? exop, IOperand[] operands, Func<ValueMappings, NamedTempValue> emitFunc)
{
if (this.PrintDebugInfo)
{
string opstr = $"[DEBUG] {op.ToString()} - ";
foreach (IOperand od in operands)
{
opstr += od.Name;
if (od.OperandType == OperandType.PC)
{
opstr += "(" + ((BranchTargetOperand)od).PC + ")";
}
opstr += " ";
}
Console.WriteLine (opstr);
}
ValueMappings mappings = new ValueMappings (operands.Length);
StorageTypedValue[] stvalues = mappings.Values;
for (int i = 0; i < operands.Length; i++)
{
IOperand operand = operands[i];
stvalues[i] = MakeStorageTypedValue (operand);
}
NamedTempValue ntv = emitFunc (mappings);
if (ntv != null)
{
string name = ntv.Name;
if (name == null)
name = LLVM.GetValueName (ntv.Value);
temps[name] = ntv.Value;
}
}
/// Invoke an LLVM operation with given value mappings.
/// The operation doesn't produce new temp values.
private void InvokeOperation (Opcode op, ExtendedOpcode? exop, IOperand[] operands, Action<ValueMappings> emitFunc)
{
InvokeOperation (op, exop, operands,
(vm) => {
emitFunc (vm);
return null;
});
}
private StorageTypedValue MakeStorageTypedValue (IOperand operand)
{
LLVMValueRef value = default (LLVMValueRef);
StorageType stype = default (StorageType);
switch (operand.OperandType)
{
case OperandType.Temp:
stype = StorageType.Temp;
value = GetTempValue (operand);
break;
case OperandType.Local:
stype = StorageType.Address;
value = GetLocalAddr (operand);
break;
case OperandType.Argument:
stype = StorageType.Address;
value = GetArgAddr (operand);
break;
case OperandType.Const:
stype = StorageType.Const;
value = GetConstValue (operand);
break;
}
return new StorageTypedValue {
Type = stype,
Value = value
};
}
private LLVMBasicBlockRef GetBranchTarget (IOperand operand)
{
BranchTargetOperand bto = (BranchTargetOperand)operand;
int target = bto.PC;
return GetOrAddBasicBlock (target, false);
}
private LLVMBasicBlockRef GetImplicitBranchTarget (int index)
{
int target = index + 1;
return GetOrAddBasicBlock (target, false);
}
private LLVMValueRef GetArgAddr (IOperand operand)
{
ArgumentOperand aod = (ArgumentOperand)operand;
return this.argAddrs[aod.Index];
}
private LLVMValueRef GetLocalAddr (IOperand operand)
{
LocalOperand lod = (LocalOperand)operand;
return this.localAddrs[lod.Index];
}
private LLVMValueRef GetTempValue (IOperand operand)
{
TempOperand tod = (TempOperand)operand;
string name = tod.Name;
return temps[tod.Name];
}
private LLVMValueRef GetConstValue (IOperand operand)
{
ConstOperand cod = (ConstOperand)operand;
if (cod is Int32ConstOperand) {
return LLVM.ConstInt (LLVM.Int32Type (), (ulong)((Int32ConstOperand)cod).Value, true);
}
if (cod is Int64ConstOperand) {
return LLVM.ConstInt (LLVM.Int64Type (), (ulong)((Int64ConstOperand)cod).Value, true);
}
if (cod is Float32ConstOperand)
{
return LLVM.ConstReal (LLVM.FloatType (), ((Float32ConstOperand)cod).Value);
}
if (cod is Float64ConstOperand) {
return LLVM.ConstReal (LLVM.FloatType (), ((Float64ConstOperand)cod).Value);
}
throw new Exception ("Unexpected. The const operand is not recognized.");
}
private LLVMValueRef GetConstValue (IntPtr constant)
{
return LLVM.ConstInt (TranslateType (RuntimeInformation.NativeIntType), (ulong)constant, true);
}
/// Translate a CLR type to an LLVM type. Basically,
/// - Primitive types will be mapped to their counterparts in LLVM
/// - Non-array class types are all mapped to pointer types
/// - Array types are mapped to pointer types of the mapped element types
private static LLVMTypeRef TranslateType (ClrType ctyp)
{
if (ctyp == RuntimeInformation.BoolType) {
return LLVM.Int1Type ();
}
if (ctyp == RuntimeInformation.Int8Type) {
return LLVM.Int8Type ();
}
if (ctyp == RuntimeInformation.Int16Type || ctyp == RuntimeInformation.UInt8Type) {
return LLVM.Int16Type ();
}
if (ctyp == RuntimeInformation.Int32Type || ctyp == RuntimeInformation.UInt16Type) {
return LLVM.Int32Type();
}
if (ctyp == RuntimeInformation.Int64Type || ctyp == RuntimeInformation.UInt32Type) {
return LLVM.Int64Type ();
}
if (ctyp == RuntimeInformation.CharType) {
return LLVM.Int16Type (); // Unicode
}
if (ctyp == RuntimeInformation.Float32Type || ctyp == RuntimeInformation.Float64Type) {
return LLVM.FloatType ();
}
if (ctyp == RuntimeInformation.NativeIntType || ctyp == RuntimeInformation.NativeUnsignedIntType) {
/* FIXME: target platform dependent */
return LLVM.Int64Type ();
}
if (ctyp == RuntimeInformation.StringType) {
return LLVM.PointerType(LLVM.Int16Type (), 0); // 0 = default address sapce
}
if (ctyp == RuntimeInformation.VoidType) {
return LLVM.VoidType();
}
Type typ = ctyp.AsSystemType;
if (typ.IsArray) {
// If this is array, recursively call this method to drill down the subtypes. Our goal
// is to make an LLVM pointer type which maps exactly all the dimensions of the array.
typ = typ.GetElementType();
ctyp = RuntimeInformation.ClrTypeFromType(typ);
return LLVM.PointerType(TranslateType (ctyp), 0); // 0 = default address sapce
}
if (typ.IsClass) {
return LLVM.PointerType(LLVM.Int64Type (), 0); // 0 = default address sapce
}
throw new Exception ($"TODO: Cannot handle type { typ.Name } yet.");
}
#region Basic Block operations
private void CreateFirstBasicBlock ()
{
currentbb = LLVM.AppendBasicBlock (function, "entry");
LLVM.PositionBuilderAtEnd (builder, currentbb);
}