Initial revision
[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 (in-package "SB!C")
15
16 (file-comment
17   "$Header$")
18
19 (defstruct (constraint
20             (:include sset-element)
21             (:constructor make-constraint (number kind x y not-p)))
22   ;; The kind of constraint we have:
23   ;;
24   ;; TYPEP
25   ;;     X is a LAMBDA-VAR and Y is a CTYPE. The value of X is 
26   ;;     constrained to be of type Y.
27   ;;
28   ;; >, <
29   ;;     X is a lambda-var and Y is a CTYPE. The relation holds 
30   ;;     between X and some object of type Y.
31   ;;
32   ;; EQL
33   ;;     X is a LAMBDA-VAR Y is a LAMBDA-VAR or a CONSTANT. The
34   ;;     relation is asserted to hold.
35   (kind nil :type (member typep < > eql))
36   ;; The operands to the relation.
37   (x nil :type lambda-var)
38   (y nil :type (or ctype lambda-var constant))
39   ;; If true, negates the sense of the constraint, so the relation 
40   ;; does *not* hold.
41   (not-p nil :type boolean))
42
43 (defvar *constraint-number*)
44
45 ;;; Return a constraint for the specified arguments. We only create a
46 ;;; new constraint if there isn't already an equivalent old one,
47 ;;; guaranteeing that all equivalent constraints are EQ. This
48 ;;; shouldn't be called on LAMBDA-VARs with no CONSTRAINTS set.
49 (defun find-constraint (kind x y not-p)
50   (declare (type lambda-var x) (type (or constant lambda-var ctype) y)
51            (type boolean not-p))
52   (or (etypecase y
53         (ctype
54          (do-sset-elements (con (lambda-var-constraints x) nil)
55            (when (and (eq (constraint-kind con) kind)
56                       (eq (constraint-not-p con) not-p)
57                       (type= (constraint-y con) y))
58              (return con))))
59         (constant
60          (do-sset-elements (con (lambda-var-constraints x) nil)
61            (when (and (eq (constraint-kind con) kind)
62                       (eq (constraint-not-p con) not-p)
63                       (eq (constraint-y con) y))
64              (return con))))
65         (lambda-var
66          (do-sset-elements (con (lambda-var-constraints x) nil)
67            (when (and (eq (constraint-kind con) kind)
68                       (eq (constraint-not-p con) not-p)
69                       (let ((cx (constraint-x con)))
70                         (eq (if (eq cx x)
71                                 (constraint-y con)
72                                 cx)
73                             y)))
74              (return con)))))
75       (let ((new (make-constraint (incf *constraint-number*) kind x y not-p)))
76         (sset-adjoin new (lambda-var-constraints x))
77         (when (lambda-var-p y)
78           (sset-adjoin new (lambda-var-constraints y)))
79         new)))
80
81 ;;; If REF is to a LAMBDA-VAR with CONSTRAINTs (i.e. we can do flow
82 ;;; analysis on it), then return the LAMBDA-VAR, otherwise NIL.
83 #!-sb-fluid (declaim (inline ok-ref-lambda-var))
84 (defun ok-ref-lambda-var (ref)
85   (declare (type ref ref))
86   (let ((leaf (ref-leaf ref)))
87     (when (and (lambda-var-p leaf)
88                (lambda-var-constraints leaf))
89       leaf)))
90
91 ;;; If CONT's USE is a REF, then return OK-REF-LAMBDA-VAR of the USE,
92 ;;; otherwise NIL.
93 #!-sb-fluid (declaim (inline ok-cont-lambda-var))
94 (defun ok-cont-lambda-var (cont)
95   (declare (type continuation cont))
96   (let ((use (continuation-use cont)))
97     (when (ref-p use)
98       (ok-ref-lambda-var use))))
99
100 ;;; Add the indicated test constraint to BLOCK, marking the block as
101 ;;; having a new assertion when the constriant was not already
102 ;;; present. We don't add the constraint if the block has multiple
103 ;;; predecessors, since it only holds on this particular path.
104 (defun add-test-constraint (block fun x y not-p)
105   (unless (rest (block-pred block))
106     (let ((con (find-constraint fun x y not-p))
107           (old (or (block-test-constraint block)
108                    (setf (block-test-constraint block) (make-sset)))))
109       (when (sset-adjoin con old)
110         (setf (block-type-asserted block) t))))
111   (values))
112
113 ;;; Add complementary constraints to the consequent and alternative
114 ;;; blocks of IF. We do nothing if X is NIL.
115 #!-sb-fluid (declaim (inline add-complement-constraints))
116 (defun add-complement-constraints (if fun x y not-p)
117   (when x
118     (add-test-constraint (if-consequent if) fun x y not-p)
119     (add-test-constraint (if-alternative if) fun x y (not not-p)))
120   (values))
121
122 ;;; Add test constraints to the consequent and alternative blocks of
123 ;;; the test represented by USE.
124 (defun add-test-constraints (use if)
125   (declare (type node use) (type cif if))
126   (typecase use
127     (ref
128      (add-complement-constraints if 'typep (ok-ref-lambda-var use)
129                                  (specifier-type 'null) t))
130     (combination
131      (let ((name (continuation-function-name
132                   (basic-combination-fun use)))
133            (args (basic-combination-args use)))
134        (case name
135          ((%typep %instance-typep)
136           (let ((type (second args)))
137             (when (constant-continuation-p type)
138               (let ((val (continuation-value type)))
139               (add-complement-constraints if 'typep
140                                           (ok-cont-lambda-var (first args))
141                                           (if (ctype-p val)
142                                               val
143                                               (specifier-type val))
144                                           nil)))))
145          ((eq eql)
146           (let* ((var1 (ok-cont-lambda-var (first args)))
147                  (arg2 (second args))
148                  (var2 (ok-cont-lambda-var arg2)))
149             (cond ((not var1))
150                   (var2
151                    (add-complement-constraints if 'eql var1 var2 nil))
152                   ((constant-continuation-p arg2)
153                    (add-complement-constraints if 'eql var1
154                                                (ref-leaf
155                                                 (continuation-use arg2))
156                                                nil)))))
157          ((< >)
158           (let* ((arg1 (first args))
159                  (var1 (ok-cont-lambda-var arg1))
160                  (arg2 (second args))
161                  (var2 (ok-cont-lambda-var arg2)))
162             (when var1
163               (add-complement-constraints if name var1 (continuation-type arg2)
164                                           nil))
165             (when var2
166               (add-complement-constraints if (if (eq name '<) '> '<)
167                                           var2 (continuation-type arg1)
168                                           nil))))
169          (t
170           (let ((ptype (gethash name *backend-predicate-types*)))
171             (when ptype
172               (add-complement-constraints if 'typep
173                                           (ok-cont-lambda-var (first args))
174                                           ptype nil))))))))
175   (values))
176
177 ;;; Set the TEST-CONSTRAINT in the successors of BLOCK according to
178 ;;; the condition it tests.
179 (defun find-test-constraints (block)
180   (declare (type cblock block))
181   (let ((last (block-last block)))
182     (when (if-p last)
183       (let ((use (continuation-use (if-test last))))
184         (when use
185           (add-test-constraints use last)))))
186
187   (setf (block-test-modified block) nil)
188   (values))
189
190 ;;; Compute the initial flow analysis sets for BLOCK:
191 ;;; -- For any lambda-var ref with a type check, add that constraint.
192 ;;; -- For any lambda-var set, delete all constraints on that var, and add
193 ;;;    those constraints to the set nuked by this block.
194 (defun find-block-type-constraints (block)
195   (declare (type cblock block))
196   (let ((gen (make-sset)))
197     (collect ((kill nil adjoin))
198
199       (let ((test (block-test-constraint block)))
200         (when test
201           (sset-union gen test)))
202
203       (do-nodes (node cont block)
204         (typecase node
205           (ref
206            (when (continuation-type-check cont)
207              (let ((var (ok-ref-lambda-var node)))
208                (when var
209                  (let* ((atype (continuation-derived-type cont))
210                         (con (find-constraint 'typep var atype nil)))
211                    (sset-adjoin con gen))))))
212           (cset
213            (let ((var (set-var node)))
214              (when (lambda-var-p var)
215                (kill var)
216                (let ((cons (lambda-var-constraints var)))
217                  (when cons
218                    (sset-difference gen cons))))))))
219
220       (setf (block-in block) nil)
221       (setf (block-gen block) gen)
222       (setf (block-kill block) (kill))
223       (setf (block-out block) (copy-sset gen))
224       (setf (block-type-asserted block) nil)
225       (values))))
226
227 ;;; Return true if X is an integer NUMERIC-TYPE.
228 (defun integer-type-p (x)
229   (declare (type ctype x))
230   (and (numeric-type-p x)
231        (eq (numeric-type-class x) 'integer)
232        (eq (numeric-type-complexp x) :real)))
233
234 ;;; Given that an inequality holds on values of type X and Y, return a
235 ;;; new type for X. If GREATER is true, then X was greater than Y,
236 ;;; otherwise less. If OR-EQUAL is true, then the inequality was
237 ;;; inclusive, i.e. >=.
238 ;;;
239 ;;; If GREATER (or not), then we max (or min) in Y's lower (or upper)
240 ;;; bound into X and return that result. If not OR-EQUAL, we can go
241 ;;; one greater (less) than Y's bound.
242 (defun constrain-integer-type (x y greater or-equal)
243   (declare (type numeric-type x y))
244   (flet ((exclude (x)
245            (cond ((not x) nil)
246                  (or-equal x)
247                  (greater (1+ x))
248                  (t (1- x))))
249          (bound (x)
250            (if greater (numeric-type-low x) (numeric-type-high x)))
251          (validate (x)
252            (if (and (numeric-type-low x) (numeric-type-high x)
253                     (> (numeric-type-low x) (numeric-type-high x)))
254                *empty-type*
255                x)))
256     (let* ((x-bound (bound x))
257            (y-bound (exclude (bound y)))
258            (new-bound (cond ((not x-bound) y-bound)
259                             ((not y-bound) x-bound)
260                             (greater (max x-bound y-bound))
261                             (t (min x-bound y-bound))))
262            (res (copy-numeric-type x)))
263       (if greater
264           (setf (numeric-type-low res) new-bound)
265           (setf (numeric-type-high res) new-bound))
266       (validate res))))
267
268 ;;; Return true if X is a float NUMERIC-TYPE.
269 (defun float-type-p (x)
270   (declare (type ctype x))
271   (and (numeric-type-p x)
272        (eq (numeric-type-class x) 'float)
273        (eq (numeric-type-complexp x) :real)))
274
275 ;;; Exactly the same as CONSTRAIN-INTEGER-TYPE, but for float numbers.
276 (defun constrain-float-type (x y greater or-equal)
277   (declare (type numeric-type x y))
278   ;; Unless :PROPAGATE-FLOAT-TYPE is in target features, then
279   ;; SB!C::BOUND-VALUE (used in the code below) is not defined, so we
280   ;; just return X without trying to calculate additional constraints.
281   #!-propagate-float-type (declare (ignore y greater or-equal))
282   #!-propagate-float-type x
283   #!+propagate-float-type
284   (labels ((exclude (x)
285              (cond ((not x) nil)
286                    (or-equal x)
287                    (greater
288                     (if (consp x)
289                         (car x)
290                         x))
291                    (t
292                     (if (consp x)
293                         x
294                         (list x)))))
295            (bound (x)
296              (if greater (numeric-type-low x) (numeric-type-high x)))
297            (max-lower-bound (x y)
298              ;; Both x and y are not null. Find the max.
299              (let ((res (max (bound-value x) (bound-value y))))
300                ;; An open lower bound is greater than a close
301                ;; lower bound because the open bound doesn't
302                ;; contain the bound, so choose an open lower
303                ;; bound.
304                (set-bound res (or (consp x) (consp y)))))
305            (min-upper-bound (x y)
306              ;; Same as above, but for the min of upper bounds
307              ;; Both x and y are not null. Find the min.
308              (let ((res (min (bound-value x) (bound-value y))))
309                ;; An open upper bound is less than a closed
310                ;; upper bound because the open bound doesn't
311                ;; contain the bound, so choose an open lower
312                ;; bound.
313                (set-bound res (or (consp x) (consp y)))))
314            (validate (x)
315              (let ((x-lo (numeric-type-low x))
316                    (x-hi (numeric-type-high x)))
317                (if (and x-lo x-hi (> (bound-value x-lo) (bound-value x-hi)))
318                    *empty-type*
319                    x))))
320     (let* ((x-bound (bound x))
321            (y-bound (exclude (bound y)))
322            (new-bound (cond ((not x-bound)
323                              y-bound)
324                             ((not y-bound)
325                              x-bound)
326                             (greater
327                              (max-lower-bound x-bound y-bound))
328                             (t
329                              (min-upper-bound x-bound y-bound))))
330            (res (copy-numeric-type x)))
331       (if greater
332           (setf (numeric-type-low res) new-bound)
333           (setf (numeric-type-high res) new-bound))
334       (validate res))))
335
336 ;;; Given the set of CONSTRAINTS for a variable and the current set of
337 ;;; restrictions from flow analysis IN, set the type for REF
338 ;;; accordingly.
339 (defun constrain-ref-type (ref constraints in)
340   (declare (type ref ref) (type sset constraints in))
341   (let ((var-cons (copy-sset constraints)))
342     (sset-intersection var-cons in)
343     (let ((res (single-value-type (node-derived-type ref)))
344           (not-res *empty-type*)
345           (leaf (ref-leaf ref)))
346       (do-sset-elements (con var-cons)
347         (let* ((x (constraint-x con))
348                (y (constraint-y con))
349                (not-p (constraint-not-p con))
350                (other (if (eq x leaf) y x))
351                (kind (constraint-kind con)))
352           (case kind
353             (typep
354              (if not-p
355                  (setq not-res (type-union not-res other))
356                  (setq res (type-intersection res other))))
357             (eql
358              (let ((other-type (leaf-type other)))
359                (if not-p
360                    (when (and (constant-p other)
361                               (member-type-p other-type))
362                      (setq not-res (type-union not-res other-type)))
363                    (let ((leaf-type (leaf-type leaf)))
364                      (when (or (constant-p other)
365                                (and (csubtypep other-type leaf-type)
366                                     (not (type= other-type leaf-type))))
367                        (change-ref-leaf ref other)
368                        (when (constant-p other) (return)))))))
369             ((< >)
370              (cond ((and (integer-type-p res) (integer-type-p y))
371                     (let ((greater (eq kind '>)))
372                       (let ((greater (if not-p (not greater) greater)))
373                         (setq res
374                               (constrain-integer-type res y greater not-p)))))
375                    #!+constrain-float-type
376                    ((and (float-type-p res) (float-type-p y))
377                     (let ((greater (eq kind '>)))
378                       (let ((greater (if not-p (not greater) greater)))
379                         (setq res
380                               (constrain-float-type res y greater not-p)))))
381                    )))))
382
383       (let* ((cont (node-cont ref))
384              (dest (continuation-dest cont)))
385         (cond ((and (if-p dest)
386                     (csubtypep (specifier-type 'null) not-res)
387                     (eq (continuation-asserted-type cont) *wild-type*))
388                (setf (node-derived-type ref) *wild-type*)
389                (change-ref-leaf ref (find-constant 't)))
390               (t
391                (derive-node-type ref (or (type-difference res not-res)
392                                          res)))))))
393
394   (values))
395
396 ;;; Deliver the results of constraint propagation to REFs in BLOCK.
397 ;;; During this pass, we also do local constraint propagation by
398 ;;; adding in constraints as we seem them during the pass through the
399 ;;; block.
400 (defun use-result-constraints (block)
401   (declare (type cblock block))
402   (let ((in (block-in block)))
403
404     (let ((test (block-test-constraint block)))
405       (when test
406         (sset-union in test)))
407
408     (do-nodes (node cont block)
409       (typecase node
410         (ref
411          (let ((var (ref-leaf node)))
412            (when (lambda-var-p var)
413              (let ((con (lambda-var-constraints var)))
414                (when con
415                  (constrain-ref-type node con in)
416                  (when (continuation-type-check cont)
417                    (sset-adjoin
418                     (find-constraint 'typep var
419                                      (continuation-asserted-type cont)
420                                      nil)
421                     in)))))))
422         (cset
423          (let ((var (set-var node)))
424            (when (lambda-var-p var)
425              (let ((cons (lambda-var-constraints var)))
426                (when cons
427                  (sset-difference in cons))))))))))
428
429 ;;; Return true if VAR would have to be closed over if environment
430 ;;; analysis ran now (i.e. if there are any uses that have a different
431 ;;; home lambda than VAR's home.)
432 (defun closure-var-p (var)
433   (declare (type lambda-var var))
434   (let ((home (lambda-home (lambda-var-home var))))
435     (flet ((frob (l)
436              (dolist (node l nil)
437                (unless (eq (node-home-lambda node) home)
438                  (return t)))))
439       (or (frob (leaf-refs var))
440           (frob (basic-var-sets var))))))
441
442 ;;; Give an empty constraints set to any var that doesn't have one and
443 ;;; isn't a set closure var. Since a var that we previously rejected
444 ;;; looks identical to one that is new, so we optimistically keep
445 ;;; hoping that vars stop being closed over or lose their sets.
446 (defun init-var-constraints (component)
447   (declare (type component component))
448   (dolist (fun (component-lambdas component))
449     (flet ((frob (x)
450              (dolist (var (lambda-vars x))
451                (unless (lambda-var-constraints var)
452                  (when (or (null (lambda-var-sets var))
453                            (not (closure-var-p var)))
454                    (setf (lambda-var-constraints var) (make-sset)))))))
455       (frob fun)
456       (dolist (let (lambda-lets fun))
457         (frob let)))))
458
459 ;;; BLOCK-IN becomes the intersection of the OUT of the prececessors.
460 ;;; Our OUT is:
461 ;;;     out U (in - kill)
462 ;;;
463 ;;; BLOCK-KILL is just a list of the lambda-vars killed, so we must
464 ;;; compute the kill set when there are any vars killed. We bum this a
465 ;;; bit by special-casing when only one var is killed, and just using
466 ;;; that var's constraints as the kill set. This set could possibly be
467 ;;; precomputed, but it would have to be invalidated whenever any
468 ;;; constraint is added, which would be a pain.
469 (defun flow-propagate-constraints (block)
470   (let* ((pred (block-pred block))
471          (in (cond (pred
472                     (let ((res (copy-sset (block-out (first pred)))))
473                       (dolist (b (rest pred))
474                         (sset-intersection res (block-out b)))
475                       res))
476                    (t
477                     (when *check-consistency*
478                       (let ((*compiler-error-context* (block-last block)))
479                         (compiler-warning
480                          "*** Unreachable code in constraint ~
481                           propagation... Bug?")))
482                     (make-sset))))
483          (kill (block-kill block))
484          (out (block-out block)))
485
486     (setf (block-in block) in)
487     (cond ((null kill)
488            (sset-union (block-out block) in))
489           ((null (rest kill))
490            (let ((con (lambda-var-constraints (first kill))))
491              (if con
492                  (sset-union-of-difference out in con)
493                  (sset-union out in))))
494           (t
495            (let ((kill-set (make-sset)))
496              (dolist (var kill)
497                (let ((con (lambda-var-constraints var)))
498                  (when con
499                    (sset-union kill-set con))))
500              (sset-union-of-difference (block-out block) in kill-set))))))
501
502 (defun constraint-propagate (component)
503   (declare (type component component))
504   (init-var-constraints component)
505
506   (do-blocks (block component)
507     (when (block-test-modified block)
508       (find-test-constraints block)))
509
510   (do-blocks (block component)
511     (cond ((block-type-asserted block)
512            (find-block-type-constraints block))
513           (t
514            (setf (block-in block) nil)
515            (setf (block-out block) (copy-sset (block-gen block))))))
516
517   (setf (block-out (component-head component)) (make-sset))
518
519   (let ((did-something nil))
520     (loop
521       (do-blocks (block component)
522         (when (flow-propagate-constraints block)
523           (setq did-something t)))
524
525       (unless did-something (return))
526       (setq did-something nil)))
527
528   (do-blocks (block component)
529     (use-result-constraints block))
530
531   (values))
532