0.7.12.55:
[sbcl.git] / src / compiler / seqtran.lisp
1 ;;;; optimizers for list and sequence functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!C")
13 \f
14 ;;;; mapping onto lists: the MAPFOO functions
15
16 (defun mapfoo-transform (fn arglists accumulate take-car)
17   (collect ((do-clauses)
18             (args-to-fn)
19             (tests))
20     (let ((n-first (gensym)))
21       (dolist (a (if accumulate
22                      arglists
23                      `(,n-first ,@(rest arglists))))
24         (let ((v (gensym)))
25           (do-clauses `(,v ,a (cdr ,v)))
26           (tests `(endp ,v))
27           (args-to-fn (if take-car `(car ,v) v))))
28
29       (let ((call `(funcall ,fn . ,(args-to-fn)))
30             (endtest `(or ,@(tests))))
31         (ecase accumulate
32           (:nconc
33            (let ((temp (gensym))
34                  (map-result (gensym)))
35              `(let ((,map-result (list nil)))
36                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
37                               (,endtest (cdr ,map-result))
38                   (setq ,temp (last (nconc ,temp ,call)))))))
39           (:list
40            (let ((temp (gensym))
41                  (map-result (gensym)))
42              `(let ((,map-result (list nil)))
43                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
44                               (,endtest (cdr ,map-result))
45                   (rplacd ,temp (setq ,temp (list ,call)))))))
46           ((nil)
47            `(let ((,n-first ,(first arglists)))
48               (do-anonymous ,(do-clauses)
49                             (,endtest ,n-first) ,call))))))))
50
51 (define-source-transform mapc (function list &rest more-lists)
52   (mapfoo-transform function (cons list more-lists) nil t))
53
54 (define-source-transform mapcar (function list &rest more-lists)
55   (mapfoo-transform function (cons list more-lists) :list t))
56
57 (define-source-transform mapcan (function list &rest more-lists)
58   (mapfoo-transform function (cons list more-lists) :nconc t))
59
60 (define-source-transform mapl (function list &rest more-lists)
61   (mapfoo-transform function (cons list more-lists) nil nil))
62
63 (define-source-transform maplist (function list &rest more-lists)
64   (mapfoo-transform function (cons list more-lists) :list nil))
65
66 (define-source-transform mapcon (function list &rest more-lists)
67   (mapfoo-transform function (cons list more-lists) :nconc nil))
68 \f
69 ;;;; mapping onto sequences: the MAP function
70
71 ;;; MAP is %MAP plus a check to make sure that any length specified in
72 ;;; the result type matches the actual result. We also wrap it in a
73 ;;; TRULY-THE for the most specific type we can determine.
74 (deftransform map ((result-type-arg fun &rest seqs) * * :node node)
75   (let* ((seq-names (make-gensym-list (length seqs)))
76          (bare `(%map result-type-arg fun ,@seq-names))
77          (constant-result-type-arg-p (constant-continuation-p result-type-arg))
78          ;; what we know about the type of the result. (Note that the
79          ;; "result type" argument is not necessarily the type of the
80          ;; result, since NIL means the result has NULL type.)
81          (result-type (if (not constant-result-type-arg-p)
82                           'consed-sequence
83                           (let ((result-type-arg-value
84                                  (continuation-value result-type-arg)))
85                             (if (null result-type-arg-value)
86                                 'null
87                                 result-type-arg-value)))))
88     `(lambda (result-type-arg fun ,@seq-names)
89        (truly-the ,result-type
90          ,(cond ((policy node (< safety 3))
91                  ;; ANSI requires the length-related type check only
92                  ;; when the SAFETY quality is 3... in other cases, we
93                  ;; skip it, because it could be expensive.
94                  bare)
95                 ((not constant-result-type-arg-p)
96                  `(sequence-of-checked-length-given-type ,bare
97                                                          result-type-arg))
98                 (t
99                  (let ((result-ctype (ir1-transform-specifier-type
100                                       result-type)))
101                    (if (array-type-p result-ctype)
102                        (let ((dims (array-type-dimensions result-ctype)))
103                          (unless (and (listp dims) (= (length dims) 1))
104                            (give-up-ir1-transform "invalid sequence type"))
105                          (let ((dim (first dims)))
106                            (if (eq dim '*)
107                                bare
108                                `(vector-of-checked-length-given-length ,bare
109                                                                        ,dim))))
110                        ;; FIXME: this is wrong, as not all subtypes of
111                        ;; VECTOR are ARRAY-TYPEs [consider, for
112                        ;; example, (OR (VECTOR T 3) (VECTOR T
113                        ;; 4))]. However, it's difficult to see what we
114                        ;; should put here... maybe we should
115                        ;; GIVE-UP-IR1-TRANSFORM if the type is a
116                        ;; subtype of VECTOR but not an ARRAY-TYPE?
117                        bare))))))))
118
119 ;;; Try to compile %MAP efficiently when we can determine sequence
120 ;;; argument types at compile time.
121 ;;;
122 ;;; Note: This transform was written to allow open coding of
123 ;;; quantifiers by expressing them in terms of (MAP NIL ..). For
124 ;;; non-NIL values of RESULT-TYPE, it's still useful, but not
125 ;;; necessarily as efficient as possible. In particular, it will be
126 ;;; inefficient when RESULT-TYPE is a SIMPLE-ARRAY with specialized
127 ;;; numeric element types. It should be straightforward to make it
128 ;;; handle that case more efficiently, but it's left as an exercise to
129 ;;; the reader, because the code is complicated enough already and I
130 ;;; don't happen to need that functionality right now. -- WHN 20000410
131 (deftransform %map ((result-type fun &rest seqs) * * :policy (>= speed space))
132   "open code"
133   (unless seqs (abort-ir1-transform "no sequence args"))
134   (unless (constant-continuation-p result-type)
135     (give-up-ir1-transform "RESULT-TYPE argument not constant"))
136   (labels (;; 1-valued SUBTYPEP, fails unless second value of SUBTYPEP is true
137            (fn-1subtypep (fn x y)
138              (multiple-value-bind (subtype-p valid-p) (funcall fn x y)
139                (if valid-p
140                    subtype-p
141                    (give-up-ir1-transform
142                     "can't analyze sequence type relationship"))))
143            (1subtypep (x y) (fn-1subtypep #'sb!xc:subtypep x y))
144            (1csubtypep (x y) (fn-1subtypep #'csubtypep x y))
145            (seq-supertype (seq)
146              (let ((ctype (continuation-type seq)))
147                (cond ((1csubtypep ctype (specifier-type 'vector)) 'vector)
148                      ((1csubtypep ctype (specifier-type 'list)) 'list)
149                      (t
150                       (give-up-ir1-transform
151                        "can't determine sequence argument type"))))))
152     (let* ((result-type-value (continuation-value result-type))
153            (result-supertype (cond ((null result-type-value) 'null)
154                                    ((1subtypep result-type-value 'vector)
155                                     'vector)
156                                    ((1subtypep result-type-value 'list)
157                                     'list)
158                                    (t
159                                     (give-up-ir1-transform
160                                      "can't determine result type"))))
161            (seq-supertypes (mapcar #'seq-supertype seqs)))
162       (cond ((and result-type-value (= 1 (length seqs)))
163              ;; The consing arity-1 cases can be implemented
164              ;; reasonably efficiently as function calls, and the cost
165              ;; of consing should be significantly larger than
166              ;; function call overhead, so we always compile these
167              ;; cases as full calls regardless of speed-versus-space
168              ;; optimization policy.
169              (cond ((subtypep 'list result-type-value)
170                     '(apply #'%map-to-list-arity-1 fun seqs))
171                    (;; (This one can be inefficient due to COERCE, but
172                     ;; the current open-coded implementation has the
173                     ;; same problem.)
174                     (subtypep result-type-value 'vector)
175                     `(coerce (apply #'%map-to-simple-vector-arity-1 fun seqs)
176                              ',result-type-value))
177                    (t (bug "impossible (?) sequence type"))))
178             (t
179              (let* ((seq-args (make-gensym-list (length seqs)))
180                     (index-bindingoids
181                      (mapcar (lambda (seq-arg seq-supertype)
182                                (let ((i (gensym "I"))) 
183                                  (ecase seq-supertype
184                                    (vector `(,i 0 (1+ ,i)))
185                                    (list `(,i ,seq-arg (rest ,i))))))
186                              seq-args seq-supertypes))
187                     (indices (mapcar #'first index-bindingoids))
188                     (index-decls (mapcar (lambda (index seq-supertype)
189                                            `(type ,(ecase seq-supertype
190                                                      (vector 'index)
191                                                      (list 'list))
192                                                   ,index))
193                                          indices seq-supertypes))
194                     (tests (mapcar (lambda (seq-arg seq-supertype index)
195                                      (ecase seq-supertype
196                                        (vector `(>= ,index (length ,seq-arg)))
197                                        (list `(endp ,index))))
198                                    seq-args seq-supertypes indices))
199                     (values (mapcar (lambda (seq-arg seq-supertype index)
200                                       (ecase seq-supertype
201                                         (vector `(aref ,seq-arg ,index))
202                                         (list `(first ,index))))
203                                     seq-args seq-supertypes indices)))
204                (multiple-value-bind (push-dacc final-result)
205                    (ecase result-supertype
206                      (null (values nil nil))
207                      (list (values `(push dacc acc) `(nreverse acc)))
208                      (vector (values `(push dacc acc)
209                                      `(coerce (nreverse acc)
210                                               ',result-type-value))))
211                  ;; (We use the same idiom, of returning a LAMBDA from
212                  ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
213                  ;; FUNCALL and ALIEN-FUNCALL, and for the same
214                  ;; reason: we need to get the runtime values of each
215                  ;; of the &REST vars.)
216                  `(lambda (result-type fun ,@seq-args)
217                     (declare (ignore result-type))
218                     (do ((really-fun (%coerce-callable-to-fun fun))
219                          ,@index-bindingoids
220                          (acc nil))
221                     ((or ,@tests)
222                      ,final-result)
223                     (declare ,@index-decls)
224                     (declare (type list acc))
225                     (declare (ignorable acc))
226                     (let ((dacc (funcall really-fun ,@values)))
227                       (declare (ignorable dacc))
228                       ,push-dacc))))))))))
229 \f
230 ;;; FIXME: once the confusion over doing transforms with known-complex
231 ;;; arrays is over, we should also transform the calls to (AND (ARRAY
232 ;;; * (*)) (NOT (SIMPLE-ARRAY * (*)))) objects.
233 (deftransform elt ((s i) ((simple-array * (*)) *) *)
234   '(aref s i))
235
236 (deftransform elt ((s i) (list *) * :policy (< safety 3))
237   '(nth i s))
238
239 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) *)
240   '(%aset s i v))
241
242 (deftransform %setelt ((s i v) (list * *) * :policy (< safety 3))
243   '(setf (car (nthcdr i s)) v))
244
245 (deftransform %check-vector-sequence-bounds ((vector start end)
246                                              (vector * *) *
247                                              :node node)
248   (if (policy node (< safety speed))
249       '(or end (length vector))
250       '(let ((length (length vector)))
251         (if (<= 0 start (or end length) length)
252             (or end length)
253             (sb!impl::signal-bounding-indices-bad-error vector start end)))))
254
255 (macrolet ((def (name)
256              `(deftransform ,name ((e l &key (test #'eql)) * *
257                                    :node node)
258                 (unless (constant-continuation-p l)
259                   (give-up-ir1-transform))
260
261                 (let ((val (continuation-value l)))
262                   (unless (policy node
263                                   (or (= speed 3)
264                                       (and (>= speed space)
265                                            (<= (length val) 5))))
266                     (give-up-ir1-transform))
267
268                   (labels ((frob (els)
269                              (if els
270                                  `(if (funcall test e ',(car els))
271                                       ',els
272                                       ,(frob (cdr els)))
273                                  nil)))
274                     (frob val))))))
275   (def member)
276   (def memq))
277
278 ;;; FIXME: We have rewritten the original code that used DOLIST to this
279 ;;; more natural MACROLET.  However, the original code suggested that when
280 ;;; this was done, a few bytes could be saved by a call to a shared
281 ;;; function.  This remains to be done.
282 (macrolet ((def (fun eq-fun)
283              `(deftransform ,fun ((item list &key test) (t list &rest t) *)
284                 "convert to EQ test"
285                 ;; FIXME: The scope of this transformation could be
286                 ;; widened somewhat, letting it work whenever the test is
287                 ;; 'EQL and we know from the type of ITEM that it #'EQ
288                 ;; works like #'EQL on it. (E.g. types FIXNUM, CHARACTER,
289                 ;; and SYMBOL.)
290                 ;;   If TEST is EQ, apply transform, else
291                 ;;   if test is not EQL, then give up on transform, else
292                 ;;   if ITEM is not a NUMBER or is a FIXNUM, apply
293                 ;;   transform, else give up on transform.
294                 (cond (test
295                        (unless (continuation-fun-is test '(eq))
296                          (give-up-ir1-transform)))
297                       ((types-equal-or-intersect (continuation-type item)
298                                                  (specifier-type 'number))
299                        (give-up-ir1-transform "Item might be a number.")))
300                 `(,',eq-fun item list))))
301   (def delete delq)
302   (def assoc assq)
303   (def member memq))
304
305 (deftransform delete-if ((pred list) (t list))
306   "open code"
307   '(do ((x list (cdr x))
308         (splice '()))
309        ((endp x) list)
310      (cond ((funcall pred (car x))
311             (if (null splice)
312                 (setq list (cdr x))
313                 (rplacd splice (cdr x))))
314            (T (setq splice x)))))
315
316 (deftransform fill ((seq item &key (start 0) (end (length seq)))
317                     (vector t &key (:start t) (:end index))
318                     *
319                     :policy (> speed space))
320   "open code"
321   (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
322     (values 
323      `(with-array-data ((data seq)
324                         (start start)
325                         (end end))
326        (declare (type (simple-array ,element-type 1) data))
327        (declare (type fixnum start end))
328        (do ((i start (1+ i)))
329            ((= i end) seq)
330          (declare (type index i))
331          ;; WITH-ARRAY-DATA did our range checks once and for all, so
332          ;; it'd be wasteful to check again on every AREF...
333          (declare (optimize (safety 0))) 
334          (setf (aref data i) item)))
335      ;; ... though we still need to check that the new element can fit
336      ;; into the vector in safe code. -- CSR, 2002-07-05
337      `((declare (type ,element-type item))))))
338 \f
339 ;;;; utilities
340
341 ;;; Return true if CONT's only use is a non-NOTINLINE reference to a
342 ;;; global function with one of the specified NAMES.
343 (defun continuation-fun-is (cont names)
344   (declare (type continuation cont) (list names))
345   (let ((use (continuation-use cont)))
346     (and (ref-p use)
347          (let ((leaf (ref-leaf use)))
348            (and (global-var-p leaf)
349                 (eq (global-var-kind leaf) :global-function)
350                 (not (null (member (leaf-source-name leaf) names
351                                    :test #'equal))))))))
352
353 ;;; If CONT is a constant continuation, the return the constant value.
354 ;;; If it is null, then return default, otherwise quietly give up the
355 ;;; IR1 transform.
356 ;;;
357 ;;; ### Probably should take an ARG and flame using the NAME.
358 (defun constant-value-or-lose (cont &optional default)
359   (declare (type (or continuation null) cont))
360   (cond ((not cont) default)
361         ((constant-continuation-p cont)
362          (continuation-value cont))
363         (t
364          (give-up-ir1-transform))))
365
366 ;;; FIXME: Why is this code commented out? (Why *was* it commented
367 ;;; out? We inherited this situation from cmucl-2.4.8, with no
368 ;;; explanation.) Should we just delete this code?
369 #|
370 ;;; This is a frob whose job it is to make it easier to pass around
371 ;;; the arguments to IR1 transforms. It bundles together the name of
372 ;;; the argument (which should be referenced in any expansion), and
373 ;;; the continuation for that argument (or NIL if unsupplied.)
374 (defstruct (arg (:constructor %make-arg (name cont))
375                 (:copier nil))
376   (name nil :type symbol)
377   (cont nil :type (or continuation null)))
378 (defmacro make-arg (name)
379   `(%make-arg ',name ,name))
380
381 ;;; If Arg is null or its CONT is null, then return Default, otherwise
382 ;;; return Arg's NAME.
383 (defun default-arg (arg default)
384   (declare (type (or arg null) arg))
385   (if (and arg (arg-cont arg))
386       (arg-name arg)
387       default))
388
389 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
390 ;;; CONT must be a constant continuation whose value we return. If not, we
391 ;;; give up.
392 (defun arg-constant-value (arg default)
393   (declare (type (or arg null) arg))
394   (if (and arg (arg-cont arg))
395       (let ((cont (arg-cont arg)))
396         (unless (constant-continuation-p cont)
397           (give-up-ir1-transform "Argument is not constant: ~S."
398                                  (arg-name arg)))
399         (continuation-value from-end))
400       default))
401
402 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
403 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
404 (defun arg-eql (arg default x)
405   (declare (type (or arg null) x))
406   (if (and arg (arg-cont arg))
407       (let ((cont (arg-cont arg)))
408         (and (constant-continuation-p cont)
409              (eql (continuation-value cont) x)))
410       (eql default x)))
411
412 (defstruct (iterator (:copier nil))
413   ;; The kind of iterator.
414   (kind nil (member :normal :result))
415   ;; A list of LET* bindings to create the initial state.
416   (binds nil :type list)
417   ;; A list of declarations for Binds.
418   (decls nil :type list)
419   ;; A form that returns the current value. This may be set with SETF to set
420   ;; the current value.
421   (current (error "Must specify CURRENT."))
422   ;; In a :NORMAL iterator, a form that tests whether there is a current value.
423   (done nil)
424   ;; In a :RESULT iterator, a form that truncates the result at the current
425   ;; position and returns it.
426   (result nil)
427   ;; A form that returns the initial total number of values. The result is
428   ;; undefined after NEXT has been evaluated.
429   (length (error "Must specify LENGTH."))
430   ;; A form that advances the state to the next value. It is an error to call
431   ;; this when the iterator is Done.
432   (next (error "Must specify NEXT.")))
433
434 ;;; Type of an index var that can go negative (in the from-end case.)
435 (deftype neg-index ()
436   `(integer -1 ,most-positive-fixnum))
437
438 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
439 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
440 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
441 ;;; the index of the current element in the sequence.
442 ;;;
443 ;;; If we can't tell whether the sequence is a list or a vector, or whether
444 ;;; the iteration is forward or backward, then GIVE-UP.
445 (defun make-sequence-iterator (sequence type &key start end from-end index)
446   (declare (symbol sequence) (type ctype type)
447            (type (or arg null) start end from-end)
448            (type (or symbol null) index))
449   (let ((from-end (arg-constant-value from-end nil)))
450     (cond ((csubtypep type (specifier-type 'vector))
451            (let* ((n-stop (gensym))
452                   (n-idx (or index (gensym)))
453                   (start (default-arg 0 start))
454                   (end (default-arg `(length ,sequence) end)))
455              (make-iterator
456               :kind :normal
457               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
458                        (,n-stop ,(if from-end `(1- ,start) ,end)))
459               :decls `((type neg-index ,n-idx ,n-stop))
460               :current `(aref ,sequence ,n-idx)
461               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
462               :next `(setq ,n-idx
463                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
464               :length (if from-end
465                           `(- ,n-idx ,n-stop)
466                           `(- ,n-stop ,n-idx)))))
467           ((csubtypep type (specifier-type 'list))
468            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
469                   (n-current (gensym))
470                   (start-p (not (arg-eql start 0 0)))
471                   (end-p (not (arg-eql end nil nil)))
472                   (start (default-arg start 0))
473                   (end (default-arg end nil)))
474              (make-iterator
475               :binds `((,n-current
476                         ,(if from-end
477                              (if (or start-p end-p)
478                                  `(nreverse (subseq ,sequence ,start
479                                                     ,@(when end `(,end))))
480                                  `(reverse ,sequence))
481                              (if start-p
482                                  `(nthcdr ,start ,sequence)
483                                  sequence)))
484                        ,@(when n-stop
485                            `((,n-stop (nthcdr (the index
486                                                    (- ,end ,start))
487                                               ,n-current))))
488                        ,@(when index
489                            `((,index ,(if from-end `(1- ,end) start)))))
490               :kind :normal
491               :decls `((list ,n-current ,n-end)
492                        ,@(when index `((type neg-index ,index))))
493               :current `(car ,n-current)
494               :done `(eq ,n-current ,n-stop)
495               :length `(- ,(or end `(length ,sequence)) ,start)
496               :next `(progn
497                        (setq ,n-current (cdr ,n-current))
498                        ,@(when index
499                            `((setq ,n-idx
500                                    ,(if from-end
501                                         `(1- ,index)
502                                         `(1+ ,index)))))))))
503           (t
504            (give-up-ir1-transform
505             "can't tell whether sequence is a list or a vector")))))
506
507 ;;; Make an iterator used for constructing result sequences. Name is a
508 ;;; variable to be bound to the result sequence. Type is the type of result
509 ;;; sequence to make. Length is an expression to be evaluated to get the
510 ;;; maximum length of the result (not evaluated in list case.)
511 (defun make-result-sequence-iterator (name type length)
512   (declare (symbol name) (type ctype type))
513
514 ;;; Define each NAME as a local macro that will call the value of the
515 ;;; function arg with the given arguments. If the argument isn't known to be a
516 ;;; function, give them an efficiency note and reference a coerced version.
517 (defmacro coerce-funs (specs &body body)
518   #!+sb-doc
519   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
520   (collect ((binds)
521             (defs))
522     (dolist (spec specs)
523       `(let ((body (progn ,@body))
524              (n-fun (arg-name ,(second spec)))
525              (fun-cont (arg-cont ,(second spec))))
526          (cond ((not fun-cont)
527                 `(macrolet ((,',(first spec) (&rest args)
528                              `(,',',(third spec) ,@args)))
529                    ,body))
530                ((not (csubtypep (continuation-type fun-cont)
531                                 (specifier-type 'function)))
532                 (when (policy *compiler-error-context*
533                               (> speed inhibit-warnings))
534                   (compiler-note
535                    "~S may not be a function, so must coerce at run-time."
536                    n-fun))
537                 (once-only ((n-fun `(if (functionp ,n-fun)
538                                         ,n-fun
539                                         (symbol-function ,n-fun))))
540                   `(macrolet ((,',(first spec) (&rest args)
541                                `(funcall ,',n-fun ,@args)))
542                      ,body)))
543                (t
544                 `(macrolet ((,',(first spec) (&rest args)
545                               `(funcall ,',n-fun ,@args)))
546                    ,body)))))))
547
548 ;;; Wrap code around the result of the body to define Name as a local macro
549 ;;; that returns true when its arguments satisfy the test according to the Args
550 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
551 ;;; transform.
552 (defmacro with-sequence-test ((name test test-not) &body body)
553   `(let ((not-p (arg-cont ,test-not)))
554      (when (and (arg-cont ,test) not-p)
555        (abort-ir1-transform "Both ~S and ~S were supplied."
556                             (arg-name ,test)
557                             (arg-name ,test-not)))
558      (coerce-funs ((,name (if not-p ,test-not ,test) eql))
559        ,@body)))
560 |#
561 \f
562 ;;;; hairy sequence transforms
563
564 ;;; FIXME: no hairy sequence transforms in SBCL?
565 \f
566 ;;;; string operations
567
568 ;;; We transform the case-sensitive string predicates into a non-keyword
569 ;;; version. This is an IR1 transform so that we don't have to worry about
570 ;;; changing the order of evaluation.
571 (macrolet ((def (fun pred*)
572              `(deftransform ,fun ((string1 string2 &key (start1 0) end1
573                                                          (start2 0) end2)
574                                    * *)
575                 `(,',pred* string1 string2 start1 end1 start2 end2))))
576   (def string< string<*)
577   (def string> string>*)
578   (def string<= string<=*)
579   (def string>= string>=*)
580   (def string= string=*)
581   (def string/= string/=*))
582
583 ;;; Return a form that tests the free variables STRING1 and STRING2
584 ;;; for the ordering relationship specified by LESSP and EQUALP. The
585 ;;; start and end are also gotten from the environment. Both strings
586 ;;; must be SIMPLE-STRINGs.
587 (macrolet ((def (name lessp equalp)
588              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
589                                     (simple-string simple-string t t t t) *)
590                 `(let* ((end1 (if (not end1) (length string1) end1))
591                         (end2 (if (not end2) (length string2) end2))
592                         (index (sb!impl::%sp-string-compare
593                                 string1 start1 end1 string2 start2 end2)))
594                   (if index
595                       (cond ((= index ,(if ',lessp 'end1 'end2)) index)
596                             ((= index ,(if ',lessp 'end2 'end1)) nil)
597                             ((,(if ',lessp 'char< 'char>)
598                                (schar string1 index)
599                                (schar string2
600                                       (truly-the index
601                                                  (+ index
602                                                     (truly-the fixnum
603                                                                (- start2
604                                                                   start1))))))
605                              index)
606                             (t nil))
607                       ,(if ',equalp 'end1 nil))))))
608   (def string<* t nil)
609   (def string<=* t t)
610   (def string>* nil nil)
611   (def string>=* nil t))
612
613 (macrolet ((def (name result-fun)
614              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
615                                    (simple-string simple-string t t t t) *)
616                 `(,',result-fun
617                   (sb!impl::%sp-string-compare
618                    string1 start1 (or end1 (length string1))
619                    string2 start2 (or end2 (length string2)))))))
620   (def string=* not)
621   (def string/=* identity))
622
623 \f
624 ;;;; string-only transforms for sequence functions
625 ;;;;
626 ;;;; Note: CMU CL had more of these, including transforms for
627 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
628 ;;;; transforms for functions which cons, since our GC overhead is
629 ;;;; sufficiently large that it doesn't seem worth it to try to
630 ;;;; economize on function call overhead or on the overhead of runtime
631 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
632 ;;;; a full call to CONCATENATE would have to look up the sequence
633 ;;;; type, which can be really slow.
634 ;;;;
635 ;;;; FIXME: It would be nicer for these transforms to work for any
636 ;;;; calls when all arguments are vectors with the same element type,
637 ;;;; rather than restricting them to STRINGs only.
638
639 ;;; Moved here from generic/vm-tran.lisp to satisfy clisp
640 ;;;
641 ;;; FIXME: Add a comment telling whether this holds for all vectors
642 ;;; or only for vectors based on simple arrays (non-adjustable, etc.).
643 (def!constant vector-data-bit-offset
644   (* sb!vm:vector-data-offset sb!vm:n-word-bits))
645
646 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
647                                 end1 end2)
648                        (simple-string simple-string &rest t)
649                        *
650                        ;; FIXME: consider replacing this policy test
651                        ;; with some tests for the STARTx and ENDx
652                        ;; indices being valid, conditional on high
653                        ;; SAFETY code.
654                        ;;
655                        ;; FIXME: It turns out that this transform is
656                        ;; critical for the performance of string
657                        ;; streams.  Make this more explicit.
658                        :policy (< (max safety space) 3))
659   `(locally
660      (declare (optimize (safety 0)))
661      (bit-bash-copy string2
662                     (the index
663                          (+ (the index (* start2 sb!vm:n-byte-bits))
664                             ,vector-data-bit-offset))
665                     string1
666                     (the index
667                          (+ (the index (* start1 sb!vm:n-byte-bits))
668                             ,vector-data-bit-offset))
669                     (the index
670                          (* (min (the index (- (or end1 (length string1))
671                                                start1))
672                                  (the index (- (or end2 (length string2))
673                                                start2)))
674                             sb!vm:n-byte-bits)))
675      string1))
676
677 ;;; FIXME: It seems as though it should be possible to make a DEFUN
678 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
679 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
680 ;;; at least once DYNAMIC-EXTENT works.
681 ;;;
682 ;;; FIXME: currently KLUDGEed because of bug 188
683 (deftransform concatenate ((rtype &rest sequences)
684                            (t &rest simple-string)
685                            simple-string
686                            :policy (< safety 3))
687   (collect ((lets)
688             (forms)
689             (all-lengths)
690             (args))
691     (dolist (seq sequences)
692       (declare (ignorable seq))
693       (let ((n-seq (gensym))
694             (n-length (gensym)))
695         (args n-seq)
696         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
697         (all-lengths n-length)
698         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
699                                res start
700                                ,n-length))
701         (forms `(setq start (opaque-identity (+ start ,n-length))))))
702     `(lambda (rtype ,@(args))
703        (declare (ignore rtype))
704        ;; KLUDGE
705        (flet ((opaque-identity (x) x))
706          (declare (notinline opaque-identity))
707          (let* (,@(lets)
708                   (res (make-string (truncate (the index (+ ,@(all-lengths)))
709                                               sb!vm:n-byte-bits)))
710                   (start ,vector-data-bit-offset))
711            (declare (type index start ,@(all-lengths)))
712            ,@(forms)
713            res)))))
714 \f
715 ;;;; CONS accessor DERIVE-TYPE optimizers
716
717 (defoptimizer (car derive-type) ((cons))
718   (let ((type (continuation-type cons))
719         (null-type (specifier-type 'null)))
720     (cond ((eq type null-type)
721            null-type)
722           ((cons-type-p type)
723            (cons-type-car-type type)))))
724
725 (defoptimizer (cdr derive-type) ((cons))
726   (let ((type (continuation-type cons))
727         (null-type (specifier-type 'null)))
728     (cond ((eq type null-type)
729            null-type)
730           ((cons-type-p type)
731            (cons-type-cdr-type type)))))
732 \f
733 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
734
735 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
736 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
737 ;;; expansion, so we factor out the condition into this function.
738 (defun check-inlineability-of-find-position-if (sequence from-end)
739   (let ((ctype (continuation-type sequence)))
740     (cond ((csubtypep ctype (specifier-type 'vector))
741            ;; It's not worth trying to inline vector code unless we
742            ;; know a fair amount about it at compile time.
743            (upgraded-element-type-specifier-or-give-up sequence)
744            (unless (constant-continuation-p from-end)
745              (give-up-ir1-transform
746               "FROM-END argument value not known at compile time")))
747           ((csubtypep ctype (specifier-type 'list))
748            ;; Inlining on lists is generally worthwhile.
749            ) 
750           (t
751            (give-up-ir1-transform
752             "sequence type not known at compile time")))))
753
754 ;;; %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for LIST data
755 (macrolet ((def (name condition)
756              `(deftransform ,name ((predicate sequence from-end start end key)
757                                    (function list t t t function)
758                                    *
759                                    :policy (> speed space)
760                                    :important t)
761                 "expand inline"
762                 `(let ((index 0)
763                        (find nil)
764                        (position nil))
765                    (declare (type index index))
766                    (dolist (i sequence
767                             (if (and end (> end index))
768                                 (sb!impl::signal-bounding-indices-bad-error
769                                  sequence start end)
770                                 (values find position)))
771                      (let ((key-i (funcall key i)))
772                        (when (and end (>= index end))
773                          (return (values find position)))
774                        (when (>= index start)
775                          (,',condition (funcall predicate key-i)
776                           ;; This hack of dealing with non-NIL
777                           ;; FROM-END for list data by iterating
778                           ;; forward through the list and keeping
779                           ;; track of the last time we found a match
780                           ;; might be more screwy than what the user
781                           ;; expects, but it seems to be allowed by
782                           ;; the ANSI standard. (And if the user is
783                           ;; screwy enough to ask for FROM-END
784                           ;; behavior on list data, turnabout is
785                           ;; fair play.)
786                           ;;
787                           ;; It's also not enormously efficient,
788                           ;; calling PREDICATE and KEY more often
789                           ;; than necessary; but all the
790                           ;; alternatives seem to have their own
791                           ;; efficiency problems.
792                           (if from-end
793                               (setf find i
794                                     position index)
795                               (return (values i index))))))
796                      (incf index))))))
797   (def %find-position-if when)
798   (def %find-position-if-not unless))
799                       
800 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
801 ;;; without loss of efficiency. (I.e., the optimizer should be able
802 ;;; to straighten everything out.)
803 (deftransform %find-position ((item sequence from-end start end key test)
804                               (t list t t t t t)
805                               *
806                               :policy (> speed space)
807                               :important t)
808   "expand inline"
809   '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
810                         ;; The order of arguments for asymmetric tests
811                         ;; (e.g. #'<, as opposed to order-independent
812                         ;; tests like #'=) is specified in the spec
813                         ;; section 17.2.1 -- the O/Zi stuff there.
814                         (lambda (i)
815                           (funcall test-fun item i)))
816                       sequence
817                       from-end
818                       start
819                       end
820                       (%coerce-callable-to-fun key)))
821
822 ;;; The inline expansions for the VECTOR case are saved as macros so
823 ;;; that we can share them between the DEFTRANSFORMs and the default
824 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
825 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
826 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
827                                                             from-end
828                                                             start
829                                                             end-arg
830                                                             element
831                                                             done-p-expr)
832   (let ((offset (gensym "OFFSET"))
833         (block (gensym "BLOCK"))
834         (index (gensym "INDEX"))
835         (n-sequence (gensym "N-SEQUENCE-"))
836         (sequence (gensym "SEQUENCE"))
837         (n-end (gensym "N-END-"))
838         (end (gensym "END-")))
839     `(let ((,n-sequence ,sequence-arg)
840            (,n-end ,end-arg))
841        (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
842                          (,start ,start)
843                          (,end (%check-vector-sequence-bounds
844                                 ,n-sequence ,start ,n-end)))
845          (block ,block
846            (macrolet ((maybe-return ()
847                         '(let ((,element (aref ,sequence ,index)))
848                            (when ,done-p-expr
849                              (return-from ,block
850                                (values ,element
851                                        (- ,index ,offset)))))))
852              (if ,from-end
853                  (loop for ,index
854                        ;; (If we aren't fastidious about declaring that 
855                        ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
856                        ;; can send us off into never-never land, since
857                        ;; INDEX is initialized to -1.)
858                        of-type index-or-minus-1
859                        from (1- ,end) downto ,start do
860                        (maybe-return))
861                  (loop for ,index of-type index from ,start below ,end do
862                        (maybe-return))))
863            (values nil nil))))))
864
865 (def!macro %find-position-vector-macro (item sequence
866                                              from-end start end key test)
867   (let ((element (gensym "ELEMENT")))
868     (%find-position-or-find-position-if-vector-expansion
869      sequence
870      from-end
871      start
872      end
873      element
874      ;; (See the LIST transform for a discussion of the correct
875      ;; argument order, i.e. whether the searched-for ,ITEM goes before
876      ;; or after the checked sequence element.)
877      `(funcall ,test ,item (funcall ,key ,element)))))
878
879 (def!macro %find-position-if-vector-macro (predicate sequence
880                                                      from-end start end key)
881   (let ((element (gensym "ELEMENT")))
882     (%find-position-or-find-position-if-vector-expansion
883      sequence
884      from-end
885      start
886      end
887      element
888      `(funcall ,predicate (funcall ,key ,element)))))
889
890 (def!macro %find-position-if-not-vector-macro (predicate sequence
891                                                          from-end start end key)
892   (let ((element (gensym "ELEMENT")))
893     (%find-position-or-find-position-if-vector-expansion
894      sequence
895      from-end
896      start
897      end
898      element
899      `(not (funcall ,predicate (funcall ,key ,element))))))
900
901 ;;; %FIND-POSITION, %FIND-POSITION-IF and %FIND-POSITION-IF-NOT for
902 ;;; VECTOR data
903 (deftransform %find-position-if ((predicate sequence from-end start end key)
904                                  (function vector t t t function)
905                                  *
906                                  :policy (> speed space)
907                                  :important t)
908   "expand inline"
909   (check-inlineability-of-find-position-if sequence from-end)
910   '(%find-position-if-vector-macro predicate sequence
911                                    from-end start end key))
912
913 (deftransform %find-position-if-not ((predicate sequence from-end start end key)
914                                      (function vector t t t function)
915                                      *
916                                      :policy (> speed space)
917                                      :important t)
918   "expand inline"
919   (check-inlineability-of-find-position-if sequence from-end)
920   '(%find-position-if-not-vector-macro predicate sequence
921                                        from-end start end key))
922
923 (deftransform %find-position ((item sequence from-end start end key test)
924                               (t vector t t t function function)
925                               *
926                               :policy (> speed space)
927                               :important t)
928   "expand inline"
929   (check-inlineability-of-find-position-if sequence from-end)
930   '(%find-position-vector-macro item sequence
931                                 from-end start end key test))
932
933 ;;; logic to unravel :TEST, :TEST-NOT, and :KEY options in FIND,
934 ;;; POSITION-IF, etc.
935 (define-source-transform effective-find-position-test (test test-not)
936   `(cond
937     ((and ,test ,test-not)
938      (error "can't specify both :TEST and :TEST-NOT"))
939     (,test (%coerce-callable-to-fun ,test))
940     (,test-not
941      ;; (Without DYNAMIC-EXTENT, this is potentially horribly
942      ;; inefficient, but since the TEST-NOT option is deprecated
943      ;; anyway, we don't care.)
944      (complement (%coerce-callable-to-fun ,test-not)))
945     (t #'eql)))
946 (define-source-transform effective-find-position-key (key)
947   `(if ,key
948        (%coerce-callable-to-fun ,key)
949        #'identity))
950
951 (macrolet ((define-find-position (fun-name values-index)
952                `(define-source-transform ,fun-name (item sequence &key
953                                                     from-end (start 0) end
954                                                     key test test-not)
955                  `(nth-value ,,values-index
956                    (%find-position ,item ,sequence
957                     ,from-end ,start
958                     ,end
959                     (effective-find-position-key ,key)
960                     (effective-find-position-test ,test ,test-not))))))
961   (define-find-position find 0)
962   (define-find-position position 1))
963
964 (macrolet ((define-find-position-if (fun-name values-index)
965                `(define-source-transform ,fun-name (predicate sequence &key
966                                                     from-end (start 0)
967                                                     end key)
968                  `(nth-value
969                    ,,values-index
970                    (%find-position-if (%coerce-callable-to-fun ,predicate)
971                     ,sequence ,from-end
972                     ,start ,end
973                     (effective-find-position-key ,key))))))
974   (define-find-position-if find-if 0)
975   (define-find-position-if position-if 1))
976
977 ;;; the deprecated functions FIND-IF-NOT and POSITION-IF-NOT. We
978 ;;; didn't bother to worry about optimizing them, except note that on
979 ;;; Sat, Oct 06, 2001 at 04:22:38PM +0100, Christophe Rhodes wrote on
980 ;;; sbcl-devel
981 ;;;
982 ;;;     My understanding is that while the :test-not argument is
983 ;;;     deprecated in favour of :test (complement #'foo) because of
984 ;;;     semantic difficulties (what happens if both :test and :test-not
985 ;;;     are supplied, etc) the -if-not variants, while officially
986 ;;;     deprecated, would be undeprecated were X3J13 actually to produce
987 ;;;     a revised standard, as there are perfectly legitimate idiomatic
988 ;;;     reasons for allowing the -if-not versions equal status,
989 ;;;     particularly remove-if-not (== filter).
990 ;;;
991 ;;;     This is only an informal understanding, I grant you, but
992 ;;;     perhaps it's worth optimizing the -if-not versions in the same
993 ;;;     way as the others?
994 ;;;
995 ;;; FIXME: Maybe remove uses of these deprecated functions (and
996 ;;; definitely of :TEST-NOT) within the implementation of SBCL.
997 (macrolet ((define-find-position-if-not (fun-name values-index)
998                `(define-source-transform ,fun-name (predicate sequence &key
999                                                     from-end (start 0)
1000                                                     end key)
1001                  `(nth-value
1002                    ,,values-index
1003                    (%find-position-if-not (%coerce-callable-to-fun ,predicate)
1004                     ,sequence ,from-end
1005                     ,start ,end
1006                     (effective-find-position-key ,key))))))
1007   (define-find-position-if-not find-if-not 0)
1008   (define-find-position-if-not position-if-not 1))