forked from dotnet/fsharp
/
IlxGen.fs
8221 lines (6877 loc) · 411 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 System.IO
open System.Reflection
open System.Collections.Generic
open System.Collections.Immutable
open Internal.Utilities
open Internal.Utilities.Collections
open FSharp.Compiler
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.Internal
open FSharp.Compiler.AbstractIL.Internal.Library
open FSharp.Compiler.AbstractIL.Extensions.ILX
open FSharp.Compiler.AbstractIL.Extensions.ILX.Types
open FSharp.Compiler.AbstractIL.Internal.BinaryConstants
open FSharp.Compiler.AttributeChecking
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.ErrorLogger
open FSharp.Compiler.Infos
open FSharp.Compiler.Import
open FSharp.Compiler.Layout
open FSharp.Compiler.Lib
open FSharp.Compiler.LowerCallsAndSeqs
open FSharp.Compiler.PrettyNaming
open FSharp.Compiler.Range
open FSharp.Compiler.SyntaxTree
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypedTreeOps.DebugPrint
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.TypeRelations
open FSharp.Compiler.XmlDoc
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)
/// Make a method that simply loads a field
let mkLdfldMethodDef (ilMethName, reprAccess, isStatic, ilTy, ilFieldName, ilPropType) =
let ilFieldSpec = mkILFieldSpecInTy(ilTy, ilFieldName, ilPropType)
let ilReturn = mkILReturn ilPropType
let ilMethodDef =
if isStatic then
mkILNonGenericStaticMethod (ilMethName, reprAccess, [], ilReturn, mkMethodBody(true, [], 2, nonBranchingInstrsToCode [mkNormalLdsfld ilFieldSpec], None))
else
mkILNonGenericInstanceMethod (ilMethName, reprAccess, [], ilReturn, mkMethodBody (true, [], 2, nonBranchingInstrsToCode [ mkLdarg0; mkNormalLdfld ilFieldSpec], None))
ilMethodDef.WithSpecialName
/// Choose the constructor parameter names for fields
let ChooseParamNames fieldNamesAndTypes =
let takenFieldNames = fieldNamesAndTypes |> List.map p23 |> Set.ofList
fieldNamesAndTypes
|> List.map (fun (ilPropName, ilFieldName, ilPropType) ->
let lowerPropName = String.uncapitalize ilPropName
let ilParamName = if takenFieldNames.Contains lowerPropName then ilPropName else lowerPropName
ilParamName, ilFieldName, ilPropType)
/// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs
let rec 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 IsILTypeByref = function ILType.Byref _ -> true | _ -> 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 findAppTr x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.App (_, _, [TType_app(tr, _)], _, _))) -> Some tr | _ -> 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 findAppTr 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 count = ref 0
AddReport (fun oc -> if !count <> 0 then oc.WriteLine (string !count + " " + nm))
(fun () -> incr count)
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
type IlxGenIntraAssemblyInfo =
{
/// 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.
StaticFieldInfo: Dictionary<ILMethodRef, ILFieldSpec>
}
/// 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
localOptimizationsAreOn: 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
/// 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
/// Whenever possible, use callvirt instead of call
alwaysCallVirt: 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
/// 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
/// The options for ILX code generation
opts: IlxGenOptions
/// Cache the generation of the "unit" type
mutable ilUnitTy: ILType option
/// Other information from the emit of this assembly
intraAssemblyInfo: IlxGenIntraAssemblyInfo
/// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType
casApplied: Dictionary<Stamp, bool>
/// Used to apply forced inlining optimizations to witnesses generated late during codegen
mutable optimizeDuringCodeGen: (bool -> Expr -> Expr)
/// What depth are we at when generating an expression?
mutable exprRecursionDepth: int
/// Delayed Method Generation - prevents stack overflows when we need to generate methods that are split into many methods by the optimizer.
delayedGenMethods: Queue<cenv -> unit>
}
override x.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 mkGetNameExpr cenv (ilt: ILType) m =
mkAsmExpr ([I_ldstr ilt.BasicQualifiedName], [], [], [cenv.g.string_ty], m)
let useCallVirt cenv boxity (mspec: ILMethodSpec) isBaseCall =
cenv.opts.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: IL.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 = List.takeUntil (fun (_, mkind) -> mkind <> Namespace) cpath
let ns = List.map fst ns
let ns = textOfPath ns
let encl = t |> List.map (fun (s, _)-> s)
let ns = if 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 CompLocForImplicitMainMethod cloc =
{cloc with Enclosing=[TypeNameForImplicitMainMethod cloc]; Namespace=None}
let CompLocForPrivateImplementationDetails cloc =
{cloc with
Enclosing=[TypeNameForPrivateImplementationDetails cloc]; Namespace=None}
/// Compute an ILTypeRef for a CompilationLocation
let rec 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)
let ComputeMemberAccess hidden = if hidden then ILMemberAccess.Assembly else ILMemberAccess.Public
// Under --publicasinternal change types from Public to Private (internal for types)
let ComputePublicTypeAccess() = ILTypeDefAccess.Public
let ComputeTypeAccess (tref: ILTypeRef) hidden =
match tref.Enclosing with
| [] -> if hidden then ILTypeDefAccess.Private else ComputePublicTypeAccess()
| _ -> ILTypeDefAccess.Nested (ComputeMemberAccess hidden)
//--------------------------------------------------------------------------
// TypeReprEnv
//--------------------------------------------------------------------------
/// Indicates how type parameters are mapped to IL type variables
[<NoEquality; NoComparison>]
type TypeReprEnv(reprs: Map<Stamp, uint16>, count: int) =
/// Lookup a type parameter
member __.Item (tp: Typar, m: range) =
try reprs.[tp.Stamp]
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), count + 1)
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 =
TypeReprEnv(count = 0, reprs = Map.empty)
/// Get the environment for a fixed set of type parameters
static member ForTypars tps =
TypeReprEnv.Empty.Add tps
/// Get the environment for within a type definition
static member ForTycon (tycon: Tycon) =
TypeReprEnv.ForTypars (tycon.TyparsNoRange)
/// Get the environment for generating a reference to items within a type definition
static member ForTyconRef (tycon: TyconRef) =
TypeReprEnv.ForTycon tycon.Deref
//--------------------------------------------------------------------------
// 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
/// 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 GenReadOnlyAttributeIfNecessary (g: TcGlobals) ty =
let add = isInByrefTy g ty && g.attrib_IsReadOnlyAttribute.TyconRef.CanDeref
if add then
let attr = mkILCustomAttribute g.ilg (g.attrib_IsReadOnlyAttribute.TypeRef, [], [], [])
Some attr
else
None
/// Generate "modreq([mscorlib]System.Runtime.InteropServices.InAttribute)" on inref types.
let GenReadOnlyModReqIfNecessary (g: TcGlobals) ty ilTy =
let add = isInByrefTy g ty && g.attrib_InAttribute.TyconRef.CanDeref
if add then
ILType.Modified(true, g.attrib_InAttribute.TypeRef, ilTy)
else
ilTy
let rec GenTypeArgAux amap m tyenv tyarg =
GenTypeAux amap m tyenv VoidNotOK PtrTypesNotOK tyarg
and GenTypeArgsAux amap m tyenv tyargs =
List.map (GenTypeArgAux amap m tyenv) (DropErasedTyargs tyargs)
and GenTyAppAux amap m tyenv repr tinst =
match repr with
| CompiledTypeRepr.ILAsmOpen ty ->
let ilTypeInst = GenTypeArgsAux amap m tyenv tinst
let ty = IL.instILType ilTypeInst ty
ty
| CompiledTypeRepr.ILAsmNamed (tref, boxity, ilTypeOpt) ->
GenILTyAppAux amap m tyenv (tref, boxity, ilTypeOpt) tinst
and GenILTyAppAux amap m tyenv (tref, boxity, ilTypeOpt) tinst =
match ilTypeOpt with
| None ->
let ilTypeInst = GenTypeArgsAux amap 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 (amap: ImportMap) m tyenv ptrsOK tcref tinst =
let g = amap.g
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 amap m tyenv ptrsOK g.ilsigptr_tcr tinst
else
#if !NO_EXTENSIONTYPING
match tcref.TypeReprInfo with
// Generate the base type, because that is always the representation of the erased type, unless the assembly is being injected
| TProvidedTypeExtensionPoint info when info.IsErased ->
GenTypeAux amap m tyenv VoidNotOK ptrsOK (info.BaseTypeForErased (m, g.obj_ty))
| _ ->
#endif
GenTyAppAux amap m tyenv (GenTyconRef tcref) tinst
and GenTypeAux amap m (tyenv: TypeReprEnv) voidOK ptrsOK ty =
let g = amap.g
#if DEBUG
voidCheck m g voidOK ty
#else
ignore voidOK
#endif
match stripTyEqnsAndMeasureEqns g ty with
| TType_app (tcref, tinst) -> GenNamedTyAppAux amap m tyenv ptrsOK tcref tinst
| TType_tuple (tupInfo, args) -> GenTypeAux amap m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args)
| TType_fun (dty, returnTy) -> EraseClosures.mkILFuncTy g.ilxPubCloEnv (GenTypeArgAux amap m tyenv dty) (GenTypeArgAux amap m tyenv returnTy)
| TType_anon (anonInfo, tinst) ->
let tref = anonInfo.ILTypeRef
let boxity = if evalAnonInfoIsStruct anonInfo then ILBoxity.AsValue else ILBoxity.AsObject
GenILTyAppAux amap m tyenv (tref, boxity, None) tinst
| TType_ucase (ucref, args) ->
let cuspec, idx = GenUnionCaseSpec amap m tyenv ucref args
EraseUnions.GetILTypeForAlternative cuspec idx
| TType_forall (tps, tau) ->
let tps = DropErasedTypars tps
if tps.IsEmpty then GenTypeAux amap m tyenv VoidNotOK ptrsOK tau
else EraseClosures.mkILTyFuncTy g.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 (amap: ImportMap) m tyenv i (fspecs: RecdField[]) =
let g = amap.g
fspecs |> Array.mapi (fun j fspec ->
let ilFieldDef = IL.mkILInstanceField(fspec.Name, GenType amap 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
IlxUnionField
(ilFieldDef.With(customAttrs = mkILCustomAttrs [(mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j )])))
and GenUnionRef (amap: ImportMap) m (tcref: TyconRef) =
let g = amap.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.ForTycon tycon
match tcref.CompiledRepresentation with
| CompiledTypeRepr.ILAsmOpen _ -> failwith "GenUnionRef m: unexpected ASM tyrep"
| CompiledTypeRepr.ILAsmNamed (tref, _, _) ->
let alternatives =
tycon.UnionCasesArray |> Array.mapi (fun i cspec ->
{ altName=cspec.CompiledName
altCustomAttrs=emptyILCustomAttrs
altFields=GenUnionCaseRef amap m tyenvinner 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 amap m tyenv tcref tyargs =
let curef = GenUnionRef amap m tcref
let tinst = GenTypeArgs amap m tyenv tyargs
IlxUnionSpec(curef, tinst)
and GenUnionCaseSpec amap m tyenv (ucref: UnionCaseRef) tyargs =
let cuspec = GenUnionSpec amap m tyenv ucref.TyconRef tyargs
cuspec, ucref.Index
and GenType amap m tyenv ty =
GenTypeAux amap m tyenv VoidNotOK PtrTypesNotOK ty
and GenTypes amap m tyenv tys = List.map (GenType amap m tyenv) tys
and GenTypePermitVoid amap m tyenv ty = (GenTypeAux amap m tyenv VoidOK PtrTypesNotOK ty)
and GenTypesPermitVoid amap m tyenv tys = List.map (GenTypePermitVoid amap m tyenv) tys
and GenTyApp amap m tyenv repr tyargs = GenTyAppAux amap m tyenv repr tyargs
and GenNamedTyApp amap m tyenv tcref tinst = GenNamedTyAppAux amap m tyenv PtrTypesNotOK tcref tinst
/// IL void types are only generated for return types
and GenReturnType amap m tyenv returnTyOpt =
match returnTyOpt with
| None -> ILType.Void
| Some returnTy ->
let ilTy = GenTypeAux amap m tyenv VoidNotOK(*1*) PtrTypesOK returnTy (*1: generate void from unit, but not accept void *)
GenReadOnlyModReqIfNecessary amap.g returnTy ilTy
and GenParamType amap m tyenv isSlotSig ty =
let ilTy = GenTypeAux amap m tyenv VoidNotOK PtrTypesOK ty
if isSlotSig then
GenReadOnlyModReqIfNecessary amap.g ty ilTy
else
ilTy
and GenParamTypes amap m tyenv isSlotSig tys =
tys |> List.map (GenParamType amap m tyenv isSlotSig)
and GenTypeArgs amap m tyenv tyargs = GenTypeArgsAux amap m tyenv tyargs
and GenTypePermitVoidAux amap m tyenv ty = GenTypeAux amap m tyenv VoidOK PtrTypesNotOK ty
// 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 'initionly' 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, ilContainerTy, vspec: Val, nm, m, cloc, ilTy) =
if isInteractive || HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then
let fieldName = vspec.CompiledName g.CompilerGlobalState
let fieldName = if isInteractive then CompilerGeneratedName fieldName else fieldName
mkILFieldSpecInTy (ilContainerTy, fieldName, 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 (rfref: RecdFieldRef) tyargs =
let tyenvinner = TypeReprEnv.ForTycon rfref.Tycon
mkILFieldSpecInTy(GenTyApp cenv.amap m tyenv rfref.TyconRef.CompiledRepresentation tyargs,
ComputeFieldName rfref.Tycon rfref.RecdField,
GenType cenv.amap m tyenvinner rfref.RecdField.FormalType)
let GenExnType amap m tyenv (ecref: TyconRef) = GenTyApp amap m tyenv ecref.CompiledRepresentation []
//--------------------------------------------------------------------------
// Closure summaries
//--------------------------------------------------------------------------
type ArityInfo = int list
[<NoEquality; NoComparison>]
type IlxClosureInfo =
{ /// The whole expression for the closure
cloExpr: Expr
/// The name of the generated closure class
cloName: string
/// The counts of curried arguments for the closure
cloArityInfo: ArityInfo
/// The formal return type
ilCloFormalReturnTy: ILType
/// An immutable array of free variable descriptions for the closure
ilCloAllFreeVars: IlxClosureFreeVar[]
/// The ILX specification for the closure
cloSpec: IlxClosureSpec
/// The attributes that get attached to the closure class
cloAttribs: Attribs
/// The generic parameters for the closure, i.e. the type variables it captures
cloILGenericParams: IL.ILGenericParameterDefs
/// The captured variables for the closure
cloFreeVars: Val list
cloFreeTyvars: Typars
cloWitnessInfos: TraitWitnessInfos
/// ILX view of the lambdas for the closures
ilCloLambdas: IlxClosureLambdas
/// The free type parameters occuring in the type of the closure (and not just its body)
/// This is used for local type functions, whose contract class must use these types
/// type Contract<'fv> =
/// abstract DirectInvoke: ty['fv]
/// type Implementation<'fv, 'fv2> : Contract<'fv> =
/// override DirectInvoke: ty['fv] = expr['fv, 'fv2]
///
/// At the callsite we generate
/// unbox ty['fv]
/// callvirt clo.DirectInvoke
localTypeFuncILGenericArgs: ILType list
/// The free type parameters for the local type function as F# TAST types
localTypeFuncContractFreeTypars: Typar list
localTypeFuncDirectILGenericParams: IL.ILGenericParameterDefs
localTypeFuncInternalFreeTypars: Typar list
}
//--------------------------------------------------------------------------
// ValStorage
//--------------------------------------------------------------------------
/// Describes the storage for a value
[<NoEquality; NoComparison>]
type ValStorage =
/// Indicates the value is always null
| Null
/// Indicates the value is stored in a static field.
| StaticField of ILFieldSpec * ValRef * (*hasLiteralAttr:*)bool * ILType * string * ILType * ILMethodRef * ILMethodRef * OptionalShadowLocal
/// Indicates the value is represented as a property that recomputes it each time it is referenced. Used for simple constants that do not cause initialization triggers
| StaticProperty of ILMethodSpec * OptionalShadowLocal
/// Indicates the value is represented as an IL method (in a "main" class for a F#
/// compilation unit, or as a member) according to its inferred or specified arity.
| Method of ValReprInfo * ValRef * ILMethodSpec * ILMethodSpec * Range.range * Typars * Typars * CurriedArgInfos * ArgReprInfo list * TraitWitnessInfos * TType list * ArgReprInfo
/// Indicates the value is stored at the given position in the closure environment accessed via "ldarg 0"
| Env of ILType * ILFieldSpec * NamedLocalIlxClosureInfo ref option
/// Indicates that the value is an argument of a method being generated
| Arg of int
/// Indicates that the value is stored in local of the method being generated. NamedLocalIlxClosureInfo is normally empty.
/// It is non-empty for 'local type functions', see comments on definition of NamedLocalIlxClosureInfo.
| Local of idx: int * realloc: bool * NamedLocalIlxClosureInfo ref option
/// Indicates if there is a shadow local storage for a local, to make sure it gets a good name in debugging
and OptionalShadowLocal =
| NoShadowLocal
| ShadowLocal of ValStorage
/// The representation of a NamedLocalClosure is based on a cloinfo. However we can't generate a cloinfo until we've
/// decided the representations of other items in the recursive set. Hence we use two phases to decide representations in
/// a recursive set. Yuck.
and NamedLocalIlxClosureInfo =
| NamedLocalIlxClosureInfoGenerator of (IlxGenEnv -> IlxClosureInfo)
| NamedLocalIlxClosureInfoGenerated of IlxClosureInfo
override __.ToString() = "<NamedLocalIlxClosureInfo>"
/// Indicates the overall representation decisions for all the elements of a namespace of module
and ModuleStorage =
{
Vals: Lazy<NameMap<ValStorage>>
SubModules: Lazy<NameMap<ModuleStorage>>
}
override __.ToString() = "<ModuleStorage>"
/// Indicate whether a call to the value can be implemented as
/// a branch. At the moment these are only used for generating branch calls back to
/// the entry label of the method currently being generated when a direct tailcall is
/// made in the method itself.
and BranchCallItem =
| BranchCallClosure of ArityInfo
| BranchCallMethod of
// Argument counts for compiled form of F# method or value
ArityInfo *
// Arg infos for compiled form of F# method or value
(TType * ArgReprInfo) list list *
// Typars for F# method or value
Typars *
// num obj args in IL
int *
// num witness args in IL
int *
// num actual args in IL
int
override __.ToString() = "<BranchCallItem>"
/// Represents a place we can branch to
and Mark =
| Mark of ILCodeLabel
member x.CodeLabel = (let (Mark lab) = x in lab)
//--------------------------------------------------------------------------
// We normally generate in the context of a "what to do next" continuation
//--------------------------------------------------------------------------
and sequel =
| EndFilter
/// Exit a 'handler' block
/// The integer says which local to save result in
| LeaveHandler of (bool (* finally? *) * int * Mark)
/// Branch to the given mark
| Br of Mark
| CmpThenBrOrContinue of Pops * ILInstr list
/// Continue and leave the value on the IL computation stack
| Continue
/// The value then do something else
| DiscardThen of sequel
/// Return from the method
| Return
/// End a scope of local variables. Used at end of 'let' and 'let rec' blocks to get tail recursive setting
/// of end-of-scope marks
| EndLocalScope of sequel * Mark
/// Return from a method whose return type is void
| ReturnVoid
and Pushes = ILType list
and Pops = int
/// The overall environment at a particular point in an expression tree.
and IlxGenEnv =
{ /// The representation decisions for the (non-erased) type parameters that are in scope
tyenv: TypeReprEnv
/// An ILType for some random type in this assembly
someTypeInThisAssembly: ILType
/// Indicates if we are generating code for the last file in a .EXE
isFinalFile: bool
/// Indicates the default "place" for stuff we're currently generating
cloc: CompileLocation
/// Hiding information down the signature chain, used to compute what's public to the assembly
sigToImplRemapInfo: (Remap * SignatureHidingInfo) list
/// All values in scope
valsInScope: ValMap<Lazy<ValStorage>>
/// All witnesses in scope and their mapping to storage for the witness value.
witnessesInScope: TraitWitnessInfoHashMap<ValStorage>
/// Suppress witnesses when not generating witness-passing code
suppressWitnesses: bool
/// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1.
/// REVIEW: generalize to arbitrary nested local loops??
innerVals: (ValRef * (BranchCallItem * Mark)) list
/// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions.
letBoundVars: ValRef list
/// The set of IL local variable indexes currently in use by lexically scoped variables, to allow reuse on different branches.
/// Really an integer set.
liveLocals: IntMap<unit>
/// Are we under the scope of a try, catch or finally? If so we can't tailcall. SEH = structured exception handling
withinSEH: bool
/// Are we inside of a recursive let binding, while loop, or a for loop?
isInLoop: bool
}
override __.ToString() = "<IlxGenEnv>"
let discard = DiscardThen Continue
let discardAndReturnVoid = DiscardThen ReturnVoid
let SetIsInLoop isInLoop eenv =
if eenv.isInLoop = isInLoop then eenv
else { eenv with isInLoop = isInLoop }
let ReplaceTyenv tyenv (eenv: IlxGenEnv) = {eenv with tyenv = tyenv }
let EnvForTypars tps eenv = {eenv with tyenv = TypeReprEnv.ForTypars tps }
let AddTyparsToEnv typars (eenv: IlxGenEnv) = {eenv with tyenv = eenv.tyenv.Add typars}
let AddSignatureRemapInfo _msg (rpi, mhi) eenv =
{ eenv with sigToImplRemapInfo = (mkRepackageRemapping rpi, mhi) :: eenv.sigToImplRemapInfo }
let OutputStorage (pps: TextWriter) s =
match s with
| StaticField _ -> pps.Write "(top)"
| StaticProperty _ -> pps.Write "(top)"
| Method _ -> pps.Write "(top)"
| Local _ -> pps.Write "(local)"
| Arg _ -> pps.Write "(arg)"
| Env _ -> pps.Write "(env)"
| Null -> pps.Write "(null)"
//--------------------------------------------------------------------------
// Augment eenv with values
//--------------------------------------------------------------------------
let AddStorageForVal (g: TcGlobals) (v, s) eenv =
let eenv = { eenv with valsInScope = eenv.valsInScope.Add v s }
// If we're compiling fslib then also bind the value as a non-local path to
// allow us to resolve the compiler-non-local-references that arise from env.fs
//
// Do this by generating a fake "looking from the outside in" non-local value reference for
// v, dereferencing it to find the corresponding signature Val, and adding an entry for the signature val.
//
// A similar code path exists in ilxgen.fs for the tables of "optimization data" for values
if g.compilingFslib then
// Passing an empty remap is sufficient for FSharp.Core.dll because it turns out the remapped type signature can
// still be resolved.
match tryRescopeVal g.fslibCcu Remap.Empty v with
| ValueNone -> eenv
| ValueSome vref ->
match vref.TryDeref with
| ValueNone ->
//let msg = sprintf "could not dereference external value reference to something in FSharp.Core.dll during code generation, v.MangledName = '%s', v.Range = %s" v.MangledName (stringOfRange v.Range)
//System.Diagnostics.Debug.Assert(false, msg)
eenv
| ValueSome gv ->
{ eenv with valsInScope = eenv.valsInScope.Add gv s }
else
eenv
let AddStorageForLocalVals g vals eenv =
List.foldBack (fun (v, s) acc -> AddStorageForVal g (v, notlazy s) acc) vals eenv
let AddStorageForLocalWitness eenv (w,s) =
{ eenv with witnessesInScope = eenv.witnessesInScope.SetItem (w, s) }
let AddStorageForLocalWitnesses witnesses eenv =
(eenv, witnesses) ||> List.fold AddStorageForLocalWitness
//--------------------------------------------------------------------------
// Lookup eenv
//--------------------------------------------------------------------------
let StorageForVal g m v eenv =
let v =
try eenv.valsInScope.[v]
with :? KeyNotFoundException ->
assert false
errorR(Error(FSComp.SR.ilUndefinedValue(showL(valAtBindL g v)), m))
notlazy (Arg 668(* random value for post-hoc diagnostic analysis on generated tree *) )
v.Force()
let StorageForValRef g m (v: ValRef) eenv = StorageForVal g m v.Deref eenv
let ComputeGenerateWitnesses (g: TcGlobals) eenv =
g.generateWitnesses && not eenv.witnessesInScope.IsEmpty && not eenv.suppressWitnesses
let TryStorageForWitness (_g: TcGlobals) eenv (w: TraitWitnessInfo) =
match eenv.witnessesInScope.TryGetValue w with
| true, storage -> Some storage
| _ -> None
let IsValRefIsDllImport g (vref: ValRef) =
vref.Attribs |> HasFSharpAttributeOpt g g.attrib_DllImportAttribute
/// Determine how a top level value is represented, when it is being represented
/// as a method.
let GetMethodSpecForMemberVal amap g (memberInfo: ValMemberInfo) (vref: ValRef) =
let m = vref.Range
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref
let tps, witnessInfos, curriedArgInfos, returnTy, retInfo =
assert(vref.ValReprInfo.IsSome)
GetTopValTypeInCompiledForm g vref.ValReprInfo.Value numEnclosingTypars vref.Type m