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