cljrs-ir 0.1.48

Intermediate representation types for clojurust compiler and interpreter
Documentation
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
(ns cljrs.compiler.optimize
  (:require [cljrs.compiler.escape :as escape]
            [cljrs.compiler.ir :as ir]))

;; ── Region allocation optimization ──────────────────────────────────────────
;;
;; Rewrites non-escaping allocations into region-backed allocations.  An
;; allocation can be region-allocated only if there exists a contiguous
;; subgraph of the CFG within which the allocation is born, used, and
;; never reachable from blocks that may unwind out of it.  We implement
;; that by computing, for each `:no-escape` allocation:
;;
;;   start = lca-of-doms({def-block} ∪ use-blocks)
;;   end   = lca-of-postdoms({def-block} ∪ use-blocks)
;;
;; If the path `start..end` is acyclic (no back-edges) and contains no
;; throw-style terminators, we wrap it in a region: `RegionStart` at the
;; head of `start`, `RegionEnd` at the head of `end`, and the alloc
;; instruction is rewritten in place to `RegionAlloc`.
;;
;; Limitations of this first pass (deliberate; revisit later):
;;
;;   - one region per allocation (no grouping of allocations sharing a
;;     start/end pair)
;;   - allocations whose region would span a back-edge are skipped
;;     (loops not optimized)
;;   - allocations whose region would contain a `:throw` or
;;     `:unreachable` terminator are skipped (no unwind-aware cleanup)
;;   - if `start` or `end` cannot be determined, the allocation is left
;;     as a regular `Alloc*`

(def alloc-op-to-region-kind
  {:alloc-vector :vector
   :alloc-map    :map
   :alloc-set    :set
   :alloc-list   :list
   :alloc-cons   :cons})

(defn alloc-operands
  "Extract the operand VarIds from an allocation instruction."
  [inst]
  (case (:op inst)
    (:alloc-vector :alloc-set :alloc-list) (:elems inst)
    :alloc-map (reduce (fn [acc [k v]] (conj (conj acc k) v)) [] (:pairs inst))
    :alloc-cons [(:head inst) (:tail inst)]
    []))

;; ── CFG analysis ────────────────────────────────────────────────────────────

(defn block-successors
  "Return the successor block IDs for a block's terminator."
  [block]
  (let [t (:terminator block)]
    (case (:op t)
      :jump        [(:target t)]
      :branch      [(:then-block t) (:else-block t)]
      :recur-jump  [(:target t)]
      ;; :return / :throw / :unreachable / nil have no successors
      [])))

(defn block-by-id-map
  [ir-func]
  (reduce (fn [m b] (assoc m (:id b) b)) {} (:blocks ir-func)))

(defn predecessor-map
  "Return {block-id #{pred-block-ids}} for the IR function."
  [ir-func]
  (reduce (fn [acc block]
            (reduce (fn [a succ]
                      (update a succ (fn [v] (conj (or v #{}) (:id block)))))
                    acc
                    (block-successors block)))
          {}
          (:blocks ir-func)))

(defn reverse-postorder
  "DFS from block 0; return blocks in reverse-postorder.  Unreachable
   blocks are not included."
  [ir-func]
  (let [by-id (block-by-id-map ir-func)]
    (loop [stack [[0 false]]
           visited #{}
           postorder []]
      (if (empty? stack)
        (vec (reverse postorder))
        (let [[bid done?] (peek stack)
              rest-stack (pop stack)]
          (cond
            done? (recur rest-stack visited (conj postorder bid))
            (contains? visited bid) (recur rest-stack visited postorder)
            :else
            (let [block (get by-id bid)
                  succs (if block (block-successors block) [])
                  new-stack (reduce (fn [s succ] (conj s [succ false]))
                                    (conj rest-stack [bid true])
                                    succs)]
              (recur new-stack (conj visited bid) postorder))))))))

;; ── Dominator analysis (iterative fixed-point) ──────────────────────────────

(defn- intersect-sets
  "Intersect a non-empty seq of sets without requiring `clojure.set`."
  [sets]
  (reduce (fn [acc s]
            (if (nil? acc)
              s
              (reduce (fn [a x] (if (contains? s x) a (disj a x))) acc acc)))
          nil
          sets))

(defn- dom-iterate
  "Generic iterative dominator computation.

   `roots` — set of block IDs initialised to `#{root}` (their only
            dominator); for forward dominators this is `#{0}`.
   `block-ids` — all block IDs to consider (typically reverse-postorder).
   `pred-fn` — `block-id → #{pred-block-ids}`.

   Returns `{block-id #{dominators}}`."
  [roots block-ids pred-fn]
  (let [universe (set block-ids)
        init (reduce (fn [m b]
                       (assoc m b (if (contains? roots b) #{b} universe)))
                     {}
                     block-ids)]
    (loop [doms init]
      (let [next-doms
            (reduce
             (fn [d b]
               (if (contains? roots b)
                 d
                 (let [computed-preds (filter (fn [p] (contains? d p)) (pred-fn b))]
                   (if (empty? computed-preds)
                     d
                     (let [intersected (intersect-sets (map (fn [p] (get d p)) computed-preds))
                           new-set (conj (or intersected #{}) b)]
                       (assoc d b new-set))))))
             doms
             block-ids)]
        (if (= next-doms doms)
          doms
          (recur next-doms))))))

(defn dominators
  "Return `{block-id #{dominator-block-ids}}` for the function.  Block 0
   dominates only itself; every other reachable block has at least block
   0 in its dominator set."
  [ir-func]
  (let [rpo (reverse-postorder ir-func)
        preds (predecessor-map ir-func)]
    (dom-iterate #{0} rpo (fn [b] (get preds b #{})))))

(defn- collect-exits
  "Return the set of terminating block IDs (`:return` / `:throw` /
   `:unreachable`)."
  [ir-func]
  (reduce (fn [acc b]
            (let [op (-> b :terminator :op)]
              (if (contains? #{:return :throw :unreachable} op)
                (conj acc (:id b))
                acc)))
          #{}
          (:blocks ir-func)))

(defn post-dominators
  "Return `{block-id #{post-dominator-block-ids}}`.  Post-dominator
   analysis runs on the reversed CFG.  All exit blocks are roots — they
   only post-dominate themselves; every reachable block reaches at least
   one exit, so its post-dominator set is non-empty."
  [ir-func]
  (let [rpo (reverse-postorder ir-func)
        by-id (block-by-id-map ir-func)
        succ-fn (fn [b] (set (block-successors (get by-id b))))
        exits (collect-exits ir-func)]
    (dom-iterate exits rpo succ-fn)))

;; ── Lowest-common-ancestor in a dominator-tree-shaped relation ──────────────
;;
;; `dom-of` is `{block #{dominators}}`.  The LCA of two blocks A and B is
;; the dominator of both that is itself dominated by every other common
;; dominator — equivalently, the largest element of `(∩ dom-of[A]
;; dom-of[B])` under the dominator partial order.

(defn lca-of
  "Lowest common ancestor of `a` and `b` in the dominator-tree induced
   by `dom-of`.  Returns nil if no common ancestor exists (e.g. one of
   the blocks is unreachable)."
  [dom-of a b]
  (let [da (get dom-of a #{})
        db (get dom-of b #{})
        common (reduce (fn [acc x] (if (contains? db x) (conj acc x) acc)) #{} da)]
    (when (seq common)
      (reduce (fn [best d]
                (cond
                  (nil? best) d
                  (contains? (get dom-of d) best) d
                  :else best))
              nil
              common))))

(defn lca-of-many
  "Fold `lca-of` over a non-empty seq of blocks."
  [dom-of blocks]
  (let [bs (seq blocks)]
    (when bs
      (reduce (fn [acc b]
                (if (nil? acc)
                  nil
                  (lca-of dom-of acc b)))
              (first bs)
              (rest bs)))))

;; ── Reachability between two blocks (avoiding the end block) ───────────────

(defn- blocks-on-path
  "Return the set of block IDs reachable from `start` whose paths
   terminate at `end`.  Includes `start` and `end`.  We stop expanding
   past `end`, so its successors aren't part of the region.  Used to
   scan for back-edges and throw blocks within the proposed region."
  [ir-func start end]
  (let [by-id (block-by-id-map ir-func)]
    (loop [stack [start] seen #{}]
      (if (empty? stack)
        seen
        (let [b (peek stack)]
          (if (contains? seen b)
            (recur (pop stack) seen)
            (let [block (get by-id b)
                  succs (if (or (nil? block) (= b end))
                          []
                          (block-successors block))]
              (recur (into (pop stack) succs)
                     (conj seen b)))))))))

(defn- has-back-edge?
  "True if any edge whose head is in `region-blocks` targets a block
   that already dominates the source — i.e. the region contains a
   loop."
  [ir-func region-blocks doms]
  (let [by-id (block-by-id-map ir-func)]
    (boolean
     (some (fn [b]
             (some (fn [succ]
                     (and (contains? region-blocks succ)
                          (contains? (get doms b #{}) succ)))
                   (block-successors (get by-id b))))
           region-blocks))))

(defn- region-contains-throw?
  "True if any block in `region-blocks` could unwind out of the region
   without running our `RegionEnd`.  We refuse to optimize anything
   reachable from a `:throw` instruction or a `:throw` /
   `:unreachable` terminator within the region — region cleanup today
   has no exception-handling integration, so an unwind would leak the
   bump-allocated chunk."
  [ir-func region-blocks]
  (let [by-id (block-by-id-map ir-func)]
    (boolean
     (some (fn [b]
             (let [block (get by-id b)
                   term-op (-> block :terminator :op)]
               (or (contains? #{:throw :unreachable} term-op)
                   (some (fn [inst] (= :throw (:op inst))) (:insts block)))))
           region-blocks))))

;; ── Use-block collection ───────────────────────────────────────────────────
;;
;; For an allocation, walk the same propagation chain as `classify-escape`
;; — through phi nodes and through the results of escape-style known
;; calls (e.g. `:assoc`) — and collect every block in which the
;; allocation, or any value derived from it, has a use.  These blocks
;; bound the region's required lifetime.

(defn- collect-use-blocks
  [alloc-var uses ir-func]
  (loop [worklist [alloc-var]
         visited #{}
         use-blocks #{}]
    (if (empty? worklist)
      use-blocks
      (let [current (first worklist)
            rest-wl (rest worklist)]
        (if (contains? visited current)
          (recur rest-wl visited use-blocks)
          (let [visited (conj visited current)
                use-list (or (get uses current) [])
                {:keys [extra-vars new-blocks]}
                (reduce
                 (fn [acc use-info]
                   (let [kind (:kind use-info)
                         kt (:type kind)
                         acc (update acc :new-blocks conj (:block use-info))]
                     (case kt
                       :known-call-arg
                       (if (escape/known-fn-arg-escapes? (:func kind) (:arg-index kind))
                         (let [call-result (escape/find-call-result current (:func kind) ir-func (:block use-info))]
                           (if call-result
                             (update acc :extra-vars conj call-result)
                             acc))
                         acc)

                       :phi-input
                       (let [block (first (filter (fn [b] (= (:id b) (:block use-info)))
                                                  (:blocks ir-func)))]
                         (if block
                           (reduce (fn [a phi]
                                     (if (and (= (:op phi) :phi)
                                              (some (fn [[_ v]] (= v current)) (:entries phi)))
                                       (update a :extra-vars conj (:dst phi))
                                       a))
                                   acc
                                   (:phis block))
                           acc))

                       acc)))
                 {:extra-vars [] :new-blocks []}
                 use-list)]
            (recur (into (vec rest-wl) extra-vars)
                   visited
                   (into use-blocks new-blocks))))))))

;; ── The pass ───────────────────────────────────────────────────────────────

(defn- next-fresh-var!
  [next-var-atom]
  (let [v @next-var-atom]
    (swap! next-var-atom inc)
    v))

(defn- insert-region-start
  "Return `block` with `RegionStart` prepended to its instruction list."
  [block region-var]
  (assoc block :insts (into [(ir/inst-region-start region-var)] (:insts block))))

(defn- insert-region-end
  "Return `block` with `RegionEnd` appended to its instruction list.

   The end block is the post-dominator of all uses, so any uses living
   *inside* the end block (e.g. the `:count` call in min-key's join
   block) need to run before cleanup.  Appending — i.e. placing
   `RegionEnd` immediately before the terminator — is the only safe
   placement."
  [block region-var]
  (assoc block :insts (conj (vec (:insts block)) (ir/inst-region-end region-var))))

(defn- rewrite-alloc-in-block
  "Replace the alloc instruction with `:dst alloc-var` in `block` with a
   region-allocate counterpart targeting `region-var`."
  [block alloc-var region-var]
  (assoc block :insts
         (mapv (fn [inst]
                 (if (and (contains? alloc-op-to-region-kind (:op inst))
                          (= (:dst inst) alloc-var))
                   (let [kind (get alloc-op-to-region-kind (:op inst))
                         operands (alloc-operands inst)]
                     (ir/inst-region-alloc (:dst inst) region-var kind operands))
                   inst))
               (:insts block))))

(defn- update-block-by-id
  [ir-func block-id update-fn]
  (assoc ir-func :blocks
         (mapv (fn [b] (if (= (:id b) block-id) (update-fn b) b))
               (:blocks ir-func))))

(defn- emit-region-for-alloc
  "Return an updated `ir-func` with one allocation rewritten into a
   region.  No-op if the safety checks fail or the start/end can't be
   determined."
  [ir-func alloc-var alloc-block use-blocks doms postdoms next-var-atom]
  (let [relevant (conj (set use-blocks) alloc-block)
        start (lca-of-many doms relevant)
        end (lca-of-many postdoms relevant)]
    (cond
      (or (nil? start) (nil? end))
      ir-func

      ;; Defining block must be dominated by `start` (start ≤ alloc-block
      ;; in the dominator tree) — otherwise inserting RegionStart there
      ;; doesn't actually precede the alloc.
      (not (contains? (get doms alloc-block #{}) start))
      ir-func

      :else
      (let [region (blocks-on-path ir-func start end)]
        (cond
          (has-back-edge? ir-func region doms)
          ir-func

          (region-contains-throw? ir-func region)
          ir-func

          :else
          (let [region-var (next-fresh-var! next-var-atom)]
            (-> ir-func
                (update-block-by-id alloc-block
                                    (fn [b] (rewrite-alloc-in-block b alloc-var region-var)))
                (update-block-by-id start
                                    (fn [b] (insert-region-start b region-var)))
                (update-block-by-id end
                                    (fn [b] (insert-region-end b region-var))))))))))

(defn optimize-regions
  "Walk all `:no-escape` allocations and rewrite each into a
   region-allocate scoped over the dominator subgraph that covers the
   allocation and all its (transitive) uses.  Allocations that don't
   meet the safety constraints are left as regular allocations.

   `ctx` is an inter-procedural analysis context (see
   `escape/make-context`) — supplying one lets escape analysis
   refine `:unknown-call-arg` uses against per-function summaries
   instead of bailing with `:arg-escape`."
  ([ir-func]
   (optimize-regions ir-func {}))
  ([ir-func ctx]
   (let [analysis (escape/analyze ir-func ctx)
         states (:states analysis)
         uses (:uses analysis)
         alloc-blocks (:alloc-blocks analysis)
         no-escape-allocs (filterv (fn [[v _]] (= :no-escape (get states v)))
                                   alloc-blocks)]
     (if (empty? no-escape-allocs)
       ir-func
       (let [doms (dominators ir-func)
             postdoms (post-dominators ir-func)
             next-var-atom (atom (:next-var ir-func))
             new-func (reduce (fn [acc-func [alloc-var alloc-block]]
                                (let [use-blocks (collect-use-blocks alloc-var uses ir-func)]
                                  (emit-region-for-alloc acc-func alloc-var alloc-block
                                                         use-blocks doms postdoms
                                                         next-var-atom)))
                              ir-func
                              no-escape-allocs)]
         (assoc new-func :next-var @next-var-atom))))))

(defn- optimize-tree
  "Optimize `ir-func` and its subfunctions (recursively), threading
   `ctx` through so summary lookups share state across the tree."
  [ir-func ctx]
  (let [optimized (optimize-regions ir-func ctx)
        new-subs (mapv (fn [sub] (optimize-tree sub ctx))
                       (or (:subfunctions optimized) []))]
    (assoc optimized :subfunctions new-subs)))

(defn optimize
  "Run all optimization passes on an IR function.  Currently only runs
   region allocation optimization, recursing into subfunctions and
   sharing inter-procedural escape summaries across the whole tree."
  [ir-func]
  (let [ctx (escape/make-context ir-func)]
    (optimize-tree ir-func ctx)))