-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathIlxGen.fs
12322 lines (10122 loc) · 502 KB
/
IlxGen.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. See License.txt in the project root for license information.
/// The ILX generator.
module internal FSharp.Compiler.IlxGen
open FSharp.Compiler.IlxGenSupport
open System
open System.IO
open System.Reflection
open System.Collections.Generic
open System.Collections.Concurrent
open System.Threading
open FSharp.Compiler.IO
open Internal.Utilities
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.BinaryConstants
open FSharp.Compiler.AbstractIL.ILX
open FSharp.Compiler.AbstractIL.ILX.Types
open FSharp.Compiler.AttributeChecking
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.Infos
open FSharp.Compiler.Import
open FSharp.Compiler.LowerStateMachines
open FSharp.Compiler.Syntax
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Text
open FSharp.Compiler.Text.LayoutRender
open FSharp.Compiler.Xml
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypedTreeOps.DebugPrint
open FSharp.Compiler.TypeHierarchy
open FSharp.Compiler.TypeRelations
let IlxGenStackGuardDepth = StackGuard.GetDepthOption "IlxGen"
let getEmptyStackGuard () =
StackGuard(IlxGenStackGuardDepth, "IlxAssemblyGenerator")
let IsNonErasedTypar (tp: Typar) = not tp.IsErased
let DropErasedTypars (tps: Typar list) = tps |> List.filter IsNonErasedTypar
let DropErasedTyargs tys =
tys
|> List.filter (fun ty ->
match ty with
| TType_measure _ -> false
| _ -> true)
let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef: ILMethodDef) = g.AddMethodGeneratedAttributes mdef
let debugDisplayMethodName = "__DebugDisplay"
let useHiddenInitCode = true
let iLdcZero = AI_ldc(DT_I4, ILConst.I4 0)
let iLdcInt64 i = AI_ldc(DT_I8, ILConst.I8 i)
let iLdcDouble i = AI_ldc(DT_R8, ILConst.R8 i)
let iLdcSingle i = AI_ldc(DT_R4, ILConst.R4 i)
/// Choose the constructor parameter names for fields
let ChooseParamNames fieldNamesAndTypes =
let takenFieldNames = fieldNamesAndTypes |> List.map p24 |> Set.ofList
fieldNamesAndTypes
|> List.map (fun (ilPropName, ilFieldName, ilPropType, attrs) ->
let lowerPropName = String.uncapitalize ilPropName
let ilParamName =
if takenFieldNames.Contains lowerPropName then
ilPropName
else
lowerPropName
ilParamName, ilFieldName, ilPropType, attrs)
/// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs
let CheckCodeDoesSomething (code: ILCode) =
code.Instrs
|> Array.exists (function
| AI_ldnull
| AI_nop
| AI_pop
| I_ret
| I_seqpoint _ -> false
| _ -> true)
/// Choose the field names for variables captured by closures
let ChooseFreeVarNames takenNames ts =
let tns = List.map (fun t -> (t, None)) ts
let rec chooseName names (t, nOpt) =
let tn =
match nOpt with
| None -> t
| Some n -> t + string n
if Zset.contains tn names then
chooseName
names
(t,
Some(
match nOpt with
| None -> 0
| Some n -> (n + 1)
))
else
let names = Zset.add tn names
tn, names
let names = Zset.empty String.order |> Zset.addList takenNames
let ts, _names = List.mapFold chooseName names tns
ts
/// We can't tailcall to methods taking byrefs. This helper helps search for them
let rec IsILTypeByref inp =
match inp with
| ILType.Byref _ -> true
| ILType.Modified(_, _, nestedTy) -> IsILTypeByref nestedTy
| _ -> false
let mainMethName = CompilerGeneratedName "main"
/// Used to query custom attributes when emitting COM interop code.
type AttributeDecoder(namedArgs) =
let nameMap =
namedArgs
|> List.map (fun (AttribNamedArg(s, _, _, c)) -> s, c)
|> NameMap.ofList
let findConst x =
match NameMap.tryFind x nameMap with
| Some(AttribExpr(_, Expr.Const(c, _, _))) -> Some c
| _ -> None
let findTyconRef x =
match NameMap.tryFind x nameMap with
| Some(AttribExpr(_, Expr.App(_, _, [ TType_app(tcref, _, _) ], _, _))) -> Some tcref
| _ -> None
member _.FindInt16 x dflt =
match findConst x with
| Some(Const.Int16 x) -> x
| _ -> dflt
member _.FindInt32 x dflt =
match findConst x with
| Some(Const.Int32 x) -> x
| _ -> dflt
member _.FindBool x dflt =
match findConst x with
| Some(Const.Bool x) -> x
| _ -> dflt
member _.FindString x dflt =
match findConst x with
| Some(Const.String x) -> x
| _ -> dflt
member _.FindTypeName x dflt =
match findTyconRef x with
| Some tr -> tr.DisplayName
| _ -> dflt
//--------------------------------------------------------------------------
// Statistics
//--------------------------------------------------------------------------
let mutable reports = (fun _ -> ())
let AddReport f =
let old = reports
reports <-
(fun oc ->
old oc
f oc)
let ReportStatistics (oc: TextWriter) = reports oc
let NewCounter nm =
let mutable count = 0
AddReport(fun oc ->
if count <> 0 then
oc.WriteLine(string count + " " + nm))
(fun () -> count <- count + 1)
let CountClosure = NewCounter "closures"
let CountMethodDef = NewCounter "IL method definitions corresponding to values"
let CountStaticFieldDef = NewCounter "IL field definitions corresponding to values"
let CountCallFuncInstructions = NewCounter "callfunc instructions (indirect calls)"
/// Non-local information related to internals of code generation within an assembly
/// A table recording the generated name of the static backing fields for each mutable top level value where
/// we may need to take the address of that value, e.g. static mutable module-bound values which are structs. These are
/// only accessible intra-assembly. Across assemblies, taking the address of static mutable module-bound values is not permitted.
/// The key to the table is the method ref for the property getter for the value, which is a stable name for the Val's
/// that come from both the signature and the implementation.
type IlxGenIntraAssemblyInfo(staticFieldInfo: ConcurrentDictionary<ILMethodRef, ILFieldSpec>) =
static member Create() =
new IlxGenIntraAssemblyInfo(new ConcurrentDictionary<_, _>(HashIdentity.Structural))
member _.GetOrAddStaticFieldInfo(info: ILMethodRef, f: System.Func<ILMethodRef, ILFieldSpec>) = staticFieldInfo.GetOrAdd(info, f)
/// Helper to make sure we take tailcalls in some situations
type FakeUnit = | Fake
/// Indicates how the generated IL code is ultimately emitted
type IlxGenBackend =
/// Indicates we are emitting code for ilwrite
| IlWriteBackend
/// Indicates we are emitting code for Reflection.Emit in F# Interactive.
| IlReflectBackend
[<NoEquality; NoComparison>]
type IlxGenOptions =
{
/// Indicates the "fragment name" for the part of the assembly we are emitting, particularly for incremental
/// emit using Reflection.Emit in F# Interactive.
fragName: string
/// Indicates if we are generating filter blocks
generateFilterBlocks: bool
/// Indicates if we are working around historical Reflection.Emit bugs
workAroundReflectionEmitBugs: bool
/// Indicates if we should/shouldn't emit constant arrays as static data blobs
emitConstantArraysUsingStaticDataBlobs: bool
/// If this is set, then the last module becomes the "main" module and its toplevel bindings are executed at startup
mainMethodInfo: Attribs option
/// Indicates if local optimizations are on
localOptimizationsEnabled: bool
/// Indicates if we are generating debug symbols
generateDebugSymbols: bool
/// Indicates that FeeFee debug values should be emitted as value 100001 for
/// easier detection in debug output
testFlagEmitFeeFeeAs100001: bool
ilxBackend: IlxGenBackend
fsiMultiAssemblyEmit: bool
/// Indicates the code is being generated in FSI.EXE and is executed immediately after code generation
/// This includes all interactively compiled code, including #load, definitions, and expressions
isInteractive: bool
/// Indicates the code generated is an interactive 'it' expression. We generate a setter to allow clearing of the underlying
/// storage, even though 'it' is not logically mutable
isInteractiveItExpr: bool
/// Suppress ToString emit
useReflectionFreeCodeGen: bool
/// Whenever possible, use callvirt instead of call
alwaysCallVirt: bool
/// When set to true, the IlxGen will delay generation of method bodies and generated them later in parallel (parallelized across files)
parallelIlxGenEnabled: bool
}
/// Compilation environment for compiling a fragment of an assembly
[<NoEquality; NoComparison>]
type cenv =
{
/// The TcGlobals for the compilation
g: TcGlobals
/// The ImportMap for reading IL
amap: ImportMap
/// Environment for EraseClosures functionality
ilxPubCloEnv: EraseClosures.cenv
/// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses.
/// It is unfortunate this is needed but it is until we supply witnesses through the compilation.
tcVal: ConstraintSolver.TcValF
/// The TAST for the assembly being emitted
viewCcu: CcuThunk
/// Collection of all debug points available for inlined code
namedDebugPointsForInlinedCode: Map<NamedDebugPointKey, range>
/// The options for ILX code generation. Only available when generating in implementation code.
optionsOpt: IlxGenOptions option
/// Cache the generation of the "unit" type
mutable ilUnitTy: ILType option
/// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType
casApplied: IDictionary<Stamp, bool>
/// Used to apply forced inlining optimizations to witnesses generated late during codegen
mutable optimizeDuringCodeGen: bool -> Expr -> Expr
/// Delayed Method Generation - which can later be parallelized across multiple files
delayedGenMethods: Queue<unit -> unit>
/// Guard the stack and move to a new one if necessary
mutable stackGuard: StackGuard
}
member cenv.options =
match cenv.optionsOpt with
| None -> failwith "per-module code generation options not available for this operation"
| Some options -> options
override _.ToString() = "<cenv>"
let mkTypeOfExpr cenv m ilTy =
let g = cenv.g
mkAsmExpr (
[ mkNormalCall (mspec_Type_GetTypeFromHandle g) ],
[],
[
mkAsmExpr ([ I_ldtoken(ILToken.ILType ilTy) ], [], [], [ g.system_RuntimeTypeHandle_ty ], m)
],
[ g.system_Type_ty ],
m
)
let useCallVirt (cenv: cenv) boxity (mspec: ILMethodSpec) isBaseCall =
cenv.options.alwaysCallVirt
&& (boxity = AsObject)
&& not mspec.CallingConv.IsStatic
&& not isBaseCall
/// Describes where items are to be placed within the generated IL namespace/typespace.
/// This should be cleaned up.
type CompileLocation =
{
Scope: ILScopeRef
TopImplQualifiedName: string
Namespace: string option
Enclosing: string list
QualifiedNameOfFile: string
}
//--------------------------------------------------------------------------
// Access this and other assemblies
//--------------------------------------------------------------------------
let mkTopName ns n =
String.concat
"."
(match ns with
| Some x -> [ x; n ]
| None -> [ n ])
let CompLocForFragment fragName (ccu: CcuThunk) =
{
QualifiedNameOfFile = fragName
TopImplQualifiedName = fragName
Scope = ccu.ILScopeRef
Namespace = None
Enclosing = []
}
let CompLocForCcu (ccu: CcuThunk) = CompLocForFragment ccu.AssemblyName ccu
let CompLocForSubModuleOrNamespace cloc (submod: ModuleOrNamespace) =
let n = submod.CompiledName
match submod.ModuleOrNamespaceType.ModuleOrNamespaceKind with
| FSharpModuleWithSuffix
| ModuleOrType ->
{ cloc with
Enclosing = cloc.Enclosing @ [ n ]
}
| Namespace _ ->
{ cloc with
Namespace = Some(mkTopName cloc.Namespace n)
}
let CompLocForFixedPath fragName qname (CompPath(sref, _, cpath)) =
let ns, t =
cpath
|> List.takeUntil (fun (_, mkind) ->
match mkind with
| Namespace _ -> false
| _ -> true)
let ns = List.map fst ns
let ns = textOfPath ns
let encl = t |> List.map (fun (s, _) -> s)
let ns = if String.IsNullOrEmpty(ns) then None else Some ns
{
QualifiedNameOfFile = fragName
TopImplQualifiedName = qname
Scope = sref
Namespace = ns
Enclosing = encl
}
let CompLocForFixedModule fragName qname (mspec: ModuleOrNamespace) =
let cloc = CompLocForFixedPath fragName qname mspec.CompilationPath
let cloc = CompLocForSubModuleOrNamespace cloc mspec
cloc
let NestedTypeRefForCompLoc cloc n =
match cloc.Enclosing with
| [] ->
let tyname = mkTopName cloc.Namespace n
mkILTyRef (cloc.Scope, tyname)
| h :: t -> mkILNestedTyRef (cloc.Scope, mkTopName cloc.Namespace h :: t, n)
let CleanUpGeneratedTypeName (nm: string) =
if nm.IndexOfAny IllegalCharactersInTypeAndNamespaceNames = -1 then
nm
else
(nm, IllegalCharactersInTypeAndNamespaceNames)
||> Array.fold (fun nm c -> nm.Replace(string c, "-"))
let TypeNameForInitClass cloc =
"<StartupCode$"
+ (CleanUpGeneratedTypeName cloc.QualifiedNameOfFile)
+ ">.$"
+ cloc.TopImplQualifiedName
let TypeNameForImplicitMainMethod cloc = TypeNameForInitClass cloc + "$Main"
let TypeNameForPrivateImplementationDetails cloc =
"<PrivateImplementationDetails$"
+ (CleanUpGeneratedTypeName cloc.QualifiedNameOfFile)
+ ">"
let CompLocForInitClass cloc =
{ cloc with
Enclosing = [ TypeNameForInitClass cloc ]
Namespace = None
}
let CompLocForPrivateImplementationDetails cloc =
{ cloc with
Enclosing = [ TypeNameForPrivateImplementationDetails cloc ]
Namespace = None
}
/// Compute an ILTypeRef for a CompilationLocation
let TypeRefForCompLoc cloc =
match cloc.Enclosing with
| [] -> mkILTyRef (cloc.Scope, TypeNameForPrivateImplementationDetails cloc)
| [ h ] ->
let tyname = mkTopName cloc.Namespace h
mkILTyRef (cloc.Scope, tyname)
| _ ->
let encl, n = List.frontAndBack cloc.Enclosing
NestedTypeRefForCompLoc { cloc with Enclosing = encl } n
/// Compute an ILType for a CompilationLocation for a non-generic type
let mkILTyForCompLoc cloc =
mkILNonGenericBoxedTy (TypeRefForCompLoc cloc)
/// Compute visibility for type members
/// based on hidden and accessibility from the source code
/// when hidden and realsig is specified then
/// as typed in source code, I.e internal or public
/// when hidden and not realsig is specified then
/// then they are internal, old behaviour (anything not public is internal)
/// otherwise it is public, by definition
let ComputeMemberAccess hidden (accessibility: Accessibility) realsig =
if (not accessibility.IsPublic) && realsig then
accessibility.AsILMemberAccess()
elif hidden then
ILMemberAccess.Assembly
else
ILMemberAccess.Public
let ComputeTypeAccess (tref: ILTypeRef) hidden (accessibility: Accessibility) realsig =
match tref.Enclosing with
| [] ->
if hidden then
ILTypeDefAccess.Private
else
ILTypeDefAccess.Public
| _ -> ILTypeDefAccess.Nested(ComputeMemberAccess hidden accessibility realsig)
//--------------------------------------------------------------------------
// TypeReprEnv
//--------------------------------------------------------------------------
/// Indicates how type parameters are mapped to IL type variables
[<NoEquality; NoComparison>]
type TypeReprEnv
(reprs: Map<Stamp, (uint16 * Typar)>, count: int, templateReplacement: (TyconRef * ILTypeRef * Typars * TyparInstantiation) option) =
static let empty = TypeReprEnv(count = 0, reprs = Map.empty, templateReplacement = None)
/// Get the template replacement information used when using struct types for state machines based on a "template" struct
member _.TemplateReplacement = templateReplacement
member _.WithTemplateReplacement(tcref, ilCloTyRef, cloFreeTyvars, templateTypeInst) =
TypeReprEnv(reprs, count, Some(tcref, ilCloTyRef, cloFreeTyvars, templateTypeInst))
member _.WithoutTemplateReplacement() = TypeReprEnv(reprs, count, None)
/// Lookup a type parameter
member _.Item(tp: Typar, m: range) =
try
reprs[tp.Stamp] |> fst
with :? KeyNotFoundException ->
errorR (InternalError("Undefined or unsolved type variable: " + showL (typarL tp), m))
// Random value for post-hoc diagnostic analysis on generated tree *
uint16 666
/// Add an additional type parameter to the environment. If the parameter is a units-of-measure parameter
/// then it is ignored, since it doesn't correspond to a .NET type parameter.
member tyenv.AddOne(tp: Typar) =
if IsNonErasedTypar tp then
TypeReprEnv(reprs.Add(tp.Stamp, (uint16 count, tp)), count + 1, templateReplacement)
else
tyenv
/// Add multiple additional type parameters to the environment.
member tyenv.Add tps =
(tyenv, tps) ||> List.fold (fun tyenv tp -> tyenv.AddOne tp)
/// Get the count of the non-erased type parameters in scope.
member _.Count = count
/// Get the empty environment, where no type parameters are in scope.
static member Empty = empty
/// Reset to the empty environment, where no type parameters are in scope.
member eenv.ResetTypars() =
TypeReprEnv(count = 0, reprs = Map.empty, templateReplacement = eenv.TemplateReplacement)
/// Get the environment for a fixed set of type parameters
member eenv.ForTypars tps = eenv.ResetTypars().Add tps
/// Get the environment for within a type definition
member eenv.ForTycon(tycon: Tycon) = eenv.ForTypars tycon.TyparsNoRange
/// Get the environment for generating a reference to items within a type definition
member eenv.ForTyconRef(tcref: TyconRef) = eenv.ForTycon tcref.Deref
/// Get a list of the Typars in this environment
member eenv.AsUserProvidedTypars() =
reprs
|> Map.toList
|> List.map (fun (_, (_, tp)) -> tp)
|> List.filter (fun tp -> not tp.IsCompilerGenerated)
|> Zset.ofList typarOrder
//--------------------------------------------------------------------------
// Generate type references
//--------------------------------------------------------------------------
/// Get the ILTypeRef or other representation information for a type
let GenTyconRef (tcref: TyconRef) =
assert (not tcref.IsTypeAbbrev)
tcref.CompiledRepresentation
type VoidNotOK =
| VoidNotOK
| VoidOK
#if DEBUG
let voidCheck m g permits ty =
if permits = VoidNotOK && isVoidTy g ty then
error (InternalError("System.Void unexpectedly detected in IL code generation. This should not occur.", m))
#endif
[<Struct>]
type DuFieldCoordinates = { CaseIdx: int; FieldIdx: int }
/// Structure for maintaining field reuse across struct unions
type UnionFieldReuseMap = MultiMap<string, DuFieldCoordinates>
let unionFieldReuseMapping thisUnionTy (cases: UnionCase[]) : UnionFieldReuseMap =
if not (isStructTyconRef thisUnionTy) then
Map.empty
else
let fieldKey (f: RecdField) = mkLowerName f.LogicalName
[
for i = 0 to cases.Length - 1 do
let fields = cases[i].RecdFieldsArray
for j = 0 to fields.Length - 1 do
let f = fields[j]
yield fieldKey f, { CaseIdx = i; FieldIdx = j }
]
|> MultiMap.ofList
/// When generating parameter and return types generate precise .NET IL pointer types.
/// These can't be generated for generic instantiations, since .NET generics doesn't
/// permit this. But for 'naked' values (locals, parameters, return values etc.) machine
/// integer values and native pointer values are compatible (though the code is unverifiable).
type PtrsOK =
| PtrTypesOK
| PtrTypesNotOK
let rec GenTypeArgAux cenv m tyenv tyarg =
GenTypeAux cenv m tyenv VoidNotOK PtrTypesNotOK tyarg
and GenTypeArgsAux cenv m tyenv tyargs =
List.map (GenTypeArgAux cenv m tyenv) (DropErasedTyargs tyargs)
and GenTyAppAux cenv m tyenv repr tinst =
match repr with
| CompiledTypeRepr.ILAsmOpen ty ->
let ilTypeInst = GenTypeArgsAux cenv m tyenv tinst
let ty = instILType ilTypeInst ty
ty
| CompiledTypeRepr.ILAsmNamed(tref, boxity, ilTypeOpt) -> GenILTyAppAux cenv m tyenv (tref, boxity, ilTypeOpt) tinst
and GenILTyAppAux cenv m tyenv (tref, boxity, ilTypeOpt) tinst =
match ilTypeOpt with
| None ->
let ilTypeInst = GenTypeArgsAux cenv m tyenv tinst
mkILTy boxity (mkILTySpec (tref, ilTypeInst))
| Some ilType -> ilType // monomorphic types include a cached ilType to avoid reallocation of an ILType node
and GenNamedTyAppAux (cenv: cenv) m (tyenv: TypeReprEnv) ptrsOK tcref tinst =
let g = cenv.g
match tyenv.TemplateReplacement with
| Some(tcref2, ilCloTyRef, cloFreeTyvars, _) when tyconRefEq g tcref tcref2 ->
let cloInst = List.map mkTyparTy cloFreeTyvars
let ilTypeInst = GenTypeArgsAux cenv m tyenv cloInst
mkILValueTy ilCloTyRef ilTypeInst
| _ ->
let tinst = DropErasedTyargs tinst
// See above note on ptrsOK
if
ptrsOK = PtrTypesOK
&& tyconRefEq g tcref g.nativeptr_tcr
&& (freeInTypes CollectTypars tinst).FreeTypars.IsEmpty
then
GenNamedTyAppAux cenv m tyenv ptrsOK g.ilsigptr_tcr tinst
else
#if !NO_TYPEPROVIDERS
match tcref.TypeReprInfo with
// Generate the base type, because that is always the representation of the erased type, unless the assembly is being injected
| TProvidedTypeRepr info when info.IsErased ->
GenTypeAux cenv m tyenv VoidNotOK ptrsOK (info.BaseTypeForErased(m, g.obj_ty_withNulls))
| _ ->
#endif
GenTyAppAux cenv m tyenv (GenTyconRef tcref) tinst
and GenTypeAux cenv m (tyenv: TypeReprEnv) voidOK ptrsOK ty =
let g = cenv.g
#if DEBUG
voidCheck m g voidOK ty
#else
ignore voidOK
#endif
match stripTyEqnsAndMeasureEqns g ty with
| TType_app(tcref, tinst, _) -> GenNamedTyAppAux cenv m tyenv ptrsOK tcref tinst
| TType_tuple(tupInfo, args) -> GenTypeAux cenv m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args)
| TType_fun(dty, returnTy, _) ->
EraseClosures.mkILFuncTy cenv.ilxPubCloEnv (GenTypeArgAux cenv m tyenv dty) (GenTypeArgAux cenv m tyenv returnTy)
| TType_anon(anonInfo, tinst) ->
let tref = anonInfo.ILTypeRef
let boxity =
if evalAnonInfoIsStruct anonInfo then
ILBoxity.AsValue
else
ILBoxity.AsObject
GenILTyAppAux cenv m tyenv (tref, boxity, None) tinst
| TType_ucase(ucref, args) ->
let cuspec, idx = GenUnionCaseSpec cenv m tyenv ucref args
EraseUnions.GetILTypeForAlternative cuspec idx
| TType_forall(tps, tau) ->
let tps = DropErasedTypars tps
if tps.IsEmpty then
GenTypeAux cenv m tyenv VoidNotOK ptrsOK tau
else
EraseClosures.mkILTyFuncTy cenv.ilxPubCloEnv
| TType_var(tp, _) -> mkILTyvarTy tyenv[tp, m]
| TType_measure _ -> g.ilg.typ_Int32
//--------------------------------------------------------------------------
// Generate ILX references to closures, classunions etc. given a tyenv
//--------------------------------------------------------------------------
and GenUnionCaseRef (cenv: cenv) m tyenv (reuseMap: UnionFieldReuseMap) i (fspecs: RecdField[]) =
let g = cenv.g
let fieldMarker = int SourceConstructFlags.Field
fspecs
|> Array.mapi (fun j fspec ->
let ilFieldDef =
mkILInstanceField (fspec.LogicalName, GenType cenv m tyenv fspec.FormalType, None, ILMemberAccess.Public)
// These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs
let mappingAttrs =
match reuseMap |> MultiMap.find (mkLowerName fspec.LogicalName) with
| [] -> [ mkCompilationMappingAttrWithVariantNumAndSeqNum g fieldMarker i j ]
| mappings ->
mappings
|> List.map (fun m -> mkCompilationMappingAttrWithVariantNumAndSeqNum g fieldMarker m.CaseIdx m.FieldIdx)
let attrs = mappingAttrs @ GenAdditionalAttributesForTy g fspec.FormalType
IlxUnionCaseField(ilFieldDef.With(customAttrs = mkILCustomAttrs attrs)))
and GenUnionRef (cenv: cenv) m (tcref: TyconRef) =
let g = cenv.g
let tycon = tcref.Deref
assert (not tycon.IsTypeAbbrev)
match tycon.UnionTypeInfo with
| ValueNone -> failwith "GenUnionRef m"
| ValueSome funion ->
cached funion.CompiledRepresentation (fun () ->
let tyenvinner = TypeReprEnv.Empty.ForTycon tycon
match tcref.CompiledRepresentation with
| CompiledTypeRepr.ILAsmOpen _ -> failwith "GenUnionRef m: unexpected ASM tyrep"
| CompiledTypeRepr.ILAsmNamed(tref, _, _) ->
let fieldReuseMap = unionFieldReuseMapping tcref tycon.UnionCasesArray
let alternatives =
tycon.UnionCasesArray
|> Array.mapi (fun i cspec ->
{
altName = cspec.CompiledName
altCustomAttrs = emptyILCustomAttrs
altFields = GenUnionCaseRef cenv m tyenvinner fieldReuseMap i cspec.RecdFieldsArray
})
let nullPermitted = IsUnionTypeWithNullAsTrueValue g tycon
let hasHelpers = ComputeUnionHasHelpers g tcref
let boxity =
(if tcref.IsStructOrEnumTycon then
ILBoxity.AsValue
else
ILBoxity.AsObject)
IlxUnionRef(boxity, tref, alternatives, nullPermitted, hasHelpers))
and ComputeUnionHasHelpers g (tcref: TyconRef) =
if tyconRefEq g tcref g.unit_tcr_canon then
NoHelpers
elif tyconRefEq g tcref g.list_tcr_canon then
SpecialFSharpListHelpers
elif tyconRefEq g tcref g.option_tcr_canon then
SpecialFSharpOptionHelpers
else
match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with
| Some(Attrib(_, _, [ AttribBoolArg b ], _, _, _, _)) -> if b then AllHelpers else NoHelpers
| Some(Attrib(_, _, _, _, _, _, m)) ->
errorR (Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded (), m))
AllHelpers
| _ -> AllHelpers (* not hiddenRepr *)
and GenUnionSpec (cenv: cenv) m tyenv tcref tyargs =
let curef = GenUnionRef cenv m tcref
let tinst = GenTypeArgs cenv m tyenv tyargs
IlxUnionSpec(curef, tinst)
and GenUnionCaseSpec cenv m tyenv (ucref: UnionCaseRef) tyargs =
let cuspec = GenUnionSpec cenv m tyenv ucref.TyconRef tyargs
cuspec, ucref.Index
and GenType cenv m tyenv ty =
GenTypeAux cenv m tyenv VoidNotOK PtrTypesNotOK ty
and GenTypes cenv m tyenv tys = List.map (GenType cenv m tyenv) tys
and GenTypePermitVoid cenv m tyenv ty =
(GenTypeAux cenv m tyenv VoidOK PtrTypesNotOK ty)
and GenTypesPermitVoid cenv m tyenv tys =
List.map (GenTypePermitVoid cenv m tyenv) tys
and GenTyApp cenv m tyenv repr tyargs = GenTyAppAux cenv m tyenv repr tyargs
and GenNamedTyApp cenv m tyenv tcref tinst =
GenNamedTyAppAux cenv m tyenv PtrTypesNotOK tcref tinst
/// IL void types are only generated for return types
and GenReturnType cenv m tyenv returnTyOpt =
match returnTyOpt with
| None -> ILType.Void
| Some returnTy ->
let ilTy =
GenTypeAux cenv m tyenv VoidNotOK (*1*) PtrTypesOK returnTy (*1: generate void from unit, but not accept void *)
GenReadOnlyModReqIfNecessary cenv.g returnTy ilTy
and GenParamType cenv m tyenv isSlotSig ty =
let ilTy = GenTypeAux cenv m tyenv VoidNotOK PtrTypesOK ty
if isSlotSig then
GenReadOnlyModReqIfNecessary cenv.g ty ilTy
else
ilTy
and GenParamTypes cenv m tyenv isSlotSig tys =
tys |> List.map (GenParamType cenv m tyenv isSlotSig)
and GenTypeArgs cenv m tyenv tyargs = GenTypeArgsAux cenv m tyenv tyargs
// Static fields generally go in a private InitializationCodeAndBackingFields section. This is to ensure all static
// fields are initialized only in their class constructors (we generate one primary
// cctor for each file to ensure initialization coherence across the file, regardless
// of how many modules are in the file). This means F# passes an extra check applied by SQL Server when it
// verifies stored procedures: SQL Server checks that all 'initonly' static fields are only initialized from
// their own class constructor.
//
// However, mutable static fields must be accessible across compilation units. This means we place them in their "natural" location
// which may be in a nested module etc. This means mutable static fields can't be used in code to be loaded by SQL Server.
//
// Computes the location where the static field for a value lives.
// - Literals go in their type/module.
// - For interactive code, we always place fields in their type/module with an accurate name
let GenFieldSpecForStaticField (isInteractive, (g: TcGlobals), ilContainerTy, vspec: Val, nm, m, cloc, ilTy) =
let fieldName = vspec.CompiledName g.CompilerGlobalState
if HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then
mkILFieldSpecInTy (ilContainerTy, fieldName, ilTy)
elif isInteractive then
mkILFieldSpecInTy (ilContainerTy, CompilerGeneratedName fieldName, ilTy)
elif g.realsig then
assert (g.CompilerGlobalState |> Option.isSome)
mkILFieldSpecInTy (
ilContainerTy,
CompilerGeneratedName(g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName(nm, m)),
ilTy
)
else
let fieldName =
// Ensure that we have an g.CompilerGlobalState
assert (g.CompilerGlobalState |> Option.isSome)
g.CompilerGlobalState.Value.IlxGenNiceNameGenerator.FreshCompilerGeneratedName(nm, m)
let ilFieldContainerTy = mkILTyForCompLoc (CompLocForInitClass cloc)
mkILFieldSpecInTy (ilFieldContainerTy, fieldName, ilTy)
let GenRecdFieldRef m cenv (tyenv: TypeReprEnv) (rfref: RecdFieldRef) tyargs =
match tyenv.TemplateReplacement with
| Some(tcref2, ilCloTyRef, cloFreeTyvars, templateTypeInst) when tyconRefEq cenv.g rfref.TyconRef tcref2 ->
// Fixup references to the fields of a struct machine template
// templateStructTy = ResumableStateMachine<TaskStateMachineData<SomeType['FreeTyVars]>
// templateTyconRef = ResumableStateMachine<'Data>
// templateTypeArgs = <TaskStateMachineData<SomeType['FreeTyVars]>
// templateTypeInst = 'Data -> TaskStateMachineData<SomeType['FreeTyVars]>
// cloFreeTyvars = <'FreeTyVars>
// ilCloTy = clo<'FreeTyVars> w.r.t envinner
// rfref = ResumableStateMachine<'Data>::Result
// rfref.RecdField.FormalType = 'Data
let ilCloTy =
let cloInst = List.map mkTyparTy cloFreeTyvars
let ilTypeInst = GenTypeArgsAux cenv m tyenv cloInst
mkILValueTy ilCloTyRef ilTypeInst
let tyenvinner = TypeReprEnv.Empty.ForTypars cloFreeTyvars
mkILFieldSpecInTy (
ilCloTy,
ComputeFieldName rfref.Tycon rfref.RecdField,
GenType cenv m tyenvinner (instType templateTypeInst rfref.RecdField.FormalType)
)
| _ ->
let tyenvinner = TypeReprEnv.Empty.ForTycon rfref.Tycon
let ilTy = GenTyApp cenv m tyenv rfref.TyconRef.CompiledRepresentation tyargs
mkILFieldSpecInTy (ilTy, ComputeFieldName rfref.Tycon rfref.RecdField, GenType cenv m tyenvinner rfref.RecdField.FormalType)
let GenExnType amap m tyenv (ecref: TyconRef) =
GenTyApp amap m tyenv ecref.CompiledRepresentation []
type ArityInfo = int list
//--------------------------------------------------------------------------
// Closure summaries
//
// Function, Object, Delegate and State Machine Closures
// =====================================================
//
// For a normal expression closure, we generate:
//
// class Implementation<cloFreeTyvars> : FSharpFunc<...> {
// override Invoke(..) { expr }
// }
//
// Local Type Functions
// ====================
//
// The input expression is:
// let input-val : FORALL<directTypars>. body-type = LAM <directTypars>. body-expr : body-type
// ...
//
// This is called at some point:
//
// input-val<directTyargs>
//
// Note 'input-val' is never used without applying it to some type arguments.
//
// Basic examples - first define some functions that extract information from generic parameters, and which are constrained:
//
// type TypeInfo<'T> = TypeInfo of System.Type
// type TypeName = TypeName of string
//
// let typeinfo<'T when 'T :> System.IComparable) = TypeInfo (typeof<'T>)
// let typename<'T when 'T :> System.IComparable) = TypeName (typeof<'T>.Name)
//
// Then here are examples:
//
// LAM <'T>{addWitness}. (typeinfo<'T>, typeinfo<'T[]>, (incr{ : 'T -> 'T)) : TypeInfo<'T> * TypeInfo<'T[]> * ('T -> 'T)
// directTypars = 'T
// cloFreeTyvars = empty
//
// or
// LAM <'T>. (typeinfo<'T>, typeinfo<'U>) : TypeInfo<'T> * TypeInfo<'U>
// directTypars = 'T
// cloFreeTyvars = 'U
//
// or
// LAM <'T>. (typeinfo<'T>, typeinfo<'U>, typename<'V>) : TypeInfo<'T> * TypeInfo<'U> * TypeName
// directTypars = 'T
// cloFreeTyvars = 'U,'V
//
// or, for witnesses:
//
// let inline incr{addWitnessForT} (x: 'T) = x + GenericZero<'T> // has witness argument for '+'
//
// LAM <'T when 'T :... op_Addition ...>{addWitnessForT}. (incr<'T>{addWitnessForT}, incr<'U>{addWitnessForU}, incr<'V>{addWitnessForV}) : ('T -> 'T) * ('U -> 'U) * ('V -> 'V)
// directTypars = 'T
// cloFreeTyvars = 'U,'V
// cloFreeTyvarsWitnesses = witnesses implied by cloFreeTyvars = {addWitnessForU, addWitnessForV}
// directTyparsWitnesses = witnesses implied by directTypars = {addWitnessForT}
//
// Define the free variable sets:
//
// cloFreeTyvars = free-tyvars-of(input-expr)
//
// where IsNamedLocalTypeFuncVal is true.
//
// The directTypars may have constraints that require some witnesses. Making those explicit with "{ ... }" syntax for witnesses:
// input-expr = {LAM <directTypars>{directWitnessInfoArgs}. body-expr : body-type }
//
// let x : FORALL<'T ... constrained ...> ... = clo<directTyargs>{directWitnessInfos}
//
// Given this, we generate this shape of code:
//
// type Implementation<cloFreeTyvars>(cloFreeTyvarsWitnesses) =
// member DirectInvoke<directTypars>(directTyparsWitnesses) : body-type =
// body-expr
//
// local x : obj = new Implementation<cloFreeTyvars>(cloFreeTyvarsWitnesses)
// ....
// ldloc x
// unbox Implementation<cloFreeTyvars>
// call Implementation<cloFreeTyvars>::DirectInvoke<directTypars>(directTyparsWitnesses)