1.0.23.68: Cleanups in constraint propagation.
[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   (defmacro do-conset-elements ((constraint conset &optional result) &body body)
157     (with-unique-names (vector index start end
158                                ignore constraint-universe-end)
159       (let* ((constraint-universe #+sb-xc-host '*constraint-universe*
160                                   #-sb-xc-host (gensym))
161              (with-array-data
162                 #+sb-xc-host '(progn)
163                 #-sb-xc-host `(with-array-data
164                                   ((,constraint-universe *constraint-universe*)
165                                    (,ignore 0) (,constraint-universe-end nil)
166                                    :check-fill-pointer t)
167                                 (declare (ignore ,ignore))
168                                 (aver (<= ,end ,constraint-universe-end)))))
169         `(let* ((,vector (conset-vector ,conset))
170                (,start (conset-min ,conset))
171                (,end (min (conset-max ,conset) (length ,vector))))
172           (,@with-array-data
173             (do ((,index ,start (1+ ,index))) ((>= ,index ,end) ,result)
174               (when (plusp (sbit ,vector ,index))
175                 (let ((,constraint (elt ,constraint-universe ,index)))
176                   ,@body))))))))
177
178   ;; Oddly, iterating just between the maximum of the two sets' minima
179   ;; and the minimum of the sets' maxima slowed down CP.
180   (defmacro do-conset-intersection
181       ((constraint conset1 conset2 &optional result) &body body)
182     `(do-conset-elements (,constraint ,conset1 ,result)
183        (when (conset-member ,constraint ,conset2)
184          ,@body)))
185
186   (defun conset-empty (conset)
187     (or (= (conset-min conset) (conset-max conset))
188         ;; TODO: I bet FIND on bit-vectors can be optimized, if it
189         ;; isn't.
190         (not (find 1 (conset-vector conset)
191                    :start (conset-min conset)
192                    ;; By inspection, supplying :END here breaks the
193                    ;; build with a "full call to
194                    ;; DATA-VECTOR-REF-WITH-OFFSET" in the
195                    ;; cross-compiler.  If that should change, add
196                    ;; :end (conset-max conset)
197                    ))))
198
199   (defun copy-conset (conset)
200     (let ((ret (%copy-conset conset)))
201       (setf (conset-vector ret) (copy-seq (conset-vector conset)))
202       ret))
203
204   (defun %conset-grow (conset new-size)
205     (declare (index new-size))
206     (setf (conset-vector conset)
207           (replace (the simple-bit-vector
208                      (make-array
209                       (ash 1 (integer-length (1- new-size)))
210                       :element-type 'bit
211                       :initial-element 0))
212                    (the simple-bit-vector
213                      (conset-vector conset)))))
214
215   (declaim (inline conset-grow))
216   (defun conset-grow (conset new-size)
217     (declare (index new-size))
218     (when (< (length (conset-vector conset)) new-size)
219       (%conset-grow conset new-size))
220     (values))
221
222   (defun conset-member (constraint conset)
223     (let ((number (%constraint-number constraint))
224           (vector (conset-vector conset)))
225       (when (< number (length vector))
226         (plusp (sbit vector number)))))
227
228   (defun conset-adjoin (constraint conset)
229     (prog1
230       (not (conset-member constraint conset))
231       (let ((number (%constraint-number constraint)))
232         (conset-grow conset (1+ number))
233         (setf (sbit (conset-vector conset) number) 1)
234         (setf (conset-min conset) (min number (conset-min conset)))
235         (when (>= number (conset-max conset))
236           (setf (conset-max conset) (1+ number))))))
237
238   (defun conset= (conset1 conset2)
239     (let* ((vector1 (conset-vector conset1))
240            (vector2 (conset-vector conset2))
241            (length1 (length vector1))
242            (length2 (length vector2)))
243       (if (= length1 length2)
244           ;; When the lengths are the same, we can rely on EQUAL being
245           ;; nicely optimized on bit-vectors.
246           (equal vector1 vector2)
247           (multiple-value-bind (shorter longer)
248               (if (< length1 length2)
249                   (values vector1 vector2)
250                   (values vector2 vector1))
251             ;; FIXME: make MISMATCH fast on bit-vectors.
252             (dotimes (index (length shorter))
253               (when (/= (sbit vector1 index) (sbit vector2 index))
254                 (return-from conset= nil)))
255             (if (find 1 longer :start (length shorter))
256                 nil
257                 t)))))
258
259   (macrolet
260       ((defconsetop (name bit-op)
261            `(defun ,name (conset-1 conset-2)
262               (declare (optimize (speed 3) (safety 0)))
263               (let* ((size-1 (length (conset-vector conset-1)))
264                      (size-2 (length (conset-vector conset-2)))
265                      (new-size (max size-1 size-2)))
266                 (conset-grow conset-1 new-size)
267                 (conset-grow conset-2 new-size))
268               (let ((vector1 (conset-vector conset-1))
269                     (vector2 (conset-vector conset-2)))
270                 (declare (simple-bit-vector vector1 vector2))
271                 (setf (conset-vector conset-1) (,bit-op vector1 vector2 t))
272                 ;; Update the extrema.
273                 ,(ecase name
274                    ((conset-union)
275                     `(setf (conset-min conset-1)
276                            (min (conset-min conset-1)
277                                 (conset-min conset-2))
278                            (conset-max conset-1)
279                            (max (conset-max conset-1)
280                                 (conset-max conset-2))))
281                    ((conset-intersection)
282                     `(let ((start (max (conset-min conset-1)
283                                        (conset-min conset-2)))
284                            (end (min (conset-max conset-1)
285                                      (conset-max conset-2))))
286                        (setf (conset-min conset-1)
287                              (if (> start end)
288                                  0
289                                  (or (position 1 (conset-vector conset-1)
290                                                :start start :end end)
291                                      0))
292                              (conset-max conset-1)
293                              (if (> start end)
294                                  0
295                                  (let ((position
296                                         (position
297                                          1 (conset-vector conset-1)
298                                          :start start :end end :from-end t)))
299                                    (if position
300                                        (1+ position)
301                                        0))))))
302                    ((conset-difference)
303                     `(setf (conset-min conset-1)
304                            (or (position 1 (conset-vector conset-1)
305                                          :start (conset-min conset-1)
306                                          :end (conset-max conset-1))
307                                0)
308                            (conset-max conset-1)
309                            (let ((position
310                                   (position
311                                    1 (conset-vector conset-1)
312                                    :start (conset-min conset-1)
313                                    :end (conset-max conset-1)
314                                    :from-end t)))
315                              (if position
316                                  (1+ position)
317                                  0))))))
318               (values))))
319     (defconsetop conset-union bit-ior)
320     (defconsetop conset-intersection bit-and)
321     (defconsetop conset-difference bit-andc2)))
322 \f
323 (defun find-constraint (kind x y not-p)
324   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
325   (etypecase y
326     (ctype
327      (do-conset-elements (con (lambda-var-constraints x) nil)
328        (when (and (eq (constraint-kind con) kind)
329                   (eq (constraint-not-p con) not-p)
330                   (type= (constraint-y con) y))
331          (return con))))
332     ((or lvar constant)
333      (do-conset-elements (con (lambda-var-constraints x) nil)
334        (when (and (eq (constraint-kind con) kind)
335                   (eq (constraint-not-p con) not-p)
336                   (eq (constraint-y con) y))
337          (return con))))
338     (lambda-var
339      (do-conset-elements (con (lambda-var-constraints x) nil)
340        (when (and (eq (constraint-kind con) kind)
341                   (eq (constraint-not-p con) not-p)
342                   (let ((cx (constraint-x con)))
343                     (eq (if (eq cx x)
344                             (constraint-y con)
345                             cx)
346                         y)))
347          (return con))))))
348
349 ;;; Return a constraint for the specified arguments. We only create a
350 ;;; new constraint if there isn't already an equivalent old one,
351 ;;; guaranteeing that all equivalent constraints are EQ. This
352 ;;; shouldn't be called on LAMBDA-VARs with no CONSTRAINTS set.
353 (defun find-or-create-constraint (kind x y not-p)
354   (declare (type lambda-var x) (type constraint-y y) (type boolean not-p))
355   (or (find-constraint kind x y not-p)
356       (let ((new (make-constraint (length *constraint-universe*)
357                                   kind x y not-p)))
358         (vector-push-extend new *constraint-universe*
359                             (* 2 (length *constraint-universe*)))
360         (conset-adjoin new (lambda-var-constraints x))
361         (when (lambda-var-p y)
362           (conset-adjoin new (lambda-var-constraints y)))
363         new)))
364
365 ;;; If REF is to a LAMBDA-VAR with CONSTRAINTs (i.e. we can do flow
366 ;;; analysis on it), then return the LAMBDA-VAR, otherwise NIL.
367 #!-sb-fluid (declaim (inline ok-ref-lambda-var))
368 (defun ok-ref-lambda-var (ref)
369   (declare (type ref ref))
370   (let ((leaf (ref-leaf ref)))
371     (when (and (lambda-var-p leaf)
372                (lambda-var-constraints leaf))
373       leaf)))
374
375 ;;; See if LVAR's single USE is a REF to a LAMBDA-VAR and they are EQL
376 ;;; according to CONSTRAINTS. Return LAMBDA-VAR if so.
377 (defun ok-lvar-lambda-var (lvar constraints)
378   (declare (type lvar lvar))
379   (let ((use (lvar-uses lvar)))
380     (cond ((ref-p use)
381            (let ((lambda-var (ok-ref-lambda-var use)))
382              (when lambda-var
383                (let ((constraint (find-constraint 'eql lambda-var lvar nil)))
384                  (when (and constraint (conset-member constraint constraints))
385                    lambda-var)))))
386           ((cast-p use)
387            (ok-lvar-lambda-var (cast-value use) constraints)))))
388
389 (defmacro do-eql-vars ((symbol (var constraints) &optional result) &body body)
390   (once-only ((var var))
391     `(let ((,symbol ,var))
392        (flet ((body-fun ()
393                 ,@body))
394          (body-fun)
395          (do-conset-elements (con ,constraints ,result)
396            (let ((other (and (eq (constraint-kind con) 'eql)
397                              (eq (constraint-not-p con) nil)
398                              (cond ((eq ,var (constraint-x con))
399                                     (constraint-y con))
400                                    ((eq ,var (constraint-y con))
401                                     (constraint-x con))
402                                    (t
403                                     nil)))))
404              (when other
405                (setq ,symbol other)
406                (when (lambda-var-p ,symbol)
407                  (body-fun)))))))))
408
409 ;;;; Searching constraints
410
411 ;;; Add the indicated test constraint to BLOCK. We don't add the
412 ;;; constraint if the block has multiple predecessors, since it only
413 ;;; holds on this particular path.
414 (defun add-test-constraint (fun x y not-p constraints target)
415   (cond ((and (eq 'eql fun) (lambda-var-p y) (not not-p))
416          (add-eql-var-var-constraint x y constraints target))
417         (t
418          (do-eql-vars (x (x constraints))
419            (let ((con (find-or-create-constraint fun x y not-p)))
420              (conset-adjoin con target)))))
421   (values))
422
423 ;;; Add complementary constraints to the consequent and alternative
424 ;;; blocks of IF. We do nothing if X is NIL.
425 (defun add-complement-constraints (fun x y not-p constraints
426                                    consequent-constraints
427                                    alternative-constraints)
428   (when x
429     (add-test-constraint fun x y not-p constraints
430                          consequent-constraints)
431     (add-test-constraint fun x y (not not-p) constraints
432                          alternative-constraints))
433   (values))
434
435 ;;; Add test constraints to the consequent and alternative blocks of
436 ;;; the test represented by USE.
437 (defun add-test-constraints (use if constraints)
438   (declare (type node use) (type cif if))
439   ;; Note: Even if we do (IF test exp exp) => (PROGN test exp)
440   ;; optimization, the *MAX-OPTIMIZE-ITERATIONS* cutoff means that we
441   ;; can't guarantee that the optimization will be done, so we still
442   ;; need to avoid barfing on this case.
443   (unless (eq (if-consequent if) (if-alternative if))
444     (let ((consequent-constraints (make-conset))
445           (alternative-constraints (make-conset)))
446       (macrolet ((add (fun x y not-p)
447                    `(add-complement-constraints ,fun ,x ,y ,not-p
448                                                 constraints
449                                                 consequent-constraints
450                                                 alternative-constraints)))
451         (typecase use
452           (ref
453            (add 'typep (ok-lvar-lambda-var (ref-lvar use) constraints)
454                 (specifier-type 'null) t))
455           (combination
456            (unless (eq (combination-kind use)
457                        :error)
458              (let ((name (lvar-fun-name
459                           (basic-combination-fun use)))
460                    (args (basic-combination-args use)))
461                (case name
462                  ((%typep %instance-typep)
463                   (let ((type (second args)))
464                     (when (constant-lvar-p type)
465                       (let ((val (lvar-value type)))
466                         (add 'typep
467                              (ok-lvar-lambda-var (first args) constraints)
468                              (if (ctype-p val)
469                                  val
470                                  (specifier-type val))
471                              nil)))))
472                  ((eq eql)
473                   (let* ((arg1 (first args))
474                          (var1 (ok-lvar-lambda-var arg1 constraints))
475                          (arg2 (second args))
476                          (var2 (ok-lvar-lambda-var arg2 constraints)))
477                     ;; The code below assumes that the constant is the
478                     ;; second argument in case of variable to constant
479                     ;; comparision which is sometimes true (see source
480                     ;; transformations for EQ, EQL and CHAR=). Fixing
481                     ;; that would result in more constant substitutions
482                     ;; which is not a universally good thing, thus the
483                     ;; unnatural asymmetry of the tests.
484                     (cond ((not var1)
485                            (when var2
486                              (add-test-constraint 'typep var2 (lvar-type arg1)
487                                                   nil constraints
488                                                   consequent-constraints)))
489                           (var2
490                            (add 'eql var1 var2 nil))
491                           ((constant-lvar-p arg2)
492                            (add 'eql var1 (ref-leaf (principal-lvar-use arg2))
493                                 nil))
494                           (t
495                            (add-test-constraint 'typep var1 (lvar-type arg2)
496                                                 nil constraints
497                                                 consequent-constraints)))))
498                  ((< >)
499                   (let* ((arg1 (first args))
500                          (var1 (ok-lvar-lambda-var arg1 constraints))
501                          (arg2 (second args))
502                          (var2 (ok-lvar-lambda-var arg2 constraints)))
503                     (when var1
504                       (add name var1 (lvar-type arg2) nil))
505                     (when var2
506                       (add (if (eq name '<) '> '<) var2 (lvar-type arg1) nil))))
507                  (t
508                   (let ((ptype (gethash name *backend-predicate-types*)))
509                     (when ptype
510                       (add 'typep (ok-lvar-lambda-var (first args) constraints)
511                            ptype nil))))))))))
512       (values consequent-constraints alternative-constraints))))
513
514 ;;;; Applying constraints
515
516 ;;; Return true if X is an integer NUMERIC-TYPE.
517 (defun integer-type-p (x)
518   (declare (type ctype x))
519   (and (numeric-type-p x)
520        (eq (numeric-type-class x) 'integer)
521        (eq (numeric-type-complexp x) :real)))
522
523 ;;; Given that an inequality holds on values of type X and Y, return a
524 ;;; new type for X. If GREATER is true, then X was greater than Y,
525 ;;; otherwise less. If OR-EQUAL is true, then the inequality was
526 ;;; inclusive, i.e. >=.
527 ;;;
528 ;;; If GREATER (or not), then we max (or min) in Y's lower (or upper)
529 ;;; bound into X and return that result. If not OR-EQUAL, we can go
530 ;;; one greater (less) than Y's bound.
531 (defun constrain-integer-type (x y greater or-equal)
532   (declare (type numeric-type x y))
533   (flet ((exclude (x)
534            (cond ((not x) nil)
535                  (or-equal x)
536                  (greater (1+ x))
537                  (t (1- x))))
538          (bound (x)
539            (if greater (numeric-type-low x) (numeric-type-high x))))
540     (let* ((x-bound (bound x))
541            (y-bound (exclude (bound y)))
542            (new-bound (cond ((not x-bound) y-bound)
543                             ((not y-bound) x-bound)
544                             (greater (max x-bound y-bound))
545                             (t (min x-bound y-bound)))))
546       (if greater
547           (modified-numeric-type x :low new-bound)
548           (modified-numeric-type x :high new-bound)))))
549
550 ;;; Return true if X is a float NUMERIC-TYPE.
551 (defun float-type-p (x)
552   (declare (type ctype x))
553   (and (numeric-type-p x)
554        (eq (numeric-type-class x) 'float)
555        (eq (numeric-type-complexp x) :real)))
556
557 ;;; Exactly the same as CONSTRAIN-INTEGER-TYPE, but for float numbers.
558 (defun constrain-float-type (x y greater or-equal)
559   (declare (type numeric-type x y))
560   (declare (ignorable x y greater or-equal)) ; for CROSS-FLOAT-INFINITY-KLUDGE
561
562   (aver (eql (numeric-type-class x) 'float))
563   (aver (eql (numeric-type-class y) 'float))
564   #+sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
565   x
566   #-sb-xc-host                    ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
567   (labels ((exclude (x)
568              (cond ((not x) nil)
569                    (or-equal x)
570                    (t
571                     (if (consp x)
572                         x
573                         (list x)))))
574            (bound (x)
575              (if greater (numeric-type-low x) (numeric-type-high x)))
576            (tighter-p (x ref)
577              (cond ((null x) nil)
578                    ((null ref) t)
579                    ((and or-equal
580                          (= (type-bound-number x) (type-bound-number ref)))
581                     ;; X is tighter if REF is not an open bound and X is
582                     (and (not (consp ref)) (consp x)))
583                    (greater
584                     (< (type-bound-number ref) (type-bound-number x)))
585                    (t
586                     (> (type-bound-number ref) (type-bound-number x))))))
587     (let* ((x-bound (bound x))
588            (y-bound (exclude (bound y)))
589            (new-bound (cond ((not x-bound)
590                              y-bound)
591                             ((not y-bound)
592                              x-bound)
593                             ((tighter-p y-bound x-bound)
594                              y-bound)
595                             (t
596                              x-bound))))
597       (if greater
598           (modified-numeric-type x :low new-bound)
599           (modified-numeric-type x :high new-bound)))))
600
601 ;;; Given the set of CONSTRAINTS for a variable and the current set of
602 ;;; restrictions from flow analysis IN, set the type for REF
603 ;;; accordingly.
604 (defun constrain-ref-type (ref constraints in)
605   (declare (type ref ref) (type conset constraints in))
606   ;; KLUDGE: The NOT-SET and NOT-FPZ here are so that we don't need to
607   ;; cons up endless union types when propagating large number of EQL
608   ;; constraints -- eg. from large CASE forms -- instead we just
609   ;; directly accumulate one XSET, and a set of fp zeroes, which we at
610   ;; the end turn into a MEMBER-TYPE.
611   ;;
612   ;; Since massive symbol cases are an especially atrocious pattern
613   ;; and the (NOT (MEMBER ...ton of symbols...)) will never turn into
614   ;; a more useful type, don't propagate their negation except for NIL
615   ;; unless SPEED > COMPILATION-SPEED.
616   (let ((res (single-value-type (node-derived-type ref)))
617         (constrain-symbols (policy ref (> speed compilation-speed)))
618         (not-set (alloc-xset))
619         (not-fpz nil)
620         (not-res *empty-type*)
621         (leaf (ref-leaf ref)))
622     (flet ((note-not (x)
623              (if (fp-zero-p x)
624                  (push x not-fpz)
625                  (when (or constrain-symbols (null x) (not (symbolp x)))
626                    (add-to-xset x not-set)))))
627       ;; KLUDGE: the implementations of DO-CONSET-INTERSECTION will
628       ;; probably run faster when the smaller set comes first, so
629       ;; don't change the order here.
630       (do-conset-intersection (con constraints in)
631         (let* ((x (constraint-x con))
632                (y (constraint-y con))
633                (not-p (constraint-not-p con))
634                (other (if (eq x leaf) y x))
635                (kind (constraint-kind con)))
636           (case kind
637             (typep
638              (if not-p
639                  (if (member-type-p other)
640                      (mapc-member-type-members #'note-not other)
641                      (setq not-res (type-union not-res other)))
642                  (setq res (type-approx-intersection2 res other))))
643             (eql
644              (unless (lvar-p other)
645                (let ((other-type (leaf-type other)))
646                  (if not-p
647                      (when (and (constant-p other)
648                                 (member-type-p other-type))
649                        (note-not (constant-value other)))
650                      (let ((leaf-type (leaf-type leaf)))
651                        (cond
652                          ((or (constant-p other)
653                               (and (leaf-refs other) ; protect from
654                                         ; deleted vars
655                                    (csubtypep other-type leaf-type)
656                                    (not (type= other-type leaf-type))))
657                           (change-ref-leaf ref other)
658                           (when (constant-p other) (return)))
659                          (t
660                           (setq res (type-approx-intersection2
661                                      res other-type)))))))))
662             ((< >)
663              (cond
664                ((and (integer-type-p res) (integer-type-p y))
665                 (let ((greater (eq kind '>)))
666                   (let ((greater (if not-p (not greater) greater)))
667                     (setq res
668                           (constrain-integer-type res y greater not-p)))))
669                ((and (float-type-p res) (float-type-p y))
670                 (let ((greater (eq kind '>)))
671                   (let ((greater (if not-p (not greater) greater)))
672                     (setq res
673                           (constrain-float-type res y greater not-p)))))))))))
674     (cond ((and (if-p (node-dest ref))
675                 (or (xset-member-p nil not-set)
676                     (csubtypep (specifier-type 'null) not-res)))
677            (setf (node-derived-type ref) *wild-type*)
678            (change-ref-leaf ref (find-constant t)))
679           (t
680            (setf not-res
681                  (type-union not-res (make-member-type :xset not-set :fp-zeroes not-fpz)))
682            (derive-node-type ref
683                              (make-single-value-type
684                               (or (type-difference res not-res)
685                                   res)))
686            (maybe-terminate-block ref nil))))
687   (values))
688
689 ;;;; Flow analysis
690
691 (defun maybe-add-eql-var-lvar-constraint (ref gen)
692   (let ((lvar (ref-lvar ref))
693         (leaf (ref-leaf ref)))
694     (when (and (lambda-var-p leaf) lvar)
695       (conset-adjoin (find-or-create-constraint 'eql leaf lvar nil)
696                      gen))))
697
698 ;;; Copy all CONSTRAINTS involving FROM-VAR - except the (EQL VAR
699 ;;; LVAR) ones - to all of the variables in the VARS list.
700 (defun inherit-constraints (vars from-var constraints target)
701   (do-conset-elements (con constraints)
702     ;; Constant substitution is controversial.
703     (unless (constant-p (constraint-y con))
704       (dolist (var vars)
705         (let ((eq-x (eq from-var (constraint-x con)))
706               (eq-y (eq from-var (constraint-y con))))
707           (when (or (and eq-x (not (lvar-p (constraint-y con))))
708                     eq-y)
709             (conset-adjoin (find-or-create-constraint
710                             (constraint-kind con)
711                             (if eq-x var (constraint-x con))
712                             (if eq-y var (constraint-y con))
713                             (constraint-not-p con))
714                            target)))))))
715
716 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR1 and VAR2 and
717 ;; inherit each other's constraints.
718 (defun add-eql-var-var-constraint (var1 var2 constraints
719                                    &optional (target constraints))
720   (let ((con (find-or-create-constraint 'eql var1 var2 nil)))
721     (when (conset-adjoin con target)
722       (collect ((eql1) (eql2))
723         (do-eql-vars (var1 (var1 constraints))
724           (eql1 var1))
725         (do-eql-vars (var2 (var2 constraints))
726           (eql2 var2))
727         (inherit-constraints (eql1) var2 constraints target)
728         (inherit-constraints (eql2) var1 constraints target))
729       t)))
730
731 ;; Add an (EQL LAMBDA-VAR LAMBDA-VAR) constraint on VAR and LVAR's
732 ;; LAMBDA-VAR if possible.
733 (defun maybe-add-eql-var-var-constraint (var lvar constraints
734                                          &optional (target constraints))
735   (declare (type lambda-var var) (type lvar lvar))
736   (let ((lambda-var (ok-lvar-lambda-var lvar constraints)))
737     (when lambda-var
738       (add-eql-var-var-constraint var lambda-var constraints target))))
739
740 ;;; Local propagation
741 ;;; -- [TODO: For any LAMBDA-VAR ref with a type check, add that
742 ;;;    constraint.]
743 ;;; -- For any LAMBDA-VAR set, delete all constraints on that var; add
744 ;;;    a type constraint based on the new value type.
745 (declaim (ftype (function (cblock conset boolean)
746                           conset)
747                 constraint-propagate-in-block))
748 (defun constraint-propagate-in-block (block gen preprocess-refs-p)
749   (do-nodes (node lvar block)
750     (typecase node
751       (bind
752        (let ((fun (bind-lambda node)))
753          (when (eq (functional-kind fun) :let)
754            (loop with call = (lvar-dest (node-lvar (first (lambda-refs fun))))
755                  for var in (lambda-vars fun)
756                  and val in (combination-args call)
757                  when (and val (lambda-var-constraints var))
758                  do (let* ((type (lvar-type val))
759                            (con (find-or-create-constraint 'typep var type
760                                                            nil)))
761                       (conset-adjoin con gen))
762                  (maybe-add-eql-var-var-constraint var val gen)))))
763       (ref
764        (when (ok-ref-lambda-var node)
765          (maybe-add-eql-var-lvar-constraint node gen)
766          (when preprocess-refs-p
767            (let* ((var (ref-leaf node))
768                   (con (lambda-var-constraints var)))
769              (constrain-ref-type node con gen)))))
770       (cast
771        (let ((lvar (cast-value node)))
772          (let ((var (ok-lvar-lambda-var lvar gen)))
773            (when var
774              (let ((atype (single-value-type (cast-derived-type node)))) ;FIXME
775                (do-eql-vars (var (var gen))
776                  (let ((con (find-or-create-constraint 'typep var atype nil)))
777                    (conset-adjoin con gen))))))))
778       (cset
779        (binding* ((var (set-var node))
780                   (nil (lambda-var-p var) :exit-if-null)
781                   (cons (lambda-var-constraints var) :exit-if-null))
782          (conset-difference gen cons)
783          (let* ((type (single-value-type (node-derived-type node)))
784                 (con (find-or-create-constraint 'typep var type nil)))
785            (conset-adjoin con gen))
786          (maybe-add-eql-var-var-constraint var (set-value node) gen)))))
787   gen)
788
789 (defun constraint-propagate-if (block gen)
790   (let ((node (block-last block)))
791     (when (if-p node)
792       (let ((use (lvar-uses (if-test node))))
793         (when (node-p use)
794           (add-test-constraints use node gen))))))
795
796 ;;; Starting from IN compute OUT and (consequent/alternative
797 ;;; constraints if the block ends with and IF). Return the list of
798 ;;; successors that may need to be recomputed.
799 (defun find-block-type-constraints (block final-pass-p)
800   (declare (type cblock block))
801   (let ((gen (constraint-propagate-in-block
802               block
803               (if final-pass-p
804                   (block-in block)
805                   (copy-conset (block-in block)))
806               final-pass-p)))
807     (setf (block-gen block) gen)
808     (multiple-value-bind (consequent-constraints alternative-constraints)
809         (constraint-propagate-if block gen)
810       (if consequent-constraints
811           (let* ((node (block-last block))
812                  (old-consequent-constraints (if-consequent-constraints node))
813                  (old-alternative-constraints (if-alternative-constraints node))
814                  (succ ()))
815             ;; Add the consequent and alternative constraints to GEN.
816             (cond ((conset-empty consequent-constraints)
817                    (setf (if-consequent-constraints node) gen)
818                    (setf (if-alternative-constraints node) gen))
819                   (t
820                    (setf (if-consequent-constraints node) (copy-conset gen))
821                    (conset-union (if-consequent-constraints node)
822                                  consequent-constraints)
823                    (setf (if-alternative-constraints node) gen)
824                    (conset-union (if-alternative-constraints node)
825                                  alternative-constraints)))
826             ;; Has the consequent been changed?
827             (unless (and old-consequent-constraints
828                          (conset= (if-consequent-constraints node)
829                                   old-consequent-constraints))
830               (push (if-consequent node) succ))
831             ;; Has the alternative been changed?
832             (unless (and old-alternative-constraints
833                          (conset= (if-alternative-constraints node)
834                                   old-alternative-constraints))
835               (push (if-alternative node) succ))
836             succ)
837           ;; There is no IF.
838           (unless (and (block-out block)
839                        (conset= gen (block-out block)))
840             (setf (block-out block) gen)
841             (block-succ block))))))
842
843 ;;; Deliver the results of constraint propagation to REFs in BLOCK.
844 ;;; During this pass, we also do local constraint propagation by
845 ;;; adding in constraints as we see them during the pass through the
846 ;;; block.
847 (defun use-result-constraints (block)
848   (declare (type cblock block))
849   (constraint-propagate-in-block block (block-in block) t))
850
851 ;;; Give an empty constraints set to any var that doesn't have one and
852 ;;; isn't a set closure var. Since a var that we previously rejected
853 ;;; looks identical to one that is new, so we optimistically keep
854 ;;; hoping that vars stop being closed over or lose their sets.
855 (defun init-var-constraints (component)
856   (declare (type component component))
857   (dolist (fun (component-lambdas component))
858     (flet ((frob (x)
859              (dolist (var (lambda-vars x))
860                (unless (lambda-var-constraints var)
861                  (when (or (null (lambda-var-sets var))
862                            (not (closure-var-p var)))
863                    (setf (lambda-var-constraints var) (make-conset)))))))
864       (frob fun)
865       (dolist (let (lambda-lets fun))
866         (frob let)))))
867
868 ;;; Return the constraints that flow from PRED to SUCC. This is
869 ;;; BLOCK-OUT unless PRED ends with an IF and test constraints were
870 ;;; added.
871 (defun block-out-for-successor (pred succ)
872   (declare (type cblock pred succ))
873   (let ((last (block-last pred)))
874     (or (when (if-p last)
875           (cond ((eq succ (if-consequent last))
876                  (if-consequent-constraints last))
877                 ((eq succ (if-alternative last))
878                  (if-alternative-constraints last))))
879         (block-out pred))))
880
881 (defun compute-block-in (block)
882   (let ((in nil))
883     (dolist (pred (block-pred block))
884       ;; If OUT has not been calculated, assume it to be the universal
885       ;; set.
886       (let ((out (block-out-for-successor pred block)))
887         (when out
888           (if in
889               (conset-intersection in out)
890               (setq in (copy-conset out))))))
891     (or in (make-conset))))
892
893 (defun update-block-in (block)
894   (let ((in (compute-block-in block)))
895     (cond ((and (block-in block) (conset= in (block-in block)))
896            nil)
897           (t
898            (setf (block-in block) in)))))
899
900 ;;; Return two lists: one of blocks that precede all loops and
901 ;;; therefore require only one constraint propagation pass and the
902 ;;; rest. This implementation does not find all such blocks.
903 ;;;
904 ;;; A more complete implementation would be:
905 ;;;
906 ;;;     (do-blocks (block component)
907 ;;;       (if (every #'(lambda (pred)
908 ;;;                      (or (member pred leading-blocks)
909 ;;;                          (eq pred head)))
910 ;;;                  (block-pred block))
911 ;;;           (push block leading-blocks)
912 ;;;           (push block rest-of-blocks)))
913 ;;;
914 ;;; Trailing blocks that succeed all loops could be found and handled
915 ;;; similarly. In practice though, these more complex solutions are
916 ;;; slightly worse performancewise.
917 (defun leading-component-blocks (component)
918   (declare (type component component))
919   (flet ((loopy-p (block)
920            (let ((n (block-number block)))
921              (dolist (pred (block-pred block))
922                (unless (< n (block-number pred))
923                  (return t))))))
924     (let ((leading-blocks ())
925           (rest-of-blocks ())
926           (seen-loop-p ()))
927       (do-blocks (block component)
928         (when (and (not seen-loop-p) (loopy-p block))
929           (setq seen-loop-p t))
930         (if seen-loop-p
931             (push block rest-of-blocks)
932             (push block leading-blocks)))
933       (values (nreverse leading-blocks) (nreverse rest-of-blocks)))))
934
935 ;;; Append OBJ to the end of LIST as if by NCONC but only if it is not
936 ;;; a member already.
937 (defun nconc-new (obj list)
938   (do ((x list (cdr x))
939        (prev nil x))
940       ((endp x) (if prev
941                     (progn
942                       (setf (cdr prev) (list obj))
943                       list)
944                     (list obj)))
945     (when (eql (car x) obj)
946       (return-from nconc-new list))))
947
948 (defun find-and-propagate-constraints (component)
949   (let ((blocks-to-process ()))
950     (flet ((enqueue (blocks)
951              (dolist (block blocks)
952                (setq blocks-to-process (nconc-new block blocks-to-process)))))
953       (multiple-value-bind (leading-blocks rest-of-blocks)
954           (leading-component-blocks component)
955         ;; Update every block once to account for changes in the
956         ;; IR1. The constraints of the lead blocks cannot be changed
957         ;; after the first pass so we might as well use them and skip
958         ;; USE-RESULT-CONSTRAINTS later.
959         (dolist (block leading-blocks)
960           (setf (block-in block) (compute-block-in block))
961           (find-block-type-constraints block t))
962         (setq blocks-to-process (copy-list rest-of-blocks))
963         ;; The rest of the blocks.
964         (dolist (block rest-of-blocks)
965           (aver (eq block (pop blocks-to-process)))
966           (setf (block-in block) (compute-block-in block))
967           (enqueue (find-block-type-constraints block nil)))
968         ;; Propagate constraints
969         (loop for block = (pop blocks-to-process)
970               while block do
971               (unless (eq block (component-tail component))
972                 (when (update-block-in block)
973                   (enqueue (find-block-type-constraints block nil)))))
974         rest-of-blocks))))
975
976 (defun constraint-propagate (component)
977   (declare (type component component))
978   (init-var-constraints component)
979
980   (unless (block-out (component-head component))
981     (setf (block-out (component-head component)) (make-conset)))
982
983   (dolist (block (find-and-propagate-constraints component))
984     (unless (block-delete-p block)
985       (use-result-constraints block)))
986
987   (values))