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