-
Notifications
You must be signed in to change notification settings - Fork 789
/
Optimizer.fs
4472 lines (3806 loc) · 216 KB
/
Optimizer.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 F# expression simplifier. The main aim is to inline simple, known functions
/// and constant values, and to eliminate non-side-affecting bindings that
/// are never used.
module internal FSharp.Compiler.Optimizer
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AttributeChecking
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.Syntax
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Layout
open FSharp.Compiler.Text.LayoutRender
open FSharp.Compiler.Text.TaggedText
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypedTreeOps.DebugPrint
open FSharp.Compiler.TypedTreePickle
open FSharp.Compiler.TypeHierarchy
open FSharp.Compiler.TypeRelations
open System.Collections.Generic
open System.Collections.ObjectModel
let OptimizerStackGuardDepth = GetEnvInteger "FSHARP_Optimizer" 50
let i_ldlen = [ I_ldlen; (AI_conv DT_I4) ]
/// size of a function call
let [<Literal>] callSize = 1
/// size of a for/while loop
let [<Literal>] forAndWhileLoopSize = 5
/// size of a try/with
let [<Literal>] tryWithSize = 5
/// size of a try/finally
let [<Literal>] tryFinallySize = 5
/// Total cost of a closure. Each closure adds a class definition
let [<Literal>] closureTotalSize = 10
/// Total cost of a method definition
let [<Literal>] methodDefnTotalSize = 1
type TypeValueInfo =
| UnknownTypeValue
/// Partial information about an expression.
///
/// We store one of these for each value in the environment, including values
/// which we know little or nothing about.
type ExprValueInfo =
| UnknownValue
/// SizeValue(size, value)
///
/// Records size info (maxDepth) for an ExprValueInfo
| SizeValue of size: int * ExprValueInfo
/// ValValue(vref, value)
///
/// Records that a value is equal to another value, along with additional
/// information.
| ValValue of ValRef * ExprValueInfo
| TupleValue of ExprValueInfo[]
/// RecdValue(tycon, values)
///
/// INVARIANT: values are in field definition order .
| RecdValue of TyconRef * ExprValueInfo[]
| UnionCaseValue of UnionCaseRef * ExprValueInfo[]
| ConstValue of Const * TType
/// CurriedLambdaValue(id, arity, size, lambdaExpression, ty)
///
/// arities: The number of bunches of untupled args and type args, and
/// the number of args in each bunch. NOTE: This include type arguments.
/// expr: The value, a lambda term.
/// ty: The type of lambda term
| CurriedLambdaValue of id: Unique * arity: int * size: int * lambdaExpr: Expr * lambdaExprTy: TType
/// ConstExprValue(size, value)
| ConstExprValue of size: int * value: Expr
type ValInfo =
{ ValMakesNoCriticalTailcalls: bool
ValExprInfo: ExprValueInfo
}
//-------------------------------------------------------------------------
// Partial information about entire namespace fragments or modules
//
// This is a somewhat nasty data structure since
// (a) we need the lookups to be very efficient
// (b) we need to be able to merge these efficiently while building up the overall data for a module
// (c) we pickle these to the binary optimization data format
// (d) we don't want the process of unpickling the data structure to
// dereference/resolve all the ValRef's in the data structure, since
// this would be slow on startup and a potential failure point should
// any of the destination values not dereference correctly.
//
// It doesn't yet feel like we've got this data structure as good as it could be
//-------------------------------------------------------------------------
/// Table of the values contained in one module
type ValInfos(entries) =
let valInfoTable =
lazy (let t = ValHash.Create ()
for vref: ValRef, x in entries do
t.Add (vref.Deref, (vref, x))
t)
// The compiler's ValRef's in TcGlobals.fs that refer to things in FSharp.Core break certain invariants that hold elsewhere,
// because they dereference to point to Val's from signatures rather than Val's from implementations.
// Thus a backup alternative resolution technique is needed for these when processing the FSharp.Core implementation files
// holding these items. This resolution must be able to distinguish between overloaded methods, so we use
// XmlDocSigOfVal as a cheap hack to get a unique item of data for a value.
let valInfosForFslib =
LazyWithContext<_, TcGlobals>.Create ((fun g ->
let dict =
Dictionary<ValRef * ValLinkageFullKey, ValRef * ValInfo>
(HashIdentity.FromFunctions
(fun (_: ValRef, k: ValLinkageFullKey) -> hash k.PartialKey)
(fun (v1, k1) (v2, k2) ->
k1.PartialKey = k2.PartialKey &&
// disambiguate overloads, somewhat low-perf but only use for a handful of overloads in FSharp.Core
match k1.TypeForLinkage, k2.TypeForLinkage with
| Some _, Some _ ->
let sig1 = XmlDocSigOfVal g true "" v1.Deref
let sig2 = XmlDocSigOfVal g true "" v2.Deref
(sig1 = sig2)
| None, None -> true
| _ -> false))
for vref, _x as p in entries do
let vkey = (vref, vref.Deref.GetLinkageFullKey())
if dict.ContainsKey vkey then
failwithf "dictionary already contains key %A" vkey
dict.Add(vkey, p)
ReadOnlyDictionary dict), id)
member x.Entries = valInfoTable.Force().Values
member x.Map f = ValInfos(Seq.map f x.Entries)
member x.Filter f = ValInfos(Seq.filter f x.Entries)
member x.TryFind (v: ValRef) = valInfoTable.Force().TryFind v.Deref
member x.TryFindForFslib (g, vref: ValRef) =
valInfosForFslib.Force(g).TryGetValue((vref, vref.Deref.GetLinkageFullKey()))
type ModuleInfo =
{ ValInfos: ValInfos
ModuleOrNamespaceInfos: NameMap<LazyModuleInfo> }
and LazyModuleInfo = InterruptibleLazy<ModuleInfo>
type ImplFileOptimizationInfo = LazyModuleInfo
type CcuOptimizationInfo = LazyModuleInfo
#if DEBUG
let braceL x = leftL (tagText "{") ^^ x ^^ rightL (tagText "}")
let seqL xL xs = Seq.fold (fun z x -> z @@ xL x) emptyL xs
let namemapL xL xmap = NameMap.foldBack (fun nm x z -> xL nm x @@ z) xmap emptyL
let rec exprValueInfoL g exprVal =
match exprVal with
| ConstValue (x, ty) -> NicePrint.layoutConst g ty x
| UnknownValue -> wordL (tagText "?")
| SizeValue (_, vinfo) -> exprValueInfoL g vinfo
| ValValue (vr, vinfo) -> bracketL ((valRefL vr ^^ wordL (tagText "alias")) --- exprValueInfoL g vinfo)
| TupleValue vinfos -> bracketL (exprValueInfosL g vinfos)
| RecdValue (_, vinfos) -> braceL (exprValueInfosL g vinfos)
| UnionCaseValue (ucr, vinfos) -> unionCaseRefL ucr ^^ bracketL (exprValueInfosL g vinfos)
| CurriedLambdaValue(_lambdaId, _arities, _bsize, expr, _ety) -> wordL (tagText "lam") ++ exprL expr (* (sprintf "lam(size=%d)" bsize) *)
| ConstExprValue (_size, x) -> exprL x
and exprValueInfosL g vinfos = commaListL (List.map (exprValueInfoL g) (Array.toList vinfos))
and moduleInfoL g (x: LazyModuleInfo) =
let x = x.Force()
braceL ((wordL (tagText "Modules: ") @@ (x.ModuleOrNamespaceInfos |> namemapL (fun nm x -> wordL (tagText nm) ^^ moduleInfoL g x) ) )
@@ (wordL (tagText "Values:") @@ (x.ValInfos.Entries |> seqL (fun (vref, x) -> valRefL vref ^^ valInfoL g x) )))
and valInfoL g (x: ValInfo) =
braceL ((wordL (tagText "ValExprInfo: ") @@ exprValueInfoL g x.ValExprInfo)
@@ (wordL (tagText "ValMakesNoCriticalTailcalls:") @@ wordL (tagText (if x.ValMakesNoCriticalTailcalls then "true" else "false"))))
#endif
type Summary<'Info> =
{ Info: 'Info
/// What's the contribution to the size of this function?
FunctionSize: int
/// What's the total contribution to the size of the assembly, including closure classes etc.?
TotalSize: int
/// Meaning: could mutate, could non-terminate, could raise exception
/// One use: an effect expr cannot be eliminated as dead code (e.g. sequencing)
/// One use: an effect=false expr cannot throw an exception? so try-with is removed.
HasEffect: bool
/// Indicates that a function may make a useful tailcall, hence when called should itself be tailcalled
MightMakeCriticalTailcall: bool
}
//-------------------------------------------------------------------------
// BoundValueInfoBySize
// Note, this is a different notion of "size" to the one used for inlining heuristics
//-------------------------------------------------------------------------
let SizeOfValueInfo valueInfo =
let rec loop acc valueInfo =
match valueInfo with
| SizeValue (vdepth, _v) -> assert (vdepth >= 0); acc + vdepth // terminate recursion at CACHED size nodes
| CurriedLambdaValue _
| ConstExprValue _
| ConstValue _
| UnknownValue -> acc + 1
| TupleValue vinfos
| RecdValue (_, vinfos)
| UnionCaseValue (_, vinfos) when vinfos.Length = 0 -> acc + 1
| TupleValue vinfos
| RecdValue (_, vinfos)
| UnionCaseValue (_, vinfos) -> loop (acc + 1) vinfos[0]
| ValValue (_vr, vinfo) -> loop (acc + 1) vinfo
loop 0 valueInfo
let [<Literal>] minDepthForASizeNode = 5 // for small vinfos do not record size info, save space
let rec MakeValueInfoWithCachedSize vdepth v =
match v with
| SizeValue(_, v) -> MakeValueInfoWithCachedSize vdepth v
| _ -> if vdepth > minDepthForASizeNode then SizeValue(vdepth, v) else v (* add nodes to stop recursion *)
let MakeSizedValueInfo v =
let vdepth = SizeOfValueInfo v
MakeValueInfoWithCachedSize vdepth v
let BoundValueInfoBySize vinfo =
let rec bound depth x =
if depth < 0 then
UnknownValue
else
match x with
| SizeValue (vdepth, vinfo) -> if vdepth < depth then x else MakeSizedValueInfo (bound depth vinfo)
| ValValue (vr, vinfo) -> ValValue (vr, bound (depth-1) vinfo)
| TupleValue vinfos -> TupleValue (Array.map (bound (depth-1)) vinfos)
| RecdValue (tcref, vinfos) -> RecdValue (tcref, Array.map (bound (depth-1)) vinfos)
| UnionCaseValue (ucr, vinfos) -> UnionCaseValue (ucr, Array.map (bound (depth-1)) vinfos)
| ConstValue _ -> x
| UnknownValue -> x
| CurriedLambdaValue _ -> x
| ConstExprValue (_size, _) -> x
let maxDepth = 6 (* beware huge constants! *)
let trimDepth = 3
let vdepth = SizeOfValueInfo vinfo
if vdepth > maxDepth
then MakeSizedValueInfo (bound trimDepth vinfo)
else MakeValueInfoWithCachedSize vdepth vinfo
//-------------------------------------------------------------------------
// Settings and optimizations
//-------------------------------------------------------------------------
let [<Literal>] jitOptDefault = true
let [<Literal>] localOptDefault = true
let [<Literal>] crossAssemblyOptimizationDefault = true
let [<Literal>] debugPointsForPipeRightDefault = true
[<RequireQualifiedAccess>]
type OptimizationProcessingMode =
| Sequential
| Parallel
type OptimizationSettings =
{
abstractBigTargets : bool
jitOptUser : bool option
localOptUser : bool option
debugPointsForPipeRight: bool option
crossAssemblyOptimizationUser : bool option
/// size after which we start chopping methods in two, though only at match targets
bigTargetSize : int
/// size after which we start enforcing splitting sub-expressions to new methods, to avoid hitting .NET IL limitations
veryBigExprSize : int
/// The size after which we don't inline
lambdaInlineThreshold : int
/// For unit testing
reportingPhase : bool
reportNoNeedToTailcall: bool
reportFunctionSizes : bool
reportHasEffect : bool
reportTotalSizes : bool
processingMode : OptimizationProcessingMode
}
static member Defaults =
{ abstractBigTargets = false
jitOptUser = None
localOptUser = None
debugPointsForPipeRight = None
bigTargetSize = 100
veryBigExprSize = 3000
crossAssemblyOptimizationUser = None
lambdaInlineThreshold = 6
reportingPhase = false
reportNoNeedToTailcall = false
reportFunctionSizes = false
reportHasEffect = false
reportTotalSizes = false
processingMode = OptimizationProcessingMode.Sequential
}
/// Determines if JIT optimizations are enabled
member x.JitOptimizationsEnabled = match x.jitOptUser with Some f -> f | None -> jitOptDefault
/// Determines if intra-assembly optimization is enabled
member x.LocalOptimizationsEnabled = match x.localOptUser with Some f -> f | None -> localOptDefault
/// Determines if cross-assembly optimization is enabled
member x.crossAssemblyOpt () =
x.LocalOptimizationsEnabled &&
x.crossAssemblyOptimizationUser |> Option.defaultValue crossAssemblyOptimizationDefault
/// Determines if we should keep optimization values
member x.KeepOptimizationValues = x.crossAssemblyOpt ()
/// Determines if we should inline calls
member x.InlineLambdas = x.LocalOptimizationsEnabled
/// Determines if we should eliminate unused bindings with no effect
member x.EliminateUnusedBindings = x.LocalOptimizationsEnabled
/// Determines if we should arrange things so we debug points for pipelines x |> f1 |> f2
/// including locals "<pipe1-input>", "<pipe1-stage1>" and so on.
/// On by default for debug code.
member x.DebugPointsForPipeRight =
not x.LocalOptimizationsEnabled &&
x.debugPointsForPipeRight |> Option.defaultValue debugPointsForPipeRightDefault
/// Determines if we should eliminate for-loops around an expr if it has no effect
///
/// This optimization is off by default, given tiny overhead of including try/with. See https://github.com/dotnet/fsharp/pull/376
member x.EliminateForLoop = x.LocalOptimizationsEnabled
/// Determines if we should eliminate try/with or try/finally around an expr if it has no effect
///
/// This optimization is off by default, given tiny overhead of including try/with. See https://github.com/dotnet/fsharp/pull/376
member _.EliminateTryWithAndTryFinally = false
/// Determines if we should eliminate first part of sequential expression if it has no effect
member x.EliminateSequential = x.LocalOptimizationsEnabled
/// Determines if we should determine branches in pattern matching based on known information, e.g.
/// eliminate a "if true then .. else ... "
member x.EliminateSwitch = x.LocalOptimizationsEnabled
/// Determines if we should eliminate gets on a record if the value is known to be a record with known info and the field is not mutable
member x.EliminateRecdFieldGet = x.LocalOptimizationsEnabled
/// Determines if we should eliminate gets on a tuple if the value is known to be a tuple with known info
member x.EliminateTupleFieldGet = x.LocalOptimizationsEnabled
/// Determines if we should eliminate gets on a union if the value is known to be that union case and the particular field has known info
member x.EliminateUnionCaseFieldGet () = x.LocalOptimizationsEnabled
/// Determines if we should eliminate non-compiler generated immediate bindings
member x.EliminateImmediatelyConsumedLocals() = x.LocalOptimizationsEnabled
/// Determines if we should expand "let x = (exp1, exp2, ...)" bindings as prior tmps
/// Also if we should expand "let x = Some exp1" bindings as prior tmps
member x.ExpandStructuralValues() = x.LocalOptimizationsEnabled
/// Determines how to process optimization of multiple files and individual optimization phases
member x.ProcessingMode() = x.processingMode
type cenv =
{ g: TcGlobals
TcVal : ConstraintSolver.TcValF
amap: Import.ImportMap
optimizing: bool
scope: CcuThunk
localInternalVals: Dictionary<Stamp, ValInfo>
settings: OptimizationSettings
emitTailcalls: bool
/// cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType
casApplied: Dictionary<Stamp, bool>
stackGuard: StackGuard
realsig: bool
}
override x.ToString() = "<cenv>"
// environment for a method
type MethodEnv =
{ mutable pipelineCount: int }
override x.ToString() = "<MethodEnv>"
type IncrementalOptimizationEnv =
{ /// An identifier to help with name generation
latestBoundId: Ident option
/// The set of lambda IDs we've inlined to reach this point. Helps to prevent recursive inlining
dontInline: Zset<Unique>
/// Recursively bound vars. If an sub-expression that is a candidate for method splitting
/// contains any of these variables then don't split it, for fear of mucking up tailcalls.
/// See FSharp 1.0 bug 2892
dontSplitVars: ValMap<unit>
/// Disable method splitting in loops
disableMethodSplitting: bool
/// The Val for the function binding being generated, if any.
functionVal: (Val * ValReprInfo) option
typarInfos: (Typar * TypeValueInfo) list
localExternalVals: LayeredMap<Stamp, ValInfo>
methEnv: MethodEnv
globalModuleInfos: LayeredMap<string, LazyModuleInfo>
}
static member Empty =
{ latestBoundId = None
dontInline = Zset.empty Int64.order
typarInfos = []
functionVal = None
dontSplitVars = ValMap.Empty
disableMethodSplitting = false
localExternalVals = LayeredMap.Empty
globalModuleInfos = LayeredMap.Empty
methEnv = { pipelineCount = 0 } }
override x.ToString() = "<IncrementalOptimizationEnv>"
//-------------------------------------------------------------------------
// IsPartialExprVal - is the expr fully known?
//-------------------------------------------------------------------------
/// IsPartialExprVal indicates the cases where we cant rebuild an expression
let rec IsPartialExprVal x =
match x with
| UnknownValue -> true
| TupleValue args | RecdValue (_, args) | UnionCaseValue (_, args) -> Array.exists IsPartialExprVal args
| ConstValue _ | CurriedLambdaValue _ | ConstExprValue _ -> false
| ValValue (_, a)
| SizeValue (_, a) -> IsPartialExprVal a
let CheckInlineValueIsComplete (v: Val) res =
if v.ShouldInline && IsPartialExprVal res then
errorR(Error(FSComp.SR.optValueMarkedInlineButIncomplete(v.DisplayName), v.Range))
//System.Diagnostics.Debug.Assert(false, sprintf "Break for incomplete inline value %s" v.DisplayName)
let check (vref: ValRef) (res: ValInfo) =
CheckInlineValueIsComplete vref.Deref res.ValExprInfo
(vref, res)
//-------------------------------------------------------------------------
// Bind information about values
//-------------------------------------------------------------------------
let EmptyModuleInfo =
notlazy { ValInfos = ValInfos([]); ModuleOrNamespaceInfos = Map.empty }
let rec UnionOptimizationInfos (minfos : seq<LazyModuleInfo>) =
notlazy
{ ValInfos =
ValInfos(seq { for minfo in minfos do yield! minfo.Force().ValInfos.Entries })
ModuleOrNamespaceInfos =
minfos
|> Seq.map (fun m -> m.Force().ModuleOrNamespaceInfos)
|> NameMap.union UnionOptimizationInfos }
let FindOrCreateModuleInfo n (ss: Map<_, _>) =
match ss.TryFind n with
| Some res -> res
| None -> EmptyModuleInfo
let FindOrCreateGlobalModuleInfo n (ss: LayeredMap<_, _>) =
match ss.TryFind n with
| Some res -> res
| None -> EmptyModuleInfo
let rec BindValueInSubModuleFSharpCore (mp: string[]) i (v: Val) vval ss =
if i < mp.Length then
{ss with ModuleOrNamespaceInfos = BindValueInModuleForFslib mp[i] mp (i+1) v vval ss.ModuleOrNamespaceInfos }
else
// REVIEW: this line looks quadratic for performance when compiling FSharp.Core
{ss with ValInfos = ValInfos(Seq.append ss.ValInfos.Entries (Seq.singleton (mkLocalValRef v, vval))) }
and BindValueInModuleForFslib n mp i v vval (ss: NameMap<_>) =
let old = FindOrCreateModuleInfo n ss
Map.add n (notlazy (BindValueInSubModuleFSharpCore mp i v vval (old.Force()))) ss
and BindValueInGlobalModuleForFslib n mp i v vval (ss: LayeredMap<_, _>) =
let old = FindOrCreateGlobalModuleInfo n ss
ss.Add(n, notlazy (BindValueInSubModuleFSharpCore mp i v vval (old.Force())))
let BindValueForFslib (nlvref : NonLocalValOrMemberRef) v vval env =
{env with globalModuleInfos = BindValueInGlobalModuleForFslib nlvref.AssemblyName nlvref.EnclosingEntity.nlr.Path 0 v vval env.globalModuleInfos }
let UnknownValInfo = { ValExprInfo=UnknownValue; ValMakesNoCriticalTailcalls=false }
let mkValInfo info (v: Val) = { ValExprInfo=info.Info; ValMakesNoCriticalTailcalls= v.MakesNoCriticalTailcalls }
(* Bind a value *)
let BindInternalLocalVal cenv (v: Val) vval env =
let vval = if v.IsMutable then UnknownValInfo else vval
match vval.ValExprInfo with
| UnknownValue -> env
| _ ->
cenv.localInternalVals[v.Stamp] <- vval
env
let BindExternalLocalVal cenv (v: Val) vval env =
let g = cenv.g
let vval = if v.IsMutable then {vval with ValExprInfo=UnknownValue } else vval
let env =
match vval.ValExprInfo with
| UnknownValue -> env
| _ ->
{ env with localExternalVals=env.localExternalVals.Add (v.Stamp, vval) }
// 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 "representations" for values
let env =
if g.compilingFSharpCore 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
| ValueSome vref -> BindValueForFslib vref.nlr v vval env
| _ -> env
else env
env
let rec BindValsInModuleOrNamespace cenv (mval: LazyModuleInfo) env =
let mval = mval.Force()
// do all the sub modules
let env = (mval.ModuleOrNamespaceInfos, env) ||> NameMap.foldBackRange (BindValsInModuleOrNamespace cenv)
let env = (env, mval.ValInfos.Entries) ||> Seq.fold (fun env (v: ValRef, vval) -> BindExternalLocalVal cenv v.Deref vval env)
env
let inline BindInternalValToUnknown cenv v env =
ignore cenv
ignore v
env
let inline BindInternalValsToUnknown cenv vs env =
ignore cenv
ignore vs
env
let BindTypar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo) :: env.typarInfos }
let BindTyparsToUnknown (tps: Typar list) env =
if isNil tps then env else
// The optimizer doesn't use the type values it could track.
// However here we mutate to provide better names for generalized type parameters
// The names chosen are 'a', 'b' etc. These are also the compiled names in the IL code
let nms = PrettyTypes.PrettyTyparNames (fun _ -> true) (env.typarInfos |> List.map (fun (tp, _) -> tp.Name) ) tps
PrettyTypes.AssignPrettyTyparNames tps nms
List.fold (fun sofar arg -> BindTypar arg UnknownTypeValue sofar) env tps
let BindCcu (ccu: CcuThunk) mval env (_g: TcGlobals) =
{ env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) }
/// Lookup information about values
let GetInfoForLocalValue cenv env (v: Val) m =
// Abstract slots do not have values
if v.IsDispatchSlot then UnknownValInfo
else
match cenv.localInternalVals.TryGetValue v.Stamp with
| true, res -> res
| _ ->
match env.localExternalVals.TryFind v.Stamp with
| Some vval -> vval
| None ->
if v.ShouldInline then
errorR(Error(FSComp.SR.optValueMarkedInlineButWasNotBoundInTheOptEnv(fullDisplayTextOfValRef (mkLocalValRef v)), m))
UnknownValInfo
let TryGetInfoForCcu env (ccu: CcuThunk) = env.globalModuleInfos.TryFind(ccu.AssemblyName)
let TryGetInfoForEntity sv n =
match sv.ModuleOrNamespaceInfos.TryFind n with
| Some info -> Some (info.Force())
| None -> None
let rec TryGetInfoForPath sv (p:_[]) i =
if i >= p.Length then Some sv else
match TryGetInfoForEntity sv p[i] with
| Some info -> TryGetInfoForPath info p (i+1)
| None -> None
let TryGetInfoForNonLocalEntityRef env (nleref: NonLocalEntityRef) =
match TryGetInfoForCcu env nleref.Ccu with
| Some ccuinfo -> TryGetInfoForPath (ccuinfo.Force()) nleref.Path 0
| None -> None
let GetInfoForNonLocalVal cenv env (vref: ValRef) =
let g = cenv.g
if vref.IsDispatchSlot then
UnknownValInfo
// REVIEW: optionally turn x-module on/off on per-module basis or
elif cenv.settings.crossAssemblyOpt () || vref.ShouldInline then
match TryGetInfoForNonLocalEntityRef env vref.nlr.EnclosingEntity.nlr with
| Some structInfo ->
match structInfo.ValInfos.TryFind vref with
| Some ninfo -> snd ninfo
| None ->
//dprintn ("\n\n*** Optimization info for value "+n+" from module "+(full_name_of_nlpath smv)+" not found, module contains values: "+String.concat ", " (NameMap.domainL structInfo.ValInfos))
//System.Diagnostics.Debug.Assert(false, sprintf "Break for module %s, value %s" (full_name_of_nlpath smv) n)
if g.compilingFSharpCore then
match structInfo.ValInfos.TryFindForFslib (g, vref) with
| true, ninfo -> snd ninfo
| _ -> UnknownValInfo
else
UnknownValInfo
| None ->
//dprintf "\n\n*** Optimization info for module %s from ccu %s not found." (full_name_of_nlpath smv) (ccu_of_nlpath smv).AssemblyName
//System.Diagnostics.Debug.Assert(false, sprintf "Break for module %s, ccu %s" (full_name_of_nlpath smv) (ccu_of_nlpath smv).AssemblyName)
UnknownValInfo
else
UnknownValInfo
let GetInfoForVal cenv env m (vref: ValRef) =
let res =
if vref.IsLocalRef then
GetInfoForLocalValue cenv env vref.binding m
else
GetInfoForNonLocalVal cenv env vref
res
let GetInfoForValWithCheck cenv env m (vref: ValRef) =
let res = GetInfoForVal cenv env m vref
check vref res |> ignore
res
let IsPartialExpr cenv env m x =
let rec isPartialExpression x =
match x with
| Expr.App (func, _, _, args, _) -> func :: args |> Seq.exists isPartialExpression
| Expr.Lambda (_, _, _, _, expr, _, _) -> expr |> isPartialExpression
| Expr.Let (TBind (_,expr,_), body, _, _) -> expr :: [body] |> List.exists isPartialExpression
| Expr.LetRec (bindings, body, _, _) -> body :: (bindings |> List.map (fun (TBind (_,expr,_)) -> expr)) |> List.exists isPartialExpression
| Expr.Sequential (expr1, expr2, _, _) -> [expr1; expr2] |> Seq.exists isPartialExpression
| Expr.Val (vr, _, _) when not vr.IsLocalRef -> ((GetInfoForVal cenv env m vr).ValExprInfo) |> IsPartialExprVal
| _ -> false
isPartialExpression x
//-------------------------------------------------------------------------
// Try to get information about values of particular types
//-------------------------------------------------------------------------
let rec stripValue = function
| ValValue(_, details) -> stripValue details (* step through ValValue "aliases" *)
| SizeValue(_, details) -> stripValue details (* step through SizeValue "aliases" *)
| vinfo -> vinfo
[<return: Struct>]
let (|StripConstValue|_|) ev =
match stripValue ev with
| ConstValue(c, _) -> ValueSome c
| _ -> ValueNone
[<return: Struct>]
let (|StripLambdaValue|_|) ev =
match stripValue ev with
| CurriedLambdaValue (id, arity, sz, expr, ty) -> ValueSome (id, arity, sz, expr, ty)
| _ -> ValueNone
let destTupleValue ev =
match stripValue ev with
| TupleValue info -> Some info
| _ -> None
let destRecdValue ev =
match stripValue ev with
| RecdValue (_tcref, info) -> Some info
| _ -> None
[<return: Struct>]
let (|StripUnionCaseValue|_|) ev =
match stripValue ev with
| UnionCaseValue (c, info) -> ValueSome (c, info)
| _ -> ValueNone
let mkBoolVal (g: TcGlobals) n = ConstValue(Const.Bool n, g.bool_ty)
let mkInt8Val (g: TcGlobals) n = ConstValue(Const.SByte n, g.sbyte_ty)
let mkInt16Val (g: TcGlobals) n = ConstValue(Const.Int16 n, g.int16_ty)
let mkInt32Val (g: TcGlobals) n = ConstValue(Const.Int32 n, g.int32_ty)
let mkInt64Val (g: TcGlobals) n = ConstValue(Const.Int64 n, g.int64_ty)
let mkUInt8Val (g: TcGlobals) n = ConstValue(Const.Byte n, g.byte_ty)
let mkUInt16Val (g: TcGlobals) n = ConstValue(Const.UInt16 n, g.uint16_ty)
let mkUInt32Val (g: TcGlobals) n = ConstValue(Const.UInt32 n, g.uint32_ty)
let mkUInt64Val (g: TcGlobals) n = ConstValue(Const.UInt64 n, g.uint64_ty)
let MakeValueInfoForValue g m vref vinfo =
#if DEBUG
let rec check x =
match x with
| ValValue (vref2, detail) -> if valRefEq g vref vref2 then error(Error(FSComp.SR.optRecursiveValValue(showL(exprValueInfoL g vinfo)), m)) else check detail
| SizeValue (_n, detail) -> check detail
| _ -> ()
check vinfo
#else
ignore g; ignore m
#endif
ValValue (vref, vinfo) |> BoundValueInfoBySize
let MakeValueInfoForRecord tcref argvals =
RecdValue (tcref, argvals) |> BoundValueInfoBySize
let MakeValueInfoForTuple argvals =
TupleValue argvals |> BoundValueInfoBySize
let MakeValueInfoForUnionCase cspec argvals =
UnionCaseValue (cspec, argvals) |> BoundValueInfoBySize
let MakeValueInfoForConst c ty = ConstValue(c, ty)
/// Helper to evaluate a unary integer operation over known values
let inline IntegerUnaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a =
match a with
| StripConstValue c ->
match c with
| Const.Bool a -> Some(mkBoolVal g (f32 (if a then 1 else 0) <> 0))
| Const.Int32 a -> Some(mkInt32Val g (f32 a))
| Const.Int64 a -> Some(mkInt64Val g (f64 a))
| Const.Int16 a -> Some(mkInt16Val g (f16 a))
| Const.SByte a -> Some(mkInt8Val g (f8 a))
| Const.Byte a -> Some(mkUInt8Val g (fu8 a))
| Const.UInt32 a -> Some(mkUInt32Val g (fu32 a))
| Const.UInt64 a -> Some(mkUInt64Val g (fu64 a))
| Const.UInt16 a -> Some(mkUInt16Val g (fu16 a))
| _ -> None
| _ -> None
/// Helper to evaluate a unary signed integer operation over known values
let inline SignedIntegerUnaryOp g f8 f16 f32 f64 a =
match a with
| StripConstValue c ->
match c with
| Const.Int32 a -> Some(mkInt32Val g (f32 a))
| Const.Int64 a -> Some(mkInt64Val g (f64 a))
| Const.Int16 a -> Some(mkInt16Val g (f16 a))
| Const.SByte a -> Some(mkInt8Val g (f8 a))
| _ -> None
| _ -> None
/// Helper to evaluate a binary integer operation over known values
let inline IntegerBinaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a b =
match a, b with
| StripConstValue c1, StripConstValue c2 ->
match c1, c2 with
| Const.Bool a, Const.Bool b -> Some(mkBoolVal g (f32 (if a then 1 else 0) (if b then 1 else 0) <> 0))
| Const.Int32 a, Const.Int32 b -> Some(mkInt32Val g (f32 a b))
| Const.Int64 a, Const.Int64 b -> Some(mkInt64Val g (f64 a b))
| Const.Int16 a, Const.Int16 b -> Some(mkInt16Val g (f16 a b))
| Const.SByte a, Const.SByte b -> Some(mkInt8Val g (f8 a b))
| Const.Byte a, Const.Byte b -> Some(mkUInt8Val g (fu8 a b))
| Const.UInt16 a, Const.UInt16 b -> Some(mkUInt16Val g (fu16 a b))
| Const.UInt32 a, Const.UInt32 b -> Some(mkUInt32Val g (fu32 a b))
| Const.UInt64 a, Const.UInt64 b -> Some(mkUInt64Val g (fu64 a b))
| _ -> None
| _ -> None
module Unchecked = Microsoft.FSharp.Core.Operators
/// Evaluate primitives based on interpretation of IL instructions.
///
/// The implementation utilizes F# arithmetic extensively, so a mistake in the implementation of F# arithmetic
/// in the core library used by the F# compiler will propagate to be a mistake in optimization.
/// The IL instructions appear in the tree through inlining.
let mkAssemblyCodeValueInfo g instrs argvals tys =
match instrs, argvals, tys with
| [ AI_add ], [t1;t2], _ ->
// Note: each use of Unchecked.(+) gets instantiated at a different type and inlined
match IntegerBinaryOp g Unchecked.(+) Unchecked.(+) Unchecked.(+) Unchecked.(+) Unchecked.(+) Unchecked.(+) Unchecked.(+) Unchecked.(+) t1 t2 with
| Some res -> res
| _ -> UnknownValue
| [ AI_sub ], [t1;t2], _ ->
// Note: each use of Unchecked.(+) gets instantiated at a different type and inlined
match IntegerBinaryOp g Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) t1 t2 with
| Some res -> res
| _ -> UnknownValue
| [ AI_mul ], [a;b], _ ->
match IntegerBinaryOp g Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) a b with
| Some res -> res
| None -> UnknownValue
| [ AI_and ], [a;b], _ ->
match IntegerBinaryOp g (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) a b with
| Some res -> res
| None -> UnknownValue
| [ AI_or ], [a;b], _ ->
match IntegerBinaryOp g (|||) (|||) (|||) (|||) (|||) (|||) (|||) (|||) a b with
| Some res -> res
| None -> UnknownValue
| [ AI_xor ], [a;b], _ ->
match IntegerBinaryOp g (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) a b with
| Some res -> res
| None -> UnknownValue
| [ AI_not ], [a], _ ->
match IntegerUnaryOp g (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) a with
| Some res -> res
| None -> UnknownValue
| [ AI_neg ], [a], _ ->
match SignedIntegerUnaryOp g (~-) (~-) (~-) (~-) a with
| Some res -> res
| None -> UnknownValue
| [ AI_ceq ], [a;b], _ ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 = a2)
| ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 = a2)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.bool_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 < a2)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 < a2)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 < a2)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 < a2)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 < a2)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.int32_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt32Val g (if a1 < a2 then 1 else 0)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.uint32_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt32Val g (if a1 < a2 then 1u else 0u)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.int16_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt16Val g (if a1 < a2 then 1s else 0s)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.uint16_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt16Val g (if a1 < a2 then 1us else 0us)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.sbyte_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkInt8Val g (if a1 < a2 then 1y else 0y)
| _ -> UnknownValue
| [ AI_clt ], [a;b], [ty] when typeEquiv g ty g.byte_ty ->
match stripValue a, stripValue b with
| ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy)
| ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy)
| ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy)
| ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy)
| ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkUInt8Val g (if a1 < a2 then 1uy else 0uy)
| _ -> UnknownValue
| [ AI_conv DT_U1 ], [a], [ty] when typeEquiv g ty g.byte_ty ->
match stripValue a with
| ConstValue(Const.SByte a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.Int16 a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.Int32 a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.Int64 a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.Byte a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.UInt16 a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.UInt32 a, _) -> mkUInt8Val g (Unchecked.byte a)
| ConstValue(Const.UInt64 a, _) -> mkUInt8Val g (Unchecked.byte a)
| _ -> UnknownValue
| [ AI_conv DT_U2 ], [a], [ty] when typeEquiv g ty g.uint16_ty ->
match stripValue a with
| ConstValue(Const.SByte a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.Int16 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.Int32 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.Int64 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.Byte a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.UInt16 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.UInt32 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| ConstValue(Const.UInt64 a, _) -> mkUInt16Val g (Unchecked.uint16 a)
| _ -> UnknownValue
| [ AI_conv DT_U4 ], [a], [ty] when typeEquiv g ty g.uint32_ty ->
match stripValue a with
| ConstValue(Const.SByte a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.Int16 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.Int32 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.Int64 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.Byte a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.UInt16 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.UInt32 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| ConstValue(Const.UInt64 a, _) -> mkUInt32Val g (Unchecked.uint32 a)
| _ -> UnknownValue
| [ AI_conv DT_U8 ], [a], [ty] when typeEquiv g ty g.uint64_ty ->
match stripValue a with
| ConstValue(Const.SByte a, _) -> mkUInt64Val g (Unchecked.uint64 a)
| ConstValue(Const.Int16 a, _) -> mkUInt64Val g (Unchecked.uint64 a)
| ConstValue(Const.Int32 a, _) -> mkUInt64Val g (Unchecked.uint64 a)