forked from ocaml-flambda/ocaml-jst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslcore.ml
1583 lines (1505 loc) · 60.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 Debuginfo.Scoped_location
type error =
Free_super_var
| Unreachable_reached
exception Error of Location.t * error
let use_dup_for_constant_arrays_bigger_than = 4
(* 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 -> Path.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, Pgenval, funcid, func, acc))
lam
!probe_handlers
(* Compile an exception/extension definition *)
let prim_fresh_oo_id =
Pccall (Primitive.simple ~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_paths env) path)
in
let name =
match path, !Clflags.for_package with
None, _ -> Ident.name ext.ext_id
| Some p, None -> Path.name p
| Some p, Some pack -> Printf.sprintf "%s.%s" pack (Path.name p)
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_alloc_mode alloc_mode =
match Alloc_mode.constrain_lower alloc_mode with
| Global -> alloc_heap
| Local -> alloc_local
let transl_exp_mode e =
let alloc_mode = Value_mode.regional_to_global_alloc e.exp_mode in
transl_alloc_mode alloc_mode
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 may_allocate_in_region lam =
let rec loop = function
| Lvar _ | Lmutvar _ | Lconst _ -> ()
| Lfunction {mode=Alloc_heap} -> ()
| Lfunction {mode=Alloc_local} -> raise Exit
| Lapply {ap_mode=Alloc_local}
| Lsend (_,_,_,_,_,Alloc_local,_) -> raise Exit
| Lprim (prim, args, _) ->
begin match Lambda.primitive_may_allocate prim with
| Some Alloc_local -> raise Exit
| None | Some Alloc_heap ->
List.iter loop args
end
| Lregion _body ->
(* [_body] might do local allocations, but not in the current region *)
()
| Lwhile {wh_cond_region=false} -> raise Exit
| Lwhile {wh_body_region=false} -> raise Exit
| Lwhile _ -> ()
| Lfor {for_region=false} -> raise Exit
| Lfor {for_from; for_to} -> loop for_from; loop for_to
| ( Lapply _ | Llet _ | Lmutlet _ | Lletrec _ | Lswitch _ | Lstringswitch _
| Lstaticraise _ | Lstaticcatch _ | Ltrywith _
| Lifthenelse _ | Lsequence _ | Lassign _ | Lsend _
| Levent _ | Lifused _) as lam ->
Lambda.iter_head_constructor loop lam
in
if not Config.stack_allocation then false
else begin
match loop lam with
| () -> false
| exception Exit -> true
end
let maybe_region lam =
let rec remove_tail_markers = 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) ->
Lsend (k, lmet, lobj, largs, Rc_normal, mode, loc)
| Lregion _ as lam -> lam
| lam ->
Lambda.shallow_map ~tail:remove_tail_markers ~non_tail:Fun.id lam
in
if not Config.stack_allocation then lam
else if may_allocate_in_region lam then Lregion lam
else remove_tail_markers lam
(* Push the default values under the functional abstractions *)
(* Also push bindings of module patterns, since this sound *)
type binding =
| Bind_value of value_binding list
| Bind_module of Ident.t * string option loc * module_presence * module_expr
let wrap_bindings bindings exp =
List.fold_left
(fun exp binds ->
{exp with exp_desc =
match binds with
| Bind_value binds -> Texp_let(Nonrecursive, binds, exp)
| Bind_module (id, name, pres, mexpr) ->
Texp_letmodule (Some id, name, pres, mexpr, exp)})
exp bindings
let rec trivial_pat pat =
match pat.pat_desc with
Tpat_var _
| Tpat_any -> true
| Tpat_construct (_, cd, [], _) ->
not cd.cstr_generalized && cd.cstr_consts = 1 && cd.cstr_nonconsts = 0
| Tpat_tuple patl ->
List.for_all trivial_pat patl
| _ -> false
let rec push_defaults loc bindings use_lhs cases partial warnings =
match cases with
[{c_lhs=pat; c_guard=None;
c_rhs={exp_desc = Texp_function { arg_label; param; cases; partial;
region; curry; warnings } }
as exp}] when bindings = [] || trivial_pat pat ->
let cases = push_defaults exp.exp_loc bindings false cases partial warnings in
[{c_lhs=pat; c_guard=None;
c_rhs={exp with exp_desc = Texp_function { arg_label; param; cases;
partial; region; curry; warnings }}}]
| [{c_lhs=pat; c_guard=None;
c_rhs={exp_attributes=[{Parsetree.attr_name = {txt="#default"};_}];
exp_desc = Texp_let
(Nonrecursive, binds,
({exp_desc = Texp_function _} as e2))}}] ->
push_defaults loc (Bind_value binds :: bindings) true
[{c_lhs=pat;c_guard=None;c_rhs=e2}]
partial warnings
| [{c_lhs=pat; c_guard=None;
c_rhs={exp_attributes=[{Parsetree.attr_name = {txt="#modulepat"};_}];
exp_desc = Texp_letmodule
(Some id, name, pres, mexpr,
({exp_desc = Texp_function _} as e2))}}] ->
push_defaults loc (Bind_module (id, name, pres, mexpr) :: bindings) true
[{c_lhs=pat;c_guard=None;c_rhs=e2}]
partial warnings
| [{c_lhs=pat; c_guard=None; c_rhs=exp} as case]
when use_lhs || trivial_pat pat && exp.exp_desc <> Texp_unreachable ->
[{case with c_rhs = wrap_bindings bindings exp}]
| {c_lhs=pat; c_rhs=exp; c_guard=_} :: _ when bindings <> [] ->
let param = Typecore.name_cases "param" cases in
let desc =
{val_type = pat.pat_type; val_kind = Val_reg;
val_attributes = []; Types.val_loc = Location.none;
val_uid = Types.Uid.internal_not_actually_unique; }
in
let env = Env.add_value param desc exp.exp_env in
let name = Ident.name param in
let exp =
let cases =
let pure_case ({c_lhs; _} as case) =
{case with c_lhs = as_computation_pattern c_lhs} in
List.map pure_case cases in
{ exp with exp_loc = loc; exp_env = env; exp_desc =
Texp_match
({exp with exp_type = pat.pat_type; exp_env = env; exp_desc =
Texp_ident
(Path.Pident param, mknoloc (Longident.Lident name),
desc, Id_value)},
cases, partial) }
in
[{c_lhs = {pat with pat_desc = Tpat_var (param, mknoloc name)};
c_guard = None; c_rhs= wrap_bindings bindings exp}]
| _ ->
cases
let push_defaults loc = push_defaults loc [] 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 ~scopes exp =
let slot =
transl_extension_path Loc_unknown
Env.initial_safe_string Predef.path_assert_failure
in
let loc = exp.exp_loc 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)
;;
let rec cut n l =
if n = 0 then ([],l) else
match l with [] -> failwith "Translcore.cut"
| a::l -> let (l1,l2) = cut (n-1) l in (a::l1,l2)
(* 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 pmode ->
let poly_mode = Option.map transl_alloc_mode pmode in
Translprim.transl_primitive loc p env ty ~poly_mode (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_alloc_mode return_mode)
end
end
let rec transl_exp ~scopes e =
transl_exp1 ~scopes ~in_new_scope:false e
(* ~in_new_scope tracks whether we just opened a new scope.
We go to some trouble to avoid introducing many new anonymous function
scopes, as `let f a b = ...` is desugared to several Pexp_fun.
*)
and transl_exp1 ~scopes ~in_new_scope 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 e else
Translobj.oo_wrap e.exp_env true (transl_exp0 ~scopes ~in_new_scope) e
and transl_exp0 ~in_new_scope ~scopes 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 body_kind = Typeopt.value_kind body.exp_env body.exp_type in
transl_let ~scopes rec_flag pat_expr_list
body_kind (event_before ~scopes body (transl_exp ~scopes body))
| Texp_function { arg_label = _; param; cases; partial;
region; curry; warnings } ->
let scopes =
if in_new_scope then scopes
else enter_anonymous_function ~scopes
in
transl_function ~scopes e param cases partial warnings region curry
| Texp_apply({ exp_desc = Texp_ident(path, _, {val_kind = Val_prim p},
Id_prim pmode);
exp_type = prim_type } as funct, oargs, pos)
when can_apply_primitive p pmode pos oargs ->
let argl, extra_args = cut p.prim_arity oargs in
let arg_exps =
List.map (function _, Arg x -> x | _ -> assert false) argl
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 prim_mode = Option.map transl_alloc_mode pmode in
let lam =
Translprim.transl_primitive_application
(of_location ~scopes e.exp_loc) p e.exp_env prim_type prim_mode
path prim_exp args 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 e = { e with exp_desc = Texp_apply(funct, oargs, pos) } in
let position = transl_apply_position pos in
let mode = transl_exp_mode e in
event_after ~scopes e
(transl_apply ~scopes ~tailcall ~inlined ~specialised ~position ~mode
lam extra_args (of_location ~scopes e.exp_loc))
end
| Texp_apply(funct, oargs, position) ->
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 e = { e with exp_desc = Texp_apply(funct, oargs, position) } in
let position = transl_apply_position position in
let mode = transl_exp_mode e in
event_after ~scopes e
(transl_apply ~scopes ~tailcall ~inlined ~specialised
~position ~mode (transl_exp ~scopes funct)
oargs (of_location ~scopes e.exp_loc))
| Texp_match(arg, pat_expr_list, partial) ->
transl_match ~scopes e arg pat_expr_list partial
| Texp_try(body, pat_expr_list) ->
let id = Typecore.name_cases "exn" pat_expr_list in
let k = Typeopt.value_kind e.exp_env e.exp_type in
Ltrywith(transl_exp ~scopes body, id,
Matching.for_trywith ~scopes k e.exp_loc (Lvar id)
(transl_cases_try ~scopes pat_expr_list),
Typeopt.value_kind e.exp_env e.exp_type)
| Texp_tuple el ->
let ll, shape = transl_list_with_shape ~scopes el in
begin try
Lconst(Const_block(0, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, Some shape,
transl_exp_mode e),
ll,
(of_location ~scopes e.exp_loc))
end
| Texp_construct(_, cstr, args) ->
let ll, shape = transl_list_with_shape ~scopes args in
if cstr.cstr_inlined <> None then begin match ll with
| [x] -> x
| _ -> assert false
end else begin match cstr.cstr_tag with
Cstr_constant n ->
Lconst(const_int n)
| Cstr_unboxed ->
(match ll with [v] -> v | _ -> assert false)
| Cstr_block n ->
begin try
Lconst(Const_block(n, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(n, Immutable, Some shape,
transl_exp_mode e),
ll,
of_location ~scopes e.exp_loc)
end
| Cstr_extension(path, is_const) ->
let lam = transl_extension_path
(of_location ~scopes e.exp_loc) e.exp_env path in
if is_const then lam
else
Lprim(Pmakeblock(0, Immutable, Some (Pgenval :: shape),
transl_exp_mode e),
lam :: ll, of_location ~scopes e.exp_loc)
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 ->
let lam = transl_exp ~scopes arg in
try
Lconst(Const_block(0, [const_int tag;
extract_constant lam]))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, None,
transl_exp_mode e),
[Lconst(const_int tag); lam],
of_location ~scopes e.exp_loc)
end
| Texp_record {fields; representation; extended_expression} ->
transl_record ~scopes e.exp_loc e.exp_env
(transl_exp_mode e)
fields representation extended_expression
| Texp_field(arg, _, lbl) ->
let targ = transl_exp ~scopes arg in
let sem =
match lbl.lbl_mut with
| Immutable -> Reads_agree
| Mutable -> Reads_vary
in
begin match lbl.lbl_repres with
Record_regular | Record_inlined _ ->
Lprim (Pfield (lbl.lbl_pos, sem), [targ],
of_location ~scopes e.exp_loc)
| Record_unboxed _ -> targ
| Record_float ->
let mode = transl_exp_mode e in
Lprim (Pfloatfield (lbl.lbl_pos, sem, mode), [targ],
of_location ~scopes e.exp_loc)
| Record_extension _ ->
Lprim (Pfield (lbl.lbl_pos + 1, sem), [targ],
of_location ~scopes e.exp_loc)
end
| Texp_setfield(arg, _, lbl, newval) ->
let mode =
let arg_mode = Value_mode.regional_to_local_alloc arg.exp_mode in
Assignment (transl_alloc_mode arg_mode)
in
let access =
match lbl.lbl_repres with
Record_regular
| Record_inlined _ ->
Psetfield(lbl.lbl_pos, maybe_pointer newval, mode)
| Record_unboxed _ -> assert false
| Record_float -> Psetfloatfield (lbl.lbl_pos, mode)
| Record_extension _ ->
Psetfield (lbl.lbl_pos + 1, maybe_pointer newval, mode)
in
Lprim(access, [transl_exp ~scopes arg; transl_exp ~scopes newval],
of_location ~scopes e.exp_loc)
| Texp_array expr_list ->
let kind = array_kind e in
let ll = transl_list ~scopes expr_list in
let mode = transl_exp_mode e 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 List.length ll <= use_dup_for_constant_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 ->
(* We cannot currently lift [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] 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. *)
let imm_array =
Lprim (Pmakearray (kind, Immutable, mode), ll,
of_location ~scopes e.exp_loc)
in
Lprim (Pduparray (kind, Mutable), [imm_array],
of_location ~scopes e.exp_loc)
| cl ->
let imm_array =
if Config.flambda2 then
Lprim (Pmakearray (kind, Immutable, mode), ll,
of_location ~scopes e.exp_loc)
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? *)
in
Lprim (Pduparray (kind, Mutable), [imm_array],
of_location ~scopes e.exp_loc)
end
with Not_constant ->
Lprim(Pmakearray (kind, Mutable, mode), ll,
of_location ~scopes e.exp_loc)
end
| Texp_ifthenelse(cond, ifso, Some ifnot) ->
Lifthenelse(transl_exp ~scopes cond,
event_before ~scopes ifso (transl_exp ~scopes ifso),
event_before ~scopes ifnot (transl_exp ~scopes ifnot),
Typeopt.value_kind e.exp_env e.exp_type)
| Texp_ifthenelse(cond, ifso, None) ->
Lifthenelse(transl_exp ~scopes cond,
event_before ~scopes ifso (transl_exp ~scopes ifso),
lambda_unit,
Pintval (* unit *))
| Texp_sequence(expr1, expr2) ->
Lsequence(transl_exp ~scopes expr1,
event_before ~scopes expr2 (transl_exp ~scopes expr2))
| Texp_while {wh_body; wh_body_region; wh_cond; wh_cond_region} ->
let cond = transl_exp ~scopes wh_cond in
let body = transl_exp ~scopes wh_body in
Lwhile {
wh_cond = if wh_cond_region then maybe_region cond else cond;
wh_cond_region;
wh_body = event_before ~scopes wh_body
(if wh_body_region then maybe_region body else body);
wh_body_region;
}
| Texp_arr_comprehension (body, blocks) ->
(*One block consists of comprehension statements connected by "and".*)
let loc = of_location ~scopes e.exp_loc in
let array_kind = Typeopt.array_kind e in
Translcomprehension.transl_arr_comprehension
body blocks ~array_kind ~scopes ~loc ~transl_exp
| Texp_list_comprehension (body, blocks) ->
let loc = of_location ~scopes e.exp_loc in
Translcomprehension.transl_list_comprehension
body blocks ~scopes ~loc ~transl_exp
| Texp_for {for_id; for_from; for_to; for_dir; for_body; for_region} ->
let body = transl_exp ~scopes for_body in
Lfor {
for_id;
for_from = transl_exp ~scopes for_from;
for_to = transl_exp ~scopes for_to;
for_dir;
for_body = event_before ~scopes for_body
(if for_region then maybe_region body else body);
for_region;
}
| Texp_send(expr, met, pos) ->
let lam =
let pos = transl_apply_position pos in
let mode = transl_exp_mode e in
let loc = of_location ~scopes e.exp_loc in
match met with
| Tmeth_val id ->
let obj = transl_exp ~scopes expr in
Lsend (Self, Lvar id, obj, [], pos, mode, loc)
| Tmeth_name nm ->
let obj = transl_exp ~scopes 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)
| 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_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, Reads_vary),
[transl_class_path loc e.exp_env cl], loc);
ap_args=[lambda_unit];
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, Pgenval, cpy,
Lapply{
ap_loc=Loc_unknown;
ap_func=Translobj.oo_prim "copy";
ap_args=[self];
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 body)
| Texp_letmodule(Some id, loc, Mp_present, modl, body) ->
let defining_expr =
let mod_scopes = enter_module_definition ~scopes id in
let lam = !transl_module ~scopes:mod_scopes Tcoerce_none None modl in
Levent (lam, {
lev_loc = of_location ~scopes loc.loc;
lev_kind = Lev_module_definition id;
lev_repr = None;
lev_env = Env.empty;
})
in
Llet(Strict, Pgenval, id, defining_expr, transl_exp ~scopes body)
| Texp_letmodule(_, _, Mp_absent, _, body) ->
transl_exp ~scopes body
| Texp_letexception(cd, body) ->
Llet(Strict, Pgenval,
cd.ext_id, transl_extension_constructor ~scopes e.exp_env None cd,
transl_exp ~scopes body)
| Texp_pack modl ->
!transl_module ~scopes Tcoerce_none None modl
| Texp_assert {exp_desc=Texp_construct(_, {cstr_name="false"}, _)} ->
assert_failed ~scopes e
| Texp_assert (cond) ->
if !Clflags.noassert
then lambda_unit
else begin
Lifthenelse
(transl_exp ~scopes cond,
lambda_unit,
assert_failed ~scopes e,
Pintval (* unit *))
end
| Texp_lazy e ->
(* when e needs no computation (constants, identifiers, ...), we
optimize the translation just as Lazy.lazy_from_val would
do *)
assert (is_heap_mode (transl_exp_mode e));
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 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 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,
[Lprim(Pmakeblock(Obj.forward_tag, Immutable, None,
alloc_heap),
[transl_exp ~scopes e],
of_location ~scopes e.exp_loc)],
of_location ~scopes e.exp_loc)
| `Identifier `Other ->
transl_exp ~scopes e
| `Other ->
(* other cases compile to a lazy block holding a function *)
let scopes = enter_lazy ~scopes in
let fn = lfunction ~kind:(Curried {nlocal=0})
~params:[Ident.create_local "param", Pgenval]
~return:Pgenval
~attr:default_function_attribute
~loc:(of_location ~scopes e.exp_loc)
~mode:alloc_heap
~region:true
~body:(maybe_region (transl_exp ~scopes 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; body; partial; warnings} ->
event_after ~scopes e
(transl_letop ~scopes e.exp_loc e.exp_env let_ ands
param body partial warnings)
| 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 e
| _ ->
let oid = Ident.create_local "open" in
let body, _ =
List.fold_left (fun (body, pos) id ->
Llet(Alias, Pgenval, id,
Lprim(mod_field pos, [Lvar oid],
of_location ~scopes od.open_loc), body),
pos + 1
) (transl_exp ~scopes e, 0)
(bound_value_identifiers od.open_bound_items)
in
Llet(pure, Pgenval, oid,
!transl_module ~scopes Tcoerce_none None od.open_expr, body)
end
| Texp_probe {name; handler=exp} ->
if !Clflags.native_code && !Clflags.probes then begin
let lam = transl_exp ~scopes 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
let body = Lambda.rename map lam in
let attr =
{ inline = Never_inline;
specialise = Always_specialise;
local = Never_local;
check = Default_check;
is_a_functor = false;
stub = false;
poll = Default_poll;
tmc_candidate = false;
} in
let funcid = Ident.create_local ("probe_handler_" ^ name) in
let handler =
let scopes = enter_value_definition ~scopes funcid in
lfunction
~kind:(Curried {nlocal=0})
~params:(List.map (fun v -> v, Pgenval) param_idents)
~return:Pgenval
~body
~loc:(of_location ~scopes exp.exp_loc)
~attr
~mode:alloc_heap
~region:true
in
let app =
{ ap_func = Lvar funcid;
ap_args = List.map (fun id -> Lvar id) arg_idents;
ap_region_close = Rc_normal;
ap_mode = alloc_heap;
ap_loc = of_location e.exp_loc ~scopes;
ap_tailcall = Default_tailcall;
ap_inlined = Never_inlined;
ap_specialised = Always_specialise;
ap_probe = Some {name};
}
in
begin match Config.flambda || Config.flambda2 with
| true ->
Llet(Strict, Pgenval, funcid, handler, Lapply app)
| false ->
(* Needs to be lifted to top level manually here,
because functions that contain other function declarations
are not inlined by Closure. For example, adding a probe into
the body of function foo will prevent foo from being inlined
into another function. *)
probe_handlers := (funcid, handler)::!probe_handlers;
Lapply app
end
end else begin
lambda_unit
end
| Texp_probe_is_enabled {name} ->
if !Clflags.native_code && !Clflags.probes then
Lprim(Pprobe_is_enabled {name}, [], of_location ~scopes e.exp_loc)
else
lambda_unit
and pure_module m =
match m.mod_desc with
Tmod_ident _ -> Alias
| Tmod_constraint (m,_,_,_) -> pure_module m
| _ -> Strict
and transl_list ~scopes expr_list =
List.map (transl_exp ~scopes) expr_list
and transl_list_with_shape ~scopes expr_list =
let transl_with_shape e =
let shape = Typeopt.value_kind e.exp_env e.exp_type in
transl_exp ~scopes e, shape
in
List.split (List.map transl_with_shape expr_list)
and transl_guard ~scopes guard rhs =
let kind = Typeopt.value_kind rhs.exp_env rhs.exp_type in
let expr = event_before ~scopes rhs (transl_exp ~scopes rhs) in
match guard with
| None -> expr
| Some cond ->
event_before ~scopes cond
(Lifthenelse(transl_exp ~scopes cond, expr, staticfail, kind))
and transl_case ~scopes {c_lhs; c_guard; c_rhs} =
c_lhs, transl_guard ~scopes c_guard c_rhs
and transl_cases ~scopes cases =
let cases =
List.filter (fun c -> c.c_rhs.exp_desc <> Texp_unreachable) cases in
List.map (transl_case ~scopes) cases
and transl_case_try ~scopes {c_lhs; c_guard; c_rhs} =
iter_exn_names Translprim.add_exception_ident c_lhs;
Misc.try_finally
(fun () -> c_lhs, transl_guard ~scopes c_guard c_rhs)
~always:(fun () ->
iter_exn_names Translprim.remove_exception_ident c_lhs)
and transl_cases_try ~scopes cases =
let cases =
List.filter (fun c -> c.c_rhs.exp_desc <> Texp_unreachable) cases in
List.map (transl_case_try ~scopes) cases
and transl_tupled_cases ~scopes patl_expr_list =
let patl_expr_list =
List.filter (fun (_,_,e) -> e.exp_desc <> Texp_unreachable)
patl_expr_list in
List.map (fun (patl, guard, expr) -> (patl, transl_guard ~scopes guard expr))
patl_expr_list
and transl_apply ~scopes
?(tailcall=Default_tailcall)
?(inlined = Default_inlined)
?(specialised = Default_specialise)
?(position=Rc_normal)
?(mode=alloc_heap)
lam sargs loc
=
let lapply funct args loc pos mode =
match funct, pos with
| Lsend((Self | Public) as k, lmet, lobj, [], _, _, _), _ ->
Lsend(k, lmet, lobj, args, pos, mode, loc)
| Lsend(Cached, lmet, lobj, ([_; _] as largs), _, _, _), _ ->
Lsend(Cached, lmet, lobj, largs @ args, pos, mode, loc)
| Lsend(k, lmet, lobj, largs, (Rc_normal | Rc_nontail), _, _),
(Rc_normal | Rc_nontail) ->
Lsend(k, lmet, lobj, largs @ args, pos, mode, loc)
| Levent(
Lsend((Self | Public) as k, lmet, lobj, [], _, _, _), _), _ ->
Lsend(k, lmet, lobj, args, pos, mode, loc)
| Levent(
Lsend(Cached, lmet, lobj, ([_; _] as largs), _, _, _), _), _ ->
Lsend(Cached, lmet, lobj, largs @ args, pos, mode, loc)
| Levent(
Lsend(k, lmet, lobj, largs, (Rc_normal | Rc_nontail), _, _), _),
(Rc_normal | Rc_nontail) ->
Lsend(k, lmet, lobj, largs @ args, pos, mode, loc)
| Lapply ({ ap_region_close = (Rc_normal | Rc_nontail) } as ap),
(Rc_normal | Rc_nontail) ->
Lapply
{ap with ap_args = ap.ap_args @ args; ap_loc = loc;
ap_region_close = pos; ap_mode = mode}
| lexp, _ ->
Lapply {
ap_loc=loc;
ap_func=lexp;
ap_args=args;
ap_region_close=pos;
ap_mode=mode;
ap_tailcall=tailcall;
ap_inlined=inlined;
ap_specialised=specialised;
ap_probe=None;
}
in
let rec build_apply lam args loc pos ap_mode = function
| Omitted { mode_closure; mode_arg; mode_ret } :: l ->
assert (pos = Rc_normal);
let defs = ref [] in
let protect name lam =
match lam with
Lvar _ | Lconst _ -> lam
| _ ->
let id = Ident.create_local name in
defs := (id, lam) :: !defs;
Lvar id
in
let lam =
if args = [] then lam else lapply lam (List.rev args) loc pos ap_mode
in
let handle = protect "func" lam in
let l =
List.map
(fun arg ->
match arg with
| Omitted _ -> arg
| Arg arg -> Arg (protect "arg" arg))
l
in