Debian Codegraph @

kernel/vmbytegen.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 (* Author: Benjamin Grégoire as part of the bytecode-based virtual reduction
12 machine, Oct 2004 *)
13 (* Extension: Arnaud Spiwack (support for native arithmetic), May 2005 *)
14
15 open Util
16 open Names
17 open Vmvalues
18 open Vmbytecodes
19 open Vmemitcodes
20 open Genlambda
21 open Vmlambda
22 open Constr
23 open Declarations
24 open Environ
25
26
27 (* Compilation of variables + computing free variables *)
28
29 (* The virtual machine doesn't distinguish closures and their environment *)
30
31 (* Representation of function environments : *)
32 (* [clos_t | code | envofs=2 | fv1 | fv2 | ... | fvn ] *)
33 (* ^ *)
34 (* The offset for accessing free variables is 2 (we must skip the code *)
35 (* pointer and the environment offset). *)
36 (* While compiling, free variables are stored in [in_env] in order *)
37 (* opposite to machine representation, so we can add new free variables *)
38 (* easily (i.e. without changing the position of previous variables) *)
39 (* Function arguments are on the stack in the same order as the *)
40 (* application : f arg1 ... argn *)
41 (* - the stack is then : *)
42 (* arg1 : ... argn : extra args : return addr : ... *)
43 (* In the function body [arg1] is represented by de Bruijn [n], and *)
44 (* [argn] by de Bruijn [1] *)
45
46 (* Representation of environments of mutual fixpoints : *)
47 (* [clos_t|C1|envofs1| ... |infix_t|Ci|envofsi| ... |infix_t|Cnbr|envofsnbr=2| fv1 | fv2 | .... | fvn | type] *)
48 (* ^ *)
49 (* type = [Ct1 | .... | Ctn] *)
50 (* Ci is the code pointer of the i-th body *)
51 (* At runtime, a fixpoint environment (which is the same as the fixpoint *)
52 (* itself) is a pointer to the field holding its code pointer. *)
53 (* In each fixpoint body, de Bruijn [nbr] represents the first fixpoint *)
54 (* and de Bruijn [1] the last one. *)
55 (* Access to these variables is performed by the [Koffsetclosure n] *)
56 (* instruction that shifts the environment pointer by [n] closuress. *)
57
58 (* This allows representing mutual fixpoints in just one block. *)
59 (* [Ct1 | ... | Ctn] is an array holding code pointers of the fixpoint *)
60 (* types. They are used in conversion tests (which requires that *)
61 (* fixpoint types must be convertible). Their environment is the one of *)
62 (* the last fixpoint : *)
63 (* [clos_t|C1| ... |infix_t|Ci| ... |infix_t|Cnbr|envofsnbr=2| fv1 | fv2 | .... | fvn | type] *)
64 (* ^ *)
65
66 (* Representation of mutual cofix : *)
67 (* a1 = [A_t | accumulate | [Cfx_t | fcofix1 ] ] *)
68 (* ... *)
69 (* anbr = [A_t | accumulate | [Cfx_t | fcofixnbr ] ] *)
70 (* *)
71 (* fcofix1 = [clos_t | code1 | envofs=2 | a1 |...| anbr | fv1 |...| fvn | type] *)
72 (* ^ *)
73 (* ... *)
74 (* fcofixnbr = [clos_t | codenbr | envofs=2 | a1 |...| anbr | fv1 |...| fvn | type] *)
75 (* ^ *)
76 (* The [ai] blocks are functions that accumulate their arguments: *)
77 (* ai arg1 argp ---> *)
78 (* ai' = [A_t | accumulate | envofs | [Cfx_t | fcofixi] | arg1 | ... | argp ] *)
79 (* If such a block is matched against, we have to force evaluation, *)
80 (* function [fcofixi] is then applied to [ai'] [arg1] ... [argp] *)
81 (* (note that [ai'] is a pointer to the closure, passed as argument) *)
82 (* Once evaluation is completed [ai'] is updated with the result: *)
83 (* ai' <-- *)
84 (* [A_t | accumulate | envofs | [Cfxe_t |fcofixi|result] | arg1 | ... | argp ] *)
85 (* This representation is nice because the application of the cofix is *)
86 (* evaluated only once (it simulates a lazy evaluation) *)
87 (* Moreover, when cofix don't have arguments, it is possible to create *)
88 (* a cycle, e.g.: *)
89 (* cofix one := cons 1 one *)
90 (* a1 = [A_t | accumulate | envofs | [Cfx_t|fcofix1] ] *)
91 (* fcofix1 = [clos_t | code | envofs | a1] *)
92 (* The result of evaluating [a1] is [cons_t | 1 | a1]. *)
93 (* When [a1] is updated : *)
94 (* a1 = [A_t | accumulate | envofs | [Cfxe_t | fcofix1 | [cons_t | 1 | a1]] ] *)
95 (* The cycle is created ... *)
96 (* *)
97 (* In Cfxe_t accumulators, we need to store [fcofixi] for testing *)
98 (* conversion of cofixpoints (which is intentional). *)
99
100 module Fv_elem =
101 struct
102 type t = fv_elem
103
104 let compare e1 e2 = match e1, e2 with
105 | FVnamed id1, FVnamed id2 -> Id.compare id1 id2
106 | FVnamed _, (FVrel _) -> -1
107 | FVrel _, FVnamed _ -> 1
108 | FVrel r1, FVrel r2 -> Int.compare r1 r2
109
110 end
111
112 module FvMap = Map.Make(Fv_elem)
113
114 type fv_or_univ =
115 | FUniv
116 | FV of fv_elem
117
118 (*spiwack: both type have been moved from Vmbytegen because I needed then
119 for the retroknowledge *)
120 type vm_env = {
121 size : int; (* longueur de la liste [n] *)
122 fv_rev : fv_or_univ list; (* [fvn; ... ;fv1] *)
123 fv_fwd : int FvMap.t; (* reverse mapping *)
124 fv_unv : int option; (* position of the universe instance *)
125 }
126
127
128 type comp_env = {
129 arity : int; (* arity of the current function, 0 if none *)
130 toplevel_univs : bool; (* is the toplevel instance on the stack *)
131 (* universes are always at the bottom. *)
132 nb_stack : int; (* number of variables on the stack *)
133 in_stack : int Range.t; (* position in the stack *)
134 pos_rec : instruction array; (* instruction to access mutually-defined functions *)
135 offset : int;
136 in_env : vm_env ref; (* The free variables of the expression *)
137 max_stack_size : int ref;
138 (* Maximal stack size reached during the current function body. Used to
139 reallocate the stack if we lack space. *)
140 }
141
142 type uinstance =
143 | Global (* Treat all levels as globally bound *)
144 | Bound of (int * int) (** Size of the local universe instance *)
145
146 type glob_env = {
147 env : Environ.env;
148 uinstance : uinstance;
149 mutable fun_code : instruction list; (** Code of closures *)
150 }
151
152 let push_fun env c =
153 env.fun_code <- Ksequence c :: env.fun_code
154
155 module Config = struct
156 let stack_threshold = 256 (* see byterun/rocq_memory.h *)
157 let stack_safety_margin = 15
158 end
159
160 type argument = ArgLambda of lambda | ArgInstance of UVars.Instance.t
161
162 let empty_fv = { size= 0; fv_rev = []; fv_fwd = FvMap.empty; fv_unv = None }
163 let push_fv d e = {
164 size = e.size + 1;
165 fv_rev = (FV d) :: e.fv_rev;
166 fv_fwd = FvMap.add d e.size e.fv_fwd;
167 fv_unv = e.fv_unv;
168 }
169
170 let fv r = !(r.in_env)
171
172 let empty_comp_env ()=
173 { arity = 0;
174 toplevel_univs = false;
175 nb_stack = 0;
176 in_stack = Range.empty;
177 pos_rec = [||];
178 offset = 0;
179 in_env = ref empty_fv;
180 max_stack_size = ref 0;
181 }
182
183 let set_max_stack_size (cenv : comp_env) stack_size =
184 if stack_size > cenv.max_stack_size.contents then
185 cenv.max_stack_size := stack_size
186
187 let ensure_stack_capacity (cenv : comp_env) code =
188 let used_safe =
189 cenv.max_stack_size.contents + Config.stack_safety_margin
190 in
191 if used_safe > Config.stack_threshold then
192 Kensurestackcapacity used_safe :: code
193 else code
194
195 (*i Creation functions for comp_env *)
196
197 let rec add_param n sz l =
198 if Int.equal n 0 then l else add_param (n - 1) sz (Range.cons (n+sz) l)
199
200 let comp_env_fun ?(univs=false) arity =
201 { arity;
202 toplevel_univs = univs;
203 nb_stack = arity;
204 in_stack = add_param arity 0 Range.empty;
205 pos_rec = [||];
206 offset = 0;
207 in_env = ref empty_fv;
208 max_stack_size = ref 0;
209 }
210
211
212 let comp_env_fix_type rfv =
213 { arity = 0;
214 toplevel_univs = false;
215 nb_stack = 0;
216 in_stack = Range.empty;
217 pos_rec = [||];
218 offset = 0;
219 in_env = rfv;
220 max_stack_size = ref 0;
221 }
222
223 let comp_env_fix ndef arity rfv =
224 { arity;
225 toplevel_univs = false;
226 nb_stack = arity;
227 in_stack = add_param arity 0 Range.empty;
228 pos_rec = Array.init ndef (fun i -> Koffsetclosure i);
229 offset = 0;
230 in_env = rfv;
231 max_stack_size = ref 0;
232 }
233
234 let comp_env_cofix_type ndef rfv =
235 { arity = 0;
236 toplevel_univs = false;
237 nb_stack = 0;
238 in_stack = Range.empty;
239 pos_rec = [||];
240 offset = ndef;
241 in_env = rfv;
242 max_stack_size = ref 0;
243 }
244
245 let comp_env_cofix ndef arity rfv =
246 { arity;
247 toplevel_univs = false;
248 nb_stack = arity;
249 in_stack = add_param arity 0 Range.empty;
250 pos_rec = Array.init ndef (fun i -> Kenvacc (ndef - 1 - i));
251 offset = ndef;
252 in_env = rfv;
253 max_stack_size = ref 0;
254 }
255
256 (* [push_param ] add function parameters on the stack *)
257 let push_param n sz r =
258 { r with
259 nb_stack = r.nb_stack + n;
260 in_stack = add_param n sz r.in_stack }
261
262 (* [push_local sz r] add a new variable on the stack at position [sz] *)
263 let push_local sz r =
264 { r with
265 nb_stack = r.nb_stack + 1;
266 in_stack = Range.cons (sz + 1) r.in_stack }
267
268 (*i Compilation of variables *)
269 let find_at fv env = FvMap.find fv env.fv_fwd
270
271 let pos_named id r =
272 let env = !(r.in_env) in
273 let cid = FVnamed id in
274 try Kenvacc(r.offset + find_at cid env)
275 with Not_found ->
276 let pos = env.size in
277 r.in_env := push_fv cid env;
278 Kenvacc (r.offset + pos)
279
280 let pos_rel i r sz =
281 if i <= r.nb_stack then
282 Kacc(sz - (Range.get r.in_stack (i-1)))
283 else
284 let i = i - r.nb_stack in
285 let nb_rec = Array.length r.pos_rec in
286 if i <= nb_rec then
287 r.pos_rec.(i - 1)
288 else
289 let i = i - nb_rec in
290 let db = FVrel(i) in
291 let env = !(r.in_env) in
292 try Kenvacc(r.offset + find_at db env)
293 with Not_found ->
294 let pos = env.size in
295 r.in_env := push_fv db env;
296 Kenvacc(r.offset + pos)
297
298 let pos_instance r sz =
299 (* Compilation of a universe variable can happen either at toplevel (the
300 current closure correspond to a constant and has local universes) or in a
301 local closure (which has no local universes). *)
302 if r.toplevel_univs then
303 (* Universe variables are represented by De Bruijn levels (not indices),
304 starting at 0. The shape of the stack will be [v1|..|vn|inst|arg1..argp]
305 with size = n + p + 1, and p = r.arity. So Kacc (sz - r.arity - 1) will access
306 the instance. *)
307 Kacc (sz - r.arity - 1)
308 else
309 let env = !(r.in_env) in
310 let pos = match env.fv_unv with
311 | None ->
312 let pos = env.size in
313 let env = {
314 size = pos + 1;
315 fv_rev = FUniv :: env.fv_rev;
316 fv_fwd = env.fv_fwd;
317 fv_unv = Some pos;
318 }
319 in
320 let () = r.in_env := env in
321 pos
322 | Some p -> p
323 in
324 Kenvacc (r.offset + pos)
325
326 let is_toplevel_inst env u = match env.uinstance with
327 | Global -> false
328 | Bound inst ->
329 UVars.eq_sizes inst (UVars.Instance.length u)
330 && let qs, us = UVars.Instance.to_array u in
331 Array.for_all_i (fun i q -> Sorts.Quality.equal q (Sorts.Quality.var i)) 0 qs
332 && Array.for_all_i (fun i l -> Univ.Level.equal l (Univ.Level.var i)) 0 us
333
334 let is_closed_inst env u = match env.uinstance with
335 | Global -> true
336 | Bound (qlen, ulen) ->
337 let qs, us = UVars.Instance.to_array u in
338 let check len = function
339 | None -> true
340 | Some j ->
341 let () = assert (j < len) in
342 false
343 in
344 Array.for_all (fun q -> check qlen (Sorts.Quality.var_index q)) qs
345 && Array.for_all (fun l -> check ulen (Univ.Level.var_index l)) us
346
347 let is_closed_sort env s = match env.uinstance with
348 | Global -> true
349 | Bound (qlen, ulen) ->
350 let check len = function
351 | None -> true
352 | Some j ->
353 let () = assert (j < len) in
354 false
355 in
356 match s with
357 | Sorts.Set | Sorts.Prop | Sorts.SProp -> true
358 | Sorts.Type u ->
359 Univ.Universe.for_all (fun (l, _) -> check ulen (Univ.Level.var_index l)) u
360 | Sorts.QSort (q, u) ->
361 check qlen (Sorts.QVar.var_index q)
362 && Univ.Universe.for_all (fun (l, _) -> check ulen (Univ.Level.var_index l)) u
363
364 (*i Examination of the continuation *)
365
366 (* Discard all instructions up to the next label. *)
367 (* This function is to be applied to the continuation before adding a *)
368 (* non-terminating instruction (branch, raise, return, appterm) *)
369 (* in front of it. *)
370
371 let rec discard_dead_code = function
372 | [] -> []
373 | (Klabel _ | Krestart ) :: _ as cont -> cont
374 | _ :: cont -> discard_dead_code cont
375
376 (* Return a label to the beginning of the given continuation. *)
377 (* If the sequence starts with a branch, use the target of that branch *)
378 (* as the label, thus avoiding a jump to a jump. *)
379
380 let label_code = function
381 | Klabel lbl :: _ as cont -> (lbl, cont)
382 | Kbranch lbl :: _ as cont -> (lbl, cont)
383 | cont -> let lbl = Label.create() in (lbl, Klabel lbl :: cont)
384
385 (* Return a branch to the continuation. That is, an instruction that,
386 when executed, branches to the continuation or performs what the
387 continuation performs. We avoid generating branches to returns. *)
388 (* spiwack: make_branch was only used once. Changed it back to the ZAM
389 one to match the appropriate semantics (old one avoided the
390 introduction of an unconditional branch operation, which seemed
391 appropriate for the 31-bit integers' code). As a memory, I leave
392 the former version in this comment.
393 let make_branch cont =
394 match cont with
395 | (Kreturn _ as return) :: cont' -> return, cont'
396 | Klabel lbl as b :: _ -> b, cont
397 | _ -> let b = Klabel(Label.create()) in b,b::cont
398 *)
399
400 let rec make_branch_2 lbl n cont =
401 function
402 Kreturn m :: _ -> (Kreturn (n + m), cont)
403 | Klabel _ :: c -> make_branch_2 lbl n cont c
404 | Kpop m :: c -> make_branch_2 lbl (n + m) cont c
405 | _ ->
406 match lbl with
407 Some lbl -> (Kbranch lbl, cont)
408 | None -> let lbl = Label.create() in (Kbranch lbl, Klabel lbl :: cont)
409
410 let make_branch cont =
411 match cont with
412 (Kbranch _ as branch) :: _ -> (branch, cont)
413 | (Kreturn _ as return) :: _ -> (return, cont)
414 | Klabel lbl :: _ -> make_branch_2 (Some lbl) 0 cont cont
415 | _ -> make_branch_2 (None) 0 cont cont
416
417 (* Check if we're in tailcall position *)
418
419 let rec is_tailcall = function
420 | Kreturn k :: _ -> Some k
421 | Klabel _ :: c -> is_tailcall c
422 | _ -> None
423
424 (* Extension of the continuation *)
425
426 (* Add a Kpop n instruction in front of a continuation *)
427 let rec add_pop n = function
428 | Kpop m :: cont -> add_pop (n+m) cont
429 | Kreturn m:: cont -> Kreturn (n+m) ::cont
430 | cont -> if Int.equal n 0 then cont else Kpop n :: cont
431
432 let add_grab arity lbl cont =
433 if Int.equal arity 1 then Klabel lbl :: cont
434 else Krestart :: Klabel lbl :: Kgrab (arity - 1) :: cont
435
436 let add_grabrec rec_arg arity lbl cont =
437 if Int.equal arity 1 && rec_arg < arity then
438 Klabel lbl :: Kgrabrec 0 :: Krestart :: cont
439 else
440 Krestart :: Klabel lbl :: Kgrabrec rec_arg ::
441 Krestart :: Kgrab (arity - 1) :: cont
442
443 (* continuation of a cofix *)
444
445 let cont_cofix arity =
446 (* accu = res *)
447 (* stk = ai::args::ra::... *)
448 (* ai = [At|accumulate|envofs|[Cfx_t|fcofix]|args] *)
449 [ Kpush;
450 Kpush; (* stk = res::res::ai::args::ra::... *)
451 Kacc 2;
452 Kfield 2;
453 Kfield 0;
454 Kmakeblock(2, cofix_evaluated_tag);
455 Kpush; (* stk = [Cfxe_t|fcofix|res]::res::ai::args::ra::...*)
456 Kacc 2;
457 Ksetfield 2; (* ai = [At|accumulate|envofs|[Cfxe_t|fcofix|res]|args] *)
458 (* stk = res::ai::args::ra::... *)
459 Kacc 0; (* accu = res *)
460 Kreturn (arity+2) ]
461
462 (* Compilation of constructors and inductive types *)
463
464
465 (*
466 If [tag] hits the OCaml limitation for non constant constructors, we switch to
467 another representation for the remaining constructors:
468 [last_variant_tag|tag - Obj.last_non_constant_constructor_tag|args]
469
470 We subtract Obj.last_non_constant_constructor_tag for efficiency of match interpretation.
471 *)
472
473 let nest_block tag arity cont =
474 Kconst (Const_b0 (tag - Obj.last_non_constant_constructor_tag)) ::
475 Kmakeblock(arity+1, Obj.last_non_constant_constructor_tag) :: cont
476
477 let code_makeblock cenv ~stack_size ~arity ~tag cont =
478 if tag < Obj.last_non_constant_constructor_tag then
479 Kmakeblock(arity, tag) :: cont
480 else begin
481 set_max_stack_size cenv (stack_size + 1);
482 Kpush :: nest_block tag arity cont
483 end
484
485 let compile_structured_constant cenv sc sz cont =
486 set_max_stack_size cenv sz;
487 Kconst sc :: cont
488
489 (* compiling application *)
490 let comp_args comp_expr cenv args sz cont =
491 let nargs_m_1 = Array.length args - 1 in
492 let c = ref (comp_expr cenv args.(0) (sz + nargs_m_1) cont) in
493 for i = 1 to nargs_m_1 do
494 c := comp_expr cenv args.(i) (sz + nargs_m_1 - i) (Kpush :: !c)
495 done;
496 !c
497
498 let comp_app comp_fun comp_arg cenv f args sz cont =
499 let nargs = Array.length args in
500 if Int.equal nargs 0 then comp_fun cenv f sz cont
501 else
502 match is_tailcall cont with
503 | Some k ->
504 comp_args comp_arg cenv args sz
505 (Kpush ::
506 comp_fun cenv f (sz + nargs)
507 (Kappterm(nargs, k + nargs) :: (discard_dead_code cont)))
508 | None ->
509 if nargs <= 4 then
510 comp_args comp_arg cenv args sz
511 (Kpush :: (comp_fun cenv f (sz+nargs) (Kshort_apply nargs :: cont)))
512 else
513 let lbl,cont1 = label_code cont in
514 Kpush_retaddr lbl ::
515 (comp_args comp_arg cenv args (sz + 3)
516 (Kpush :: (comp_fun cenv f (sz+3+nargs) (Kapply nargs :: cont1))))
517
518 (* Compiling free variables *)
519
520 let compile_fv_elem cenv fv sz cont =
521 match fv with
522 | FV (FVrel i) -> pos_rel i cenv sz :: cont
523 | FV (FVnamed id) -> pos_named id cenv :: cont
524 | FUniv -> pos_instance cenv sz :: cont
525
526 let rec compile_fv cenv l sz cont =
527 match l with
528 | [] -> cont
529 | [fvn] ->
530 let () = set_max_stack_size cenv (sz + 1) in
531 compile_fv_elem cenv fvn sz cont
532 | fvn :: tl ->
533 compile_fv_elem cenv fvn sz
534 (Kpush :: compile_fv cenv tl (sz + 1) cont)
535
536
537 (* Compiling constants *)
538
539 let rec get_alias env kn =
540 let cb = lookup_constant kn env in
541 let tps = cb.const_body_code in
542 match tps with
543 | None -> kn
544 | Some tps ->
545 (match tps with
546 | BCalias kn' -> get_alias env kn'
547 | _ -> kn)
548
549 (* Some primitives are not implemented natively by the VM, but calling OCaml
550 code instead *)
551 let get_caml_prim = let open CPrimitives in function
552 | Arraymake -> Some CAML_Arraymake
553 | Arrayget -> Some CAML_Arrayget
554 | Arraydefault -> Some CAML_Arraydefault
555 | Arrayset -> Some CAML_Arrayset
556 | Arraycopy -> Some CAML_Arraycopy
557 | Arraylength -> Some CAML_Arraylength
558 | Stringmake -> Some CAML_Stringmake
559 | Stringlength -> Some CAML_Stringlength
560 | Stringget -> Some CAML_Stringget
561 | Stringsub -> Some CAML_Stringsub
562 | Stringcat -> Some CAML_Stringcat
563 | Stringcompare -> Some CAML_Stringcompare
564 | _ -> None
565
566 (* sz is the size of the local stack *)
567 let rec compile_lam env cenv lam sz cont =
568 let () = set_max_stack_size cenv sz in
569 match node lam with
570 | Lrel(_, i) -> pos_rel i cenv sz :: cont
571
572 | Lint i -> compile_structured_constant cenv (Const_b0 i) sz cont
573
574 | Lval v -> compile_structured_constant cenv (Const_val (get_lval v)) sz cont
575
576 | Luint i -> compile_structured_constant cenv (Const_uint i) sz cont
577
578 | Lfloat f -> compile_structured_constant cenv (Const_float f) sz cont
579
580 | Lstring s -> compile_structured_constant cenv (Const_string s) sz cont
581
582 | Lproj (p,arg) ->
583 compile_lam env cenv arg sz (Kproj (Projection.Repr.arg p) :: cont)
584
585 | Lvar id -> pos_named id cenv :: cont
586
587 | Levar (evk, args) ->
588 if Array.is_empty args then
589 compile_structured_constant cenv (Const_evar evk) sz cont
590 else
591 (** Arguments are reversed in evar instances *)
592 let args = Array.copy args in
593 let () = Array.rev args in
594 comp_app compile_structured_constant (compile_lam env) cenv (Const_evar evk) args sz cont
595
596 | Lconst (kn,u) -> compile_constant env cenv kn u [||] sz cont
597
598 | Lind (ind,u) ->
599 if UVars.Instance.is_empty u then
600 compile_structured_constant cenv (Const_ind ind) sz cont
601 else comp_app compile_structured_constant (compile_instance env) cenv
602 (Const_ind ind) [|u|] sz cont
603
604 | Lsort s ->
605 (* We represent universes as a global constant with local universes
606 passed as the local universe instance, where we will substitute (after
607 evaluation) [Var 0,...,Var n] with values of [arg0,...,argn] *)
608 let compile_instance cenv () sz cont =
609 let () = set_max_stack_size cenv sz in
610 pos_instance cenv sz :: cont
611 in
612 if is_closed_sort env s then
613 compile_structured_constant cenv (Const_sort s) sz cont
614 else
615 comp_app compile_structured_constant compile_instance cenv
616 (Const_sort s) [|()|] sz cont
617
618 | Llet (_id,def,body) ->
619 compile_lam env cenv def sz
620 (Kpush ::
621 compile_lam env (push_local sz cenv) body (sz+1) (add_pop 1 cont))
622
623 | Lprod (dom,codom) ->
624 let cont1 =
625 Kpush :: compile_lam env cenv dom (sz+1) (Kmakeblock (2,0) :: cont) in
626 compile_lam env cenv codom sz cont1
627
628 | Llam (ids,body) ->
629 let arity = Array.length ids in
630 let r_fun = comp_env_fun arity in
631 let lbl_fun = Label.create() in
632 let cont_fun = compile_lam env r_fun body arity [Kreturn arity] in
633 let cont_fun = ensure_stack_capacity r_fun cont_fun in
634 let () = push_fun env (add_grab arity lbl_fun cont_fun) in
635 let fv = fv r_fun in
636 compile_fv cenv fv.fv_rev sz (Kclosure(lbl_fun,fv.size) :: cont)
637
638 | Lapp (f, args) ->
639 begin match node f with
640 | Lconst (kn,u) -> compile_constant env cenv kn u args sz cont
641 | _ -> comp_app (compile_lam env) (compile_lam env) cenv f args sz cont
642 end
643
644 | Lfix ((rec_args, _, init), (_decl, types, bodies)) ->
645 let ndef = Array.length types in
646 let rfv = ref empty_fv in
647 let lbl_types = Array.make ndef Label.no in
648 let lbl_bodies = Array.make ndef Label.no in
649 (* Compiling types *)
650 for i = 0 to ndef - 1 do
651 let env_type = comp_env_fix_type rfv in
652 let fcode = compile_lam env env_type types.(i) 0 [Kstop] in
653 let fcode = ensure_stack_capacity env_type fcode in
654 let lbl,fcode = label_code fcode in
655 lbl_types.(i) <- lbl;
656 push_fun env fcode
657 done;
658 (* Compiling bodies *)
659 for i = 0 to ndef - 1 do
660 let params,body = decompose_Llam bodies.(i) in
661 let arity = Array.length params in
662 let env_body = comp_env_fix ndef arity rfv in
663 let cont1 = compile_lam env env_body body arity [Kreturn arity] in
664 let cont1 = ensure_stack_capacity env_body cont1 in
665 let lbl = Label.create () in
666 lbl_bodies.(i) <- lbl;
667 let fcode = add_grabrec rec_args.(i) arity lbl cont1 in
668 push_fun env fcode
669 done;
670 let fv = !rfv in
671 compile_fv cenv fv.fv_rev sz
672 (Kclosurerec(fv.size,init,lbl_types,lbl_bodies) :: cont)
673
674
675 | Lcofix(init, (_decl,types,bodies)) ->
676 let ndef = Array.length types in
677 let lbl_types = Array.make ndef Label.no in
678 let lbl_bodies = Array.make ndef Label.no in
679 (* Compiling types *)
680 let rfv = ref empty_fv in
681 for i = 0 to ndef - 1 do
682 let env_type = comp_env_cofix_type ndef rfv in
683 let fcode = compile_lam env env_type types.(i) 0 [Kstop] in
684 let fcode = ensure_stack_capacity env_type fcode in
685 let lbl,fcode = label_code fcode in
686 lbl_types.(i) <- lbl;
687 push_fun env fcode
688 done;
689 (* Compiling bodies *)
690 for i = 0 to ndef - 1 do
691 let params,body = decompose_Llam bodies.(i) in
692 let arity = Array.length params in
693 let env_body = comp_env_cofix ndef arity rfv in
694 let lbl = Label.create () in
695 (* 4 stack slots are needed to update the cofix when forced *)
696 let () = set_max_stack_size env_body (arity + 4) in
697 let cont = compile_lam env env_body body (arity+1) (cont_cofix arity) in
698 let cont = ensure_stack_capacity env_body cont in
699 lbl_bodies.(i) <- lbl;
700 push_fun env (add_grab (arity+1) lbl cont)
701 done;
702 let fv = !rfv in
703 let () = set_max_stack_size cenv (sz + fv.size + ndef + 2) in
704 compile_fv cenv fv.fv_rev sz
705 (Kclosurecofix(fv.size, init, lbl_types, lbl_bodies) :: cont)
706
707 | Lcase ((ci, rtbl, _), t, a, branches) ->
708 let ind = ci.ci_ind in
709 let mib = lookup_mind (fst ind) env.env in
710 let oib = mib.mind_packets.(snd ind) in
711 let lbl_consts = Array.make oib.mind_nb_constant Label.no in
712 let nallblock = oib.mind_nb_args + 1 in (* +1 : accumulate *)
713 let nconst = Array.length branches.constant_branches in
714 let nblock = min nallblock (Obj.last_non_constant_constructor_tag + 1) in
715 let lbl_blocks = Array.make nblock Label.no in
716 let neblock = max 0 (nallblock - Obj.last_non_constant_constructor_tag) in
717 let lbl_eblocks = Array.make neblock Label.no in
718 let branch1, cont = make_branch cont in
719 (* Compilation of the return type *)
720 let ret_env = { cenv with max_stack_size = ref 0 } in
721 let fcode = compile_lam env ret_env t sz [Kpop sz; Kstop] in
722 let fcode = ensure_stack_capacity ret_env fcode in
723 let lbl_typ,fcode = label_code fcode in
724 let () = push_fun env fcode in
725 (* Compilation of the branches *)
726 let lbl_sw = Label.create () in
727 let sz_b,branch,is_tailcall =
728 match branch1 with
729 | Kreturn k ->
730 assert (Int.equal k sz) ;
731 sz, branch1, true
732 | Kbranch _ -> sz+3, Kjump, false
733 | _ -> assert false
734 in
735
736 let cont = discard_dead_code cont in
737 let c = ref cont in
738 (* Perform the extra match if needed (too many block constructors) *)
739 if neblock <> 0 then begin
740 let lbl_b, code_b =
741 label_code (
742 Kpush :: Kfield 0 :: Kswitch(lbl_eblocks, [||]) :: !c) in
743 lbl_blocks.(Obj.last_non_constant_constructor_tag) <- lbl_b;
744 c := code_b
745 end;
746
747 (* Compilation of constant branches *)
748 for i = nconst - 1 downto 0 do
749 let aux =
750 compile_lam env cenv branches.constant_branches.(i) sz_b (branch::!c)
751 in
752 let lbl_b,code_b = label_code aux in
753 lbl_consts.(i) <- lbl_b;
754 c := code_b
755 done;
756 (* -1 for accu branch *)
757 for i = nallblock - 2 downto 0 do
758 let tag = i + 1 in
759 let (ids, body) = branches.nonconstant_branches.(i) in
760 let arity = Array.length ids in
761 let code_b =
762 compile_lam env (push_param arity sz_b cenv)
763 body (sz_b+arity) (add_pop arity (branch::!c)) in
764 let code_b =
765 if tag < Obj.last_non_constant_constructor_tag then begin
766 set_max_stack_size cenv (sz_b + arity);
767 Kpushfields arity :: code_b
768 end
769 else begin
770 set_max_stack_size cenv (sz_b + arity + 1);
771 Kacc 0::Kpop 1::Kpushfields(arity+1)::Kpop 1::code_b
772 end
773 in
774 let lbl_b, code_b = label_code code_b in
775 if tag < Obj.last_non_constant_constructor_tag then lbl_blocks.(tag) <- lbl_b
776 else lbl_eblocks.(tag - Obj.last_non_constant_constructor_tag) <- lbl_b;
777 c := code_b
778 done;
779
780 let annot =
781 {rtbl = rtbl; tailcall = is_tailcall;
782 Vmvalues.max_stack_size = cenv.max_stack_size.contents - sz}
783 in
784
785 (* Compiling branch for accumulators *)
786 let lbl_accu, code_accu =
787 set_max_stack_size cenv (sz+3);
788 label_code(Kmakeswitchblock(lbl_typ,lbl_sw,annot,sz) :: branch :: !c)
789 in
790 lbl_blocks.(0) <- lbl_accu;
791
792 c := Klabel lbl_sw :: Kswitch(lbl_consts,lbl_blocks) :: code_accu;
793 let code_sw =
794 match branch1 with
795 (* spiwack : branch1 can't be a lbl anymore it's a Branch instead
796 | Klabel lbl -> Kpush_retaddr lbl :: !c *)
797 | Kbranch lbl -> Kpush_retaddr lbl :: !c
798 | _ -> !c
799 in
800 compile_lam env cenv a sz code_sw
801
802 | Lmakeblock (_, tag, args) ->
803 let arity = Array.length args in
804 let cont = code_makeblock cenv ~stack_size:(sz+arity-1) ~arity ~tag cont in
805 if Int.equal arity 0 then cont
806 else comp_args (compile_lam env) cenv args sz cont
807
808 | Lparray (args, def) ->
809 let v, cont = match as_value 0 args with
810 | None ->
811 (* build the ocaml array *)
812 unsafe_mkPArray args def, cont
813 | Some v ->
814 (* dump the blob as is, but copy the resulting parray afterwards so that
815 the blob is left untouched by modifications to the resulting parray *)
816 let lbl = Label.create () in
817 let v = unsafe_mkPArray_val v def in
818 (* dummy label, the array will never be an accumulator *)
819 v, Klabel lbl :: Kcamlprim (CAML_Arraycopy, lbl) :: cont
820 in
821 compile_lam env cenv v sz cont
822
823 | Lprim (kn, op, args) ->
824
825 begin match get_caml_prim op with
826 | Some cop ->
827 let arity = CPrimitives.arity op in
828 let nparams = CPrimitives.nparams op in
829 let nargs = arity - nparams in
830 assert (arity = Array.length args && arity <= 4 && nargs >= 1);
831 let (jump, cont) = make_branch cont in
832 let lbl_default = Label.create () in
833 let default =
834 let cont = [Kshort_apply arity; jump] in
835 let cont = Kpush :: compile_get_global env cenv kn (sz + arity) cont in
836 let cont =
837 if Int.equal nparams 0 then cont
838 else
839 let params = Array.sub args 0 nparams in
840 Kpush :: comp_args (compile_lam env) cenv params (sz + nargs) cont in
841 Klabel lbl_default :: cont in
842 let () = push_fun env default in
843 let cont = Kcamlprim (cop, lbl_default) :: cont in
844 comp_args (compile_lam env) cenv (Array.sub args nparams nargs) sz cont
845 | None ->
846 comp_args (compile_lam env) cenv args sz (Kprim(op, kn)::cont)
847 end
848
849 and compile_get_global env cenv (kn,u) sz cont =
850 let () = set_max_stack_size cenv sz in
851 if UVars.Instance.is_empty u then
852 Kgetglobal kn :: cont
853 else
854 comp_app (fun _ _ _ cont -> Kgetglobal kn :: cont)
855 (compile_instance env) cenv () [|u|] sz cont
856
857 and compile_instance env cenv u sz cont =
858 let () = set_max_stack_size cenv sz in
859 if is_toplevel_inst env u then
860 (* Optimization: do not reallocate the same instance *)
861 pos_instance cenv sz :: cont
862 else if is_closed_inst env u then
863 (* Optimization: allocate closed instances globally *)
864 compile_structured_constant cenv (Const_univ_instance u) sz cont
865 else
866 pos_instance cenv sz :: Ksubstinstance u :: cont
867
868 and compile_constant env cenv kn u args sz cont =
869 let () = set_max_stack_size cenv sz in
870 if UVars.Instance.is_empty u then
871 (* normal compilation *)
872 comp_app (fun _ _ sz cont ->
873 compile_get_global env cenv (kn,u) sz cont)
874 (compile_lam env) cenv () args sz cont
875 else
876 let compile_arg cenv constr_or_uni sz cont =
877 match constr_or_uni with
878 | ArgLambda t -> compile_lam env cenv t sz cont
879 | ArgInstance u -> compile_instance env cenv u sz cont
880 in
881 let all =
882 Array.init (Array.length args + 1)
883 (fun i -> if Int.equal i 0 then ArgInstance u else ArgLambda args.(i - 1))
884 in
885 comp_app (fun _ _ _ cont -> Kgetglobal kn :: cont)
886 compile_arg cenv () all sz cont
887
888 let rocq_subst_instance : UVars.Instance.t -> UVars.Instance.t -> UVars.Instance.t =
889 UVars.subst_instance_instance
890
891 let () = Callback.register "rocq_subst_instance" rocq_subst_instance
892
893 let is_univ_copy (maxq,maxu) u =
894 let qs,us = UVars.Instance.to_array u in
895 let check_array max var_index a =
896 Array.length a = max
897 && Array.for_all_i (fun i x -> Option.equal Int.equal (var_index x) (Some i)) 0 a
898 in
899 check_array maxq Sorts.Quality.var_index qs
900 && check_array maxu Univ.Level.var_index us
901
902 let dump_bytecode_flag, dump_bytecode = CDebug.create_full ~name:"vmbytecode" ()
903
904 let dump_bytecodes init code fvs =
905 dump_bytecode Pp.(fun () ->
906 str "code =" ++ fnl () ++
907 pp_bytecodes init ++ fnl () ++
908 pp_bytecodes code ++ fnl () ++
909 str "fv = " ++
910 prlist_with_sep (fun () -> str "; ") pp_fv_elem fvs ++
911 fnl ())
912
913 let skip_suffix l =
914 let rec aux = function
915 | [] -> None
916 | b :: l ->
917 match aux l with
918 | None -> if b then None else Some [b]
919 | Some l -> Some (b :: l)
920 in
921 match aux l with None -> [] | Some l -> l
922
923 let compile ~uinstance env sigma c =
924 Label.reset_label_counter ();
925 let lam = lambda_of_constr env sigma c in
926 let params, body = decompose_Llam lam in
927 let arity = Array.length params in
928 let mask =
929 let rels = Genlambda.free_rels body in
930 let init i = Int.Set.mem (arity - i) rels in
931 let mask = List.init arity init in
932 Array.of_list @@ skip_suffix mask
933 in
934 let cont = [Kstop] in
935 let uclosed = match uinstance with
936 | Global -> true
937 | Bound univ -> UVars.eq_sizes (0, 0) univ
938 in
939 let cenv, init_code, fun_code =
940 if uclosed then
941 let cenv = empty_comp_env () in
942 let env = { env; fun_code = []; uinstance } in
943 let cont = compile_lam env cenv lam 0 cont in
944 let cont = ensure_stack_capacity cenv cont in
945 cenv, cont, env.fun_code
946 else
947 (* We are going to generate a lambda, but merge the universe closure
948 * with the function closure if it exists.
949 *)
950 let cenv = empty_comp_env () in
951 let full_arity = arity + 1 in
952 let r_fun = comp_env_fun ~univs:true arity in
953 let lbl_fun = Label.create () in
954 let env = { env; fun_code = []; uinstance } in
955 let cont_fun = compile_lam env r_fun body full_arity [Kreturn full_arity] in
956 let cont_fun = ensure_stack_capacity r_fun cont_fun in
957 let () = push_fun env (add_grab full_arity lbl_fun cont_fun) in
958 let fv = fv r_fun in
959 let init_code = compile_fv cenv fv.fv_rev 0 (Kclosure(lbl_fun,fv.size) :: cont) in
960 let init_code = ensure_stack_capacity cenv init_code in
961 cenv, init_code, env.fun_code
962 in
963 let map_fv = function
964 | FV fv -> fv
965 | FUniv -> assert false
966 in
967 let fv = List.rev_map map_fv (!(cenv.in_env).fv_rev) in
968 dump_bytecodes init_code fun_code fv;
969 let res = init_code @ fun_code in
970 let code, patch = to_memory (Array.of_list fv) res in
971 mask, code, patch
972
973 let warn_compile_error =
974 CWarnings.create ~name:"bytecode-compiler-failed-compilation" ~category:CWarnings.CoreCategories.bytecode_compiler
975 Vmerrors.pr_error
976
977 let compile ~fail_on_error ~uinstance env sigma c =
978 try NewProfile.profile "vm_compile" (fun () -> Some (compile ~uinstance env sigma c)) ()
979 with Vmerrors.CompileError msg as exn ->
980 let exn = Exninfo.capture exn in
981 if fail_on_error then
982 Exninfo.iraise exn
983 else begin
984 warn_compile_error msg;
985 None
986 end
987
988 let compile_constant_body ~fail_on_error env univs = function
989 | Undef _ | OpaqueDef _ -> Some BCconstant
990 | Primitive _ | Symbol _ -> None
991 | Def body ->
992 let instance_size = UVars.AbstractContext.size (Declareops.universes_context univs) in
993 let alias =
994 match kind body with
995 | Const (kn',u) when is_univ_copy instance_size u ->
996 (* we use the canonical name of the constant*)
997 let con = Constant.make1 (Constant.canonical kn') in
998 let kn = get_alias env con in
999 let cb = lookup_constant kn env in
1000 begin match cb.const_body with
1001 | Primitive _ -> None
1002 | _ -> Some kn
1003 end
1004 | _ -> None in
1005 match alias with
1006 | Some kn -> Some (BCalias kn)
1007 | _ ->
1008 let uinstance = Bound instance_size in
1009 let res = compile ~fail_on_error ~uinstance env (empty_evars env) body in
1010 Option.map (fun (mask, code, patch) -> BCdefined (mask, code, patch)) res
1011
1012 let compile ~fail_on_error env sigma c =
1013 compile ~fail_on_error ~uinstance:Global env sigma c
1014
1015 (* Shortcut of the previous function used during module strengthening *)
1016
1017 let compile_alias kn = BCalias (Constant.make1 (Constant.canonical kn))