100f3ee11ef016336e7d2e3e409762c69ffcd922
[sbcl.git] / src / compiler / knownfun.lisp
1 ;;;; This file contains stuff for maintaining a database of special
2 ;;;; information about functions known to the compiler. This includes
3 ;;;; semantic information such as side effects and type inference
4 ;;;; functions as well as transforms and IR2 translators.
5
6 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; more information.
8 ;;;;
9 ;;;; This software is derived from the CMU CL system, which was
10 ;;;; written at Carnegie Mellon University and released into the
11 ;;;; public domain. The software is in the public domain and is
12 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
13 ;;;; files for more information.
14
15 (in-package "SB!C")
16
17 (/show0 "knownfun.lisp 17")
18
19 ;;; IR1 boolean function attributes
20 ;;;
21 ;;; There are a number of boolean attributes of known functions which
22 ;;; we like to have in IR1. This information is mostly side effect
23 ;;; information of a sort, but it is different from the kind of
24 ;;; information we want in IR2. We aren't interested in a fine
25 ;;; breakdown of side effects, since we do very little code motion on
26 ;;; IR1. We are interested in some deeper semantic properties such as
27 ;;; whether it is safe to pass stack closures to.
28 ;;;
29 ;;; FIXME: This whole notion of "bad" explicit attributes is bad for
30 ;;; maintenance. How confident are we that we have no defknowns for functions
31 ;;; with functional arguments that are missing the CALL attribute? Much better
32 ;;; to have NO-CALLS, as it is much less likely to break accidentally.
33 (!def-boolean-attribute ir1
34   ;; may call functions that are passed as arguments. In order to
35   ;; determine what other effects are present, we must find the
36   ;; effects of all arguments that may be functions.
37   call
38   ;; may fail to return during correct execution. Errors are O.K.
39   ;; UNUSED, BEWARE OF BITROT.
40   unwind
41   ;; the (default) worst case. Includes all the other bad things, plus
42   ;; any other possible bad thing. If this is present, the above bad
43   ;; attributes will be explicitly present as well.
44   any
45   ;; all arguments are safe for dynamic extent.
46   ;; (We used to have an UNSAFE attribute, which was basically the inverse
47   ;; of this, but it was unused and bitrotted, so when we started making
48   ;; use of the information we flipped the name and meaning the safe way
49   ;; around.)
50   dx-safe
51   ;; may be constant-folded. The function has no side effects, but may
52   ;; be affected by side effects on the arguments. e.g. SVREF, MAPC.
53   ;; Functions that side-effect their arguments are not considered to
54   ;; be foldable. Although it would be "legal" to constant fold them
55   ;; (since it "is an error" to modify a constant), we choose not to
56   ;; mark these functions as foldable in this database.
57   foldable
58   ;; may be eliminated if value is unused. The function has no side
59   ;; effects except possibly cons. If a function might signal errors,
60   ;; then it is not flushable even if it is movable, foldable or
61   ;; unsafely-flushable. Implies UNSAFELY-FLUSHABLE. (In safe code
62   ;; type checking of arguments is always performed by the caller, so
63   ;; a function which SHOULD signal an error if arguments are not of
64   ;; declared types may be FLUSHABLE.)
65   flushable
66   ;; unsafe call may be eliminated if value is unused. The function
67   ;; has no side effects except possibly cons and signalling an error
68   ;; in the safe code. If a function MUST signal errors, then it is
69   ;; not unsafely-flushable even if it is movable or foldable.
70   unsafely-flushable
71   ;; return value is important, and ignoring it is probably a mistake.
72   ;; Unlike the other attributes, this is used only for style
73   ;; warnings and has no effect on optimization.
74   important-result
75   ;; may be moved with impunity. Has no side effects except possibly
76   ;; consing, and is affected only by its arguments.
77   ;; UNUSED, BEWARE OF BITROT.
78   movable
79   ;; The function is a true predicate likely to be open-coded. Convert
80   ;; any non-conditional uses into (IF <pred> T NIL). Not usually
81   ;; specified to DEFKNOWN, since this is implementation dependent,
82   ;; and is usually automatically set by the DEFINE-VOP :CONDITIONAL
83   ;; option.
84   predicate
85   ;; Inhibit any warning for compiling a recursive definition.
86   ;; (Normally the compiler warns when compiling a recursive
87   ;; definition for a known function, since it might be a botched
88   ;; interpreter stub.)
89   recursive
90   ;; The function does explicit argument type checking, so the
91   ;; declared type should not be asserted when a definition is
92   ;; compiled.
93   explicit-check
94   ;; The function should always be translated by a VOP (i.e. it should
95   ;; should never be converted into a full call).  This is used strictly
96   ;; as a consistency checking mechanism inside the compiler during IR2
97   ;; transformation.
98   always-translatable)
99
100 (defstruct (fun-info #-sb-xc-host (:pure t))
101   ;; boolean attributes of this function.
102   (attributes (missing-arg) :type attributes)
103   ;; TRANSFORM structures describing transforms for this function
104   (transforms () :type list)
105   ;; a function which computes the derived type for a call to this
106   ;; function by examining the arguments. This is null when there is
107   ;; no special method for this function.
108   (derive-type nil :type (or function null))
109   ;; a function that does various unspecified code transformations by
110   ;; directly hacking the IR. Returns true if further optimizations of
111   ;; the call shouldn't be attempted.
112   ;;
113   ;; KLUDGE: This return convention (non-NIL if you shouldn't do
114   ;; further optimiz'ns) is backwards from the return convention for
115   ;; transforms. -- WHN 19990917
116   (optimizer nil :type (or function null))
117   ;; a function computing the constant or literal arguments which are
118   ;; destructively modified by the call.
119   (destroyed-constant-args nil :type (or function null))
120   ;; If true, a special-case LTN annotation method that is used in
121   ;; place of the standard type/policy template selection. It may use
122   ;; arbitrary code to choose a template, decide to do a full call, or
123   ;; conspire with the IR2-CONVERT method to do almost anything. The
124   ;; COMBINATION node is passed as the argument.
125   (ltn-annotate nil :type (or function null))
126   ;; If true, the special-case IR2 conversion method for this
127   ;; function. This deals with funny functions, and anything else that
128   ;; can't be handled using the template mechanism. The COMBINATION
129   ;; node and the IR2-BLOCK are passed as arguments.
130   (ir2-convert nil :type (or function null))
131   ;; If true, the function can stack-allocate the result. The
132   ;; COMBINATION node is passed as an argument.
133   (stack-allocate-result nil :type (or function null))
134   ;; all the templates that could be used to translate this function
135   ;; into IR2, sorted by increasing cost.
136   (templates nil :type list)
137   ;; If non-null, then this function is a unary type predicate for
138   ;; this type.
139   (predicate-type nil :type (or ctype null))
140   ;; If non-null, the index of the argument which becomes the result
141   ;; of the function.
142   (result-arg nil :type (or index null)))
143
144 (defprinter (fun-info)
145   (attributes :test (not (zerop attributes))
146               :prin1 (decode-ir1-attributes attributes))
147   (transforms :test transforms)
148   (derive-type :test derive-type)
149   (optimizer :test optimizer)
150   (ltn-annotate :test ltn-annotate)
151   (ir2-convert :test ir2-convert)
152   (templates :test templates)
153   (predicate-type :test predicate-type))
154 \f
155 ;;;; interfaces to defining macros
156
157 ;;; an IR1 transform
158 (defstruct (transform (:copier nil))
159   ;; the function type which enables this transform.
160   ;;
161   ;; (Note that declaring this :TYPE FUN-TYPE probably wouldn't
162   ;; work because some function types, like (SPECIFIER-TYPE 'FUNCTION0
163   ;; itself, are represented as BUILT-IN-TYPE, and at least as of
164   ;; sbcl-0.pre7.54 or so, that's inconsistent with being a
165   ;; FUN-TYPE.)
166   (type (missing-arg) :type ctype)
167   ;; the transformation function. Takes the COMBINATION node and
168   ;; returns a lambda expression, or throws out.
169   (function (missing-arg) :type function)
170   ;; string used in efficiency notes
171   (note (missing-arg) :type string)
172   ;; T if we should emit a failure note even if SPEED=INHIBIT-WARNINGS.
173   (important nil :type (member t nil)))
174
175 (defprinter (transform) type note important)
176
177 ;;; Grab the FUN-INFO and enter the function, replacing any old
178 ;;; one with the same type and note.
179 (declaim (ftype (function (t list function &optional (or string null)
180                              (member t nil))
181                           *)
182                 %deftransform))
183 (defun %deftransform (name type fun &optional note important)
184   (let* ((ctype (specifier-type type))
185          (note (or note "optimize"))
186          (info (fun-info-or-lose name))
187          (old (find-if (lambda (x)
188                          (and (type= (transform-type x) ctype)
189                               (string-equal (transform-note x) note)
190                               (eq (transform-important x) important)))
191                        (fun-info-transforms info))))
192     (cond (old
193            (style-warn 'sb!kernel:redefinition-with-deftransform
194                        :transform old)
195            (setf (transform-function old) fun
196                  (transform-note old) note))
197           (t
198            (push (make-transform :type ctype :function fun :note note
199                                  :important important)
200                  (fun-info-transforms info))))
201     name))
202
203 ;;; Make a FUN-INFO structure with the specified type, attributes
204 ;;; and optimizers.
205 (declaim (ftype (function (list list attributes &key
206                                 (:derive-type (or function null))
207                                 (:optimizer (or function null))
208                                 (:destroyed-constant-args (or function null))
209                                 (:result-arg (or index null))
210                                 (:overwrite-fndb-silently boolean))
211                           *)
212                 %defknown))
213 (defun %defknown (names type attributes
214                   &key derive-type optimizer destroyed-constant-args result-arg
215                     overwrite-fndb-silently)
216   (let ((ctype (specifier-type type))
217         (info (make-fun-info :attributes attributes
218                              :derive-type derive-type
219                              :optimizer optimizer
220                              :destroyed-constant-args destroyed-constant-args
221                              :result-arg result-arg)))
222     (dolist (name names)
223       (unless overwrite-fndb-silently
224         (let ((old-fun-info (info :function :info name)))
225           (when old-fun-info
226             ;; This is handled as an error because it's generally a bad
227             ;; thing to blow away all the old optimization stuff. It's
228             ;; also a potential source of sneaky bugs:
229             ;;    DEFKNOWN FOO
230             ;;    DEFTRANSFORM FOO
231             ;;    DEFKNOWN FOO ; possibly hidden inside some macroexpansion
232             ;;    ; Now the DEFTRANSFORM doesn't exist in the target Lisp.
233             ;; However, it's continuable because it might be useful to do
234             ;; it when testing new optimization stuff interactively.
235             (cerror "Go ahead, overwrite it."
236                     "~@<overwriting old FUN-INFO ~2I~_~S ~I~_for ~S~:>"
237                     old-fun-info name))))
238       (setf (info :function :type name) ctype)
239       (setf (info :function :where-from name) :declared)
240       (setf (info :function :kind name) :function)
241       (setf (info :function :info name) info)))
242   names)
243
244 ;;; Return the FUN-INFO for NAME or die trying. Since this is
245 ;;; used by callers who want to modify the info, and the info may be
246 ;;; shared, we copy it. We don't have to copy the lists, since each
247 ;;; function that has generators or transforms has already been
248 ;;; through here.
249 (declaim (ftype (sfunction (t) fun-info) fun-info-or-lose))
250 (defun fun-info-or-lose (name)
251   (let (;; FIXME: Do we need this rebinding here? It's a literal
252         ;; translation of the old CMU CL rebinding to
253         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
254         ;; and it's not obvious whether the rebinding to itself is
255         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
256         (*info-environment* *info-environment*))
257     (let ((old (info :function :info name)))
258       (unless old (error "~S is not a known function." name))
259       (setf (info :function :info name) (copy-fun-info old)))))
260 \f
261 ;;;; generic type inference methods
262
263 ;;; Derive the type to be the type of the xxx'th arg. This can normally
264 ;;; only be done when the result value is that argument.
265 (defun result-type-first-arg (call)
266   (declare (type combination call))
267   (let ((lvar (first (combination-args call))))
268     (when lvar (lvar-type lvar))))
269 (defun result-type-last-arg (call)
270   (declare (type combination call))
271   (let ((lvar (car (last (combination-args call)))))
272     (when lvar (lvar-type lvar))))
273
274 ;;; Derive the result type according to the float contagion rules, but
275 ;;; always return a float. This is used for irrational functions that
276 ;;; preserve realness of their arguments.
277 (defun result-type-float-contagion (call)
278   (declare (type combination call))
279   (reduce #'numeric-contagion (combination-args call)
280           :key #'lvar-type
281           :initial-value (specifier-type 'single-float)))
282
283 ;;; Return a closure usable as a derive-type method for accessing the
284 ;;; N'th argument. If arg is a list, result is a list. If arg is a
285 ;;; vector, result is a vector with the same element type.
286 (defun sequence-result-nth-arg (n)
287   (lambda (call)
288     (declare (type combination call))
289     (let ((lvar (nth (1- n) (combination-args call))))
290       (when lvar
291         (let ((type (lvar-type lvar)))
292           (if (array-type-p type)
293               (specifier-type
294                `(vector ,(type-specifier (array-type-element-type type))))
295               (let ((ltype (specifier-type 'list)))
296                 (when (csubtypep type ltype)
297                   ltype))))))))
298
299 ;;; Derive the type to be the type specifier which is the Nth arg.
300 (defun result-type-specifier-nth-arg (n)
301   (lambda (call)
302     (declare (type combination call))
303     (let ((lvar (nth (1- n) (combination-args call))))
304       (when (and lvar (constant-lvar-p lvar))
305         (careful-specifier-type (lvar-value lvar))))))
306
307 ;;; Derive the type to be the type specifier which is the Nth arg,
308 ;;; with the additional restriptions noted in the CLHS for STRING and
309 ;;; SIMPLE-STRING, defined to specialize on CHARACTER, and for VECTOR
310 ;;; (under the page for MAKE-SEQUENCE).
311 (defun creation-result-type-specifier-nth-arg (n)
312   (lambda (call)
313     (declare (type combination call))
314     (let ((lvar (nth (1- n) (combination-args call))))
315       (when (and lvar (constant-lvar-p lvar))
316         (let* ((specifier (lvar-value lvar))
317                (lspecifier (if (atom specifier) (list specifier) specifier)))
318           (cond
319             ((eq (car lspecifier) 'string)
320              (destructuring-bind (string &rest size)
321                  lspecifier
322                (declare (ignore string))
323                (careful-specifier-type
324                 `(vector character ,@(when size size)))))
325             ((eq (car lspecifier) 'simple-string)
326              (destructuring-bind (simple-string &rest size)
327                  lspecifier
328                (declare (ignore simple-string))
329                (careful-specifier-type
330                 `(simple-array character ,@(if size (list size) '((*)))))))
331             (t
332              (let ((ctype (careful-specifier-type specifier)))
333                (if (and (array-type-p ctype)
334                         (eq (array-type-specialized-element-type ctype)
335                             *wild-type*))
336                    ;; I don't think I'm allowed to modify what I get
337                    ;; back from SPECIFIER-TYPE; it is, after all,
338                    ;; cached.  Better copy it, then.
339                    (let ((real-ctype (copy-structure ctype)))
340                      (setf (array-type-element-type real-ctype)
341                            *universal-type*
342                            (array-type-specialized-element-type real-ctype)
343                            *universal-type*)
344                      real-ctype)
345                    ctype)))))))))
346
347 (defun remove-non-constants-and-nils (fun)
348   (lambda (list)
349     (remove-if-not #'lvar-value
350                    (remove-if-not #'constant-lvar-p (funcall fun list)))))
351
352 ;;; FIXME: bad name (first because it uses 1-based indexing; second
353 ;;; because it doesn't get the nth constant arguments)
354 (defun nth-constant-args (&rest indices)
355   (lambda (list)
356     (let (result)
357       (do ((i 1 (1+ i))
358            (list list (cdr list))
359            (indices indices))
360           ((null indices) (nreverse result))
361         (when (= i (car indices))
362           (when (constant-lvar-p (car list))
363             (push (car list) result))
364           (setf indices (cdr indices)))))))
365
366 ;;; FIXME: a number of the sequence functions not only do not destroy
367 ;;; their argument if it is empty, but also leave it alone if :start
368 ;;; and :end bound a null sequence, or if :count is 0.  This test is a
369 ;;; bit complicated to implement, verging on the impossible, but for
370 ;;; extra points (fill #\1 "abc" :start 0 :end 0) should not cause a
371 ;;; warning.
372 (defun nth-constant-nonempty-sequence-args (&rest indices)
373   (lambda (list)
374     (let (result)
375       (do ((i 1 (1+ i))
376            (list list (cdr list))
377            (indices indices))
378           ((null indices) (nreverse result))
379         (when (= i (car indices))
380           (when (constant-lvar-p (car list))
381             (let ((value (lvar-value (car list))))
382               (unless (or (typep value 'null)
383                           (typep value '(vector * 0)))
384                 (push (car list) result))))
385           (setf indices (cdr indices)))))))
386
387 (/show0 "knownfun.lisp end of file")