Remove a workaround in bit-vector consets
[sbcl.git] / src / compiler / constraint.lisp
1 ;;;; This file implements the constraint propagation phase of the
2 ;;;; compiler, which uses global flow analysis to obtain dynamic type
3 ;;;; information.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 ;;; TODO:
15 ;;;
16 ;;; -- documentation
17 ;;;
18 ;;; -- MV-BIND, :ASSIGNMENT
19 ;;;
20 ;;; Note: The functions in this file that accept constraint sets are
21 ;;; actually receiving the constraint sets associated with nodes,
22 ;;; blocks, and lambda-vars.  It might be make CP easier to understand
23 ;;; and work on if these functions traded in nodes, blocks, and
24 ;;; lambda-vars directly.
25
26 ;;; Problems:
27 ;;;
28 ;;; -- Constraint propagation badly interacts with bottom-up type
29 ;;; inference. Consider
30 ;;;
31 ;;; (defun foo (n &aux (i 42))
32 ;;;   (declare (optimize speed))
33 ;;;   (declare (fixnum n)
34 ;;;            #+nil (type (integer 0) i))
35 ;;;   (tagbody
36 ;;;      (setq i 0)
37 ;;;    :loop
38 ;;;      (when (>= i n) (go :exit))
39 ;;;      (setq i (1+ i))
40 ;;;      (go :loop)
41 ;;;    :exit))
42 ;;;
43 ;;; In this case CP cannot even infer that I is of class INTEGER.
44 ;;;
45 ;;; -- In the above example if we place the check after SETQ, CP will
46 ;;; fail to infer (< I FIXNUM): it does not understand that this
47 ;;; constraint follows from (TYPEP I (INTEGER 0 0)).
48
49 (in-package "SB!C")
50
51 ;;; *CONSTRAINT-UNIVERSE* gets bound in IR1-PHASES to a fresh,
52 ;;; zero-length, non-zero-total-size vector-with-fill-pointer.
53 (declaim (type (and vector (not simple-vector)) *constraint-universe*))
54 (defvar *constraint-universe*)
55
56 (deftype constraint-y () '(or ctype lvar lambda-var constant))
57
58 (defstruct (constraint
59             (:include sset-element)
60             (:constructor make-constraint (number kind x y not-p))
61             (:copier nil))
62   ;; the kind of constraint we have:
63   ;;
64   ;; TYPEP
65   ;;     X is a LAMBDA-VAR and Y is a CTYPE. The value of X is
66   ;;     constrained to be of type Y.
67   ;;
68   ;; > or <
69   ;;     X is a lambda-var and Y is a CTYPE. The relation holds
70   ;;     between X and some object of type Y.
71   ;;
72   ;; EQL
73   ;;     X is a LAMBDA-VAR and Y is a LVAR, a LAMBDA-VAR or a CONSTANT.
74   ;;     The relation is asserted to hold.
75   (kind nil :type (member typep < > eql))
76   ;; The operands to the relation.
77   (x nil :type lambda-var)
78   (y nil :type constraint-y)
79   ;; If true, negates the sense of the constraint, so the relation
80   ;; does *not* hold.
81   (not-p nil :type boolean))
82 \f
83 ;;; Historically, CMUCL and SBCL have used a sparse set implementation
84 ;;; for which most operations are O(n) (see sset.lisp), but at the
85 ;;; cost of at least a full word of pointer for each constraint set
86 ;;; element.  Using bit-vectors instead of pointer structures saves a
87 ;;; lot of space and thus GC time (particularly on 64-bit machines),
88 ;;; and saves time on copy, union, intersection, and difference
89 ;;; operations; but makes iteration slower.  Circa September 2008,
90 ;;; switching to bit-vectors gave a modest (5-10%) improvement in real
91 ;;; compile time for most Lisp systems, and as much as 20-30% for some
92 ;;; particularly CP-dependent systems.
93
94 ;;; It's bad to leave commented code in files, but if some clever
95 ;;; person comes along and makes SSETs better than bit-vectors as sets
96 ;;; for constraint propagation, or if bit-vectors on some XC host
97 ;;; really lose compared to SSETs, here's the conset API as a wrapper
98 ;;; around SSETs:
99 #+nil
100 (progn
101   (deftype conset () 'sset)
102   (declaim (ftype (sfunction (conset) boolean) conset-empty))
103   (declaim (ftype (sfunction (conset) conset) copy-conset))
104   (declaim (ftype (sfunction (constraint conset) boolean) conset-member))
105   (declaim (ftype (sfunction (constraint conset) boolean) conset-adjoin))
106   (declaim (ftype (sfunction (conset conset) boolean) conset=))
107   (declaim (ftype (sfunction (conset conset) (values)) conset-union))
108   (declaim (ftype (sfunction (conset conset) (values)) conset-intersection))
109   (declaim (ftype (sfunction (conset conset) (values)) conset-difference))
110   (defun make-conset () (make-sset))
111   (defmacro do-conset-elements ((constraint conset &optional result) &body body)
112     `(do-sset-elements (,constraint ,conset ,result) ,@body))
113   (defmacro do-conset-intersection
114       ((constraint conset1 conset2 &optional result) &body body)
115     `(do-conset-elements (,constraint ,conset1 ,result)
116        (when (conset-member ,constraint ,conset2)
117          ,@body)))
118   (defun conset-empty (conset) (sset-empty conset))
119   (defun copy-conset (conset) (copy-sset conset))
120   (defun conset-member (constraint conset) (sset-member constraint conset))
121   (defun conset-adjoin (constraint conset) (sset-adjoin constraint conset))
122   (defun conset= (conset1 conset2) (sset= conset1 conset2))
123   ;; Note: CP doesn't ever care whether union, intersection, and
124   ;; difference change the first set.  (This is an important degree of
125   ;; freedom, since some ways of implementing sets lose a great deal
126   ;; when these operations are required to track changes.)
127   (defun conset-union (conset1 conset2)
128     (sset-union conset1 conset2) (values))
129   (defun conset-intersection (conset1 conset2)
130     (sset-intersection conset1 conset2) (values))
131   (defun conset-difference (conset1 conset2)
132     (sset-difference conset1 conset2) (values)))
133
134 (locally
135     ;; This is performance critical for the compiler, and benefits
136     ;; from the following declarations.  Probably you'll want to
137     ;; disable these declarations when debugging consets.
138     (declare #-sb-xc-host (optimize (speed 3) (safety 0) (space 0)))
139   (declaim (inline %constraint-number))
140   (defun %constraint-number (constraint)
141     (sset-element-number constraint))
142   (defstruct (conset
143               (:constructor make-conset ())
144               (:copier %copy-conset))
145     (vector (make-array
146              ;; FIXME: make POWER-OF-TWO-CEILING available earlier?
147              (ash 1 (integer-length (1- (length *constraint-universe*))))
148              :element-type 'bit :initial-element 0)
149             :type simple-bit-vector)
150     ;; Bit-vectors win over lightweight hashes for copy, union,
151     ;; intersection, difference, but lose for iteration if you iterate
152     ;; over the whole vector.  Tracking extrema helps a bit.
153     (min 0 :type fixnum)
154     (max 0 :type fixnum))
155
156   (defun conset-empty (conset)
157     (or (= (conset-min conset) (conset-max conset))
158         (not (find 1 (conset-vector conset)
159                    :start (conset-min conset)
160                    ;; the :end argument can be commented out when
161                    ;; bootstrapping on a < 1.0.9 SBCL errors out with
162                    ;; a full call to DATA-VECTOR-REF-WITH-OFFSET.
163                    :end (conset-max conset)))))
164
165   (defun copy-conset (conset)
166     (let ((ret (%copy-conset conset)))
167       (setf (conset-vector ret) (copy-seq (conset-vector conset)))
168       ret))
169
170   (defun %conset-grow (conset new-size)
171     (declare (type index new-size))
172     (setf (conset-vector conset)
173           (replace (the simple-bit-vector
174                      (make-array
175                       (ash 1 (integer-length (1- new-size)))
176                       :element-type 'bit
177                       :initial-element 0))
178                    (the simple-bit-vector
179                      (conset-vector conset)))))
180
181   (declaim (inline conset-grow))
182   (defun conset-grow (conset new-size)
183     (declare (type index new-size))
184     (when (< (length (conset-vector conset)) new-size)
185       (%conset-grow conset new-size))
186     (values))
187
188   (defun conset-member (constraint conset)
189     (let ((number (%constraint-number constraint))
190           (vector (conset-vector conset)))
191       (when (< number (length vector))
192         (plusp (sbit vector number)))))
193
194   (defun conset-adjoin (constraint conset)
195     (let ((number (%constraint-number constraint)))
196       (conset-grow conset (1+ number))
197       (setf (sbit (conset-vector conset) number) 1)
198       (setf (conset-min conset) (min number (conset-min conset)))
199       (when (>= number (conset-max conset))
200         (setf (conset-max conset) (1+ number))))
201     conset)
202
203   (defun conset= (conset1 conset2)
204     (let* ((vector1 (conset-vector conset1))
205            (vector2 (conset-vector conset2))
206            (length1 (length vector1))
207            (length2 (length vector2)))
208       (if (= length1 length2)
209           ;; When the lengths are the same, we can rely on EQUAL being
210           ;; nicely optimized on bit-vectors.
211           (equal vector1 vector2)
212           (multiple-value-bind (shorter longer)
213               (if (< length1 length2)
214                   (values vector1 vector2)
215                   (values vector2 vector1))
216             ;; FIXME: make MISMATCH fast on bit-vectors.
217             (dotimes (index (length shorter))
218               (when (/= (sbit vector1 index) (sbit vector2 index))
219                 (return-from conset= nil)))
220             (if (find 1 longer :start (length shorter))
221                 nil
222                 t)))))
223
224   (macrolet
225       ((defconsetop (name bit-op)
226            `(defun ,name (conset-1 conset-2)
227               (declare (optimize (speed 3) (safety 0)))
228               (let* ((size-1 (length (conset-vector conset-1)))
229                      (size-2 (length (conset-vector conset-2)))
230                      (new-size (max size-1 size-2)))
231                 (conset-grow conset-1 new-size)
232                 (conset-grow conset-2 new-size))
233               (let ((vector1 (conset-vector conset-1))
234                     (vector2 (conset-vector conset-2)))
235                 (declare (simple-bit-vector vector1 vector2))
236                 (setf (conset-vector conset-1) (,bit-op vector1 vector2 t))
237                 ;; Update the extrema.
238                 ,(ecase name
239                    ((conset-union)
240                     `(setf (conset-min conset-1)
241                            (min (conset-min conset-1)
242                                 (conset-min conset-2))
243                            (conset-max conset-1)
244                            (max (conset-max conset-1)
245                                 (conset-max conset-2))))
246                    ((conset-intersection)
247                     `(let ((start (max (conset-min conset-1)
248                                        (conset-min conset-2)))
249                            (end (min (conset-max conset-1)
250                                      (conset-max conset-2))))
251                        (setf (conset-min conset-1)
252                              (if (> start end)
253                                  0
254                                  (or (position 1 (conset-vector conset-1)
255                                                :start start :end end)
256                                      0))
257                              (conset-max conset-1)
258                              (if (> start end)
259                                  0
260                                  (let ((position
261                                         (position
262                                          1 (conset-vector conset-1)
263                                          :start start :end end :from-end t)))
264                                    (if position
265                                        (1+ position)
266                                        0))))))
267                    ((conset-difference)
268                     `(setf (conset-min conset-1)
269                            (or (position 1 (conset-vector conset-1)
270                                          :start (conset-min conset-1)
271                                          :end (conset-max conset-1))
272                                0)
273                            (conset-max conset-1)
274                            (let ((position
275                                   (position
276                                    1 (conset-vector conset-1)
277                                    :start (conset-min conset-1)
278                                    :end (conset-max conset-1)
279                                    :from-end t)))
280                              (if position
281                                  (1+ position)
282                                  0))))))
283               (values))))
284     (defconsetop conset-union bit-ior)
285     (defconsetop conset-intersection bit-and)
286     (defconsetop conset-difference bit-andc2)))
287 \f
288 ;;; Constraints are hash-consed. Unfortunately, types aren't, so we have
289 ;;; to over-approximate and then linear search through the potential hits.
290 ;;; LVARs can only be found in EQL (not-p = NIL) constraints, while constant
291 ;;; and lambda-vars can only be found in EQL constraints.
292 (defun find-constraint (kind x y not-p)
293   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
294   (etypecase y
295     (ctype
296        (awhen (lambda-var-ctype-constraints x)
297          (dolist (con (gethash (sb!kernel::type-class-info y) it) nil)
298            (when (and (eq (constraint-kind con) kind)
299                       (eq (constraint-not-p con) not-p)
300                       (type= (constraint-y con) y))
301              (return-from find-constraint con)))
302          nil))
303     (lvar
304        (awhen (lambda-var-eq-constraints x)
305          (gethash y it)))
306     ((or constant lambda-var)
307        (awhen (lambda-var-eq-constraints x)
308          (let ((cache (gethash y it)))
309            (declare (type list cache))
310            (if not-p (cdr cache) (car cache)))))))
311
312 ;;; The most common operations on consets are iterating through the constraints
313 ;;; that are related to a certain variable in a given conset.  Storing the
314 ;;; constraints related to each variable in vectors allows us to easily iterate
315 ;;; through the intersection of such constraints and the constraints in a conset.
316 ;;;
317 ;;; EQL-var constraints assert that two lambda-vars are EQL.
318 ;;; Private constraints assert that a lambda-var is EQL or not EQL to a constant.
319 ;;; Inheritable constraints are constraints that may be propagated to EQL
320 ;;; lambda-vars (along with EQL-var constraints).
321 ;;;
322 ;;; Lambda-var -- lvar EQL constraints only serve one purpose: remember whether
323 ;;; an lvar is (only) written to by a ref to that lambda-var, and aren't ever
324 ;;; propagated.
325 ;;;
326 ;;; Finally, the lambda-var conset is only used to track the whole set of
327 ;;; constraints associated with a given lambda-var, and thus easily delete
328 ;;; such constraints from a conset.
329 (defun register-constraint (x con y)
330   (declare (type lambda-var x) (type constraint con) (type constraint-y y))
331   (conset-adjoin con (lambda-var-constraints x))
332   (macrolet ((ensuref (place default)
333                `(or ,place (setf ,place ,default)))
334              (ensure-hash (place)
335                `(ensuref ,place (make-hash-table)))
336              (ensure-vec (place)
337                `(ensuref ,place (make-array 8 :adjustable t :fill-pointer 0))))
338     (etypecase y
339       (ctype
340        (let ((index (ensure-hash (lambda-var-ctype-constraints x)))
341              (vec   (ensure-vec  (lambda-var-inheritable-constraints x))))
342          (push con (gethash (sb!kernel::type-class-info y) index))
343          (vector-push-extend con vec)))
344       (lvar
345        (let ((index (ensure-hash (lambda-var-eq-constraints x))))
346          (setf (gethash y index) con)))
347       ((or constant lambda-var)
348        (let* ((index (ensure-hash (lambda-var-eq-constraints x)))
349               (cons  (ensuref (gethash y index) (list nil))))
350          (if (constraint-not-p con)
351              (setf (cdr cons) con)
352              (setf (car cons) con)))
353        (typecase y
354          (constant
355           (let ((vec (ensure-vec (lambda-var-private-constraints x))))
356             (vector-push-extend con vec)))
357          (lambda-var
358           (let ((vec (if (constraint-not-p con)
359                          (ensure-vec (lambda-var-inheritable-constraints x))
360                          (ensure-vec (lambda-var-eql-var-constraints x)))))
361             (vector-push-extend con vec)))))))
362   nil)
363
364 ;;; Return a constraint for the specified arguments. We only create a
365 ;;; new constraint if there isn't already an equivalent old one,
366 ;;; guaranteeing that all equivalent constraints are EQ. This
367 ;;; shouldn't be called on LAMBDA-VARs with no CONSTRAINTS set.
368 (defun find-or-create-constraint (kind x y not-p)
369   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
370   (or (find-constraint kind x y not-p)
371       (let ((new (make-constraint (length *constraint-universe*)
372                                   kind x y not-p)))
373         (vector-push-extend new *constraint-universe*
374                             (1+ (length *constraint-universe*)))
375         (register-constraint x new y)
376         (when (lambda-var-p y)
377           (register-constraint y new x))
378         new)))
379 \f
380 ;;; Actual conset interface
381 ;;;
382 ;;; Constraint propagation needs to iterate over the set of lambda-vars known to
383 ;;; be EQL to a given variable (including itself), via DO-EQL-VARS.
384 ;;;
385 ;;; It also has to iterate through constraints that are inherited by EQL variables
386 ;;; (DO-INHERITABLE-CONSTRAINTS), and through constraints used by
387 ;;; CONSTRAIN-REF-TYPE (to derive the type of a REF to a lambda-var).
388 ;;;
389 ;;; Consets must keep track of which lvars are EQL to a given lambda-var (result
390 ;;; from a REF to the lambda-var): CONSET-LVAR-LAMBDA-VAR-EQL-P and
391 ;;; CONSET-ADD-LVAR-LAMBDA-VAR-EQL.  This, as all other constraints, must of
392 ;;; course be cleared when a lambda-var's constraints are dropped because of
393 ;;; assignment.
394 ;;;
395 ;;; Consets must be able to add constraints to a given lambda-var
396 ;;; (CONSET-ADD-CONSTRAINT), and to the set of variables EQL to a given
397 ;;; lambda-var (CONSET-ADD-CONSTRAINT-TO-EQL).
398 ;;;
399 ;;; When a lambda-var is assigned to, all the constraints involving that variable
400 ;;; must be dropped: constraint propagation is flow-sensitive, so the constraints
401 ;;; relate to the variable at a given range of program point.  In such cases,
402 ;;; constraint propagation calls CONSET-CLEAR-LAMBDA-VAR.
403 ;;;
404 ;;; Finally, one of the main strengths of constraint propagation in SBCL is the
405 ;;; tracking of EQL variables to help constraint propagation.  When two variables
406 ;;; are known to be EQL (e.g. after a branch), ADD-EQL-VAR-VAR-CONSTRAINT is
407 ;;; called to add the EQL constraint, but also have each equality class inherit
408 ;;; the other's (inheritable) constraints.
409 ;;;
410 ;;; On top of that, we have the usual bulk set operations: intersection, copy,
411 ;;; equality or emptiness testing.  There's also union, but that's only an
412 ;;; optimisation to avoid useless copies in ADD-TEST-CONSTRAINTS and
413 ;;; FIND-BLOCK-TYPE-CONSTRAINTS.
414 (defmacro do-conset-constraints-intersection ((symbol (conset constraints) &optional result)
415                                               &body body)
416   (let ((min (gensym "MIN"))
417         (max (gensym "MAX")))
418     (once-only ((conset conset)
419                 (constraints constraints))
420       `(flet ((body (,symbol)
421                 (declare (type constraint ,symbol))
422                 ,@body))
423          (when ,constraints
424            (let ((,min (conset-min ,conset))
425                  (,max (conset-max ,conset)))
426              (declare (optimize speed))
427              (map nil (lambda (constraint)
428                         (declare (type constraint constraint))
429                         (let ((number (constraint-number constraint)))
430                           (when (and (<= ,min number)
431                                      (< number ,max)
432                                      (conset-member constraint ,conset))
433                             (body constraint))))
434                   ,constraints)))
435          ,result))))
436
437 (defmacro do-eql-vars ((symbol (var constraints) &optional result) &body body)
438   (once-only ((var         var)
439               (constraints constraints))
440     `(flet ((body-fun (,symbol)
441               ,@body))
442        (body-fun ,var)
443        (do-conset-constraints-intersection
444            (con (,constraints (lambda-var-eql-var-constraints ,var)) ,result)
445          (let ((x (constraint-x con))
446                (y (constraint-y con)))
447            (body-fun (if (eq ,var x) y x)))))))
448
449 (defmacro do-inheritable-constraints ((symbol (conset variable) &optional result)
450                                       &body body)
451   (once-only ((conset   conset)
452               (variable variable))
453     `(block nil
454        (flet ((body-fun (,symbol)
455                 ,@body))
456          (do-conset-constraints-intersection
457              (con (,conset (lambda-var-inheritable-constraints ,variable)))
458            (body-fun con))
459          (do-conset-constraints-intersection
460              (con (,conset (lambda-var-eql-var-constraints ,variable)) ,result)
461            (body-fun con))))))
462
463 (defmacro do-propagatable-constraints ((symbol (conset variable) &optional result)
464                                        &body body)
465   (once-only ((conset conset)
466               (variable variable))
467     `(block nil
468        (flet ((body-fun (,symbol)
469                 ,@body))
470          (do-conset-constraints-intersection
471              (con (,conset (lambda-var-private-constraints ,variable)))
472            (body-fun con))
473          (do-conset-constraints-intersection
474              (con (,conset (lambda-var-eql-var-constraints ,variable)))
475            (body-fun con))
476          (do-conset-constraints-intersection
477              (con (,conset (lambda-var-inheritable-constraints ,variable)) ,result)
478            (body-fun con))))))
479
480 (declaim (inline conset-lvar-lambda-var-eql-p conset-add-lvar-lambda-var-eql))
481 (defun conset-lvar-lambda-var-eql-p (conset lvar lambda-var)
482   (let ((constraint (find-constraint 'eql lambda-var lvar nil)))
483     (and constraint
484          (conset-member constraint conset))))
485
486 (defun conset-add-lvar-lambda-var-eql (conset lvar lambda-var)
487   (let ((constraint (find-or-create-constraint 'eql lambda-var lvar nil)))
488     (conset-adjoin constraint conset)))
489
490 (declaim (inline conset-add-constraint conset-add-constraint-to-eql))
491 (defun conset-add-constraint (conset kind x y not-p)
492   (declare (type conset conset)
493            (type lambda-var x))
494   (conset-adjoin (find-or-create-constraint kind x y not-p)
495                  conset))
496
497 (defun conset-add-constraint-to-eql (conset kind x y not-p &optional (target conset))
498   (declare (type conset target conset)
499            (type lambda-var x))
500   (do-eql-vars (x (x conset))
501     (conset-add-constraint target kind x y not-p)))
502
503 (declaim (inline conset-clear-lambda-var))
504 (defun conset-clear-lambda-var (conset var)
505   (conset-difference conset (lambda-var-constraints var)))
506
507 ;;; Copy all CONSTRAINTS involving FROM-VAR - except the (EQL VAR
508 ;;; LVAR) ones - to all of the variables in the VARS list.
509 (defun inherit-constraints (vars from-var constraints target)
510   (do-inheritable-constraints (con (constraints from-var))
511     (let ((eq-x (eq from-var (constraint-x con)))
512           (eq-y (eq from-var (constraint-y con))))
513       (dolist (var vars)
514         (conset-add-constraint target
515                                (constraint-kind con)
516                                (if eq-x var (constraint-x con))
517                                (if eq-y var (constraint-y con))
518                                (constraint-not-p con))))))
519
520 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR1 and VAR2 and
521 ;; inherit each other's constraints.
522 (defun add-eql-var-var-constraint (var1 var2 constraints
523                                    &optional (target constraints))
524   (let ((constraint (find-or-create-constraint 'eql var1 var2 nil)))
525     (unless (conset-member constraint target)
526       (conset-adjoin constraint target)
527       (collect ((eql1) (eql2))
528         (do-eql-vars (var1 (var1 constraints))
529           (eql1 var1))
530         (do-eql-vars (var2 (var2 constraints))
531           (eql2 var2))
532         (inherit-constraints (eql1) var2 constraints target)
533         (inherit-constraints (eql2) var1 constraints target))
534       t)))
535 \f
536 ;;; If REF is to a LAMBDA-VAR with CONSTRAINTs (i.e. we can do flow
537 ;;; analysis on it), then return the LAMBDA-VAR, otherwise NIL.
538 #!-sb-fluid (declaim (inline ok-ref-lambda-var))
539 (defun ok-ref-lambda-var (ref)
540   (declare (type ref ref))
541   (let ((leaf (ref-leaf ref)))
542     (when (and (lambda-var-p leaf)
543                (lambda-var-constraints leaf))
544       leaf)))
545
546 ;;; See if LVAR's single USE is a REF to a LAMBDA-VAR and they are EQL
547 ;;; according to CONSTRAINTS. Return LAMBDA-VAR if so.
548 (defun ok-lvar-lambda-var (lvar constraints)
549   (declare (type lvar lvar))
550   (let ((use (lvar-uses lvar)))
551     (cond ((ref-p use)
552            (let ((lambda-var (ok-ref-lambda-var use)))
553              (and lambda-var
554                   (conset-lvar-lambda-var-eql-p constraints lvar lambda-var)
555                   lambda-var)))
556           ((cast-p use)
557            (ok-lvar-lambda-var (cast-value use) constraints)))))
558 ;;;; Searching constraints
559
560 ;;; Add the indicated test constraint to TARGET.
561 (defun precise-add-test-constraint (fun x y not-p constraints target)
562   (if (and (eq 'eql fun) (lambda-var-p y) (not not-p))
563       (add-eql-var-var-constraint x y constraints target)
564       (conset-add-constraint-to-eql constraints fun x y not-p target))
565   (values))
566
567 (defun add-test-constraint (quick-p fun x y not-p constraints target)
568   (cond (quick-p
569          (conset-add-constraint target fun x y not-p))
570         (t
571          (precise-add-test-constraint fun x y not-p constraints target))))
572 ;;; Add complementary constraints to the consequent and alternative
573 ;;; blocks of IF. We do nothing if X is NIL.
574 (declaim (inline precise-add-test-constraint quick-add-complement-constraints))
575 (defun precise-add-complement-constraints (fun x y not-p constraints
576                                            consequent-constraints
577                                            alternative-constraints)
578   (when x
579     (precise-add-test-constraint fun x y not-p constraints
580                                 consequent-constraints)
581     (precise-add-test-constraint fun x y (not not-p) constraints
582                                  alternative-constraints))
583   (values))
584
585 (defun quick-add-complement-constraints (fun x y not-p
586                                          consequent-constraints
587                                          alternative-constraints)
588   (when x
589     (conset-add-constraint consequent-constraints fun x y not-p)
590     (conset-add-constraint alternative-constraints fun x y (not not-p)))
591   (values))
592
593 (defun add-complement-constraints (quick-p fun x y not-p constraints
594                                    consequent-constraints
595                                    alternative-constraints)
596   (if quick-p
597       (quick-add-complement-constraints fun x y not-p
598                                         consequent-constraints
599                                         alternative-constraints)
600       (precise-add-complement-constraints fun x y not-p constraints
601                                           consequent-constraints
602                                           alternative-constraints)))
603
604 (defun add-combination-test-constraints (use constraints
605                                          consequent-constraints
606                                          alternative-constraints
607                                          quick-p)
608   (flet ((add (fun x y not-p)
609            (add-complement-constraints quick-p
610                                        fun x y not-p
611                                        constraints
612                                        consequent-constraints
613                                        alternative-constraints))
614          (prop (triples target)
615            (map nil (lambda (constraint)
616                       (destructuring-bind (kind x y &optional not-p)
617                           constraint
618                         (when (and kind x y)
619                           (add-test-constraint quick-p
620                                                kind x y
621                                                not-p constraints
622                                                target))))
623                 triples)))
624     (when (eq (combination-kind use) :known)
625       (binding* ((info (combination-fun-info use) :exit-if-null)
626                  (propagate (fun-info-constraint-propagate-if
627                              info)
628                             :exit-if-null))
629         (multiple-value-bind (lvar type if else)
630             (funcall propagate use constraints)
631           (prop if consequent-constraints)
632           (prop else alternative-constraints)
633           (when (and lvar type)
634             (add 'typep (ok-lvar-lambda-var lvar constraints)
635                  type nil)
636             (return-from add-combination-test-constraints)))))
637     (let* ((name (lvar-fun-name
638                   (basic-combination-fun use)))
639            (args (basic-combination-args use))
640            (ptype (gethash name *backend-predicate-types*)))
641       (when ptype
642         (add 'typep (ok-lvar-lambda-var (first args)
643                                         constraints)
644              ptype nil)))))
645
646 ;;; Add test constraints to the consequent and alternative blocks of
647 ;;; the test represented by USE.
648 (defun add-test-constraints (use if constraints)
649   (declare (type node use) (type cif if))
650   ;; Note: Even if we do (IF test exp exp) => (PROGN test exp)
651   ;; optimization, the *MAX-OPTIMIZE-ITERATIONS* cutoff means that we
652   ;; can't guarantee that the optimization will be done, so we still
653   ;; need to avoid barfing on this case.
654   (unless (eq (if-consequent if) (if-alternative if))
655     (let ((consequent-constraints (make-conset))
656           (alternative-constraints (make-conset))
657           (quick-p (policy if (> compilation-speed speed))))
658       (macrolet ((add (fun x y not-p)
659                    `(add-complement-constraints quick-p
660                                                 ,fun ,x ,y ,not-p
661                                                 constraints
662                                                 consequent-constraints
663                                                 alternative-constraints)))
664         (typecase use
665           (ref
666            (add 'typep (ok-lvar-lambda-var (ref-lvar use) constraints)
667                 (specifier-type 'null) t))
668           (combination
669            (unless (eq (combination-kind use)
670                        :error)
671              (let ((name (lvar-fun-name
672                           (basic-combination-fun use)))
673                    (args (basic-combination-args use)))
674                (case name
675                  ((%typep %instance-typep)
676                   (let ((type (second args)))
677                     (when (constant-lvar-p type)
678                       (let ((val (lvar-value type)))
679                         (add 'typep
680                              (ok-lvar-lambda-var (first args) constraints)
681                              (if (ctype-p val)
682                                  val
683                                  (let ((*compiler-error-context* use))
684                                    (specifier-type val)))
685                              nil)))))
686                  ((eq eql)
687                   (let* ((arg1 (first args))
688                          (var1 (ok-lvar-lambda-var arg1 constraints))
689                          (arg2 (second args))
690                          (var2 (ok-lvar-lambda-var arg2 constraints)))
691                     ;; The code below assumes that the constant is the
692                     ;; second argument in case of variable to constant
693                     ;; comparison which is sometimes true (see source
694                     ;; transformations for EQ, EQL and CHAR=). Fixing
695                     ;; that would result in more constant substitutions
696                     ;; which is not a universally good thing, thus the
697                     ;; unnatural asymmetry of the tests.
698                     (cond ((not var1)
699                            (when var2
700                              (add-test-constraint quick-p
701                                                   'typep var2 (lvar-type arg1)
702                                                   nil constraints
703                                                   consequent-constraints)))
704                           (var2
705                            (add 'eql var1 var2 nil))
706                           ((constant-lvar-p arg2)
707                            (add 'eql var1
708                                 (find-constant (lvar-value arg2))
709                                 nil))
710                           (t
711                            (add-test-constraint quick-p
712                                                 'typep var1 (lvar-type arg2)
713                                                 nil constraints
714                                                 consequent-constraints)))))
715                  ((< >)
716                   (let* ((arg1 (first args))
717                          (var1 (ok-lvar-lambda-var arg1 constraints))
718                          (arg2 (second args))
719                          (var2 (ok-lvar-lambda-var arg2 constraints)))
720                     (when var1
721                       (add name var1 (lvar-type arg2) nil))
722                     (when var2
723                       (add (if (eq name '<) '> '<) var2 (lvar-type arg1) nil))))
724                  (t
725                   (add-combination-test-constraints use constraints
726                                                     consequent-constraints
727                                                     alternative-constraints
728                                                     quick-p))))))))
729       (values consequent-constraints alternative-constraints))))
730
731 ;;;; Applying constraints
732
733 ;;; Return true if X is an integer NUMERIC-TYPE.
734 (defun integer-type-p (x)
735   (declare (type ctype x))
736   (and (numeric-type-p x)
737        (eq (numeric-type-class x) 'integer)
738        (eq (numeric-type-complexp x) :real)))
739
740 ;;; Given that an inequality holds on values of type X and Y, return a
741 ;;; new type for X. If GREATER is true, then X was greater than Y,
742 ;;; otherwise less. If OR-EQUAL is true, then the inequality was
743 ;;; inclusive, i.e. >=.
744 ;;;
745 ;;; If GREATER (or not), then we max (or min) in Y's lower (or upper)
746 ;;; bound into X and return that result. If not OR-EQUAL, we can go
747 ;;; one greater (less) than Y's bound.
748 (defun constrain-integer-type (x y greater or-equal)
749   (declare (type numeric-type x y))
750   (flet ((exclude (x)
751            (cond ((not x) nil)
752                  (or-equal x)
753                  (greater (1+ x))
754                  (t (1- x))))
755          (bound (x)
756            (if greater (numeric-type-low x) (numeric-type-high x))))
757     (let* ((x-bound (bound x))
758            (y-bound (exclude (bound y)))
759            (new-bound (cond ((not x-bound) y-bound)
760                             ((not y-bound) x-bound)
761                             (greater (max x-bound y-bound))
762                             (t (min x-bound y-bound)))))
763       (if greater
764           (modified-numeric-type x :low new-bound)
765           (modified-numeric-type x :high new-bound)))))
766
767 ;;; Return true if X is a float NUMERIC-TYPE.
768 (defun float-type-p (x)
769   (declare (type ctype x))
770   (and (numeric-type-p x)
771        (eq (numeric-type-class x) 'float)
772        (eq (numeric-type-complexp x) :real)))
773
774 ;;; Exactly the same as CONSTRAIN-INTEGER-TYPE, but for float numbers.
775 ;;;
776 ;;; In contrast to the integer version, here the input types can have
777 ;;; open bounds in addition to closed ones and we don't increment or
778 ;;; decrement a bound to honor OR-EQUAL being NIL but put an open bound
779 ;;; into the result instead, if appropriate.
780 (defun constrain-float-type (x y greater or-equal)
781   (declare (type numeric-type x y))
782   (declare (ignorable x y greater or-equal)) ; for CROSS-FLOAT-INFINITY-KLUDGE
783
784   (aver (eql (numeric-type-class x) 'float))
785   (aver (eql (numeric-type-class y) 'float))
786   #+sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
787   x
788   #-sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
789   (labels ((exclude (x)
790              (cond ((not x) nil)
791                    (or-equal x)
792                    (t
793                     (if (consp x)
794                         x
795                         (list x)))))
796            (bound (x)
797              (if greater (numeric-type-low x) (numeric-type-high x)))
798            (tighter-p (x ref)
799              (cond ((null x) nil)
800                    ((null ref) t)
801                    ((= (type-bound-number x) (type-bound-number ref))
802                     ;; X is tighter if X is an open bound and REF is not
803                     (and (consp x) (not (consp ref))))
804                    (greater
805                     (< (type-bound-number ref) (type-bound-number x)))
806                    (t
807                     (> (type-bound-number ref) (type-bound-number x))))))
808     (let* ((x-bound (bound x))
809            (y-bound (exclude (bound y)))
810            (new-bound (cond ((not x-bound)
811                              y-bound)
812                             ((not y-bound)
813                              x-bound)
814                             ((tighter-p y-bound x-bound)
815                              y-bound)
816                             (t
817                              x-bound))))
818       (if greater
819           (modified-numeric-type x :low new-bound)
820           (modified-numeric-type x :high new-bound)))))
821
822 ;;; Return true if LEAF is "visible" from NODE.
823 (defun leaf-visible-from-node-p (leaf node)
824   (cond
825    ((lambda-var-p leaf)
826     ;; A LAMBDA-VAR is visible iif it is homed in a CLAMBDA that is an
827     ;; ancestor for NODE.
828     (let ((leaf-lambda (lambda-var-home leaf)))
829       (loop for lambda = (node-home-lambda node)
830             then (lambda-parent lambda)
831             while lambda
832             when (eq lambda leaf-lambda)
833             return t)))
834    ;; FIXME: Check on FUNCTIONALs (CLAMBDAs and OPTIONAL-DISPATCHes),
835    ;; not just LAMBDA-VARs.
836    (t
837     ;; Assume everything else is globally visible.
838     t)))
839
840 ;;; Given the set of CONSTRAINTS for a variable and the current set of
841 ;;; restrictions from flow analysis IN, set the type for REF
842 ;;; accordingly.
843 (defun constrain-ref-type (ref in)
844   (declare (type ref ref) (type conset in))
845   ;; KLUDGE: The NOT-SET and NOT-FPZ here are so that we don't need to
846   ;; cons up endless union types when propagating large number of EQL
847   ;; constraints -- eg. from large CASE forms -- instead we just
848   ;; directly accumulate one XSET, and a set of fp zeroes, which we at
849   ;; the end turn into a MEMBER-TYPE.
850   ;;
851   ;; Since massive symbol cases are an especially atrocious pattern
852   ;; and the (NOT (MEMBER ...ton of symbols...)) will never turn into
853   ;; a more useful type, don't propagate their negation except for NIL
854   ;; unless SPEED > COMPILATION-SPEED.
855   (let ((res (single-value-type (node-derived-type ref)))
856         (constrain-symbols (policy ref (> speed compilation-speed)))
857         (not-set (alloc-xset))
858         (not-fpz nil)
859         (not-res *empty-type*)
860         (leaf (ref-leaf ref)))
861     (declare (type lambda-var leaf))
862     (flet ((note-not (x)
863              (if (fp-zero-p x)
864                  (push x not-fpz)
865                  (when (or constrain-symbols (null x) (not (symbolp x)))
866                    (add-to-xset x not-set)))))
867       (do-propagatable-constraints (con (in leaf))
868         (let* ((x (constraint-x con))
869                (y (constraint-y con))
870                (not-p (constraint-not-p con))
871                (other (if (eq x leaf) y x))
872                (kind (constraint-kind con)))
873           (case kind
874             (typep
875              (if not-p
876                  (if (member-type-p other)
877                      (mapc-member-type-members #'note-not other)
878                      (setq not-res (type-union not-res other)))
879                  (setq res (type-approx-intersection2 res other))))
880             (eql
881              (let ((other-type (leaf-type other)))
882                (if not-p
883                    (when (and (constant-p other)
884                               (member-type-p other-type))
885                      (note-not (constant-value other)))
886                    (let ((leaf-type (leaf-type leaf)))
887                      (cond
888                        ((or (constant-p other)
889                             (and (leaf-refs other) ; protect from
890                                         ; deleted vars
891                                  (csubtypep other-type leaf-type)
892                                  (not (type= other-type leaf-type))
893                                  ;; Don't change to a LEAF not visible here.
894                                  (leaf-visible-from-node-p other ref)))
895                         (change-ref-leaf ref other)
896                         (when (constant-p other) (return)))
897                        (t
898                         (setq res (type-approx-intersection2
899                                    res other-type))))))))
900             ((< >)
901              (cond
902                ((and (integer-type-p res) (integer-type-p y))
903                 (let ((greater (eq kind '>)))
904                   (let ((greater (if not-p (not greater) greater)))
905                     (setq res
906                           (constrain-integer-type res y greater not-p)))))
907                ((and (float-type-p res) (float-type-p y))
908                 (let ((greater (eq kind '>)))
909                   (let ((greater (if not-p (not greater) greater)))
910                     (setq res
911                           (constrain-float-type res y greater not-p)))))))))))
912     (cond ((and (if-p (node-dest ref))
913                 (or (xset-member-p nil not-set)
914                     (csubtypep (specifier-type 'null) not-res)))
915            (setf (node-derived-type ref) *wild-type*)
916            (change-ref-leaf ref (find-constant t)))
917           (t
918            (setf not-res
919                  (type-union not-res (make-member-type :xset not-set :fp-zeroes not-fpz)))
920            (derive-node-type ref
921                              (make-single-value-type
922                               (or (type-difference res not-res)
923                                   res)))
924            (maybe-terminate-block ref nil))))
925   (values))
926
927 ;;;; Flow analysis
928
929 (defun maybe-add-eql-var-lvar-constraint (ref gen)
930   (let ((lvar (ref-lvar ref))
931         (leaf (ref-leaf ref)))
932     (when (and (lambda-var-p leaf) lvar)
933       (conset-add-lvar-lambda-var-eql gen lvar leaf))))
934
935 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR and LVAR's
936 ;; LAMBDA-VAR if possible.
937 (defun maybe-add-eql-var-var-constraint (var lvar constraints
938                                          &optional (target constraints))
939   (declare (type lambda-var var) (type lvar lvar))
940   (let ((lambda-var (ok-lvar-lambda-var lvar constraints)))
941     (when lambda-var
942       (add-eql-var-var-constraint var lambda-var constraints target))))
943
944 ;;; Local propagation
945 ;;; -- [TODO: For any LAMBDA-VAR ref with a type check, add that
946 ;;;    constraint.]
947 ;;; -- For any LAMBDA-VAR set, delete all constraints on that var; add
948 ;;;    a type constraint based on the new value type.
949 (declaim (ftype (function (cblock conset boolean)
950                           conset)
951                 constraint-propagate-in-block))
952 (defun constraint-propagate-in-block (block gen preprocess-refs-p)
953   (do-nodes (node lvar block)
954     (typecase node
955       (bind
956        (let ((fun (bind-lambda node)))
957          (when (eq (functional-kind fun) :let)
958            (loop with call = (lvar-dest (node-lvar (first (lambda-refs fun))))
959                  for var in (lambda-vars fun)
960                  and val in (combination-args call)
961                  when (and val (lambda-var-constraints var))
962                  do (let ((type (lvar-type val)))
963                       (unless (eq type *universal-type*)
964                         (conset-add-constraint gen 'typep var type nil)))
965                     (maybe-add-eql-var-var-constraint var val gen)))))
966       (ref
967        (when (ok-ref-lambda-var node)
968          (maybe-add-eql-var-lvar-constraint node gen)
969          (when preprocess-refs-p
970            (constrain-ref-type node gen))))
971       (cast
972        (let ((lvar (cast-value node)))
973          (let ((var (ok-lvar-lambda-var lvar gen)))
974            (when var
975              (let ((atype (single-value-type (cast-derived-type node)))) ;FIXME
976                (unless (eq atype *universal-type*)
977                  (conset-add-constraint-to-eql gen 'typep var atype nil)))))))
978       (cset
979        (binding* ((var (set-var node))
980                   (nil (lambda-var-p var) :exit-if-null)
981                   (nil (lambda-var-constraints var) :exit-if-null))
982          (when (policy node (and (= speed 3) (> speed compilation-speed)))
983            (let ((type (lambda-var-type var)))
984              (unless (eql *universal-type* type)
985                (do-eql-vars (other (var gen))
986                  (unless (eql other var)
987                    (conset-add-constraint gen 'typep other type nil))))))
988          (conset-clear-lambda-var gen var)
989          (let ((type (single-value-type (node-derived-type node))))
990            (unless (eq type *universal-type*)
991              (conset-add-constraint gen 'typep var type nil)))
992          (unless (policy node (> compilation-speed speed))
993            (maybe-add-eql-var-var-constraint var (set-value node) gen))))
994       (combination
995        (when (eq (combination-kind node) :known)
996          (binding* ((info (combination-fun-info node) :exit-if-null)
997                     (propagate (fun-info-constraint-propagate info)
998                                :exit-if-null)
999                     (constraints (funcall propagate node gen))
1000                     (register (if (policy node
1001                                           (> compilation-speed speed))
1002                                   #'conset-add-constraint
1003                                   #'conset-add-constraint-to-eql)))
1004            (map nil (lambda (constraint)
1005                       (destructuring-bind (kind x y &optional not-p)
1006                           constraint
1007                         (when (and kind x y)
1008                           (funcall register gen
1009                                    kind x y
1010                                    not-p))))
1011                 constraints))))))
1012   gen)
1013
1014 (defun constraint-propagate-if (block gen)
1015   (let ((node (block-last block)))
1016     (when (if-p node)
1017       (let ((use (lvar-uses (if-test node))))
1018         (when (node-p use)
1019           (add-test-constraints use node gen))))))
1020
1021 ;;; Starting from IN compute OUT and (consequent/alternative
1022 ;;; constraints if the block ends with an IF). Return the list of
1023 ;;; successors that may need to be recomputed.
1024 (defun find-block-type-constraints (block final-pass-p)
1025   (declare (type cblock block))
1026   (let ((gen (constraint-propagate-in-block
1027               block
1028               (if final-pass-p
1029                   (block-in block)
1030                   (copy-conset (block-in block)))
1031               final-pass-p)))
1032     (setf (block-gen block) gen)
1033     (multiple-value-bind (consequent-constraints alternative-constraints)
1034         (constraint-propagate-if block gen)
1035       (if consequent-constraints
1036           (let* ((node (block-last block))
1037                  (old-consequent-constraints (if-consequent-constraints node))
1038                  (old-alternative-constraints (if-alternative-constraints node))
1039                  (succ ()))
1040             ;; Add the consequent and alternative constraints to GEN.
1041             (cond ((conset-empty consequent-constraints)
1042                    (setf (if-consequent-constraints node) gen)
1043                    (setf (if-alternative-constraints node) gen))
1044                   (t
1045                    (setf (if-consequent-constraints node) (copy-conset gen))
1046                    (conset-union (if-consequent-constraints node)
1047                                  consequent-constraints)
1048                    (setf (if-alternative-constraints node) gen)
1049                    (conset-union (if-alternative-constraints node)
1050                                  alternative-constraints)))
1051             ;; Has the consequent been changed?
1052             (unless (and old-consequent-constraints
1053                          (conset= (if-consequent-constraints node)
1054                                   old-consequent-constraints))
1055               (push (if-consequent node) succ))
1056             ;; Has the alternative been changed?
1057             (unless (and old-alternative-constraints
1058                          (conset= (if-alternative-constraints node)
1059                                   old-alternative-constraints))
1060               (push (if-alternative node) succ))
1061             succ)
1062           ;; There is no IF.
1063           (unless (and (block-out block)
1064                        (conset= gen (block-out block)))
1065             (setf (block-out block) gen)
1066             (block-succ block))))))
1067
1068 ;;; Deliver the results of constraint propagation to REFs in BLOCK.
1069 ;;; During this pass, we also do local constraint propagation by
1070 ;;; adding in constraints as we see them during the pass through the
1071 ;;; block.
1072 (defun use-result-constraints (block)
1073   (declare (type cblock block))
1074   (constraint-propagate-in-block block (block-in block) t))
1075
1076 ;;; Give an empty constraints set to any var that doesn't have one and
1077 ;;; isn't a set closure var. Since a var that we previously rejected
1078 ;;; looks identical to one that is new, so we optimistically keep
1079 ;;; hoping that vars stop being closed over or lose their sets.
1080 (defun init-var-constraints (component)
1081   (declare (type component component))
1082   (dolist (fun (component-lambdas component))
1083     (flet ((frob (x)
1084              (dolist (var (lambda-vars x))
1085                (unless (lambda-var-constraints var)
1086                  (when (or (null (lambda-var-sets var))
1087                            (not (closure-var-p var)))
1088                    (setf (lambda-var-constraints var) (make-conset)))))))
1089       (frob fun)
1090       (dolist (let (lambda-lets fun))
1091         (frob let)))))
1092
1093 ;;; Return the constraints that flow from PRED to SUCC. This is
1094 ;;; BLOCK-OUT unless PRED ends with an IF and test constraints were
1095 ;;; added.
1096 (defun block-out-for-successor (pred succ)
1097   (declare (type cblock pred succ))
1098   (let ((last (block-last pred)))
1099     (or (when (if-p last)
1100           (cond ((eq succ (if-consequent last))
1101                  (if-consequent-constraints last))
1102                 ((eq succ (if-alternative last))
1103                  (if-alternative-constraints last))))
1104         (block-out pred))))
1105
1106 (defun compute-block-in (block)
1107   (let ((in nil))
1108     (dolist (pred (block-pred block))
1109       ;; If OUT has not been calculated, assume it to be the universal
1110       ;; set.
1111       (let ((out (block-out-for-successor pred block)))
1112         (when out
1113           (if in
1114               (conset-intersection in out)
1115               (setq in (copy-conset out))))))
1116     (or in (make-conset))))
1117
1118 (defun update-block-in (block)
1119   (let ((in (compute-block-in block)))
1120     (cond ((and (block-in block) (conset= in (block-in block)))
1121            nil)
1122           (t
1123            (setf (block-in block) in)))))
1124
1125 ;;; Return two lists: one of blocks that precede all loops and
1126 ;;; therefore require only one constraint propagation pass and the
1127 ;;; rest. This implementation does not find all such blocks.
1128 ;;;
1129 ;;; A more complete implementation would be:
1130 ;;;
1131 ;;;     (do-blocks (block component)
1132 ;;;       (if (every #'(lambda (pred)
1133 ;;;                      (or (member pred leading-blocks)
1134 ;;;                          (eq pred head)))
1135 ;;;                  (block-pred block))
1136 ;;;           (push block leading-blocks)
1137 ;;;           (push block rest-of-blocks)))
1138 ;;;
1139 ;;; Trailing blocks that succeed all loops could be found and handled
1140 ;;; similarly. In practice though, these more complex solutions are
1141 ;;; slightly worse performancewise.
1142 (defun leading-component-blocks (component)
1143   (declare (type component component))
1144   (flet ((loopy-p (block)
1145            (let ((n (block-number block)))
1146              (dolist (pred (block-pred block))
1147                (unless (< n (block-number pred))
1148                  (return t))))))
1149     (let ((leading-blocks ())
1150           (rest-of-blocks ())
1151           (seen-loop-p ()))
1152       (do-blocks (block component)
1153         (when (and (not seen-loop-p) (loopy-p block))
1154           (setq seen-loop-p t))
1155         (if seen-loop-p
1156             (push block rest-of-blocks)
1157             (push block leading-blocks)))
1158       (values (nreverse leading-blocks) (nreverse rest-of-blocks)))))
1159
1160 ;;; Append OBJ to the end of LIST as if by NCONC but only if it is not
1161 ;;; a member already.
1162 (defun nconc-new (obj list)
1163   (do ((x list (cdr x))
1164        (prev nil x))
1165       ((endp x) (if prev
1166                     (progn
1167                       (setf (cdr prev) (list obj))
1168                       list)
1169                     (list obj)))
1170     (when (eql (car x) obj)
1171       (return-from nconc-new list))))
1172
1173 (defun find-and-propagate-constraints (component)
1174   (let ((blocks-to-process ()))
1175     (flet ((enqueue (blocks)
1176              (dolist (block blocks)
1177                (setq blocks-to-process (nconc-new block blocks-to-process)))))
1178       (multiple-value-bind (leading-blocks rest-of-blocks)
1179           (leading-component-blocks component)
1180         ;; Update every block once to account for changes in the
1181         ;; IR1. The constraints of the lead blocks cannot be changed
1182         ;; after the first pass so we might as well use them and skip
1183         ;; USE-RESULT-CONSTRAINTS later.
1184         (dolist (block leading-blocks)
1185           (setf (block-in block) (compute-block-in block))
1186           (find-block-type-constraints block t))
1187         (setq blocks-to-process (copy-list rest-of-blocks))
1188         ;; The rest of the blocks.
1189         (dolist (block rest-of-blocks)
1190           (aver (eq block (pop blocks-to-process)))
1191           (setf (block-in block) (compute-block-in block))
1192           (enqueue (find-block-type-constraints block nil)))
1193         ;; Propagate constraints
1194         (loop for block = (pop blocks-to-process)
1195               while block do
1196               (unless (eq block (component-tail component))
1197                 (when (update-block-in block)
1198                   (enqueue (find-block-type-constraints block nil)))))
1199         rest-of-blocks))))
1200
1201 (defun constraint-propagate (component)
1202   (declare (type component component))
1203   (init-var-constraints component)
1204
1205   (unless (block-out (component-head component))
1206     (setf (block-out (component-head component)) (make-conset)))
1207
1208   (dolist (block (find-and-propagate-constraints component))
1209     (unless (block-delete-p block)
1210       (use-result-constraints block)))
1211
1212   (values))