This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
/
ilreflect.fs
2046 lines (1785 loc) · 109 KB
/
ilreflect.fs
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
//----------------------------------------------------------------------------
// Write Abstract IL structures at runtime using Reflection.Emit
//----------------------------------------------------------------------------
module internal Microsoft.FSharp.Compiler.AbstractIL.ILRuntimeWriter
open Internal.Utilities
open Microsoft.FSharp.Compiler.AbstractIL
open Microsoft.FSharp.Compiler.AbstractIL.Internal
open Microsoft.FSharp.Compiler.AbstractIL.Internal.Library
open Microsoft.FSharp.Compiler.AbstractIL.Diagnostics
open Microsoft.FSharp.Compiler.AbstractIL.Extensions
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX.Types
open Microsoft.FSharp.Compiler.AbstractIL.IL
open Microsoft.FSharp.Core.Printf
open System
open System.IO
open System.Reflection
open System.Reflection.Emit
open System.Runtime.InteropServices
open System.Collections.Generic
#if FX_RESHAPED_REFLECTION
open Microsoft.FSharp.Core.ReflectionAdapters
#endif
let codeLabelOrder = ComparisonIdentity.Structural<ILCodeLabel>
// Convert the output of convCustomAttr
open Microsoft.FSharp.Compiler.AbstractIL.ILAsciiWriter
let wrapCustomAttr setCustomAttr (cinfo, bytes) =
setCustomAttr(cinfo, bytes)
//----------------------------------------------------------------------------
// logging to enable debugging
//----------------------------------------------------------------------------
let logRefEmitCalls = false
type System.Reflection.Emit.AssemblyBuilder with
member asmB.DefineDynamicModuleAndLog(a,b,c) =
#if FX_RESHAPED_REFEMIT
ignore b
ignore c
let modB = asmB.DefineDynamicModule(a)
#else
let modB = asmB.DefineDynamicModule(a,b,c)
if logRefEmitCalls then printfn "let moduleBuilder%d = assemblyBuilder%d.DefineDynamicModule(%A,%A,%A)" (abs <| hash modB) (abs <| hash asmB) a b c
#endif
modB
member asmB.SetCustomAttributeAndLog(cinfo,bytes) =
if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash asmB) cinfo bytes
wrapCustomAttr asmB.SetCustomAttribute (cinfo, bytes)
#if FX_RESHAPED_REFEMIT
#else
member asmB.AddResourceFileAndLog(nm1, nm2, attrs) =
if logRefEmitCalls then printfn "assemblyBuilder%d.AddResourceFile(%A, %A, enum %d)" (abs <| hash asmB) nm1 nm2 (LanguagePrimitives.EnumToValue attrs)
asmB.AddResourceFile(nm1,nm2,attrs)
#endif
member asmB.SetCustomAttributeAndLog(cab) =
if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A)" (abs <| hash asmB) cab
asmB.SetCustomAttribute(cab)
type System.Reflection.Emit.ModuleBuilder with
member modB.GetArrayMethodAndLog(aty,nm,flags,rty,tys) =
if logRefEmitCalls then printfn "moduleBuilder%d.GetArrayMethod(%A,%A,%A,%A,%A)" (abs <| hash modB) aty nm flags rty tys
modB.GetArrayMethod(aty,nm,flags,rty,tys)
#if FX_RESHAPED_REFEMIT
#else
member modB.DefineDocumentAndLog(file,lang,vendor,doctype) =
let symDoc = modB.DefineDocument(file,lang,vendor,doctype)
if logRefEmitCalls then printfn "let docWriter%d = moduleBuilder%d.DefineDocument(@%A,System.Guid(\"%A\"),System.Guid(\"%A\"),System.Guid(\"%A\"))" (abs <| hash symDoc) (abs <| hash modB) file lang vendor doctype
symDoc
#endif
member modB.GetTypeAndLog(nameInModule,flag1,flag2) =
if logRefEmitCalls then printfn "moduleBuilder%d.GetType(%A,%A,%A) |> ignore" (abs <| hash modB) nameInModule flag1 flag2
modB.GetType(nameInModule,flag1,flag2)
member modB.DefineTypeAndLog(name,attrs) =
let typB = modB.DefineType(name,attrs)
if logRefEmitCalls then printfn "let typeBuilder%d = moduleBuilder%d.DefineType(%A,enum %d)" (abs <| hash typB) (abs <| hash modB) name (LanguagePrimitives.EnumToValue attrs)
typB
#if FX_RESHAPED_REFEMIT
#else
member modB.DefineManifestResourceAndLog(name,stream,attrs) =
if logRefEmitCalls then printfn "moduleBuilder%d.DefineManifestResource(%A,%A,enum %d)" (abs <| hash modB) name stream (LanguagePrimitives.EnumToValue attrs)
modB.DefineManifestResource(name,stream,attrs)
#endif
member modB.SetCustomAttributeAndLog(cinfo,bytes) =
if logRefEmitCalls then printfn "moduleBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash modB) cinfo bytes
wrapCustomAttr modB.SetCustomAttribute (cinfo,bytes)
type System.Reflection.Emit.ConstructorBuilder with
member consB.SetImplementationFlagsAndLog(attrs) =
if logRefEmitCalls then printfn "constructorBuilder%d.SetImplementationFlags(enum %d)" (abs <| hash consB) (LanguagePrimitives.EnumToValue attrs)
consB.SetImplementationFlags(attrs)
member consB.DefineParameterAndLog(n,attr,nm) =
if logRefEmitCalls then printfn "constructorBuilder%d.DefineParameter(%d,enum %d,%A)" (abs <| hash consB) n (LanguagePrimitives.EnumToValue attr) nm
consB.DefineParameter(n,attr,nm)
member consB.GetILGeneratorAndLog() =
let ilG = consB.GetILGenerator()
if logRefEmitCalls then printfn "let ilg%d = constructorBuilder%d.GetILGenerator()" (abs <| hash ilG) (abs <| hash consB)
ilG
type System.Reflection.Emit.MethodBuilder with
member methB.SetImplementationFlagsAndLog(attrs) =
if logRefEmitCalls then printfn "methodBuilder%d.SetImplementationFlags(enum %d)" (abs <| hash methB) (LanguagePrimitives.EnumToValue attrs)
methB.SetImplementationFlags(attrs)
member methB.SetReturnTypeAndLog(rt:System.Type) =
if logRefEmitCalls then printfn "methodBuilder%d.SetReturnType(typeof<%s>)" (abs <| hash methB) rt.FullName
methB.SetReturnType(rt)
member methB.SetParametersAndLog(ps) =
if logRefEmitCalls then printfn "methodBuilder%d.SetParameters(%A)" (abs <| hash methB) ps
methB.SetParameters(ps)
member methB.DefineParameterAndLog(n,attr,nm) =
if logRefEmitCalls then printfn "methodBuilder%d.DefineParameter(%d,enum %d,%A)" (abs <| hash methB) n (LanguagePrimitives.EnumToValue attr) nm
methB.DefineParameter(n,attr,nm)
member methB.DefineGenericParametersAndLog(gps) =
if logRefEmitCalls then printfn "let gps%d = methodBuilder%d.DefineGenericParameters(%A)" (abs <| hash methB) (abs <| hash methB) gps
methB.DefineGenericParameters(gps)
member methB.GetILGeneratorAndLog() =
let ilG = methB.GetILGenerator()
if logRefEmitCalls then printfn "let ilg%d = methodBuilder%d.GetILGenerator()" (abs <| hash ilG) (abs <| hash methB)
ilG
member methB.SetCustomAttributeAndLog(cinfo,bytes) =
if logRefEmitCalls then printfn "methodBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash methB) cinfo bytes
wrapCustomAttr methB.SetCustomAttribute (cinfo,bytes)
type System.Reflection.Emit.TypeBuilder with
member typB.CreateTypeAndLog() =
if logRefEmitCalls then printfn "typeBuilder%d.CreateType()" (abs <| hash typB)
#if FX_RESHAPED_REFEMIT
typB.CreateTypeInfo().AsType()
#else
typB.CreateType()
#endif
member typB.DefineNestedTypeAndLog(name,attrs) =
let res = typB.DefineNestedType(name,attrs)
if logRefEmitCalls then printfn "let typeBuilder%d = typeBuilder%d.DefineNestedType(\"%s\",enum %d)" (abs <| hash res) (abs <| hash typB) name (LanguagePrimitives.EnumToValue attrs)
res
member typB.DefineMethodAndLog(name,attrs,cconv) =
let methB = typB.DefineMethod(name,attrs,cconv)
if logRefEmitCalls then printfn "let methodBuilder%d = typeBuilder%d.DefineMethod(\"%s\",enum %d,enum %d)" (abs <| hash methB) (abs <| hash typB) name (LanguagePrimitives.EnumToValue attrs) (LanguagePrimitives.EnumToValue cconv)
methB
member typB.DefineGenericParametersAndLog(gps) =
if logRefEmitCalls then printfn "typeBuilder%d.DefineGenericParameters(%A)" (abs <| hash typB) gps
typB.DefineGenericParameters(gps)
member typB.DefineConstructorAndLog(attrs,cconv,parms) =
let consB = typB.DefineConstructor(attrs,cconv,parms)
if logRefEmitCalls then printfn "let constructorBuilder%d = typeBuilder%d.DefineConstructor(enum %d,CallingConventions.%A,%A)" (abs <| hash consB) (abs <| hash typB) (LanguagePrimitives.EnumToValue attrs) cconv parms
consB
member typB.DefineFieldAndLog(nm,ty:System.Type,attrs) =
let fieldB = typB.DefineField(nm,ty,attrs)
if logRefEmitCalls then printfn "let fieldBuilder%d = typeBuilder%d.DefineField(\"%s\",typeof<%s>,enum %d)" (abs <| hash fieldB) (abs <| hash typB) nm ty.FullName (LanguagePrimitives.EnumToValue attrs)
fieldB
member typB.DefinePropertyAndLog(nm,attrs,ty:System.Type,args) =
if logRefEmitCalls then printfn "typeBuilder%d.DefineProperty(\"%A\",enum %d,typeof<%s>,%A)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName args
typB.DefineProperty(nm,attrs,ty,args)
member typB.DefineEventAndLog(nm,attrs,ty:System.Type) =
if logRefEmitCalls then printfn "typeBuilder%d.DefineEvent(\"%A\",enum %d,typeof<%A>)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName
typB.DefineEvent(nm,attrs,ty)
member typB.SetParentAndLog(ty:System.Type) =
if logRefEmitCalls then printfn "typeBuilder%d.SetParent(typeof<%s>)" (abs <| hash typB) ty.FullName
typB.SetParent(ty)
member typB.AddInterfaceImplementationAndLog(ty) =
if logRefEmitCalls then printfn "typeBuilder%d.AddInterfaceImplementation(%A)" (abs <| hash typB) ty
typB.AddInterfaceImplementation(ty)
member typB.InvokeMemberAndLog(nm,_flags,args) =
#if FX_RESHAPED_REFEMIT
let t = typB.CreateTypeAndLog()
let m =
if t <> null then t.GetMethod(nm, (args |> Seq.map(fun x -> x.GetType()) |> Seq.toArray))
else null
if m <> null then m.Invoke(null, args)
else raise (MissingMethodException(nm))
#else
if logRefEmitCalls then printfn "typeBuilder%d.InvokeMember(\"%s\",enum %d,null,null,%A,Globalization.CultureInfo.InvariantCulture)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue _flags) args
typB.InvokeMember(nm,_flags,null,null,args,Globalization.CultureInfo.InvariantCulture)
#endif
member typB.SetCustomAttributeAndLog(cinfo,bytes) =
if logRefEmitCalls then printfn "typeBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash typB) cinfo bytes
wrapCustomAttr typB.SetCustomAttribute (cinfo,bytes)
type System.Reflection.Emit.OpCode with
member opcode.RefEmitName = (string (System.Char.ToUpper(opcode.Name.[0])) + opcode.Name.[1..]).Replace(".","_").Replace("_i4","_I4")
type System.Reflection.Emit.ILGenerator with
member ilG.DeclareLocalAndLog(ty:System.Type,isPinned) =
if logRefEmitCalls then printfn "ilg%d.DeclareLocal(typeof<%s>,%b)" (abs <| hash ilG) ty.FullName isPinned
ilG.DeclareLocal(ty,isPinned)
member ilG.MarkLabelAndLog(lab) =
if logRefEmitCalls then printfn "ilg%d.MarkLabel(label%d_%d)" (abs <| hash ilG) (abs <| hash ilG) (abs <| hash lab)
ilG.MarkLabel(lab)
#if FX_RESHAPED_REFEMIT
#else
member ilG.MarkSequencePointAndLog(symDoc, l1, c1, l2, c2) =
if logRefEmitCalls then printfn "ilg%d.MarkSequencePoint(docWriter%d, %A, %A, %A, %A)" (abs <| hash ilG) (abs <| hash symDoc) l1 c1 l2 c2
ilG.MarkSequencePoint(symDoc, l1, c1, l2, c2)
#endif
member ilG.BeginExceptionBlockAndLog() =
if logRefEmitCalls then printfn "ilg%d.BeginExceptionBlock()" (abs <| hash ilG)
ilG.BeginExceptionBlock()
member ilG.EndExceptionBlockAndLog() =
if logRefEmitCalls then printfn "ilg%d.EndExceptionBlock()" (abs <| hash ilG)
ilG.EndExceptionBlock()
member ilG.BeginFinallyBlockAndLog() =
if logRefEmitCalls then printfn "ilg%d.BeginFinallyBlock()" (abs <| hash ilG)
ilG.BeginFinallyBlock()
member ilG.BeginCatchBlockAndLog(ty) =
if logRefEmitCalls then printfn "ilg%d.BeginCatchBlock(%A)" (abs <| hash ilG) ty
ilG.BeginCatchBlock(ty)
member ilG.BeginExceptFilterBlockAndLog() =
if logRefEmitCalls then printfn "ilg%d.BeginExceptFilterBlock()" (abs <| hash ilG)
ilG.BeginExceptFilterBlock()
member ilG.BeginFaultBlockAndLog() =
if logRefEmitCalls then printfn "ilg%d.BeginFaultBlock()" (abs <| hash ilG)
ilG.BeginFaultBlock()
member ilG.DefineLabelAndLog() =
let lab = ilG.DefineLabel()
if logRefEmitCalls then printfn "let label%d_%d = ilg%d.DefineLabel()" (abs <| hash ilG) (abs <| hash lab) (abs <| hash ilG)
lab
member x.EmitAndLog (op:OpCode) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s)" (abs <| hash x) op.RefEmitName
x.Emit(op)
member x.EmitAndLog (op:OpCode,v:Label) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s,label%d_%d)" (abs <| hash x) op.RefEmitName (abs <| hash x) (abs <| hash v);
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:int16) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, int16 %d)" (abs <| hash x) op.RefEmitName v;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:int32) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, %d)" (abs <| hash x) op.RefEmitName v;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:MethodInfo) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, methodBuilder%d) // method %s" (abs <| hash x) op.RefEmitName (abs <| hash v) v.Name;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:string) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s,\"@%s\")" (abs <| hash x) op.RefEmitName v;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:Type) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, typeof<%s>)" (abs <| hash x) op.RefEmitName v.FullName;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:FieldInfo) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, fieldBuilder%d) // field %s" (abs <| hash x) op.RefEmitName (abs <| hash v) v.Name;
x.Emit(op,v)
member x.EmitAndLog (op:OpCode,v:ConstructorInfo) =
if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s,constructor_%s)" (abs <| hash x) op.RefEmitName v.DeclaringType.Name;
x.Emit(op,v)
//----------------------------------------------------------------------------
// misc
//----------------------------------------------------------------------------
let inline flagsIf b x = if b then x else enum 0
module Zmap =
let force x m str = match Zmap.tryFind x m with Some y -> y | None -> failwithf "Zmap.force: %s: x = %+A" str x
let equalTypes (s:Type) (t:Type) = s.Equals(t)
let equalTypeLists ss tt = List.lengthsEqAndForall2 equalTypes ss tt
let getGenericArgumentsOfType (typT : Type) =
if typT.IsGenericType then typT.GetGenericArguments() else [| |]
let getGenericArgumentsOfMethod (methI : MethodInfo) =
if methI.IsGenericMethod then methI.GetGenericArguments() else [| |]
let getTypeConstructor (ty: Type) =
if ty.IsGenericType then ty.GetGenericTypeDefinition() else ty
//----------------------------------------------------------------------------
// convAssemblyRef
//----------------------------------------------------------------------------
let convAssemblyRef (aref:ILAssemblyRef) =
let asmName = new System.Reflection.AssemblyName()
asmName.Name <- aref.Name;
(match aref.PublicKey with
| None -> ()
| Some (PublicKey bytes) -> asmName.SetPublicKey(bytes)
| Some (PublicKeyToken bytes) -> asmName.SetPublicKeyToken(bytes));
let setVersion (major,minor,build,rev) =
asmName.Version <- System.Version (int32 major,int32 minor,int32 build, int32 rev)
Option.iter setVersion aref.Version;
// asmName.ProcessorArchitecture <- System.Reflection.ProcessorArchitecture.MSIL;
#if FX_RESHAPED_GLOBALIZATION
#else
//Option.iter (fun name -> asmName.CultureInfo <- System.Globalization.CultureInfo.CreateSpecificCulture(name)) aref.Locale;
asmName.CultureInfo <- System.Globalization.CultureInfo.InvariantCulture;
#endif
asmName
/// The global environment.
type cenv =
{ ilg: ILGlobals
tryFindSysILTypeRef : string -> ILTypeRef option
generatePdb: bool
resolveAssemblyRef: (ILAssemblyRef -> Choice<string,System.Reflection.Assembly> option) }
/// Convert an Abstract IL type reference to Reflection.Emit System.Type value.
// This ought to be an adequate substitute for this whole function, but it needs
// to be thoroughly tested.
// Type.GetType(tref.QualifiedName)
// [] ,name -> name
// [ns] ,name -> ns+name
// [ns;typeA;typeB],name -> ns+typeA+typeB+name
let convTypeRefAux (cenv:cenv) (tref:ILTypeRef) =
let qualifiedName = (String.concat "+" (tref.Enclosing @ [ tref.Name ])).Replace(",", @"\,")
match tref.Scope with
| ILScopeRef.Assembly asmref ->
let assembly =
match cenv.resolveAssemblyRef asmref with
| Some (Choice1Of2 path) ->
FileSystem.AssemblyLoadFrom(path)
| Some (Choice2Of2 assembly) ->
assembly
| None ->
let asmName = convAssemblyRef asmref
FileSystem.AssemblyLoad(asmName)
let typT = assembly.GetType(qualifiedName)
typT |> nonNull "convTypeRefAux"
| ILScopeRef.Module _
| ILScopeRef.Local _ ->
let typT = Type.GetType(qualifiedName)
typT |> nonNull "convTypeRefAux"
/// The (local) emitter env (state). Some of these fields are effectively global accumulators
/// and could be placed as hash tables in the global environment.
[<AutoSerializable(false)>]
type emEnv =
{ emTypMap : Zmap<ILTypeRef,Type * TypeBuilder * ILTypeDef * Type option (*the created type*) > ;
emConsMap : Zmap<ILMethodRef,ConstructorBuilder>;
emMethMap : Zmap<ILMethodRef,MethodBuilder>;
emFieldMap : Zmap<ILFieldRef,FieldBuilder>;
emPropMap : Zmap<ILPropertyRef,PropertyBuilder>;
emLocals : LocalBuilder[];
emLabels : Zmap<IL.ILCodeLabel,Label>;
emTyvars : Type[] list; // stack
emEntryPts : (TypeBuilder * string) list
delayedFieldInits : (unit -> unit) list}
let orderILTypeRef = ComparisonIdentity.Structural<ILTypeRef>
let orderILMethodRef = ComparisonIdentity.Structural<ILMethodRef>
let orderILFieldRef = ComparisonIdentity.Structural<ILFieldRef>
let orderILPropertyRef = ComparisonIdentity.Structural<ILPropertyRef>
let emEnv0 =
{ emTypMap = Zmap.empty orderILTypeRef;
emConsMap = Zmap.empty orderILMethodRef;
emMethMap = Zmap.empty orderILMethodRef;
emFieldMap = Zmap.empty orderILFieldRef;
emPropMap = Zmap.empty orderILPropertyRef;
emLocals = [| |];
emLabels = Zmap.empty codeLabelOrder;
emTyvars = [];
emEntryPts = []
delayedFieldInits = [] }
let envBindTypeRef emEnv (tref:ILTypeRef) (typT,typB,typeDef)=
match typT with
| null -> failwithf "binding null type in envBindTypeRef: %s\n" tref.Name;
| _ -> {emEnv with emTypMap = Zmap.add tref (typT,typB,typeDef,None) emEnv.emTypMap}
let envUpdateCreatedTypeRef emEnv (tref:ILTypeRef) =
// The tref's TypeBuilder has been created, so we have a Type proper.
// Update the tables to include this created type (the typT held prior to this is (i think) actually (TypeBuilder :> Type).
// The (TypeBuilder :> Type) does not implement all the methods that a Type proper does.
let typT,typB,typeDef,_createdTypOpt = Zmap.force tref emEnv.emTypMap "envGetTypeDef: failed"
if typB.IsCreated() then
let typ = typB.CreateTypeAndLog()
#if ENABLE_MONO_SUPPORT
// Mono has a bug where executing code that includes an array type
// match "match x with :? C[] -> ..." before the full loading of an object of type
// causes a failure when C is later loaded. One workaround for this is to attempt to do a fake allocation
// of objects. We use System.Runtime.Serialization.FormatterServices.GetUninitializedObject to do
// the fake allocation - this creates an "empty" object, even if the object doesn't have
// a constructor. It is not usable in partial trust code.
if runningOnMono && typ.IsClass && not typ.IsAbstract && not typ.IsGenericType && not typ.IsGenericTypeDefinition then
try
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typ) |> ignore
with e -> ()
#endif
{emEnv with emTypMap = Zmap.add tref (typT,typB,typeDef,Some typ) emEnv.emTypMap}
else
#if DEBUG
printf "envUpdateCreatedTypeRef: expected type to be created\n";
#endif
emEnv
let convTypeRef cenv emEnv preferCreated (tref:ILTypeRef) =
match Zmap.tryFind tref emEnv.emTypMap with
| Some (_typT,_typB,_typeDef,Some createdTyp) when preferCreated -> createdTyp |> nonNull "convTypeRef: null create type table?"
| Some (typT,_typB,_typeDef,_) -> typT |> nonNull "convTypeRef: null type table?"
| None -> convTypeRefAux cenv tref
let envBindConsRef emEnv (mref:ILMethodRef) consB =
{emEnv with emConsMap = Zmap.add mref consB emEnv.emConsMap}
let envGetConsB emEnv (mref:ILMethodRef) =
Zmap.force mref emEnv.emConsMap "envGetConsB: failed"
let envBindMethodRef emEnv (mref:ILMethodRef) methB =
{emEnv with emMethMap = Zmap.add mref methB emEnv.emMethMap}
let envGetMethB emEnv (mref:ILMethodRef) =
Zmap.force mref emEnv.emMethMap "envGetMethB: failed"
let envBindFieldRef emEnv fref fieldB =
{emEnv with emFieldMap = Zmap.add fref fieldB emEnv.emFieldMap}
let envGetFieldB emEnv fref =
Zmap.force fref emEnv.emFieldMap "- envGetMethB: failed"
let envBindPropRef emEnv (pref:ILPropertyRef) propB =
{emEnv with emPropMap = Zmap.add pref propB emEnv.emPropMap}
let envGetPropB emEnv pref =
Zmap.force pref emEnv.emPropMap "- envGetPropB: failed"
let envGetTypB emEnv (tref:ILTypeRef) =
Zmap.force tref emEnv.emTypMap "envGetTypB: failed"
|> (fun (_typT,typB,_typeDef,_createdTypOpt) -> typB)
let envGetTypeDef emEnv (tref:ILTypeRef) =
Zmap.force tref emEnv.emTypMap "envGetTypeDef: failed"
|> (fun (_typT,_typB,typeDef,_createdTypOpt) -> typeDef)
let envSetLocals emEnv locs = assert (emEnv.emLocals.Length = 0); // check "locals" is not yet set (scopes once only)
{emEnv with emLocals = locs}
let envGetLocal emEnv i = emEnv.emLocals.[i] // implicit bounds checking
let envSetLabel emEnv name lab =
assert (not (Zmap.mem name emEnv.emLabels));
{emEnv with emLabels = Zmap.add name lab emEnv.emLabels}
let envGetLabel emEnv name =
Zmap.find name emEnv.emLabels
let envPushTyvars emEnv typs = {emEnv with emTyvars = typs :: emEnv.emTyvars}
let envPopTyvars emEnv = {emEnv with emTyvars = List.tail emEnv.emTyvars}
let envGetTyvar emEnv u16 =
match emEnv.emTyvars with
| [] -> failwith "envGetTyvar: not scope of type vars"
| tvs::_ -> let i = int32 u16
if i<0 || i>= Array.length tvs then
failwith (sprintf "want tyvar #%d, but only had %d tyvars" i (Array.length tvs))
else
tvs.[i]
let isEmittedTypeRef emEnv tref = Zmap.mem tref emEnv.emTypMap
let envAddEntryPt emEnv mref = {emEnv with emEntryPts = mref::emEnv.emEntryPts}
let envPopEntryPts emEnv = {emEnv with emEntryPts = []},emEnv.emEntryPts
//----------------------------------------------------------------------------
// convCallConv
//----------------------------------------------------------------------------
let convCallConv (Callconv (hasThis,basic)) =
let ccA = match hasThis with ILThisConvention.Static -> CallingConventions.Standard
| ILThisConvention.InstanceExplicit -> CallingConventions.ExplicitThis
| ILThisConvention.Instance -> CallingConventions.HasThis
let ccB = match basic with ILArgConvention.Default -> enum 0
| ILArgConvention.CDecl -> enum 0
| ILArgConvention.StdCall -> enum 0
| ILArgConvention.ThisCall -> enum 0 // XXX: check all these
| ILArgConvention.FastCall -> enum 0
| ILArgConvention.VarArg -> CallingConventions.VarArgs
ccA ||| ccB
//----------------------------------------------------------------------------
// convType
//----------------------------------------------------------------------------
let rec convTypeSpec cenv emEnv preferCreated (tspec:ILTypeSpec) =
let typT = convTypeRef cenv emEnv preferCreated tspec.TypeRef
let tyargs = List.map (convTypeAux cenv emEnv preferCreated) tspec.GenericArgs
match isNil tyargs,typT.IsGenericType with
| _ ,true -> typT.MakeGenericType(List.toArray tyargs) |> nonNull "convTypeSpec: generic"
| true,false -> typT |> nonNull "convTypeSpec: non generic"
| _ ,false -> failwithf "- convTypeSpec: non-generic type '%O' has type instance of length %d?" typT tyargs.Length
and convTypeAux cenv emEnv preferCreated typ =
match typ with
| ILType.Void -> Type.GetType("System.Void")
| ILType.Array (shape,eltType) ->
let baseT = convTypeAux cenv emEnv preferCreated eltType |> nonNull "convType: array base"
let nDims = shape.Rank
// MakeArrayType() returns "eltType[]"
// MakeArrayType(1) returns "eltType[*]"
// MakeArrayType(2) returns "eltType[,]"
// MakeArrayType(3) returns "eltType[,,]"
// All non-equal.
if nDims=1
then baseT.MakeArrayType()
else baseT.MakeArrayType shape.Rank
| ILType.Value tspec -> convTypeSpec cenv emEnv preferCreated tspec |> nonNull "convType: value"
| ILType.Boxed tspec -> convTypeSpec cenv emEnv preferCreated tspec |> nonNull "convType: boxed"
| ILType.Ptr eltType -> let baseT = convTypeAux cenv emEnv preferCreated eltType |> nonNull "convType: ptr eltType"
baseT.MakePointerType() |> nonNull "convType: ptr"
| ILType.Byref eltType -> let baseT = convTypeAux cenv emEnv preferCreated eltType |> nonNull "convType: byref eltType"
baseT.MakeByRefType() |> nonNull "convType: byref"
| ILType.TypeVar tv -> envGetTyvar emEnv tv |> nonNull "convType: tyvar"
// Consider completing the following cases:
| ILType.Modified (false, _, modifiedTy) -> convTypeAux cenv emEnv preferCreated modifiedTy
| ILType.Modified (true, _, _) -> failwith "convType: modreq"
| ILType.FunctionPointer _callsig -> failwith "convType: fptr"
// [Bug 4063].
// The convType functions convert AbsIL types into concrete Type values.
// The emitted types have (TypeBuilder:>Type) and (TypeBuilderInstantiation:>Type).
// These can be used to construct the concrete Type for a given AbsIL type.
// This is the convType function.
// Certain functions here, e.g. convMethodRef, convConstructorSpec assume they get the "Builders" for emitted types.
//
// The "LookupType" function (see end of file) provides AbsIL to Type lookup (post emit).
// The external use (reflection and pretty printing) requires the created Type (rather than the builder).
// convCreatedType ensures created types are used where possible.
// Note: typeBuilder.CreateType() freezes the type and makes a proper Type for the collected information.
//------
// REVIEW: "convType becomes convCreatedType", the functions could be combined.
// If convCreatedType replaced convType functions like convMethodRef, convConstructorSpec, ... (and more?)
// will need to be fixed for emitted types to handle both TypeBuilder and later Type proper.
/// Uses TypeBuilder/TypeBuilderInstantiation for emitted types.
let convType cenv emEnv typ = convTypeAux cenv emEnv false typ
// Used for ldtoken
let convTypeOrTypeDef cenv emEnv typ =
match typ with
// represents an uninstantiated "TypeDef" or "TypeRef"
| ILType.Boxed tspec when tspec.GenericArgs.IsEmpty -> convTypeRef cenv emEnv false tspec.TypeRef
| _ -> convType cenv emEnv typ
let convTypes cenv emEnv (typs:ILTypes) = List.map (convType cenv emEnv) typs
let convTypesToArray cenv emEnv (typs:ILTypes) = convTypes cenv emEnv typs |> List.toArray
/// Uses the .CreateType() for emitted type if available.
let convCreatedType cenv emEnv typ = convTypeAux cenv emEnv true typ
let convCreatedTypeRef cenv emEnv typ = convTypeRef cenv emEnv true typ
//----------------------------------------------------------------------------
// convFieldInit
//----------------------------------------------------------------------------
let convFieldInit x =
match x with
| ILFieldInit.String s -> box s
| ILFieldInit.Bool bool -> box bool
| ILFieldInit.Char u16 -> box (char (int u16))
| ILFieldInit.Int8 i8 -> box i8
| ILFieldInit.Int16 i16 -> box i16
| ILFieldInit.Int32 i32 -> box i32
| ILFieldInit.Int64 i64 -> box i64
| ILFieldInit.UInt8 u8 -> box u8
| ILFieldInit.UInt16 u16 -> box u16
| ILFieldInit.UInt32 u32 -> box u32
| ILFieldInit.UInt64 u64 -> box u64
| ILFieldInit.Single ieee32 -> box ieee32
| ILFieldInit.Double ieee64 -> box ieee64
| ILFieldInit.Null -> (null :> Object)
//----------------------------------------------------------------------------
// Some types require hard work...
//----------------------------------------------------------------------------
// This is gross. TypeBuilderInstantiation should really be a public type, since we
// have to use alternative means for various Method/Field/Constructor lookups. However since
// it isn't we resort to this technique...
let TypeBuilderInstantiationT =
let ty =
#if ENABLE_MONO_SUPPORT
if runningOnMono then
Type.GetType("System.Reflection.MonoGenericClass")
else
#endif
Type.GetType("System.Reflection.Emit.TypeBuilderInstantiation")
assert (not (isNull ty))
ty
let typeIsNotQueryable (typ : Type) =
#if FX_RESHAPED_REFLECTION
let typ = typ.GetTypeInfo()
#endif
(typ :? TypeBuilder) || ((typ.GetType()).Equals(TypeBuilderInstantiationT))
//----------------------------------------------------------------------------
// convFieldSpec
//----------------------------------------------------------------------------
let queryableTypeGetField _emEnv (parentT:Type) (fref: ILFieldRef) =
parentT.GetField(fref.Name, BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Static )
|> nonNull "queryableTypeGetField"
let nonQueryableTypeGetField (parentTI:Type) (fieldInfo : FieldInfo) : FieldInfo =
if parentTI.IsGenericType then TypeBuilder.GetField(parentTI,fieldInfo) else fieldInfo
let convFieldSpec cenv emEnv fspec =
let fref = fspec.FieldRef
let tref = fref.EnclosingTypeRef
let parentTI = convType cenv emEnv fspec.EnclosingType
if isEmittedTypeRef emEnv tref then
// NOTE: if "convType becomes convCreatedType", then handle queryable types here too. [bug 4063] (necessary? what repro?)
let fieldB = envGetFieldB emEnv fref
nonQueryableTypeGetField parentTI fieldB
else
// Prior type.
if typeIsNotQueryable parentTI then
let parentT = getTypeConstructor parentTI
let fieldInfo = queryableTypeGetField emEnv parentT fref
nonQueryableTypeGetField parentTI fieldInfo
else
queryableTypeGetField emEnv parentTI fspec.FieldRef
//----------------------------------------------------------------------------
// convMethodRef
//----------------------------------------------------------------------------
let queryableTypeGetMethodBySearch cenv emEnv parentT (mref:ILMethodRef) =
assert(not (typeIsNotQueryable(parentT)));
let cconv = (if mref.CallingConv.IsStatic then BindingFlags.Static else BindingFlags.Instance)
let methInfos = parentT.GetMethods(cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic) |> Array.toList
(* First, filter on name, if unique, then binding "done" *)
let tyargTs = getGenericArgumentsOfType parentT
let methInfos = methInfos |> List.filter (fun methInfo -> methInfo.Name = mref.Name)
match methInfos with
| [methInfo] ->
methInfo
| _ ->
(* Second, type match. Note type erased (non-generic) F# code would not type match but they have unique names *)
let select (methInfo:MethodInfo) =
(* mref implied Types *)
let mtyargTIs = getGenericArgumentsOfMethod methInfo
if mtyargTIs.Length <> mref.GenericArity then false (* method generic arity mismatch *) else
let argTs,resT =
let emEnv = envPushTyvars emEnv (Array.append tyargTs mtyargTIs)
let argTs = convTypes cenv emEnv mref.ArgTypes
let resT = convType cenv emEnv mref.ReturnType
argTs,resT
(* methInfo implied Types *)
let haveArgTs = methInfo.GetParameters() |> Array.toList |> List.map (fun param -> param.ParameterType)
let haveResT = methInfo.ReturnType
(* check for match *)
if argTs.Length <> haveArgTs.Length then false (* method argument length mismatch *) else
let res = equalTypes resT haveResT && equalTypeLists argTs haveArgTs
res
match List.tryFind select methInfos with
| None -> failwith "convMethodRef: could not bind to method"
| Some methInfo -> methInfo (* return MethodInfo for (generic) type's (generic) method *)
|> nonNull "convMethodRef"
let queryableTypeGetMethod cenv emEnv parentT (mref:ILMethodRef) =
assert(not (typeIsNotQueryable(parentT)));
if mref.GenericArity = 0 then
let tyargTs = getGenericArgumentsOfType parentT
let argTs,resT =
let emEnv = envPushTyvars emEnv tyargTs
let argTs = convTypesToArray cenv emEnv mref.ArgTypes
let resT = convType cenv emEnv mref.ReturnType
argTs,resT
let stat = mref.CallingConv.IsStatic
let cconv = (if stat then BindingFlags.Static else BindingFlags.Instance)
let methInfo =
try
parentT.GetMethod(mref.Name,cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic,
null,
argTs,
#if FX_RESHAPED_REFLECTION
(null:obj[]))
#else
(null:ParameterModifier[]))
#endif
// This can fail if there is an ambiguity w.r.t. return type
with _ -> null
if (isNonNull methInfo && equalTypes resT methInfo.ReturnType) then
methInfo
else
queryableTypeGetMethodBySearch cenv emEnv parentT mref
else
queryableTypeGetMethodBySearch cenv emEnv parentT mref
let nonQueryableTypeGetMethod (parentTI:Type) (methInfo : MethodInfo) : MethodInfo =
if (parentTI.IsGenericType &&
not (equalTypes parentTI (getTypeConstructor parentTI)))
then TypeBuilder.GetMethod(parentTI,methInfo )
else methInfo
let convMethodRef cenv emEnv (parentTI:Type) (mref:ILMethodRef) =
let parent = mref.EnclosingTypeRef
if isEmittedTypeRef emEnv parent then
// NOTE: if "convType becomes convCreatedType", then handle queryable types here too. [bug 4063]
// Emitted type, can get fully generic MethodBuilder from env.
let methB = envGetMethB emEnv mref
nonQueryableTypeGetMethod parentTI methB
|> nonNull "convMethodRef (emitted)"
else
// Prior type.
if typeIsNotQueryable parentTI then
let parentT = getTypeConstructor parentTI
let methInfo = queryableTypeGetMethod cenv emEnv parentT mref
nonQueryableTypeGetMethod parentTI methInfo
else
queryableTypeGetMethod cenv emEnv parentTI mref
//----------------------------------------------------------------------------
// convMethodSpec
//----------------------------------------------------------------------------
let convMethodSpec cenv emEnv (mspec:ILMethodSpec) =
let typT = convType cenv emEnv mspec.EnclosingType (* (instanced) parent Type *)
let methInfo = convMethodRef cenv emEnv typT mspec.MethodRef (* (generic) method of (generic) parent *)
let methInfo =
if isNil mspec.GenericArgs then
methInfo // non generic
else
let minstTs = convTypesToArray cenv emEnv mspec.GenericArgs
let methInfo = methInfo.MakeGenericMethod minstTs // instantiate method
methInfo
methInfo |> nonNull "convMethodSpec"
//----------------------------------------------------------------------------
// - QueryableTypeGetConstructors: get a constructor on a non-TypeBuilder type
//----------------------------------------------------------------------------
let queryableTypeGetConstructor cenv emEnv (parentT:Type) (mref:ILMethodRef) =
let tyargTs = getGenericArgumentsOfType parentT
let reqArgTs =
let emEnv = envPushTyvars emEnv tyargTs
convTypesToArray cenv emEnv mref.ArgTypes
parentT.GetConstructor(BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance,null, reqArgTs,null)
let nonQueryableTypeGetConstructor (parentTI:Type) (consInfo : ConstructorInfo) : ConstructorInfo =
if parentTI.IsGenericType then TypeBuilder.GetConstructor(parentTI,consInfo) else consInfo
//----------------------------------------------------------------------------
// convConstructorSpec (like convMethodSpec)
//----------------------------------------------------------------------------
let convConstructorSpec cenv emEnv (mspec:ILMethodSpec) =
let mref = mspec.MethodRef
let parentTI = convType cenv emEnv mspec.EnclosingType
if isEmittedTypeRef emEnv mref.EnclosingTypeRef then
// NOTE: if "convType becomes convCreatedType", then handle queryable types here too. [bug 4063]
let consB = envGetConsB emEnv mref
nonQueryableTypeGetConstructor parentTI consB |> nonNull "convConstructorSpec: (emitted)"
else
// Prior type.
if typeIsNotQueryable parentTI then
let parentT = getTypeConstructor parentTI
let ctorG = queryableTypeGetConstructor cenv emEnv parentT mref
nonQueryableTypeGetConstructor parentTI ctorG
else
queryableTypeGetConstructor cenv emEnv parentTI mref
//----------------------------------------------------------------------------
// emitLabelMark
//----------------------------------------------------------------------------
let emitLabelMark emEnv (ilG:ILGenerator) (label:ILCodeLabel) =
let lab = envGetLabel emEnv label
ilG.MarkLabelAndLog(lab)
//----------------------------------------------------------------------------
// emitInstr cenv - I_arith
//----------------------------------------------------------------------------
///Emit comparison instructions.
let emitInstrCompare emEnv (ilG:ILGenerator) comp targ =
match comp with
| BI_beq -> ilG.EmitAndLog(OpCodes.Beq,envGetLabel emEnv targ)
| BI_bge -> ilG.EmitAndLog(OpCodes.Bge ,envGetLabel emEnv targ)
| BI_bge_un -> ilG.EmitAndLog(OpCodes.Bge_Un ,envGetLabel emEnv targ)
| BI_bgt -> ilG.EmitAndLog(OpCodes.Bgt ,envGetLabel emEnv targ)
| BI_bgt_un -> ilG.EmitAndLog(OpCodes.Bgt_Un ,envGetLabel emEnv targ)
| BI_ble -> ilG.EmitAndLog(OpCodes.Ble ,envGetLabel emEnv targ)
| BI_ble_un -> ilG.EmitAndLog(OpCodes.Ble_Un ,envGetLabel emEnv targ)
| BI_blt -> ilG.EmitAndLog(OpCodes.Blt ,envGetLabel emEnv targ)
| BI_blt_un -> ilG.EmitAndLog(OpCodes.Blt_Un ,envGetLabel emEnv targ)
| BI_bne_un -> ilG.EmitAndLog(OpCodes.Bne_Un ,envGetLabel emEnv targ)
| BI_brfalse -> ilG.EmitAndLog(OpCodes.Brfalse,envGetLabel emEnv targ)
| BI_brtrue -> ilG.EmitAndLog(OpCodes.Brtrue ,envGetLabel emEnv targ)
/// Emit the volatile. prefix
let emitInstrVolatile (ilG:ILGenerator) = function
| Volatile -> ilG.EmitAndLog(OpCodes.Volatile)
| Nonvolatile -> ()
/// Emit the align. prefix
let emitInstrAlign (ilG:ILGenerator) = function
| Aligned -> ()
| Unaligned1 -> ilG.Emit(OpCodes.Unaligned,1L) // note: doc says use "long" overload!
| Unaligned2 -> ilG.Emit(OpCodes.Unaligned,2L)
| Unaligned4 -> ilG.Emit(OpCodes.Unaligned,3L)
/// Emit the tail. prefix if necessary
let emitInstrTail (ilG:ILGenerator) tail emitTheCall =
match tail with
| Tailcall -> ilG.EmitAndLog(OpCodes.Tailcall); emitTheCall(); ilG.EmitAndLog(OpCodes.Ret)
| Normalcall -> emitTheCall()
let emitInstrNewobj cenv emEnv (ilG:ILGenerator) mspec varargs =
match varargs with
| None -> ilG.EmitAndLog(OpCodes.Newobj,convConstructorSpec cenv emEnv mspec)
| Some _vartyps -> failwith "emit: pending new varargs" // XXX - gap
let emitSilverlightCheck (ilG:ILGenerator) =
ignore ilG
()
let emitInstrCall cenv emEnv (ilG:ILGenerator) opCall tail (mspec:ILMethodSpec) varargs =
emitInstrTail ilG tail (fun () ->
if mspec.MethodRef.Name = ".ctor" || mspec.MethodRef.Name = ".cctor" then
let cinfo = convConstructorSpec cenv emEnv mspec
match varargs with
| None -> ilG.EmitAndLog (opCall,cinfo)
| Some _vartyps -> failwith "emitInstrCall: .ctor and varargs"
else
let minfo = convMethodSpec cenv emEnv mspec
match varargs with
| None -> ilG.EmitAndLog(opCall,minfo)
| Some vartyps -> ilG.EmitCall (opCall,minfo,convTypesToArray cenv emEnv vartyps)
)
let getGenericMethodDefinition q (ty:Type) =
let gminfo =
match q with
| Quotations.Patterns.Call(_,minfo,_) -> minfo.GetGenericMethodDefinition()
| _ -> failwith "unexpected failure decoding quotation at ilreflect startup"
gminfo.MakeGenericMethod [| ty |]
let getArrayMethInfo n ty =
match n with
| 2 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.GetArray2D<int> null 0 0 @@> ty
| 3 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.GetArray3D<int> null 0 0 0 @@> ty
| 4 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.GetArray4D<int> null 0 0 0 0 @@> ty
| _ -> invalidArg "n" "not expecting array dimension > 4"
let setArrayMethInfo n ty =
match n with
| 2 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray2D<int> null 0 0 0 @@> ty
| 3 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray3D<int> null 0 0 0 0 @@> ty
| 4 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray4D<int> null 0 0 0 0 0 @@> ty
| _ -> invalidArg "n" "not expecting array dimension > 4"
//----------------------------------------------------------------------------
// emitInstr cenv
//----------------------------------------------------------------------------
let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr =
match instr with
| AI_add -> ilG.EmitAndLog(OpCodes.Add)
| AI_add_ovf -> ilG.EmitAndLog(OpCodes.Add_Ovf)
| AI_add_ovf_un -> ilG.EmitAndLog(OpCodes.Add_Ovf_Un)
| AI_and -> ilG.EmitAndLog(OpCodes.And)
| AI_div -> ilG.EmitAndLog(OpCodes.Div)
| AI_div_un -> ilG.EmitAndLog(OpCodes.Div_Un)
| AI_ceq -> ilG.EmitAndLog(OpCodes.Ceq)
| AI_cgt -> ilG.EmitAndLog(OpCodes.Cgt)
| AI_cgt_un -> ilG.EmitAndLog(OpCodes.Cgt_Un)
| AI_clt -> ilG.EmitAndLog(OpCodes.Clt)
| AI_clt_un -> ilG.EmitAndLog(OpCodes.Clt_Un)
(* conversion *)
| AI_conv dt -> (match dt with
| DT_I -> ilG.EmitAndLog(OpCodes.Conv_I)
| DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_I1)
| DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_I2)
| DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_I4)
| DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_I8)
| DT_U -> ilG.EmitAndLog(OpCodes.Conv_U)
| DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_U1)
| DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_U2)
| DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_U4)
| DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_U8)
| DT_R -> ilG.EmitAndLog(OpCodes.Conv_R_Un)
| DT_R4 -> ilG.EmitAndLog(OpCodes.Conv_R4)
| DT_R8 -> ilG.EmitAndLog(OpCodes.Conv_R8)
| DT_REF -> failwith "AI_conv DT_REF?" // XXX - check
)
(* conversion - ovf checks *)
| AI_conv_ovf dt -> (match dt with
| DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I)
| DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1)
| DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2)
| DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4)
| DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8)
| DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U)
| DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1)
| DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2)
| DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4)
| DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8)
| DT_R -> failwith "AI_conv_ovf DT_R?" // XXX - check
| DT_R4 -> failwith "AI_conv_ovf DT_R4?" // XXX - check
| DT_R8 -> failwith "AI_conv_ovf DT_R8?" // XXX - check
| DT_REF -> failwith "AI_conv_ovf DT_REF?" // XXX - check
)
(* conversion - ovf checks and unsigned *)
| AI_conv_ovf_un dt -> (match dt with
| DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I_Un)
| DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1_Un)
| DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2_Un)
| DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4_Un)
| DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8_Un)
| DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U_Un)
| DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1_Un)
| DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2_Un)
| DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4_Un)
| DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8_Un)
| DT_R -> failwith "AI_conv_ovf_un DT_R?" // XXX - check
| DT_R4 -> failwith "AI_conv_ovf_un DT_R4?" // XXX - check
| DT_R8 -> failwith "AI_conv_ovf_un DT_R8?" // XXX - check
| DT_REF -> failwith "AI_conv_ovf_un DT_REF?" // XXX - check
)
| AI_mul -> ilG.EmitAndLog(OpCodes.Mul)
| AI_mul_ovf -> ilG.EmitAndLog(OpCodes.Mul_Ovf)
| AI_mul_ovf_un -> ilG.EmitAndLog(OpCodes.Mul_Ovf_Un)
| AI_rem -> ilG.EmitAndLog(OpCodes.Rem)
| AI_rem_un -> ilG.EmitAndLog(OpCodes.Rem_Un)
| AI_shl -> ilG.EmitAndLog(OpCodes.Shl)
| AI_shr -> ilG.EmitAndLog(OpCodes.Shr)
| AI_shr_un -> ilG.EmitAndLog(OpCodes.Shr_Un)
| AI_sub -> ilG.EmitAndLog(OpCodes.Sub)
| AI_sub_ovf -> ilG.EmitAndLog(OpCodes.Sub_Ovf)
| AI_sub_ovf_un -> ilG.EmitAndLog(OpCodes.Sub_Ovf_Un)
| AI_xor -> ilG.EmitAndLog(OpCodes.Xor)
| AI_or -> ilG.EmitAndLog(OpCodes.Or)
| AI_neg -> ilG.EmitAndLog(OpCodes.Neg)
| AI_not -> ilG.EmitAndLog(OpCodes.Not)
| AI_ldnull -> ilG.EmitAndLog(OpCodes.Ldnull)
| AI_dup -> ilG.EmitAndLog(OpCodes.Dup)
| AI_pop -> ilG.EmitAndLog(OpCodes.Pop)
| AI_ckfinite -> ilG.EmitAndLog(OpCodes.Ckfinite)
| AI_nop -> ilG.EmitAndLog(OpCodes.Nop)
| AI_ldc (DT_I4,ILConst.I4 i32) -> ilG.EmitAndLog(OpCodes.Ldc_I4,i32)
| AI_ldc (DT_I8,ILConst.I8 i64) -> ilG.Emit(OpCodes.Ldc_I8,i64)
| AI_ldc (DT_R4,ILConst.R4 r32) -> ilG.Emit(OpCodes.Ldc_R4,r32)
| AI_ldc (DT_R8,ILConst.R8 r64) -> ilG.Emit(OpCodes.Ldc_R8,r64)
| AI_ldc (_ ,_ ) -> failwith "emitInstrI_arith (AI_ldc (typ,const)) iltyped"
| I_ldarg u16 -> ilG.EmitAndLog(OpCodes.Ldarg ,int16 u16)
| I_ldarga u16 -> ilG.EmitAndLog(OpCodes.Ldarga,int16 u16)
| I_ldind (align,vol,dt) -> emitInstrAlign ilG align;
emitInstrVolatile ilG vol;
(match dt with
| DT_I -> ilG.EmitAndLog(OpCodes.Ldind_I)
| DT_I1 -> ilG.EmitAndLog(OpCodes.Ldind_I1)
| DT_I2 -> ilG.EmitAndLog(OpCodes.Ldind_I2)
| DT_I4 -> ilG.EmitAndLog(OpCodes.Ldind_I4)
| DT_I8 -> ilG.EmitAndLog(OpCodes.Ldind_I8)
| DT_R -> failwith "emitInstr cenv: ldind R"