forked from EnzymeAD/Enzyme.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.jl
More file actions
7275 lines (6592 loc) · 244 KB
/
compiler.jl
File metadata and controls
7275 lines (6592 loc) · 244 KB
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
module Compiler
import ..Enzyme
import Enzyme:
Const,
Active,
Duplicated,
DuplicatedNoNeed,
BatchDuplicated,
BatchDuplicatedNoNeed,
BatchDuplicatedFunc,
Annotation,
guess_activity,
eltype,
API,
EnzymeContext,
TypeTree,
typetree,
TypeTreeTable,
only!,
shift!,
data0!,
merge!,
to_md,
to_fullmd,
TypeAnalysis,
FnTypeInfo,
Logic,
allocatedinline,
ismutabletype,
create_fresh_codeinfo,
add_edge!
using Enzyme
import EnzymeCore
import EnzymeCore: EnzymeRules, ABI, FFIABI, DefaultABI
using LLVM, GPUCompiler, Libdl
import Enzyme_jll
import GPUCompiler: CompilerJob, compile, safe_name
using LLVM.Interop
import LLVM: Target, TargetMachine
import SparseArrays
using Printf
using Preferences
bitcode_replacement() = parse(Bool, @load_preference("bitcode_replacement", "true"))
bitcode_replacement!(val) = @set_preferences!("bitcode_replacement" => string(val))
function cpu_name()
ccall(:jl_get_cpu_name, String, ())
end
function cpu_features()
return ccall(:jl_get_cpu_features, String, ())
end
# Define EnzymeTarget
# Base.@kwdef
struct EnzymeTarget{Target<:AbstractCompilerTarget} <: AbstractCompilerTarget
target::Target
end
GPUCompiler.llvm_triple(target::EnzymeTarget) = GPUCompiler.llvm_triple(target.target)
GPUCompiler.llvm_datalayout(target::EnzymeTarget) = GPUCompiler.llvm_datalayout(target.target)
GPUCompiler.llvm_machine(target::EnzymeTarget) = GPUCompiler.llvm_machine(target.target)
GPUCompiler.nest_target(::EnzymeTarget, other::AbstractCompilerTarget) = EnzymeTarget(other)
GPUCompiler.have_fma(target::EnzymeTarget, T::Type) = GPUCompiler.have_fma(target.target, T)
GPUCompiler.dwarf_version(target::EnzymeTarget) = GPUCompiler.dwarf_version(target.target)
module Runtime end
abstract type AbstractEnzymeCompilerParams <: AbstractCompilerParams end
struct EnzymeCompilerParams{Params<:AbstractCompilerParams} <: AbstractEnzymeCompilerParams
params::Params
TT::Type{<:Tuple}
mode::API.CDerivativeMode
width::Int
rt::Type{<:Annotation{T} where {T}}
run_enzyme::Bool
abiwrap::Bool
# Whether, in split mode, acessible primal argument data is modified
# between the call and the split
modifiedBetween::NTuple{N,Bool} where {N}
# Whether to also return the primal
returnPrimal::Bool
# Whether to (in aug fwd) += by one
shadowInit::Bool
expectedTapeType::Type
# Whether to use the pointer ABI, default true
ABI::Type{<:ABI}
# Whether to error if the function is written to
err_if_func_written::Bool
# Whether runtime activity is enabled
runtimeActivity::Bool
# Whether to enforce that a zero derivative propagates as a zero (and never a nan)
strongZero::Bool
end
# FIXME: Should this take something like PTXCompilerParams/CUDAParams?
struct PrimalCompilerParams <: AbstractEnzymeCompilerParams
mode::API.CDerivativeMode
end
function EnzymeCompilerParams(TT, mode, width, rt, run_enzyme, abiwrap,
modifiedBetween, returnPrimal, shadowInit,
expectedTapeType, ABI,
err_if_func_written, runtimeActivity, strongZero)
params = PrimalCompilerParams(mode)
EnzymeCompilerParams(
params,
TT,
mode,
width,
rt,
run_enzyme,
abiwrap,
modifiedBetween,
returnPrimal,
shadowInit,
expectedTapeType,
ABI,
err_if_func_written,
runtimeActivity,
strongZero
)
end
DefaultCompilerTarget(; kwargs...) =
GPUCompiler.NativeCompilerTarget(; jlruntime = true, kwargs...)
# TODO: Audit uses
function EnzymeTarget()
EnzymeTarget(DefaultCompilerTarget())
end
# TODO: We shouldn't blanket opt-out
GPUCompiler.check_invocation(job::CompilerJob{EnzymeTarget}, entry::LLVM.Function) = nothing
GPUCompiler.runtime_module(::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams}) = Runtime
# GPUCompiler.isintrinsic(::CompilerJob{EnzymeTarget}, fn::String) = true
# GPUCompiler.can_throw(::CompilerJob{EnzymeTarget}) = true
# TODO: encode debug build or not in the compiler job
# https://github.com/JuliaGPU/CUDAnative.jl/issues/368
GPUCompiler.runtime_slug(job::CompilerJob{EnzymeTarget}) = "enzyme"
# provide a specific interpreter to use.
if VERSION >= v"1.11.0-DEV.1552"
struct EnzymeCacheToken
target_type::Type
always_inline::Any
method_table::Core.MethodTable
param_type::Type
last_fwd_rule_world::Union{Nothing, Tuple}
last_rev_rule_world::Union{Nothing, Tuple}
last_ina_rule_world::Union{Nothing, Tuple}
end
@inline EnzymeCacheToken(target_type::Type, always_inline::Any, method_table::Core.MethodTable, param_type::Type, world::UInt, is_forward::Bool, is_reverse::Bool, inactive_rule::Bool) =
EnzymeCacheToken(target_type, always_inline, method_table, param_type,
is_forward ? (Enzyme.Compiler.Interpreter.get_rule_signatures(EnzymeRules.forward, Tuple{<:EnzymeCore.EnzymeRules.FwdConfig, <:Annotation, Type{<:Annotation}, Vararg{Annotation}}, world)...,) : nothing,
is_reverse ? (Enzyme.Compiler.Interpreter.get_rule_signatures(EnzymeRules.augmented_primal, Tuple{<:EnzymeCore.EnzymeRules.RevConfig, <:Annotation, Type{<:Annotation}, Vararg{Annotation}}, world)...,) : nothing,
inactive_rule ? (Enzyme.Compiler.Interpreter.get_rule_signatures(EnzymeRules.inactive, Tuple{Vararg{Any}}, world)...,) : nothing
)
GPUCompiler.ci_cache_token(job::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams}) =
EnzymeCacheToken(
typeof(job.config.target),
job.config.always_inline,
GPUCompiler.method_table(job),
typeof(job.config.params),
job.world,
job.config.params.mode == API.DEM_ForwardMode,
job.config.params.mode != API.DEM_ForwardMode,
true
)
GPUCompiler.get_interpreter(job::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams}) =
Interpreter.EnzymeInterpreter(
GPUCompiler.ci_cache_token(job),
GPUCompiler.method_table(job),
job.world,
job.config.params.mode,
true
)
else
# the codeinstance cache to use -- should only be used for the constructor
# Note that the only way the interpreter modifies codegen is either not inlining a fwd mode
# rule or not inlining a rev mode rule. Otherwise, all caches can be re-used.
const GLOBAL_FWD_CACHE = GPUCompiler.CodeCache()
const GLOBAL_REV_CACHE = GPUCompiler.CodeCache()
function enzyme_ci_cache(job::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams})
return if job.config.params.mode == API.DEM_ForwardMode
GLOBAL_FWD_CACHE
else
GLOBAL_REV_CACHE
end
end
GPUCompiler.ci_cache(job::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams}) =
enzyme_ci_cache(job)
GPUCompiler.get_interpreter(job::CompilerJob{<:Any,<:AbstractEnzymeCompilerParams}) =
Interpreter.EnzymeInterpreter(
enzyme_ci_cache(job),
GPUCompiler.method_table(job),
job.world,
job.config.params.mode,
true
)
end
import GPUCompiler: @safe_debug, @safe_info, @safe_warn, @safe_error
include("compiler/utils.jl")
include("compiler/orcv2.jl")
include("gradientutils.jl")
# Julia function to LLVM stem and arity
const cmplx_known_ops =
Dict{DataType,Tuple{Symbol,Int,Union{Nothing,Tuple{Symbol,DataType}}}}(
typeof(Base.inv) => (:cmplx_inv, 1, nothing),
typeof(Base.sqrt) => (:cmplx_sqrt, 1, nothing),
)
const known_ops = Dict{DataType,Tuple{Symbol,Int,Union{Nothing,Tuple{Symbol,DataType}}}}(
typeof(Base.cbrt) => (:cbrt, 1, nothing),
typeof(Base.rem2pi) => (:jl_rem2pi, 2, nothing),
typeof(Base.sqrt) => (:sqrt, 1, nothing),
typeof(Base.sin) => (:sin, 1, nothing),
typeof(Base.sinc) => (:sincn, 1, nothing),
typeof(Base.sincos) => (:__fd_sincos_1, 1, nothing),
typeof(Base.sincospi) => (:sincospi, 1, nothing),
typeof(Base.sinpi) => (:sinpi, 1, nothing),
typeof(Base.cospi) => (:cospi, 1, nothing),
typeof(Base.:^) => (:pow, 2, nothing),
typeof(Base.rem) => (:fmod, 2, nothing),
typeof(Base.cos) => (:cos, 1, nothing),
typeof(Base.tan) => (:tan, 1, nothing),
typeof(Base.exp) => (:exp, 1, nothing),
typeof(Base.exp2) => (:exp2, 1, nothing),
typeof(Base.expm1) => (:expm1, 1, nothing),
typeof(Base.exp10) => (:exp10, 1, nothing),
typeof(Base.FastMath.exp_fast) => (:exp, 1, nothing),
typeof(Base.log) => (:log, 1, nothing),
typeof(Base.FastMath.log) => (:log, 1, nothing),
typeof(Base.log1p) => (:log1p, 1, nothing),
typeof(Base.log2) => (:log2, 1, nothing),
typeof(Base.log10) => (:log10, 1, nothing),
typeof(Base.asin) => (:asin, 1, nothing),
typeof(Base.acos) => (:acos, 1, nothing),
typeof(Base.atan) => (:atan, 1, nothing),
typeof(Base.atan) => (:atan2, 2, nothing),
typeof(Base.sinh) => (:sinh, 1, nothing),
typeof(Base.FastMath.sinh_fast) => (:sinh, 1, nothing),
typeof(Base.cosh) => (:cosh, 1, nothing),
typeof(Base.FastMath.cosh_fast) => (:cosh, 1, nothing),
typeof(Base.tanh) => (:tanh, 1, nothing),
typeof(Base.ldexp) => (:ldexp, 2, nothing),
typeof(Base.FastMath.tanh_fast) => (:tanh, 1, nothing),
typeof(Base.fma_emulated) => (:fma, 3, nothing),
)
@inline function find_math_method(@nospecialize(func::Type), sparam_vals::Core.SimpleVector)
if func ∈ keys(known_ops)
name, arity, toinject = known_ops[func]
Tys = (Float32, Float64)
if length(sparam_vals) == arity
T = first(sparam_vals)
if (T isa Type)
T = T::Type
legal = T ∈ Tys
if legal
if name == :ldexp
if !(sparam_vals[2] <: Integer)
legal = false
end
elseif name == :pow
if sparam_vals[2] <: Integer
name = :powi
elseif sparam_vals[2] != T
legal = false
end
elseif name == :jl_rem2pi
else
if !all(==(T), sparam_vals)
legal = false
end
end
end
if legal
return name, toinject, T
end
end
end
end
if func ∈ keys(cmplx_known_ops)
name, arity, toinject = cmplx_known_ops[func]
Tys = (Complex{Float32}, Complex{Float64})
if length(sparam_vals) == arity
if name == :cmplx_in || name == :cmplx_jn || name == :cmplx_yn
if (sparam_vals[2] ∈ Tys) && sparam_vals[2].parameters[1] == sparam_vals[1]
return name, toinject, sparam_vals[2]
end
end
T = first(sparam_vals)
if (T isa Type)
T = T::Type
legal = T ∈ Tys
if legal
if !all(==(T), sparam_vals)
legal = false
end
end
if legal
return name, toinject, T
end
end
end
end
return nothing, nothing, nothing
end
include("llvm/attributes.jl")
include("typeutils/conversion.jl")
include("typeutils/jltypes.jl")
include("typeutils/lltypes.jl")
include("analyses/activity.jl")
# User facing interface
abstract type AbstractThunk{FA,RT,TT,Width} end
struct CombinedAdjointThunk{PT,FA,RT,TT,Width,ReturnPrimal} <: AbstractThunk{FA,RT,TT,Width}
adjoint::PT
end
struct ForwardModeThunk{PT,FA,RT,TT,Width,ReturnPrimal} <: AbstractThunk{FA,RT,TT,Width}
adjoint::PT
end
struct AugmentedForwardThunk{PT,FA,RT,TT,Width,ReturnPrimal,TapeType} <:
AbstractThunk{FA,RT,TT,Width}
primal::PT
end
struct AdjointThunk{PT,FA,RT,TT,Width,TapeType} <: AbstractThunk{FA,RT,TT,Width}
adjoint::PT
end
struct PrimalErrorThunk{PT,FA,RT,TT,Width,ReturnPrimal} <: AbstractThunk{FA,RT,TT,Width}
adjoint::PT
end
@inline return_type(::AbstractThunk{FA,RT}) where {FA,RT} = RT
@inline return_type(
::Type{AugmentedForwardThunk{PT,FA,RT,TT,Width,ReturnPrimal,TapeType}},
) where {PT,FA,RT,TT,Width,ReturnPrimal,TapeType} = RT
@inline EnzymeRules.tape_type(
::Type{AugmentedForwardThunk{PT,FA,RT,TT,Width,ReturnPrimal,TapeType}},
) where {PT,FA,RT,TT,Width,ReturnPrimal,TapeType} = TapeType
@inline EnzymeRules.tape_type(
::AugmentedForwardThunk{PT,FA,RT,TT,Width,ReturnPrimal,TapeType},
) where {PT,FA,RT,TT,Width,ReturnPrimal,TapeType} = TapeType
@inline EnzymeRules.tape_type(
::Type{AdjointThunk{PT,FA,RT,TT,Width,TapeType}},
) where {PT,FA,RT,TT,Width,TapeType} = TapeType
@inline EnzymeRules.tape_type(
::AdjointThunk{PT,FA,RT,TT,Width,TapeType},
) where {PT,FA,RT,TT,Width,TapeType} = TapeType
@inline fn_type(::Type{<:CombinedAdjointThunk{<:Any,FA}}) where FA = FA
@inline fn_type(::Type{<:ForwardModeThunk{<:Any,FA}}) where FA = FA
@inline fn_type(::Type{<:AugmentedForwardThunk{<:Any,FA}}) where FA = FA
@inline fn_type(::Type{<:AdjointThunk{<:Any,FA}}) where FA = FA
@inline fn_type(::Type{<:PrimalErrorThunk{<:Any,FA}}) where FA = FA
using .JIT
include("jlrt.jl")
include("errors.jl")
AnyArray(Length::Int) = NamedTuple{ntuple(Symbol, Val(Length)),NTuple{Length,Any}}
const JuliaEnzymeNameMap = Dict{String,Any}(
"enz_val_true" => Val(true),
"enz_val_false" => Val(false),
"enz_val_1" => Val(1),
"enz_any_array_1" => AnyArray(1),
"enz_any_array_2" => AnyArray(2),
"enz_any_array_3" => AnyArray(3),
"enz_runtime_exc" => EnzymeRuntimeException,
"enz_runtime_mi_exc" => EnzymeRuntimeExceptionMI,
"enz_mut_exc" => EnzymeMutabilityException,
"enz_runtime_activity_exc" => EnzymeRuntimeActivityError{Cstring, Nothing, Nothing},
"enz_runtime_activity_str_exc" => EnzymeRuntimeActivityError{String, Nothing, Nothing},
"enz_runtime_activity_mi_exc" => EnzymeRuntimeActivityError{Cstring, Core.MethodInstance, UInt},
"enz_no_type_exc" => EnzymeNoTypeError{Nothing, Nothing},
"enz_no_type_mi_exc" => EnzymeNoTypeError{Core.MethodInstance, UInt},
"enz_no_shadow_exc" => EnzymeNoShadowError,
"enz_no_derivative_exc" => EnzymeNoDerivativeError{Nothing, Nothing},
"enz_no_derivative_mi_exc" => EnzymeNoDerivativeError{Core.MethodInstance, UInt},
"enz_non_const_kwarg_exc" => NonConstantKeywordArgException,
"enz_callconv_mismatch_exc"=> CallingConventionMismatchError{Cstring},
"enz_illegal_ta_exc" => IllegalTypeAnalysisException,
"enz_illegal_first_pointer_exc" => IllegalFirstPointerException,
"enz_internal_exc" => EnzymeInternalError,
"enz_non_scalar_return_exc" => EnzymeNonScalarReturnException,
)
const JuliaGlobalNameMap = Dict{String,Any}(
"jl_type_type" => Type,
"jl_any_type" => Any,
"jl_datatype_type" => DataType,
"jl_methtable_type" => Core.MethodTable,
"jl_symbol_type" => Symbol,
"jl_simplevector_type" => Core.SimpleVector,
"jl_nothing_type" => Nothing,
"jl_tvar_type" => TypeVar,
"jl_typeofbottom_type" => Core.TypeofBottom,
"jl_bottom_type" => Union{},
"jl_unionall_type" => UnionAll,
"jl_uniontype_type" => Union,
"jl_emptytuple_type" => Tuple{},
"jl_emptytuple" => (),
"jl_int8_type" => Int8,
"jl_uint8_type" => UInt8,
"jl_int16_type" => Int16,
"jl_uint16_type" => UInt16,
"jl_int32_type" => Int32,
"jl_uint32_type" => UInt32,
"jl_int64_type" => Int64,
"jl_uint64_type" => UInt64,
"jl_float16_type" => Float16,
"jl_float32_type" => Float32,
"jl_float64_type" => Float64,
"jl_ssavalue_type" => Core.SSAValue,
"jl_slotnumber_type" => Core.SlotNumber,
"jl_argument_type" => Core.Argument,
"jl_bool_type" => Bool,
"jl_char_type" => Char,
"jl_false" => false,
"jl_true" => true,
"jl_abstractstring_type" => AbstractString,
"jl_string_type" => String,
"jl_an_empty_string" => "",
"jl_function_type" => Function,
"jl_builtin_type" => Core.Builtin,
"jl_module_type" => Core.Module,
"jl_globalref_type" => Core.GlobalRef,
"jl_ref_type" => Ref,
"jl_pointer_typename" => Ptr,
"jl_voidpointer_type" => Ptr{Nothing},
"jl_abstractarray_type" => AbstractArray,
"jl_densearray_type" => DenseArray,
"jl_array_type" => Array,
"jl_array_any_type" => Array{Any,1},
"jl_array_symbol_type" => Array{Symbol,1},
"jl_array_uint8_type" => Array{UInt8,1},
# "jl_array_uint32_type" => Array{UInt32, 1},
"jl_array_int32_type" => Array{Int32,1},
"jl_expr_type" => Expr,
"jl_method_type" => Method,
"jl_method_instance_type" => Core.MethodInstance,
"jl_code_instance_type" => Core.CodeInstance,
"jl_const_type" => Core.Const,
"jl_llvmpointer_type" => Core.LLVMPtr,
"jl_namedtuple_type" => NamedTuple,
"jl_task_type" => Task,
"jl_uint8pointer_type" => Ptr{UInt8},
"jl_nothing" => nothing,
"jl_anytuple_type" => Tuple,
"jl_vararg_type" => Core.TypeofVararg,
"jl_opaque_closure_type" => Core.OpaqueClosure,
"jl_array_uint64_type" => Array{UInt64,1},
"jl_binding_type" => Core.Binding,
)
include("absint.jl")
include("llvm/transforms.jl")
include("llvm/passes.jl")
include("typeutils/make_zero.jl")
function nested_codegen!(mode::API.CDerivativeMode, mod::LLVM.Module, @nospecialize(f), @nospecialize(tt::Type), world::UInt)
funcspec = my_methodinstance(mode == API.DEM_ForwardMode ? Forward : Reverse, typeof(f), tt, world)
nested_codegen!(mode, mod, funcspec, world)
end
function prepare_llvm(interp, mod::LLVM.Module, job, meta)
for f in functions(mod)
attributes = function_attributes(f)
push!(attributes, StringAttribute("enzymejl_world", string(job.world)))
end
for (mi, k) in meta.compiled
k_name = GPUCompiler.safe_name(k.specfunc)
if !haskey(functions(mod), k_name)
continue
end
llvmfn = functions(mod)[k_name]
RT = return_type(interp, mi)
_, _, returnRoots0 = get_return_info(RT)
returnRoots = returnRoots0 !== nothing
attributes = function_attributes(llvmfn)
push!(
attributes,
StringAttribute("enzymejl_mi", string(convert(UInt, pointer_from_objref(mi)))),
)
push!(
attributes,
StringAttribute("enzymejl_rt", string(convert(UInt, unsafe_to_pointer(RT)))),
)
if EnzymeRules.has_easy_rule_from_sig(Interpreter.simplify_kw(mi.specTypes); job.world)
push!(attributes, LLVM.StringAttribute("enzyme_LocalReadOnlyOrThrow"))
end
if startswith(LLVM.name(llvmfn), "japi3") || startswith(LLVM.name(llvmfn), "japi1")
continue
end
if is_sret_union(RT)
attr = StringAttribute("enzymejl_sret_union_bytes", string(union_alloca_type(RT)))
push!(parameter_attributes(llvmfn, 1), attr)
for u in LLVM.uses(llvmfn)
u = LLVM.user(u)
@assert isa(u, LLVM.CallInst)
LLVM.API.LLVMAddCallSiteAttribute(u, LLVM.API.LLVMAttributeIndex(1), attr)
end
end
if returnRoots
attr = StringAttribute("enzymejl_returnRoots", string(length(eltype(returnRoots0).parameters[1])))
push!(parameter_attributes(llvmfn, 2), attr)
for u in LLVM.uses(llvmfn)
u = LLVM.user(u)
@assert isa(u, LLVM.CallInst)
LLVM.API.LLVMAddCallSiteAttribute(u, LLVM.API.LLVMAttributeIndex(2), attr)
end
end
fixup_1p12_sret!(llvmfn)
end
# We explicitly save the type of alloca's before they get lowered
for f in functions(mod)
for bb in blocks(f), inst in instructions(bb)
if !isa(inst, LLVM.CallInst)
continue
end
fn = LLVM.called_operand(inst)
if !isa(fn, LLVM.Function)
continue
end
if LLVM.name(fn) == "julia.gc_alloc_obj"
legal, RT, _ = abs_typeof(inst)
if legal
metadata(inst)["enzymejl_gc_alloc_rt"] = MDNode(LLVM.Metadata[MDString(string(convert(UInt, unsafe_to_pointer(RT))))])
end
end
end
end
end
include("compiler/optimize.jl")
include("compiler/interpreter.jl")
include("compiler/validation.jl")
include("typeutils/inference.jl")
import .Interpreter: isKWCallSignature
const mod_to_edges = Dict{LLVM.Module, Vector{Any}}()
mutable struct HandlerState
primalf::Union{Nothing, LLVM.Function}
must_wrap::Bool
actualRetType::Union{Nothing, Type}
lowerConvention::Bool
loweredArgs::Set{Int}
boxedArgs::Set{Int}
removedRoots::Set{Int}
fnsToInject::Vector{Tuple{Symbol,Type}}
end
function handleCustom(state::HandlerState, custom, k_name::String, llvmfn::LLVM.Function, name::String, attrs::Vector{LLVM.Attribute} = LLVM.Attribute[], setlink::Bool = true, noinl::Bool = true)
attributes = function_attributes(llvmfn)
custom[k_name] = linkage(llvmfn)
if setlink
linkage!(llvmfn, LLVM.API.LLVMExternalLinkage)
end
for a in attrs
push!(attributes, a)
end
push!(attributes, StringAttribute("enzyme_math", name))
if noinl
push!(attributes, EnumAttribute("noinline", 0))
end
state.must_wrap |= llvmfn == state.primalf
nothing
end
function handle_compiled(state::HandlerState, edges::Vector, run_enzyme::Bool, mode::API.CDerivativeMode, world::UInt, method_table, custom::Dict{String, LLVM.API.LLVMLinkage}, mod::LLVM.Module, mi::Core.MethodInstance, k_name::String, @nospecialize(rettype::Type))::Nothing
has_custom_rule = false
specTypes = Interpreter.simplify_kw(mi.specTypes)
if mode == API.DEM_ForwardMode
has_custom_rule =
EnzymeRules.has_frule_from_sig(specTypes; world, method_table)
if has_custom_rule
@safe_debug "Found frule for" mi.specTypes
end
else
has_custom_rule =
EnzymeRules.has_rrule_from_sig(specTypes; world, method_table)
if has_custom_rule
@safe_debug "Found rrule for" mi.specTypes
end
end
if !haskey(functions(mod), k_name)
return
end
llvmfn = functions(mod)[k_name]
if llvmfn == state.primalf
state.actualRetType = rettype
end
if EnzymeRules.noalias_from_sig(mi.specTypes; world, method_table)
push!(edges, mi)
push!(return_attributes(llvmfn), EnumAttribute("noalias"))
for u in LLVM.uses(llvmfn)
c = LLVM.user(u)
if !isa(c, LLVM.CallInst)
continue
end
cf = LLVM.called_operand(c)
if cf == llvmfn
LLVM.API.LLVMAddCallSiteAttribute(
c,
LLVM.API.LLVMAttributeReturnIndex,
LLVM.EnumAttribute("noalias", 0),
)
end
end
end
func = mi.specTypes.parameters[1]
@static if VERSION < v"1.11-"
else
if func == typeof(Core.memoryref)
attributes = function_attributes(llvmfn)
push!(attributes, EnumAttribute("alwaysinline", 0))
end
end
meth = mi.def
name = meth.name
jlmod = meth.module
julia_activity_rule(llvmfn, method_table)
if has_custom_rule
handleCustom(
state,
custom,
k_name,
llvmfn,
"enzyme_custom",
LLVM.Attribute[StringAttribute("enzyme_preserve_primal", "*")],
)
return
end
sparam_vals = mi.specTypes.parameters[2:end] # mi.sparam_vals
if func == typeof(Base.eps) ||
func == typeof(Base.nextfloat) ||
func == typeof(Base.prevfloat)
if LLVM.version().major <= 15
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_inactive_inout",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("readnone"),
EnumAttribute("speculatable"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
EnumAttribute("nounwind"),
StringAttribute("enzyme_shouldrecompute"),
],
)
else
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_inactive_inout",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("memory", NoEffects.data),
EnumAttribute("speculatable"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
EnumAttribute("nounwind"),
StringAttribute("enzyme_shouldrecompute"),
],
)
end
return
end
if func == typeof(Base.to_tuple_type)
if LLVM.version().major <= 15
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_to_tuple_type",
LLVM.Attribute[
EnumAttribute("readonly"),
EnumAttribute("inaccessiblememonly", 0),
EnumAttribute("speculatable", 0),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
],
)
else
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_to_tuple_type",
LLVM.Attribute[
EnumAttribute(
"memory",
MemoryEffect(
(MRI_NoModRef << getLocationPos(ArgMem)) |
(MRI_Ref << getLocationPos(InaccessibleMem)) |
(MRI_NoModRef << getLocationPos(Other)),
).data,
),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
EnumAttribute("speculatable", 0),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
],
)
end
return
end
if func == typeof(Base.mightalias)
if LLVM.version().major <= 15
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_mightalias",
LLVM.Attribute[
EnumAttribute("readonly"),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
StringAttribute("enzyme_no_escaping_allocation"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
StringAttribute("enzyme_ta_norecur"),
],
true,
false,
)
else
handleCustom(
state,
custom,
k_name,
llvmfn,
"jl_mightalias",
LLVM.Attribute[
EnumAttribute("memory", ReadOnlyEffects.data),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
StringAttribute("enzyme_no_escaping_allocation"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
StringAttribute("enzyme_ta_norecur"),
],
true,
false,
)
end
return
end
if func == typeof(Base.Threads.threadid) || func == typeof(Base.Threads.nthreads)
name = (func == typeof(Base.Threads.threadid)) ? "jl_threadid" : "jl_nthreads"
if LLVM.version().major <= 15
handleCustom(
state,
custom,
k_name,
llvmfn,
name,
LLVM.Attribute[
EnumAttribute("readonly"),
EnumAttribute("inaccessiblememonly"),
EnumAttribute("speculatable"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
EnumAttribute("nounwind"),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
StringAttribute("enzyme_no_escaping_allocation"),
],
)
else
handleCustom(
state,
custom,
k_name,
llvmfn,
name,
LLVM.Attribute[
EnumAttribute(
"memory",
MemoryEffect(
(MRI_NoModRef << getLocationPos(ArgMem)) |
(MRI_Ref << getLocationPos(InaccessibleMem)) |
(MRI_NoModRef << getLocationPos(Other)),
).data,
),
EnumAttribute("speculatable"),
EnumAttribute("willreturn"),
EnumAttribute("nosync"),
EnumAttribute("nofree"),
EnumAttribute("nounwind"),
StringAttribute("enzyme_shouldrecompute"),
StringAttribute("enzyme_inactive"),
StringAttribute("enzyme_no_escaping_allocation"),
],
)
end
return
end
# Since this is noreturn and it can't write to any operations in the function
# in a way accessible by the function. Ideally the attributor should actually
# handle this and similar not impacting the read/write behavior of the calling
# fn, but it doesn't presently so for now we will ensure this by hand
if func == typeof(Base.Checked.throw_overflowerr_binaryop)
if LLVM.version().major <= 15
handleCustom(
state,
custom,
k_name,
llvmfn,
"enz_noop",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("readonly"),
StringAttribute("enzyme_ta_norecur"),
],
)
else
handleCustom(
state,
custom,
k_name,
llvmfn,
"enz_noop",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("memory", ReadOnlyEffects.data),
StringAttribute("enzyme_ta_norecur"),
],
)
end
return
end
if EnzymeRules.is_inactive_from_sig(specTypes; world, method_table)
push!(edges, mi)
handleCustom(
state,
custom,
k_name,
llvmfn,
"enz_noop",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("nofree"),
StringAttribute("enzyme_no_escaping_allocation"),
StringAttribute("enzyme_ta_norecur"),
],
)
return
end
if EnzymeRules.is_inactive_noinl_from_sig(specTypes; world, method_table)
push!(edges, mi)
handleCustom(
state,
custom,
k_name,
llvmfn,
"enz_noop",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("nofree"),
StringAttribute("enzyme_no_escaping_allocation"),
StringAttribute("enzyme_ta_norecur"),
],
false,
false,
)
for bb in blocks(llvmfn)
for inst in instructions(bb)
if isa(inst, LLVM.CallInst)
LLVM.API.LLVMAddCallSiteAttribute(
inst,
reinterpret(
LLVM.API.LLVMAttributeIndex,
LLVM.API.LLVMAttributeFunctionIndex,
),
StringAttribute("no_escaping_allocation"),
)
LLVM.API.LLVMAddCallSiteAttribute(
inst,
reinterpret(
LLVM.API.LLVMAttributeIndex,
LLVM.API.LLVMAttributeFunctionIndex,
),
StringAttribute("enzyme_inactive"),
)
LLVM.API.LLVMAddCallSiteAttribute(
inst,
reinterpret(
LLVM.API.LLVMAttributeIndex,
LLVM.API.LLVMAttributeFunctionIndex,
),
EnumAttribute("nofree"),
)
end
end
end
return
end
if func === typeof(Base.match)
handleCustom(
state,
custom,
k_name,
llvmfn,
"base_match",
LLVM.Attribute[
StringAttribute("enzyme_inactive"),
EnumAttribute("nofree"),
StringAttribute("enzyme_no_escaping_allocation"),
],
false,
false,
)
for bb in blocks(llvmfn)
for inst in instructions(bb)
if isa(inst, LLVM.CallInst)
LLVM.API.LLVMAddCallSiteAttribute(
inst,
reinterpret(