-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtranslcore.ml
2006 lines (1917 loc) · 80.4 KB
/
translcore.ml
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
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Translation from typed abstract syntax to lambda terms,
for the core language *)
open Misc
open Asttypes
open Primitive
open Types
open Typedtree
open Typeopt
open Lambda
open Translmode
open Debuginfo.Scoped_location
type error =
Free_super_var
| Unreachable_reached
| Bad_probe_layout of Ident.t
| Illegal_record_field of Jkind.Sort.const
| Void_sort of type_expr
exception Error of Location.t * error
let use_dup_for_constant_mutable_arrays_bigger_than = 4
(* CR layouts v7: In the places where this is used, we will want to allow
float#, but not void yet (e.g., the left of a semicolon and loop bodies). we
still default to value before checking for void, to allow for sort variables
arising in situations like
let foo () = raise Foo; ()
When this sanity check is removed, consider whether we are still defaulting
appropriately.
*)
let sort_must_not_be_void loc ty sort =
if Jkind.Sort.is_void_defaulting sort then raise (Error (loc, Void_sort ty))
let layout_exp sort e = layout e.exp_env e.exp_loc sort e.exp_type
let layout_pat sort p = layout p.pat_env p.pat_loc sort p.pat_type
(* This is `Lambda.must_be_value` for the special case of record fields, where
we allow the unboxed float layout. Its result is never actually used in that
case - it would be fine to return garbage.
*)
let record_field_kind l =
match l with
| Punboxed_float Pfloat64 -> Pboxedfloatval Pfloat64
| _ -> must_be_value l
(* CR layouts v5: This function is only used for sanity checking the
typechecker. When we allow arbitrary layouts in structures, it will have
outlived its usefulness and should be deleted. *)
let check_record_field_sort loc sort repres =
match Jkind.Sort.get_default_value sort, repres with
| Value, _ -> ()
| Float64, Record_ufloat -> ()
| Float64, (Record_boxed _ | Record_inlined _
| Record_unboxed | Record_float) ->
raise (Error (loc, Illegal_record_field Float64))
| Void, _ ->
raise (Error (loc, Illegal_record_field Void))
| (Word | Bits32 | Bits64 as const), _ ->
(* CR layouts v2.1: support unboxed ints here *)
raise (Error (loc, Illegal_record_field const))
(* Forward declaration -- to be filled in by Translmod.transl_module *)
let transl_module =
ref((fun ~scopes:_ _cc _rootpath _modl -> assert false) :
scopes:scopes -> module_coercion -> Longident.t option ->
module_expr -> lambda)
let transl_object =
ref (fun ~scopes:_ _id _s _cl -> assert false :
scopes:scopes -> Ident.t -> string list -> class_expr -> lambda)
(* Probe handlers are generated from %probe as closed functions
during transl_exp and immediately lifted to top level. *)
let probe_handlers = ref []
let clear_probe_handlers () = probe_handlers := []
let declare_probe_handlers lam =
List.fold_left (fun acc (funcid, func) ->
Llet(Strict, Lambda.layout_function, funcid, func, acc))
lam
!probe_handlers
(* Compile an exception/extension definition *)
let prim_fresh_oo_id =
Pccall
(Lambda.simple_prim_on_values ~name:"caml_fresh_oo_id" ~arity:1 ~alloc:false)
let transl_extension_constructor ~scopes env path ext =
let path =
Printtyp.wrap_printing_env env ~error:true (fun () ->
Option.map (Printtyp.rewrite_double_underscore_longidents env) path)
in
let name =
match path with
| None -> Ident.name ext.ext_id
| Some path -> Format.asprintf "%a" Pprintast.longident path
in
let loc = of_location ~scopes ext.ext_loc in
match ext.ext_kind with
Text_decl _ ->
(* Extension constructors are currently always Alloc_heap.
They could be Alloc_local, but that would require changes
to pattern typing, as patterns can close over them. *)
Lprim (Pmakeblock (Obj.object_tag, Immutable_unique, None, alloc_heap),
[Lconst (Const_base (Const_string (name, ext.ext_loc, None)));
Lprim (prim_fresh_oo_id, [Lconst (const_int 0)], loc)],
loc)
| Text_rebind(path, _lid) ->
transl_extension_path loc env path
(* To propagate structured constants *)
exception Not_constant
let extract_constant = function
Lconst sc -> sc
| _ -> raise Not_constant
let extract_float = function
Const_base(Const_float f) -> f
| _ -> fatal_error "Translcore.extract_float"
let transl_apply_position position =
match position with
| Default -> Rc_normal
| Nontail -> Rc_nontail
| Tail ->
if Config.stack_allocation then Rc_close_at_apply
else Rc_normal
let maybe_region get_layout lam =
let rec remove_tail_markers_and_exclave = function
| Lapply ({ap_region_close = Rc_close_at_apply} as ap) ->
Lapply ({ap with ap_region_close = Rc_normal})
| Lsend (k, lmet, lobj, largs, Rc_close_at_apply, mode, loc, layout) ->
Lsend (k, lmet, lobj, largs, Rc_normal, mode, loc, layout)
| Lregion _ as lam -> lam
| Lexclave lam -> lam
| lam ->
Lambda.shallow_map ~tail:remove_tail_markers_and_exclave ~non_tail:Fun.id lam
in
if not Config.stack_allocation then lam
else if may_allocate_in_region lam then Lregion (lam, get_layout ())
else remove_tail_markers_and_exclave lam
let maybe_region_layout layout lam =
maybe_region (fun () -> layout) lam
let maybe_region_exp sort exp lam =
maybe_region (fun () -> layout_exp sort exp) lam
let is_alloc_heap = function Alloc_heap -> true | Alloc_local -> false
(* In cases where we're careful to preserve syntactic arity, we disable
the arity fusion attempted by simplif.ml *)
let function_attribute_disallowing_arity_fusion =
{ default_function_attribute with may_fuse_arity = false }
(** A well-formed function parameter list is of the form
[G @ L @ [ Final_arg ]],
where the values of G and L are of the form [More_args { partial_mode }],
where [partial_mode] has locality Global in G and locality Local in L.
[curried_function_kind p] checks the well-formedness of the list and returns
the corresponding [curried_function_kind]. [nlocal] is populated as follows:
- if {v |L| > 0 v}, then {v nlocal = |L| + 1 v}.
- if {v |L| = 0 v},
* if the function returns at mode local, the final arg has mode local,
or the function itself is allocated locally, then {v nlocal = 1 v}.
* otherwise, {v nlocal = 0 v}.
*)
(* CR-someday: Now that some functions' arity won't be changed downstream of
lambda (see [may_fuse_arity = false]), we could change [nlocal] to be
more expressive. I suggest the variant:
{[
type partial_application_is_local_when =
| Applied_up_to_nth_argument_from_end of int
| Never
]}
I believe this will allow us to get rid of the complicated logic for
|L| = 0, and help clarify how clients use this type. I plan on doing
this in a follow-on PR.
*)
let curried_function_kind
: (function_curry * Mode.Alloc.l) list
-> return_mode:alloc_mode
-> alloc_mode:alloc_mode
-> curried_function_kind
=
let rec loop params ~return_mode ~alloc_mode ~running_count
~found_local_already
=
match params with
| [] -> Misc.fatal_error "Expected to find [Final_arg] at end of list"
| [ Final_arg, final_arg_mode ] ->
let nlocal =
if running_count = 0
&& is_alloc_heap return_mode
&& is_alloc_heap alloc_mode
&& is_alloc_heap (transl_alloc_mode_l final_arg_mode)
then 0
else running_count + 1
in
{ nlocal }
| (Final_arg, _) :: _ -> Misc.fatal_error "Found [Final_arg] too early"
| (More_args { partial_mode }, _) :: params ->
match transl_alloc_mode_l partial_mode with
| Alloc_heap when not found_local_already ->
loop params ~return_mode ~alloc_mode
~running_count:0 ~found_local_already
| Alloc_local ->
loop params ~return_mode ~alloc_mode
~running_count:(running_count + 1) ~found_local_already:true
| Alloc_heap ->
Misc.fatal_error
"A function argument with a Global partial_mode unexpectedly \
found following a function argument with a Local partial_mode"
in
fun params ~return_mode ~alloc_mode ->
loop params ~return_mode ~alloc_mode ~running_count:0
~found_local_already:false
(* Insertion of debugging events *)
let event_before ~scopes exp lam =
Translprim.event_before (of_location ~scopes exp.exp_loc) exp lam
let event_after ~scopes exp lam =
Translprim.event_after (of_location ~scopes exp.exp_loc) exp lam
let event_function ~scopes exp lam =
if !Clflags.debug && not !Clflags.native_code then
let repr = Some (ref 0) in
let (info, body) = lam repr in
(info,
Levent(body, {lev_loc = of_location ~scopes exp.exp_loc;
lev_kind = Lev_function;
lev_repr = repr;
lev_env = exp.exp_env}))
else
lam None
(* Assertions *)
let assert_failed loc ~scopes exp =
let slot =
transl_extension_path Loc_unknown
(Lazy.force Env.initial) Predef.path_assert_failure
in
let (fname, line, char) =
Location.get_pos_info loc.Location.loc_start
in
let loc = of_location ~scopes exp.exp_loc in
Lprim(Praise Raise_regular, [event_after ~scopes exp
(Lprim(Pmakeblock(0, Immutable, None, alloc_heap),
[slot;
Lconst(Const_block(0,
[Const_base(Const_string (fname, exp.exp_loc, None));
Const_base(Const_int line);
Const_base(Const_int char)]))], loc))], loc)
type fusable_function =
{ params : function_param list
; body : function_body
; return_sort : Jkind.sort
; return_mode : alloc_mode
; region : bool
}
(* [fuse_method_arity] is what ensures that a n-ary method is compiled as a
(n+1)-ary function, where the first parameter is self. It fuses together the
self and method parameters.
Input: fun self -> fun method_param_1 ... method_param_n -> body
Output: fun self method_param_1 ... method_param_n -> body
It detects whether the AST is a method by the presence of [Texp_poly] on the
inner function. This is only ever added to methods.
*)
let fuse_method_arity (parent : fusable_function) : fusable_function =
match parent with
| { params = [ self_param ];
return_mode = Alloc_heap;
body =
Tfunction_body { exp_desc = Texp_function method_; exp_extra; }
}
when
List.exists
(function (Texp_poly _, _, _) -> true | _ -> false)
exp_extra
->
begin match transl_alloc_mode_r method_.alloc_mode with
| Alloc_heap -> ()
| Alloc_local ->
(* If we support locally-allocated objects, we'll also have to
pass the new mode back to the caller.
*)
Misc.fatal_error "Locally-allocated method body!"
end;
let self_param =
{ self_param
with fp_curry = More_args
{ partial_mode =
Mode.Alloc.disallow_right Mode.Alloc.legacy }
}
in
{ params = self_param :: method_.params;
body = method_.body;
return_mode = transl_alloc_mode_l method_.ret_mode;
return_sort = method_.ret_sort;
region = method_.region;
}
| _ -> parent
(* Translation of expressions *)
let rec iter_exn_names f pat =
match pat.pat_desc with
| Tpat_var (id, _, _, _) -> f id
| Tpat_alias (p, id, _, _, _) ->
f id;
iter_exn_names f p
| _ -> ()
let transl_ident loc env ty path desc kind =
match desc.val_kind, kind with
| Val_prim p, Id_prim (poly_mode, poly_sort) ->
Translprim.transl_primitive loc p env ty ~poly_mode ~poly_sort (Some path)
| Val_anc _, Id_value ->
raise(Error(to_location loc, Free_super_var))
| (Val_reg | Val_self _), Id_value ->
transl_value_path loc env path
| _ -> fatal_error "Translcore.transl_exp: bad Texp_ident"
let can_apply_primitive p pmode pos args =
let is_omitted = function
| Arg _ -> false
| Omitted _ -> true
in
if List.exists (fun (_, arg) -> is_omitted arg) args then false
else begin
let nargs = List.length args in
if nargs = p.prim_arity then true
else if nargs < p.prim_arity then false
else if pos <> Typedtree.Tail then true
else begin
let return_mode = Ctype.prim_mode pmode p.prim_native_repr_res in
is_heap_mode (transl_locality_mode_l return_mode)
end
end
let rec transl_exp ~scopes sort e =
transl_exp1 ~scopes ~in_new_scope:false sort e
(* ~in_new_scope tracks whether we just opened a new scope.
When we just opened a new scope, we avoid introducing an extraneous anonymous
function scope and instead inherit the new scope. E.g., [let f x = ...] is
parsed as a let-bound Pexp_function node [let f = fun x -> ...].
We give it f's scope.
*)
and transl_exp1 ~scopes ~in_new_scope sort e =
let eval_once =
(* Whether classes for immediate objects must be cached *)
match e.exp_desc with
Texp_function _ | Texp_for _ | Texp_while _ -> false
| _ -> true
in
if eval_once then transl_exp0 ~scopes ~in_new_scope sort e else
Translobj.oo_wrap e.exp_env true (transl_exp0 ~scopes ~in_new_scope sort) e
and transl_exp0 ~in_new_scope ~scopes sort e =
match e.exp_desc with
| Texp_ident(path, _, desc, kind, _) ->
transl_ident (of_location ~scopes e.exp_loc)
e.exp_env e.exp_type path desc kind
| Texp_constant cst -> Lconst (Const_base cst)
| Texp_let(rec_flag, pat_expr_list, body) ->
let return_layout = layout_exp sort body in
transl_let ~scopes ~return_layout rec_flag pat_expr_list
(event_before ~scopes body (transl_exp ~scopes sort body))
| Texp_function { params; body; region; ret_sort; ret_mode; alloc_mode } ->
transl_function ~in_new_scope ~scopes e params body
~alloc_mode ~ret_mode ~ret_sort ~region
| Texp_apply({ exp_desc = Texp_ident(path, _, {val_kind = Val_prim p},
Id_prim (pmode, psort), _);
exp_type = prim_type; } as funct, oargs, pos, ap_mode)
when can_apply_primitive p pmode pos oargs ->
let rec cut_args prim_repr oargs =
match prim_repr, oargs with
| [], _ -> [], oargs
| _, [] -> failwith "Translcore cut_args"
| ((_, arg_repr) :: prim_repr), ((_, Arg (x, _)) :: oargs) ->
let arg_exps, extra_args = cut_args prim_repr oargs in
let arg_sort =
Jkind.Sort.of_const
(Translprim.sort_of_native_repr arg_repr ~poly_sort:psort)
in
(x, arg_sort) :: arg_exps, extra_args
| _, ((_, Omitted _) :: _) -> assert false
in
let arg_exps, extra_args = cut_args p.prim_native_repr_args oargs in
let args = transl_list ~scopes arg_exps in
let prim_exp = if extra_args = [] then Some e else None in
let position =
if extra_args = [] then transl_apply_position pos
else Rc_normal
in
let lam =
Translprim.transl_primitive_application
(of_location ~scopes e.exp_loc) p e.exp_env prim_type
~poly_mode:pmode ~poly_sort:psort
path prim_exp args (List.map fst arg_exps) position
in
if extra_args = [] then lam
else begin
let tailcall = Translattribute.get_tailcall_attribute funct in
let inlined = Translattribute.get_inlined_attribute funct in
let specialised = Translattribute.get_specialised_attribute funct in
let position = transl_apply_position pos in
let mode = transl_locality_mode_l ap_mode in
let result_layout = layout_exp sort e in
event_after ~scopes e
(transl_apply ~scopes ~tailcall ~inlined ~specialised ~position ~mode
~result_layout lam extra_args (of_location ~scopes e.exp_loc))
end
| Texp_apply(funct, oargs, position, ap_mode) ->
let tailcall = Translattribute.get_tailcall_attribute funct in
let inlined = Translattribute.get_inlined_attribute funct in
let specialised = Translattribute.get_specialised_attribute funct in
let result_layout = layout_exp sort e in
let position = transl_apply_position position in
let mode = transl_locality_mode_l ap_mode in
event_after ~scopes e
(transl_apply ~scopes ~tailcall ~inlined ~specialised ~result_layout
~position ~mode (transl_exp ~scopes Jkind.Sort.for_function funct)
oargs (of_location ~scopes e.exp_loc))
| Texp_match(arg, arg_sort, pat_expr_list, partial) ->
transl_match ~scopes ~arg_sort ~return_sort:sort e arg pat_expr_list
partial
| Texp_try(body, pat_expr_list) ->
let id = Typecore.name_cases "exn" pat_expr_list in
let return_layout = layout_exp sort e in
Ltrywith(transl_exp ~scopes sort body, id,
Matching.for_trywith ~scopes ~return_layout e.exp_loc (Lvar id)
(transl_cases_try ~scopes sort pat_expr_list),
return_layout)
| Texp_tuple (el, alloc_mode) ->
let ll, shape =
transl_list_with_shape ~scopes
(List.map (fun (_, a) -> (a, Jkind.Sort.for_tuple_element)) el)
in
begin try
Lconst(Const_block(0, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, Some shape,
transl_alloc_mode_r alloc_mode),
ll,
(of_location ~scopes e.exp_loc))
end
| Texp_construct(_, cstr, args, alloc_mode) ->
let ll, shape =
transl_list_with_shape ~scopes
(List.map (fun a -> (a, Jkind.Sort.for_constructor_arg)) args)
in
if cstr.cstr_inlined <> None then begin match ll with
| [x] -> x
| _ -> assert false
end else begin match cstr.cstr_tag, cstr.cstr_repr with
| Ordinary {runtime_tag}, _ when cstr.cstr_constant ->
(* CR layouts v5: This could have void args, but for now we've ruled
that out with the jkind check in transl_list_with_shape *)
Lconst(const_int runtime_tag)
| Ordinary _, Variant_unboxed ->
(match ll with [v] -> v | _ -> assert false)
| Ordinary {runtime_tag}, Variant_boxed _ ->
begin try
Lconst(Const_block(runtime_tag, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(runtime_tag, Immutable, Some shape,
transl_alloc_mode_r (Option.get alloc_mode)),
ll,
of_location ~scopes e.exp_loc)
end
| Extension (path, _), Variant_extensible ->
let lam = transl_extension_path
(of_location ~scopes e.exp_loc) e.exp_env path in
if cstr.cstr_constant
then
(* CR layouts v5: This could have void args, but for now we've ruled
that out with the jkind check in transl_list_with_shape. *)
lam
else
Lprim(Pmakeblock(0, Immutable, Some (Pgenval :: shape),
transl_alloc_mode_r (Option.get alloc_mode)),
lam :: ll, of_location ~scopes e.exp_loc)
| Extension _, (Variant_boxed _ | Variant_unboxed)
| Ordinary _, Variant_extensible -> assert false
end
| Texp_extension_constructor (_, path) ->
transl_extension_path (of_location ~scopes e.exp_loc) e.exp_env path
| Texp_variant(l, arg) ->
let tag = Btype.hash_variant l in
begin match arg with
None -> Lconst(const_int tag)
| Some (arg, alloc_mode) ->
let lam = transl_exp ~scopes Jkind.Sort.for_poly_variant arg in
try
Lconst(Const_block(0, [const_int tag;
extract_constant lam]))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, None,
transl_alloc_mode_r alloc_mode),
[Lconst(const_int tag); lam],
of_location ~scopes e.exp_loc)
end
| Texp_record {fields; representation; extended_expression; alloc_mode} ->
transl_record ~scopes e.exp_loc e.exp_env
(Option.map transl_alloc_mode_r alloc_mode)
fields representation extended_expression
| Texp_field(arg, id, lbl, float) ->
let targ = transl_exp ~scopes Jkind.Sort.for_record arg in
let sem =
match lbl.lbl_mut with
| Immutable -> Reads_agree
| Mutable -> Reads_vary
in
let lbl_sort = Jkind.sort_of_jkind lbl.lbl_jkind in
check_record_field_sort id.loc lbl_sort lbl.lbl_repres;
begin match lbl.lbl_repres with
Record_boxed _ | Record_inlined (_, Variant_boxed _) ->
Lprim (Pfield (lbl.lbl_pos, maybe_pointer e, sem), [targ],
of_location ~scopes e.exp_loc)
| Record_unboxed | Record_inlined (_, Variant_unboxed) -> targ
| Record_float ->
let alloc_mode =
match float with
| Boxing (alloc_mode, _) -> alloc_mode
| Non_boxing _ -> assert false
in
let mode = transl_alloc_mode_r alloc_mode in
Lprim (Pfloatfield (lbl.lbl_pos, sem, mode), [targ],
of_location ~scopes e.exp_loc)
| Record_ufloat ->
Lprim (Pufloatfield (lbl.lbl_pos, sem), [targ],
of_location ~scopes e.exp_loc)
| Record_inlined (_, Variant_extensible) ->
Lprim (Pfield (lbl.lbl_pos + 1, maybe_pointer e, sem), [targ],
of_location ~scopes e.exp_loc)
end
| Texp_setfield(arg, arg_mode, id, lbl, newval) ->
(* CR layouts v2.5: When we allow `any` in record fields and check
representability on construction, [sort_of_jkind] will be unsafe here.
Probably we should add a sort to `Texp_setfield` in the typed tree,
then. *)
let lbl_sort = Jkind.sort_of_jkind lbl.lbl_jkind in
check_record_field_sort id.loc lbl_sort lbl.lbl_repres;
let mode =
Assignment (transl_modify_mode arg_mode)
in
let access =
match lbl.lbl_repres with
Record_boxed _
| Record_inlined (_, Variant_boxed _) ->
Psetfield(lbl.lbl_pos, maybe_pointer newval, mode)
| Record_unboxed | Record_inlined (_, Variant_unboxed) ->
assert false
| Record_float -> Psetfloatfield (lbl.lbl_pos, mode)
| Record_ufloat -> Psetufloatfield (lbl.lbl_pos, mode)
| Record_inlined (_, Variant_extensible) ->
Psetfield (lbl.lbl_pos + 1, maybe_pointer newval, mode)
in
Lprim(access, [transl_exp ~scopes Jkind.Sort.for_record arg;
transl_exp ~scopes lbl_sort newval],
of_location ~scopes e.exp_loc)
| Texp_array (amut, element_sort, expr_list, alloc_mode) ->
let mode = transl_alloc_mode_r alloc_mode in
let kind = array_kind e element_sort in
let ll =
transl_list ~scopes
(List.map (fun e -> (e, element_sort)) expr_list)
in
let loc = of_location ~scopes e.exp_loc in
let makearray mutability =
Lprim (Pmakearray (kind, mutability, mode), ll, loc)
in
let duparray_to_mutable array =
Lprim (Pduparray (kind, Mutable), [array], loc)
in
let imm_array = makearray Immutable in
let lambda_arr_mut : Lambda.mutable_flag =
match (amut : Asttypes.mutable_flag) with
| Mutable -> Mutable
| Immutable -> Immutable
in
begin try
(* For native code the decision as to which compilation strategy to
use is made later. This enables the Flambda passes to lift certain
kinds of array definitions to symbols. *)
(* Deactivate constant optimization if array is small enough *)
if amut = Asttypes.Mutable &&
List.length ll <= use_dup_for_constant_mutable_arrays_bigger_than
then begin
raise Not_constant
end;
(* Pduparray only works in Alloc_heap mode *)
if is_local_mode mode then raise Not_constant;
begin match List.map extract_constant ll with
| exception Not_constant
when kind = Pfloatarray && amut = Asttypes.Mutable ->
(* We cannot currently lift mutable [Pintarray] arrays safely in
Flambda because [caml_modify] might be called upon them
(e.g. from code operating on polymorphic arrays, or functions
such as [caml_array_blit].
To avoid having different Lambda code for bytecode/Closure
vs. Flambda, we always generate [Pduparray] for mutable arrays
here, and deal with it in [Bytegen] (or in the case of Closure,
in [Cmmgen], which already has to handle [Pduparray Pmakearray
Pfloatarray] in the case where the array turned out to be
inconstant).
When not [Pfloatarray], the exception propagates to the handler
below. *)
duparray_to_mutable imm_array
| cl ->
let const =
if Config.flambda2 then
imm_array
else
match kind with
| Paddrarray | Pintarray ->
Lconst(Const_block(0, cl))
| Pfloatarray ->
Lconst(Const_float_array(List.map extract_float cl))
| Pgenarray ->
raise Not_constant (* can this really happen? *)
| Punboxedfloatarray _ | Punboxedintarray _ ->
Misc.fatal_error "Use flambda2 for unboxed arrays"
in
match amut with
| Mutable -> duparray_to_mutable const
| Immutable -> const
end
with Not_constant ->
makearray lambda_arr_mut
end
| Texp_list_comprehension comp ->
let loc = of_location ~scopes e.exp_loc in
Transl_list_comprehension.comprehension
~transl_exp ~scopes ~loc comp
| Texp_array_comprehension (_amut, elt_sort, comp) ->
(* We can ignore mutability here since we've already checked in in the
type checker; both mutable and immutable arrays are created the same
way *)
let loc = of_location ~scopes e.exp_loc in
let array_kind = Typeopt.array_kind e elt_sort in
Transl_array_comprehension.comprehension
~transl_exp ~scopes ~loc ~array_kind comp
| Texp_ifthenelse(cond, ifso, Some ifnot) ->
Lifthenelse(transl_exp ~scopes Jkind.Sort.for_predef_value cond,
event_before ~scopes ifso (transl_exp ~scopes sort ifso),
event_before ~scopes ifnot (transl_exp ~scopes sort ifnot),
layout_exp sort e)
| Texp_ifthenelse(cond, ifso, None) ->
Lifthenelse(transl_exp ~scopes Jkind.Sort.for_predef_value cond,
event_before ~scopes ifso (transl_exp ~scopes sort ifso),
lambda_unit,
Lambda.layout_unit)
| Texp_sequence(expr1, sort', expr2) ->
sort_must_not_be_void expr1.exp_loc expr1.exp_type sort';
Lsequence(transl_exp ~scopes sort' expr1,
event_before ~scopes expr2 (transl_exp ~scopes sort expr2))
| Texp_while {wh_body; wh_body_sort; wh_cond} ->
sort_must_not_be_void wh_body.exp_loc wh_body.exp_type wh_body_sort;
let cond = transl_exp ~scopes Jkind.Sort.for_predef_value wh_cond in
let body = transl_exp ~scopes wh_body_sort wh_body in
Lwhile {
wh_cond = maybe_region_layout layout_int cond;
wh_body = event_before ~scopes wh_body
(maybe_region_layout layout_unit body);
}
| Texp_for {for_id; for_from; for_to; for_dir; for_body; for_body_sort} ->
sort_must_not_be_void for_body.exp_loc for_body.exp_type for_body_sort;
let body = transl_exp ~scopes for_body_sort for_body in
Lfor {
for_id;
for_loc = of_location ~scopes e.exp_loc;
for_from = transl_exp ~scopes Jkind.Sort.for_predef_value for_from;
for_to = transl_exp ~scopes Jkind.Sort.for_predef_value for_to;
for_dir;
for_body = event_before ~scopes for_body
(maybe_region_layout layout_unit body);
}
| Texp_send(expr, met, pos) ->
let lam =
let pos = transl_apply_position pos in
let mode = Lambda.alloc_heap in
let loc = of_location ~scopes e.exp_loc in
let layout = layout_exp sort e in
match met with
| Tmeth_val id ->
let obj = transl_exp ~scopes Jkind.Sort.for_object expr in
Lsend (Self, Lvar id, obj, [], pos, mode, loc, layout)
| Tmeth_name nm ->
let obj = transl_exp ~scopes Jkind.Sort.for_object expr in
let (tag, cache) = Translobj.meth obj nm in
let kind = if cache = [] then Public else Cached in
Lsend (kind, tag, obj, cache, pos, mode, loc, layout)
| Tmeth_ancestor(meth, path_self) ->
let self = transl_value_path loc e.exp_env path_self in
Lapply {ap_loc = loc;
ap_func = Lvar meth;
ap_args = [self];
ap_result_layout = layout;
ap_mode = mode;
ap_region_close = pos;
ap_probe = None;
ap_tailcall = Default_tailcall;
ap_inlined = Default_inlined;
ap_specialised = Default_specialise}
in
event_after ~scopes e lam
| Texp_new (cl, {Location.loc=loc}, _, pos) ->
let loc = of_location ~scopes loc in
let pos = transl_apply_position pos in
Lapply{
ap_loc=loc;
ap_func=
Lprim(Pfield (0, Pointer, Reads_vary),
[transl_class_path loc e.exp_env cl], loc);
ap_args=[lambda_unit];
ap_result_layout=layout_exp sort e;
ap_region_close=pos;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=Default_inlined;
ap_specialised=Default_specialise;
ap_probe=None;
}
| Texp_instvar(path_self, path, _) ->
let loc = of_location ~scopes e.exp_loc in
let self = transl_value_path loc e.exp_env path_self in
let var = transl_value_path loc e.exp_env path in
Lprim(Pfield_computed Reads_vary, [self; var], loc)
| Texp_setinstvar(path_self, path, _, expr) ->
let loc = of_location ~scopes e.exp_loc in
let self = transl_value_path loc e.exp_env path_self in
let var = transl_value_path loc e.exp_env path in
transl_setinstvar ~scopes loc self var expr
| Texp_override(path_self, modifs) ->
let loc = of_location ~scopes e.exp_loc in
let self = transl_value_path loc e.exp_env path_self in
let cpy = Ident.create_local "copy" in
Llet(Strict, Lambda.layout_object, cpy,
Lapply{
ap_loc=Loc_unknown;
ap_func=Translobj.oo_prim "copy";
ap_args=[self];
ap_result_layout=Lambda.layout_object;
ap_region_close=Rc_normal;
ap_mode=alloc_heap;
ap_tailcall=Default_tailcall;
ap_inlined=Default_inlined;
ap_specialised=Default_specialise;
ap_probe=None;
},
List.fold_right
(fun (id, _, expr) rem ->
Lsequence(transl_setinstvar ~scopes Loc_unknown
(Lvar cpy) (Lvar id) expr, rem))
modifs
(Lvar cpy))
| Texp_letmodule(None, loc, Mp_present, modl, body) ->
let lam = !transl_module ~scopes Tcoerce_none None modl in
Lsequence(Lprim(Pignore, [lam], of_location ~scopes loc.loc),
transl_exp ~scopes sort body)
| Texp_letmodule(Some id, _loc, Mp_present, modl, body) ->
let defining_expr =
let mod_scopes = enter_module_definition ~scopes id in
!transl_module ~scopes:mod_scopes Tcoerce_none None modl
in
Llet(Strict, Lambda.layout_module, id, defining_expr,
transl_exp ~scopes sort body)
| Texp_letmodule(_, _, Mp_absent, _, body) ->
transl_exp ~scopes sort body
| Texp_letexception(cd, body) ->
Llet(Strict, Lambda.layout_block,
cd.ext_id, transl_extension_constructor ~scopes e.exp_env None cd,
transl_exp ~scopes sort body)
| Texp_pack modl ->
!transl_module ~scopes Tcoerce_none None modl
| Texp_assert ({exp_desc=Texp_construct(_, {cstr_name="false"}, _, _)}, loc) ->
assert_failed loc ~scopes e
| Texp_assert (cond, loc) ->
if !Clflags.noassert
then lambda_unit
else begin
Lifthenelse
(transl_exp ~scopes Jkind.Sort.for_predef_value cond,
lambda_unit,
assert_failed loc ~scopes e,
Lambda.layout_unit)
end
| Texp_lazy e ->
(* when e needs no computation (constants, identifiers, ...), we
optimize the translation just as Lazy.lazy_from_val would
do *)
begin match Typeopt.classify_lazy_argument e with
| `Constant_or_function ->
(* A constant expr (of type <> float if [Config.flat_float_array] is
true) gets compiled as itself. *)
transl_exp ~scopes Jkind.Sort.for_lazy_body e
| `Float_that_cannot_be_shortcut ->
(* We don't need to wrap with Popaque: this forward
block will never be shortcutted since it points to a float
and Config.flat_float_array is true. *)
Lprim(Pmakeblock(Obj.forward_tag, Immutable, None,
alloc_heap),
[transl_exp ~scopes Jkind.Sort.for_lazy_body e],
of_location ~scopes e.exp_loc)
| `Identifier `Forward_value ->
(* CR-someday mshinwell: Consider adding a new primitive
that expresses the construction of forward_tag blocks.
We need to use [Popaque] here to prevent unsound
optimisation in Flambda, but the concept of a mutable
block doesn't really match what is going on here. This
value may subsequently turn into an immediate... *)
Lprim (Popaque Lambda.layout_lazy,
[Lprim(Pmakeblock(Obj.forward_tag, Immutable, None,
alloc_heap),
[transl_exp ~scopes Jkind.Sort.for_lazy_body e],
of_location ~scopes e.exp_loc)],
of_location ~scopes e.exp_loc)
| `Identifier `Other ->
transl_exp ~scopes Jkind.Sort.for_lazy_body e
| `Other ->
(* other cases compile to a lazy block holding a function. The
typechecker enforces that e has jkind value. *)
let scopes = enter_lazy ~scopes in
let fn = lfunction ~kind:(Curried {nlocal=0})
~params:[{ name = Ident.create_local "param";
layout = Lambda.layout_unit;
attributes = Lambda.default_param_attribute;
mode = alloc_heap}]
~return:Lambda.layout_lazy_contents
~attr:function_attribute_disallowing_arity_fusion
~loc:(of_location ~scopes e.exp_loc)
~mode:alloc_heap
~ret_mode:alloc_heap
~region:true
~body:(maybe_region_layout
Lambda.layout_lazy_contents
(transl_exp ~scopes Jkind.Sort.for_lazy_body e))
in
Lprim(Pmakeblock(Config.lazy_tag, Mutable, None, alloc_heap), [fn],
of_location ~scopes e.exp_loc)
end
| Texp_object (cs, meths) ->
let cty = cs.cstr_type in
let cl = Ident.create_local "object" in
!transl_object ~scopes cl meths
{ cl_desc = Tcl_structure cs;
cl_loc = e.exp_loc;
cl_type = Cty_signature cty;
cl_env = e.exp_env;
cl_attributes = [];
}
| Texp_letop{let_; ands; param; param_sort; body; body_sort; partial} ->
event_after ~scopes e
(transl_letop ~scopes e.exp_loc e.exp_env let_ ands
param param_sort body body_sort partial)
| Texp_unreachable ->
raise (Error (e.exp_loc, Unreachable_reached))
| Texp_open (od, e) ->
let pure = pure_module od.open_expr in
(* this optimization shouldn't be needed because Simplif would
actually remove the [Llet] when it's not used.
But since [scan_used_globals] runs before Simplif, we need to
do it. *)
begin match od.open_bound_items with
| [] when pure = Alias -> transl_exp ~scopes sort e
| _ ->
let oid = Ident.create_local "open" in
let body, _ =
(* CR layouts v5: Currently we only allow values at the top of a
module. When that changes, some adjustments may be needed
here. *)
List.fold_left (fun (body, pos) id ->
Llet(Alias, Lambda.layout_module_field, id,
Lprim(mod_field pos, [Lvar oid],
of_location ~scopes od.open_loc), body),
pos + 1
) (transl_exp ~scopes sort e, 0)
(bound_value_identifiers od.open_bound_items)
in
Llet(pure, Lambda.layout_module, oid,
!transl_module ~scopes Tcoerce_none None od.open_expr, body)
end
| Texp_probe {name; handler=exp; enabled_at_init} ->
if !Clflags.native_code && !Clflags.probes then begin
let lam = transl_exp ~scopes Jkind.Sort.for_probe_body exp in
let map =
Ident.Set.fold (fun v acc -> Ident.Map.add v (Ident.rename v) acc)
(free_variables lam)
Ident.Map.empty
in
let arg_idents, param_idents = Ident.Map.bindings map |> List.split in
List.iter (fun id ->
(* CR layouts: The probe hack.
The lambda translation wants to know the jkinds of all function
parameters. Here we're building a function whose arguments are all
the free variables in a probe handler. At the moment, we just check
that they are all values.
It's really hacky to be doing this kind of jkind check this late.
The middle-end folks have plans to eliminate the need for it by
reworking the way probes are compiled. For that reason, I haven't
bothered to give a particularly good error or handle the Not_found
case from env.
(We could probably calculate the jkinds of these variables here
rather than requiring them all to be value, but that would be even
more hacky.) *)
(* CR layouts v2.5: if we get close to releasing other jkind somebody
actually might put in a probe, check with the middle-end team about
the status of fixing this. *)
let path = Path.Pident id in
match
Subst.Lazy.force_value_description (Env.find_value path e.exp_env)
with
| {val_type; _} -> begin
match
Ctype.check_type_jkind
e.exp_env (Ctype.correct_levels val_type)
(Jkind.value ~why:Probe)
with
| Ok _ -> ()
| Error _ -> raise (Error (e.exp_loc, Bad_probe_layout id))
end
| exception Not_found ->
(* Might be a module, which are all values. Otherwise raise. *)
ignore (Env.find_module_lazy path e.exp_env)
) arg_idents;
let body = Lambda.rename map lam in
let attr =
{ inline = Never_inline;
specialise = Always_specialise;
local = Never_local;
check = Default_check;
loop = Never_loop;
is_a_functor = false;
is_opaque = false;
stub = false;
poll = Default_poll;
tmc_candidate = false;
unbox_return = false;
may_fuse_arity = false;
} in
let funcid = Ident.create_local ("probe_handler_" ^ name) in
let return_layout = layout_unit (* Probe bodies have type unit. *) in
let handler =
let assume_zero_alloc = get_assume_zero_alloc ~scopes in
let scopes = enter_value_definition ~scopes ~assume_zero_alloc funcid in
lfunction
~kind:(Curried {nlocal=0})
(* CR layouts: Adjust param layouts when we allow other things in
probes. *)
~params:(List.map (fun name -> { name; layout = layout_probe_arg; attributes = Lambda.default_param_attribute; mode = alloc_heap }) param_idents)
~return:return_layout
~body:(maybe_region_layout return_layout body)
~loc:(of_location ~scopes exp.exp_loc)
~attr
~mode:alloc_heap
~ret_mode:alloc_heap
~region:true
in
let app =
{ ap_func = Lvar funcid;
ap_args = List.map (fun id -> Lvar id) arg_idents;