0.pre7.83:
[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 (def-source-transform mapc (function list &rest more-lists)
52   (mapfoo-transform function (cons list more-lists) nil t))
53
54 (def-source-transform mapcar (function list &rest more-lists)
55   (mapfoo-transform function (cons list more-lists) :list t))
56
57 (def-source-transform mapcan (function list &rest more-lists)
58   (mapfoo-transform function (cons list more-lists) :nconc t))
59
60 (def-source-transform mapl (function list &rest more-lists)
61   (mapfoo-transform function (cons list more-lists) nil nil))
62
63 (def-source-transform maplist (function list &rest more-lists)
64   (mapfoo-transform function (cons list more-lists) :list nil))
65
66 (def-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 (> speed safety))
91                  bare)
92                 ((not constant-result-type-arg-p)
93                  `(sequence-of-checked-length-given-type ,bare
94                                                          result-type-arg))
95                 (t
96                  (let ((result-ctype (specifier-type result-type)))
97                    (if (array-type-p result-ctype)
98                        (let* ((dims (array-type-dimensions result-ctype))
99                               (dim (first dims)))
100                          (if (eq dim '*)
101                              bare
102                              `(vector-of-checked-length-given-length ,bare
103                                                                      ,dim)))
104                        bare))))))))
105
106 ;;; Try to compile %MAP efficiently when we can determine sequence
107 ;;; argument types at compile time.
108 ;;;
109 ;;; Note: This transform was written to allow open coding of
110 ;;; quantifiers by expressing them in terms of (MAP NIL ..). For
111 ;;; non-NIL values of RESULT-TYPE, it's still useful, but not
112 ;;; necessarily as efficient as possible. In particular, it will be
113 ;;; inefficient when RESULT-TYPE is a SIMPLE-ARRAY with specialized
114 ;;; numeric element types. It should be straightforward to make it
115 ;;; handle that case more efficiently, but it's left as an exercise to
116 ;;; the reader, because the code is complicated enough already and I
117 ;;; don't happen to need that functionality right now. -- WHN 20000410
118 (deftransform %map ((result-type fun &rest seqs) * * :policy (>= speed space))
119   "open code"
120   (unless seqs (abort-ir1-transform "no sequence args"))
121   (unless (constant-continuation-p result-type)
122     (give-up-ir1-transform "RESULT-TYPE argument not constant"))
123   (labels (;; 1-valued SUBTYPEP, fails unless second value of SUBTYPEP is true
124            (fn-1subtypep (fn x y)
125              (multiple-value-bind (subtype-p valid-p) (funcall fn x y)
126                (if valid-p
127                    subtype-p
128                    (give-up-ir1-transform
129                     "can't analyze sequence type relationship"))))
130            (1subtypep (x y) (fn-1subtypep #'sb!xc:subtypep x y))
131            (1csubtypep (x y) (fn-1subtypep #'csubtypep x y))
132            (seq-supertype (seq)
133              (let ((ctype (continuation-type seq)))
134                (cond ((1csubtypep ctype (specifier-type 'vector)) 'vector)
135                      ((1csubtypep ctype (specifier-type 'list)) 'list)
136                      (t
137                       (give-up-ir1-transform
138                        "can't determine sequence argument type"))))))
139     (let* ((result-type-value (continuation-value result-type))
140            (result-supertype (cond ((null result-type-value) 'null)
141                                    ((1subtypep result-type-value 'vector)
142                                     'vector)
143                                    ((1subtypep result-type-value 'list)
144                                     'list)
145                                    (t
146                                     (give-up-ir1-transform
147                                      "can't determine result type"))))
148            (seq-supertypes (mapcar #'seq-supertype seqs)))
149       (cond ((and result-type-value (= 1 (length seqs)))
150              ;; The consing arity-1 cases can be implemented
151              ;; reasonably efficiently as function calls, and the cost
152              ;; of consing should be significantly larger than
153              ;; function call overhead, so we always compile these
154              ;; cases as full calls regardless of speed-versus-space
155              ;; optimization policy.
156              (cond ((subtypep 'list result-type-value)
157                     '(apply #'%map-to-list-arity-1 fun seqs))
158                    (;; (This one can be inefficient due to COERCE, but
159                     ;; the current open-coded implementation has the
160                     ;; same problem.)
161                     (subtypep result-type-value 'vector)
162                     `(coerce (apply #'%map-to-simple-vector-arity-1 fun seqs)
163                              ',result-type-value))
164                    (t (give-up-ir1-transform
165                        "internal error: unexpected sequence type"))))
166             (t
167              (let* ((seq-args (make-gensym-list (length seqs)))
168                     (index-bindingoids
169                      (mapcar (lambda (seq-arg seq-supertype)
170                                (let ((i (gensym "I"))) 
171                                  (ecase seq-supertype
172                                    (vector `(,i 0 (1+ ,i)))
173                                    (list `(,i ,seq-arg (rest ,i))))))
174                              seq-args seq-supertypes))
175                     (indices (mapcar #'first index-bindingoids))
176                     (index-decls (mapcar (lambda (index seq-supertype)
177                                            `(type ,(ecase seq-supertype
178                                                      (vector 'index)
179                                                      (list 'list))
180                                                   ,index))
181                                          indices seq-supertypes))
182                     (tests (mapcar (lambda (seq-arg seq-supertype index)
183                                      (ecase seq-supertype
184                                        (vector `(>= ,index (length ,seq-arg)))
185                                        (list `(endp ,index))))
186                                    seq-args seq-supertypes indices))
187                     (values (mapcar (lambda (seq-arg seq-supertype index)
188                                       (ecase seq-supertype
189                                         (vector `(aref ,seq-arg ,index))
190                                         (list `(first ,index))))
191                                     seq-args seq-supertypes indices)))
192                (multiple-value-bind (push-dacc final-result)
193                    (ecase result-supertype
194                      (null (values nil nil))
195                      (list (values `(push dacc acc) `(nreverse acc)))
196                      (vector (values `(push dacc acc)
197                                      `(coerce (nreverse acc)
198                                               ',result-type-value))))
199                  ;; (We use the same idiom, of returning a LAMBDA from
200                  ;; DEFTRANSFORM, as is used in the DEFTRANSFORMs for
201                  ;; FUNCALL and ALIEN-FUNCALL, and for the same
202                  ;; reason: we need to get the runtime values of each
203                  ;; of the &REST vars.)
204                  `(lambda (result-type fun ,@seq-args)
205                     (declare (ignore result-type))
206                     (do ((really-fun (%coerce-callable-to-fun fun))
207                          ,@index-bindingoids
208                          (acc nil))
209                     ((or ,@tests)
210                      ,final-result)
211                     (declare ,@index-decls)
212                     (declare (type list acc))
213                     (declare (ignorable acc))
214                     (let ((dacc (funcall really-fun ,@values)))
215                       (declare (ignorable dacc))
216                       ,push-dacc))))))))))
217 \f
218 (deftransform elt ((s i) ((simple-array * (*)) *) * :when :both)
219   '(aref s i))
220
221 (deftransform elt ((s i) (list *) * :when :both)
222   '(nth i s))
223
224 (deftransform %setelt ((s i v) ((simple-array * (*)) * *) * :when :both)
225   '(%aset s i v))
226
227 (deftransform %setelt ((s i v) (list * *))
228   '(setf (car (nthcdr i s)) v))
229
230 ;;; FIXME: I still think (DOLIST (..) (DEFTRANSFORM ..)) is weird.
231 ;;; For that matter, it would be nice to use DEF-FROB for these
232 ;;; sorts of things, so folks looking for the definitions of
233 ;;; FOO can search for '\(def.*\<foo\>' and have a chance in hell..
234 (dolist (name '(member memq))
235   (deftransform name ((e l &key (test #'eql)) '* '* :node node :when :both
236                       :eval-name t)
237     (unless (constant-continuation-p l)
238       (give-up-ir1-transform))
239
240     (let ((val (continuation-value l)))
241       (unless (policy node
242                       (or (= speed 3)
243                           (and (>= speed space)
244                                (<= (length val) 5))))
245         (give-up-ir1-transform))
246
247       (labels ((frob (els)
248                  (if els
249                      `(if (funcall test e ',(car els))
250                           ',els
251                           ,(frob (cdr els)))
252                      nil)))
253         (frob val)))))
254
255 ;;; FIXME: Rewrite this so that these definitions of DELETE, ASSOC, and MEMBER
256 ;;; are lexically findable:
257 ;;; (MACROLET ((DEF-FROB (X Y) ..))
258 ;;;   (DEF-FROB DELETE DELQ)
259 ;;;   (DEF-FROB ASSOC ASSQ)
260 ;;;   (DEF-FROB MEMBER MEMQ))
261 ;;; And while I'm at it, I could save a few byte by implementing the
262 ;;; transform body as call to a shared function instead of duplicated
263 ;;; macroexpanded code.
264 (dolist (x '((delete delq)
265              (assoc assq)
266              (member memq)))
267   (destructuring-bind (fun eq-fun) x
268     (deftransform fun ((item list &key test) '(t list &rest t) '*
269                         :eval-name t)
270       "convert to EQ test"
271       ;; FIXME: The scope of this transformation could be widened somewhat,
272       ;; letting it work whenever the test is 'EQL and we know from the
273       ;; type of ITEM that it #'EQ works like #'EQL on it. (E.g. types
274       ;; FIXNUM, CHARACTER, and SYMBOL.)
275       ;;   If TEST is EQ, apply transform, else
276       ;;   if test is not EQL, then give up on transform, else
277       ;;   if ITEM is not a NUMBER or is a FIXNUM, apply transform, else
278       ;;   give up on transform.
279       (cond (test
280              (unless (continuation-function-is test '(eq))
281                (give-up-ir1-transform)))
282             ((types-equal-or-intersect (continuation-type item)
283                                        (specifier-type 'number))
284              (give-up-ir1-transform "Item might be a number.")))
285       `(,eq-fun item list))))
286
287 (deftransform delete-if ((pred list) (t list))
288   "open code"
289   '(do ((x list (cdr x))
290         (splice '()))
291        ((endp x) list)
292      (cond ((funcall pred (car x))
293             (if (null splice)
294                 (setq list (cdr x))
295                 (rplacd splice (cdr x))))
296            (T (setq splice x)))))
297
298 (deftransform fill ((seq item &key (start 0) (end (length seq)))
299                     (vector t &key (:start t) (:end index))
300                     *
301                     :policy (> speed space))
302   "open code"
303   (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
304     `(with-array-data ((data seq)
305                        (start start)
306                        (end end))
307        (declare (type (simple-array ,element-type 1) data))
308        (do ((i start (1+ i)))
309            ((= i end) seq)
310          (declare (type index i))
311          ;; WITH-ARRAY-DATA did our range checks once and for all, so
312          ;; it'd be wasteful to check again on every AREF.
313          (declare (optimize (safety 0))) 
314          (setf (aref data i) item)))))
315 \f
316 ;;;; utilities
317
318 ;;; Return true if CONT's only use is a non-notinline reference to a
319 ;;; global function with one of the specified NAMES.
320 (defun continuation-function-is (cont names)
321   (declare (type continuation cont) (list names))
322   (let ((use (continuation-use cont)))
323     (and (ref-p use)
324          (let ((leaf (ref-leaf use)))
325            (and (global-var-p leaf)
326                 (eq (global-var-kind leaf) :global-function)
327                 (not (null (member (leaf-name leaf) names :test #'equal))))))))
328
329 ;;; If CONT is a constant continuation, the return the constant value.
330 ;;; If it is null, then return default, otherwise quietly give up the
331 ;;; IR1 transform.
332 ;;;
333 ;;; ### Probably should take an ARG and flame using the NAME.
334 (defun constant-value-or-lose (cont &optional default)
335   (declare (type (or continuation null) cont))
336   (cond ((not cont) default)
337         ((constant-continuation-p cont)
338          (continuation-value cont))
339         (t
340          (give-up-ir1-transform))))
341
342 #|
343 ;;; This is a frob whose job it is to make it easier to pass around
344 ;;; the arguments to IR1 transforms. It bundles together the name of
345 ;;; the argument (which should be referenced in any expansion), and
346 ;;; the continuation for that argument (or NIL if unsupplied.)
347 (defstruct (arg (:constructor %make-arg (name cont))
348                 (:copier nil))
349   (name nil :type symbol)
350   (cont nil :type (or continuation null)))
351 (defmacro make-arg (name)
352   `(%make-arg ',name ,name))
353
354 ;;; If Arg is null or its CONT is null, then return Default, otherwise
355 ;;; return Arg's NAME.
356 (defun default-arg (arg default)
357   (declare (type (or arg null) arg))
358   (if (and arg (arg-cont arg))
359       (arg-name arg)
360       default))
361
362 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
363 ;;; CONT must be a constant continuation whose value we return. If not, we
364 ;;; give up.
365 (defun arg-constant-value (arg default)
366   (declare (type (or arg null) arg))
367   (if (and arg (arg-cont arg))
368       (let ((cont (arg-cont arg)))
369         (unless (constant-continuation-p cont)
370           (give-up-ir1-transform "Argument is not constant: ~S."
371                                  (arg-name arg)))
372         (continuation-value from-end))
373       default))
374
375 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
376 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
377 (defun arg-eql (arg default x)
378   (declare (type (or arg null) x))
379   (if (and arg (arg-cont arg))
380       (let ((cont (arg-cont arg)))
381         (and (constant-continuation-p cont)
382              (eql (continuation-value cont) x)))
383       (eql default x)))
384
385 (defstruct (iterator (:copier nil))
386   ;; The kind of iterator.
387   (kind nil (member :normal :result))
388   ;; A list of LET* bindings to create the initial state.
389   (binds nil :type list)
390   ;; A list of declarations for Binds.
391   (decls nil :type list)
392   ;; A form that returns the current value. This may be set with SETF to set
393   ;; the current value.
394   (current (error "Must specify CURRENT."))
395   ;; In a :Normal iterator, a form that tests whether there is a current value.
396   (done nil)
397   ;; In a :Result iterator, a form that truncates the result at the current
398   ;; position and returns it.
399   (result nil)
400   ;; A form that returns the initial total number of values. The result is
401   ;; undefined after NEXT has been evaluated.
402   (length (error "Must specify LENGTH."))
403   ;; A form that advances the state to the next value. It is an error to call
404   ;; this when the iterator is Done.
405   (next (error "Must specify NEXT.")))
406
407 ;;; Type of an index var that can go negative (in the from-end case.)
408 (deftype neg-index ()
409   `(integer -1 ,most-positive-fixnum))
410
411 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
412 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
413 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
414 ;;; the index of the current element in the sequence.
415 ;;;
416 ;;; If we can't tell whether the sequence is a list or a vector, or whether
417 ;;; the iteration is forward or backward, then GIVE-UP.
418 (defun make-sequence-iterator (sequence type &key start end from-end index)
419   (declare (symbol sequence) (type ctype type)
420            (type (or arg null) start end from-end)
421            (type (or symbol null) index))
422   (let ((from-end (arg-constant-value from-end nil)))
423     (cond ((csubtypep type (specifier-type 'vector))
424            (let* ((n-stop (gensym))
425                   (n-idx (or index (gensym)))
426                   (start (default-arg 0 start))
427                   (end (default-arg `(length ,sequence) end)))
428              (make-iterator
429               :kind :normal
430               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
431                        (,n-stop ,(if from-end `(1- ,start) ,end)))
432               :decls `((type neg-index ,n-idx ,n-stop))
433               :current `(aref ,sequence ,n-idx)
434               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
435               :next `(setq ,n-idx
436                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
437               :length (if from-end
438                           `(- ,n-idx ,n-stop)
439                           `(- ,n-stop ,n-idx)))))
440           ((csubtypep type (specifier-type 'list))
441            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
442                   (n-current (gensym))
443                   (start-p (not (arg-eql start 0 0)))
444                   (end-p (not (arg-eql end nil nil)))
445                   (start (default-arg start 0))
446                   (end (default-arg end nil)))
447              (make-iterator
448               :binds `((,n-current
449                         ,(if from-end
450                              (if (or start-p end-p)
451                                  `(nreverse (subseq ,sequence ,start
452                                                     ,@(when end `(,end))))
453                                  `(reverse ,sequence))
454                              (if start-p
455                                  `(nthcdr ,start ,sequence)
456                                  sequence)))
457                        ,@(when n-stop
458                            `((,n-stop (nthcdr (the index
459                                                    (- ,end ,start))
460                                               ,n-current))))
461                        ,@(when index
462                            `((,index ,(if from-end `(1- ,end) start)))))
463               :kind :normal
464               :decls `((list ,n-current ,n-end)
465                        ,@(when index `((type neg-index ,index))))
466               :current `(car ,n-current)
467               :done `(eq ,n-current ,n-stop)
468               :length `(- ,(or end `(length ,sequence)) ,start)
469               :next `(progn
470                        (setq ,n-current (cdr ,n-current))
471                        ,@(when index
472                            `((setq ,n-idx
473                                    ,(if from-end
474                                         `(1- ,index)
475                                         `(1+ ,index)))))))))
476           (t
477            (give-up-ir1-transform
478             "can't tell whether sequence is a list or a vector")))))
479
480 ;;; Make an iterator used for constructing result sequences. Name is a
481 ;;; variable to be bound to the result sequence. Type is the type of result
482 ;;; sequence to make. Length is an expression to be evaluated to get the
483 ;;; maximum length of the result (not evaluated in list case.)
484 (defun make-result-sequence-iterator (name type length)
485   (declare (symbol name) (type ctype type))
486
487 ;;; Defines each Name as a local macro that will call the value of the
488 ;;; Fun-Arg with the given arguments. If the argument isn't known to be a
489 ;;; function, give them an efficiency note and reference a coerced version.
490 (defmacro coerce-functions (specs &body body)
491   #!+sb-doc
492   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
493   (collect ((binds)
494             (defs))
495     (dolist (spec specs)
496       `(let ((body (progn ,@body))
497              (n-fun (arg-name ,(second spec)))
498              (fun-cont (arg-cont ,(second spec))))
499          (cond ((not fun-cont)
500                 `(macrolet ((,',(first spec) (&rest args)
501                              `(,',',(third spec) ,@args)))
502                    ,body))
503                ((not (csubtypep (continuation-type fun-cont)
504                                 (specifier-type 'function)))
505                 (when (policy *compiler-error-context*
506                               (> speed inhibit-warnings))
507                   (compiler-note
508                    "~S may not be a function, so must coerce at run-time."
509                    n-fun))
510                 (once-only ((n-fun `(if (functionp ,n-fun)
511                                         ,n-fun
512                                         (symbol-function ,n-fun))))
513                   `(macrolet ((,',(first spec) (&rest args)
514                                `(funcall ,',n-fun ,@args)))
515                      ,body)))
516                (t
517                 `(macrolet ((,',(first spec) (&rest args)
518                               `(funcall ,',n-fun ,@args)))
519                    ,body)))))))
520
521 ;;; Wrap code around the result of the body to define Name as a local macro
522 ;;; that returns true when its arguments satisfy the test according to the Args
523 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
524 ;;; transform.
525 (defmacro with-sequence-test ((name test test-not) &body body)
526   `(let ((not-p (arg-cont ,test-not)))
527      (when (and (arg-cont ,test) not-p)
528        (abort-ir1-transform "Both ~S and ~S were supplied."
529                             (arg-name ,test)
530                             (arg-name ,test-not)))
531      (coerce-functions ((,name (if not-p ,test-not ,test) eql))
532        ,@body)))
533 |#
534 \f
535 ;;;; hairy sequence transforms
536
537 ;;; FIXME: no hairy sequence transforms in SBCL?
538 \f
539 ;;;; string operations
540
541 ;;; We transform the case-sensitive string predicates into a non-keyword
542 ;;; version. This is an IR1 transform so that we don't have to worry about
543 ;;; changing the order of evaluation.
544 (dolist (stuff '((string< string<*)
545                  (string> string>*)
546                  (string<= string<=*)
547                  (string>= string>=*)
548                  (string= string=*)
549                  (string/= string/=*)))
550   (destructuring-bind (fun pred*) stuff
551     (deftransform fun ((string1 string2 &key (start1 0) end1
552                                 (start2 0) end2)
553                        '* '* :eval-name t)
554       `(,pred* string1 string2 start1 end1 start2 end2))))
555
556 ;;; Return a form that tests the free variables STRING1 and STRING2 for the
557 ;;; ordering relationship specified by Lessp and Equalp. The start and end are
558 ;;; also gotten from the environment. Both strings must be simple strings.
559 (dolist (stuff '((string<* t nil)
560                  (string<=* t t)
561                  (string>* nil nil)
562                  (string>=* nil t)))
563   (destructuring-bind (name lessp equalp) stuff
564     (deftransform name ((string1 string2 start1 end1 start2 end2)
565                         '(simple-string simple-string t t t t) '*
566                         :eval-name t)
567       `(let* ((end1 (if (not end1) (length string1) end1))
568               (end2 (if (not end2) (length string2) end2))
569               (index (sb!impl::%sp-string-compare
570                       string1 start1 end1 string2 start2 end2)))
571          (if index
572              (cond ((= index ,(if lessp 'end1 'end2)) index)
573                    ((= index ,(if lessp 'end2 'end1)) nil)
574                    ((,(if lessp 'char< 'char>)
575                      (schar string1 index)
576                      (schar string2
577                             (truly-the index
578                                        (+ index
579                                           (truly-the fixnum
580                                                      (- start2 start1))))))
581                     index)
582                    (t nil))
583              ,(if equalp 'end1 nil))))))
584
585 (dolist (stuff '((string=* not)
586                  (string/=* identity)))
587   (destructuring-bind (name result-fun) stuff
588     (deftransform name ((string1 string2 start1 end1 start2 end2)
589                         '(simple-string simple-string t t t t) '*
590                         :eval-name t)
591       `(,result-fun
592         (sb!impl::%sp-string-compare
593          string1 start1 (or end1 (length string1))
594          string2 start2 (or end2 (length string2)))))))
595 \f
596 ;;;; string-only transforms for sequence functions
597 ;;;;
598 ;;;; Note: CMU CL had more of these, including transforms for
599 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
600 ;;;; transforms for functions which cons, since our GC overhead is
601 ;;;; sufficiently large that it doesn't seem worth it to try to
602 ;;;; economize on function call overhead or on the overhead of runtime
603 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
604 ;;;; a full call to CONCATENATE would have to look up the sequence
605 ;;;; type, which can be really slow.
606 ;;;;
607 ;;;; FIXME: It would be nicer for these transforms to work for any
608 ;;;; calls when all arguments are vectors with the same element type,
609 ;;;; rather than restricting them to STRINGs only.
610
611 ;;; FIXME: Shouldn't we be testing for legality of
612 ;;;   * START1, START2, END1, and END2 indices?
613 ;;;   * size of copied string relative to destination string?
614 ;;; (Either there should be tests conditional on SAFETY>=SPEED, or
615 ;;; the transform should be conditional on SPEED>SAFETY.)
616 ;;;
617 ;;; FIXME: Also, the transform should probably be dependent on
618 ;;; SPEED>SPACE.
619 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
620                                 end1 end2)
621                        (simple-string simple-string &rest t))
622   `(locally
623      (declare (optimize (safety 0)))
624      (bit-bash-copy string2
625                     (the index
626                          (+ (the index (* start2 sb!vm:n-byte-bits))
627                             ,vector-data-bit-offset))
628                     string1
629                     (the index
630                          (+ (the index (* start1 sb!vm:n-byte-bits))
631                             ,vector-data-bit-offset))
632                     (the index
633                          (* (min (the index (- (or end1 (length string1))
634                                                start1))
635                                  (the index (- (or end2 (length string2))
636                                                start2)))
637                             sb!vm:n-byte-bits)))
638      string1))
639
640 ;;; FIXME: It seems as though it should be possible to make a DEFUN
641 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
642 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
643 ;;; at least once DYNAMIC-EXTENT works.
644 (deftransform concatenate ((rtype &rest sequences)
645                            (t &rest simple-string)
646                            simple-string)
647   (collect ((lets)
648             (forms)
649             (all-lengths)
650             (args))
651     (dolist (seq sequences)
652       (declare (ignore seq))
653       (let ((n-seq (gensym))
654             (n-length (gensym)))
655         (args n-seq)
656         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
657         (all-lengths n-length)
658         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
659                                res start
660                                ,n-length))
661         (forms `(setq start (+ start ,n-length)))))
662     `(lambda (rtype ,@(args))
663        (declare (ignore rtype))
664        (let* (,@(lets)
665               (res (make-string (truncate (the index (+ ,@(all-lengths)))
666                                           sb!vm:n-byte-bits)))
667               (start ,vector-data-bit-offset))
668          (declare (type index start ,@(all-lengths)))
669          ,@(forms)
670          res))))
671 \f
672 ;;;; CONS accessor DERIVE-TYPE optimizers
673
674 (defoptimizer (car derive-type) ((cons))
675   (let ((type (continuation-type cons))
676         (null-type (specifier-type 'null)))
677     (cond ((eq type null-type)
678            null-type)
679           ((cons-type-p type)
680            (cons-type-car-type type)))))
681
682 (defoptimizer (cdr derive-type) ((cons))
683   (let ((type (continuation-type cons))
684         (null-type (specifier-type 'null)))
685     (cond ((eq type null-type)
686            null-type)
687           ((cons-type-p type)
688            (cons-type-cdr-type type)))))
689 \f
690 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
691
692 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
693 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
694 ;;; expansion, so we factor out the condition into this function.
695 (defun check-inlineability-of-find-position-if (sequence from-end)
696   (let ((ctype (continuation-type sequence)))
697     (cond ((csubtypep ctype (specifier-type 'vector))
698            ;; It's not worth trying to inline vector code unless we
699            ;; know a fair amount about it at compile time.
700            (upgraded-element-type-specifier-or-give-up sequence)
701            (unless (constant-continuation-p from-end)
702              (give-up-ir1-transform
703               "FROM-END argument value not known at compile time")))
704           ((csubtypep ctype (specifier-type 'list))
705            ;; Inlining on lists is generally worthwhile.
706            ) 
707           (t
708            (give-up-ir1-transform
709             "sequence type not known at compile time")))))
710
711 ;;; %FIND-POSITION-IF for LIST data
712 (deftransform %find-position-if ((predicate sequence from-end start end key)
713                                  (function list t t t function)
714                                  *
715                                  :policy (> speed space)
716                                  :important t)
717   "expand inline"
718   '(let ((index 0)
719          (find nil)
720          (position nil))
721      (declare (type index index))
722      (dolist (i sequence (values find position))
723        (let ((key-i (funcall key i)))
724          (when (and end (>= index end))
725            (return (values find position)))
726          (when (>= index start)
727            (when (funcall predicate key-i)
728              ;; This hack of dealing with non-NIL FROM-END for list
729              ;; data by iterating forward through the list and keeping
730              ;; track of the last time we found a match might be more
731              ;; screwy than what the user expects, but it seems to be
732              ;; allowed by the ANSI standard. (And if the user is
733              ;; screwy enough to ask for FROM-END behavior on list
734              ;; data, turnabout is fair play.)
735              ;;
736              ;; It's also not enormously efficient, calling PREDICATE
737              ;; and KEY more often than necessary; but all the
738              ;; alternatives seem to have their own efficiency
739              ;; problems.
740              (if from-end
741                  (setf find i
742                        position index)
743                  (return (values i index))))))
744        (incf index))))
745
746 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
747 ;;; without loss of efficiency. (I.e., the optimizer should be able
748 ;;; to straighten everything out.)
749 (deftransform %find-position ((item sequence from-end start end key test)
750                               (t list t t t t t)
751                               *
752                               :policy (> speed space)
753                               :important t)
754   "expand inline"
755   '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
756                         ;; I'm having difficulty believing I'm
757                         ;; reading it right, but as far as I can see,
758                         ;; the only guidance that ANSI gives for the
759                         ;; order of arguments to asymmetric tests is
760                         ;; the character-set dependent example from
761                         ;; the definition of FIND,
762                         ;;   (find #\d "here are some.." :test #'char>)
763                         ;;     => #\Space
764                         ;; (In ASCII, we have (CHAR> #\d #\SPACE)=>T.)
765                         ;; (Neither the POSITION definition page nor
766                         ;; section 17.2 ("Rules about Test Functions")
767                         ;; seem to consider the possibility of
768                         ;; asymmetry.)
769                         ;;
770                         ;; So, judging from the example, we want to
771                         ;; do (FUNCALL TEST-FUN ITEM I), because
772                         ;; (FUNCALL #'CHAR> #\d #\SPACE)=>T.
773                         ;;
774                         ;; -- WHN (whose attention was drawn to it by
775                         ;;         Alexey Dejneka's bug report/fix)
776                         (lambda (i)
777                           (funcall test-fun item i)))
778                       sequence
779                       from-end
780                       start
781                       end
782                       (%coerce-callable-to-fun key)))
783
784 ;;; The inline expansions for the VECTOR case are saved as macros so
785 ;;; that we can share them between the DEFTRANSFORMs and the default
786 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
787 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
788 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
789                                                             from-end
790                                                             start
791                                                             end-arg
792                                                             element
793                                                             done-p-expr)
794   (let ((offset (gensym "OFFSET"))
795         (block (gensym "BLOCK"))
796         (index (gensym "INDEX"))
797         (n-sequence (gensym "N-SEQUENCE-"))
798         (sequence (gensym "SEQUENCE"))
799         (n-end (gensym "N-END-"))
800         (end (gensym "END-")))
801     `(let ((,n-sequence ,sequence-arg)
802            (,n-end ,end-arg))
803        (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
804                          (,start ,start)
805                          (,end (or ,n-end (length ,n-sequence))))
806          (block ,block
807            (macrolet ((maybe-return ()
808                         '(let ((,element (aref ,sequence ,index)))
809                            (when ,done-p-expr
810                              (return-from ,block
811                                (values ,element
812                                        (- ,index ,offset)))))))
813              (if ,from-end
814                  (loop for ,index
815                        ;; (If we aren't fastidious about declaring that 
816                        ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
817                        ;; can send us off into never-never land, since
818                        ;; INDEX is initialized to -1.)
819                        of-type index-or-minus-1
820                        from (1- ,end) downto ,start do
821                        (maybe-return))
822                  (loop for ,index of-type index from ,start below ,end do
823                        (maybe-return))))
824            (values nil nil))))))
825
826 (def!macro %find-position-vector-macro (item sequence
827                                              from-end start end key test)
828   (let ((element (gensym "ELEMENT")))
829     (%find-position-or-find-position-if-vector-expansion
830      sequence
831      from-end
832      start
833      end
834      element
835      ;; (See the LIST transform for a discussion of the correct
836      ;; argument order, i.e. whether the searched-for ,ITEM goes before
837      ;; or after the checked sequence element.)
838      `(funcall ,test ,item (funcall ,key ,element)))))
839
840 (def!macro %find-position-if-vector-macro (predicate sequence
841                                                      from-end start end key)
842   (let ((element (gensym "ELEMENT")))
843     (%find-position-or-find-position-if-vector-expansion
844      sequence
845      from-end
846      start
847      end
848      element
849      `(funcall ,predicate (funcall ,key ,element)))))
850
851 ;;; %FIND-POSITION and %FIND-POSITION-IF for VECTOR data
852 (deftransform %find-position-if ((predicate sequence from-end start end key)
853                                  (function vector t t t function)
854                                  *
855                                  :policy (> speed space)
856                                  :important t)
857   "expand inline"
858   (check-inlineability-of-find-position-if sequence from-end)
859   '(%find-position-if-vector-macro predicate sequence
860                                    from-end start end key))
861 (deftransform %find-position ((item sequence from-end start end key test)
862                               (t vector t t t function function)
863                               *
864                               :policy (> speed space)
865                               :important t)
866   "expand inline"
867   (check-inlineability-of-find-position-if sequence from-end)
868   '(%find-position-vector-macro item sequence
869                                 from-end start end key test))