Source file specialize.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
open! Stdlib
open Code
open Flow
let function_arity info x =
let rec arity info x acc =
get_approx
info
(fun x ->
match Flow.Info.def info x with
| Some (Closure (l, _)) -> Some (List.length l)
| Some (Special (Alias_prim prim)) -> (
try Some (Primitive.arity prim) with Not_found -> None)
| Some (Apply { f; args; _ }) -> (
if List.mem f ~set:acc
then None
else
match arity info f (f :: acc) with
| Some n ->
let diff = n - List.length args in
if diff > 0 then Some diff else None
| None -> None)
| _ -> None)
None
(fun u v ->
match u, v with
| Some n, Some m when n = m -> u
| _ -> None)
x
in
arity info x []
let specialize_instr function_arity (acc, free_pc, ) i =
match i with
| Let (x, Apply { f; args; exact = false }), loc when Config.Flag.optcall () -> (
let n' = List.length args in
match function_arity f with
| None -> i :: acc, free_pc, extra
| Some n when n = n' ->
(Let (x, Apply { f; args; exact = true }), loc) :: acc, free_pc, extra
| Some n when n < n' ->
let v = Code.Var.fresh () in
let args, rest = List.take n args in
( (Let (v, Apply { f; args; exact = true }), loc)
:: (Let (x, Apply { f = v; args = rest; exact = false }), loc)
:: acc
, free_pc
, extra )
| Some n when n > n' ->
let missing = Array.init (n - n') ~f:(fun _ -> Code.Var.fresh ()) in
let missing = Array.to_list missing in
let block =
let params' = Array.init (n - n') ~f:(fun _ -> Code.Var.fresh ()) in
let params' = Array.to_list params' in
let return' = Code.Var.fresh () in
{ params = params'
; body =
[ Let (return', Apply { f; args = args @ params'; exact = true }), noloc ]
; branch = Return return', noloc
}
in
( (Let (x, Closure (missing, (free_pc, missing))), loc) :: acc
, free_pc + 1
, (free_pc, block) :: extra )
| _ -> i :: acc, free_pc, extra)
| _ -> i :: acc, free_pc, extra
let specialize_instrs ~function_arity p =
let blocks, free_pc =
Addr.Map.fold
(fun pc block (blocks, free_pc) ->
let body, free_pc, =
List.fold_right block.body ~init:([], free_pc, []) ~f:(fun i acc ->
specialize_instr function_arity acc i)
in
let blocks =
List.fold_left extra ~init:blocks ~f:(fun blocks (pc, b) ->
Addr.Map.add pc b blocks)
in
Addr.Map.add pc { block with Code.body } blocks, free_pc)
p.blocks
(Addr.Map.empty, p.free_pc)
in
{ p with blocks; free_pc }
let f = specialize_instrs