a938962f64e472185cc112145290217829fc3671
[sbcl.git] / src / compiler / seqtran.lisp
1 ;;;; optimizers for list and sequence functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!C")
13 \f
14 ;;;; mapping onto lists: the MAPFOO functions
15
16 (defun mapfoo-transform (fn arglists accumulate take-car)
17   (collect ((do-clauses)
18             (args-to-fn)
19             (tests))
20     (let ((n-first (gensym)))
21       (dolist (a (if accumulate
22                      arglists
23                      `(,n-first ,@(rest arglists))))
24         (let ((v (gensym)))
25           (do-clauses `(,v ,a (cdr ,v)))
26           (tests `(endp ,v))
27           (args-to-fn (if take-car `(car ,v) v))))
28
29       (let ((call `(funcall ,fn . ,(args-to-fn)))
30             (endtest `(or ,@(tests))))
31         (ecase accumulate
32           (:nconc
33            (let ((temp (gensym))
34                  (map-result (gensym)))
35              `(let ((,map-result (list nil)))
36                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
37                               (,endtest (cdr ,map-result))
38                   (setq ,temp (last (nconc ,temp ,call)))))))
39           (:list
40            (let ((temp (gensym))
41                  (map-result (gensym)))
42              `(let ((,map-result (list nil)))
43                 (do-anonymous ((,temp ,map-result) . ,(do-clauses))
44                               (,endtest (cdr ,map-result))
45                   (rplacd ,temp (setq ,temp (list ,call)))))))
46           ((nil)
47            `(let ((,n-first ,(first arglists)))
48               (do-anonymous ,(do-clauses)
49                             (,endtest ,n-first) ,call))))))))
50
51 (define-source-transform mapc (function list &rest more-lists)
52   (mapfoo-transform function (cons list more-lists) nil t))
53
54 (define-source-transform mapcar (function list &rest more-lists)
55   (mapfoo-transform function (cons list more-lists) :list t))
56
57 (define-source-transform mapcan (function list &rest more-lists)
58   (mapfoo-transform function (cons list more-lists) :nconc t))
59
60 (define-source-transform mapl (function list &rest more-lists)
61   (mapfoo-transform function (cons list more-lists) nil nil))
62
63 (define-source-transform maplist (function list &rest more-lists)
64   (mapfoo-transform function (cons list more-lists) :list nil))
65
66 (define-source-transform mapcon (function list &rest more-lists)
67   (mapfoo-transform function (cons list more-lists) :nconc nil))
68 \f
69 ;;;; mapping onto sequences: the MAP function
70
71 ;;; MAP is %MAP plus a check to make sure that any length specified in
72 ;;; the result type matches the actual result. We also wrap it in a
73 ;;; TRULY-THE for the most specific type we can determine.
74 (deftransform map ((result-type-arg fun &rest seqs) * * :node node)
75   (let* ((seq-names (make-gensym-list (length seqs)))
76          (bare `(%map result-type-arg fun ,@seq-names))
77          (constant-result-type-arg-p (constant-continuation-p result-type-arg))
78          ;; what we know about the type of the result. (Note that the
79          ;; "result type" argument is not necessarily the type of the
80          ;; result, since NIL means the result has NULL type.)
81          (result-type (if (not constant-result-type-arg-p)
82                           'consed-sequence
83                           (let ((result-type-arg-value
84                                  (continuation-value result-type-arg)))
85                             (if (null result-type-arg-value)
86                                 'null
87                                 result-type-arg-value)))))
88     `(lambda (result-type-arg fun ,@seq-names)
89        (truly-the ,result-type
90          ,(cond ((policy node (> 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 (macrolet ((def-frob (name)
231              `(deftransform ,name ((e l &key (test #'eql)) * * :node node :when :both)
232                 (unless (constant-continuation-p l)
233                   (give-up-ir1-transform))
234
235                 (let ((val (continuation-value l)))
236                   (unless (policy node
237                                   (or (= speed 3)
238                                       (and (>= speed space)
239                                            (<= (length val) 5))))
240                     (give-up-ir1-transform))
241
242                   (labels ((frob (els)
243                              (if els
244                                  `(if (funcall test e ',(car els))
245                                       ',els
246                                       ,(frob (cdr els)))
247                                  nil)))
248                     (frob val))))))
249   (def-frob member)
250   (def-frob memq))
251
252 ;;; FIXME: We have rewritten the original code that used DOLIST to this
253 ;;; more natural MACROLET.  However, the original code suggested that when
254 ;;; this was done, a few bytes could be saved by a call to a shared
255 ;;; function.  This remains to be done.
256 (macrolet ((def-frob (fun eq-fun)
257              `(deftransform ,fun ((item list &key test) (t list &rest t) *)
258                 "convert to EQ test"
259                 ;; FIXME: The scope of this transformation could be
260                 ;; widened somewhat, letting it work whenever the test is
261                 ;; 'EQL and we know from the type of ITEM that it #'EQ
262                 ;; works like #'EQL on it. (E.g. types FIXNUM, CHARACTER,
263                 ;; and SYMBOL.)
264                 ;;   If TEST is EQ, apply transform, else
265                 ;;   if test is not EQL, then give up on transform, else
266                 ;;   if ITEM is not a NUMBER or is a FIXNUM, apply
267                 ;;   transform, else give up on transform.
268                 (cond (test
269                        (unless (continuation-function-is test '(eq))
270                          (give-up-ir1-transform)))
271                       ((types-equal-or-intersect (continuation-type item)
272                                                  (specifier-type 'number))
273                        (give-up-ir1-transform "Item might be a number.")))
274                 `(,',eq-fun item list))))
275   (def-frob delete delq)
276   (def-frob assoc assq)
277   (def-frob member memq))
278
279 (deftransform delete-if ((pred list) (t list))
280   "open code"
281   '(do ((x list (cdr x))
282         (splice '()))
283        ((endp x) list)
284      (cond ((funcall pred (car x))
285             (if (null splice)
286                 (setq list (cdr x))
287                 (rplacd splice (cdr x))))
288            (T (setq splice x)))))
289
290 (deftransform fill ((seq item &key (start 0) (end (length seq)))
291                     (vector t &key (:start t) (:end index))
292                     *
293                     :policy (> speed space))
294   "open code"
295   (let ((element-type (upgraded-element-type-specifier-or-give-up seq)))
296     `(with-array-data ((data seq)
297                        (start start)
298                        (end end))
299        (declare (type (simple-array ,element-type 1) data))
300        (do ((i start (1+ i)))
301            ((= i end) seq)
302          (declare (type index i))
303          ;; WITH-ARRAY-DATA did our range checks once and for all, so
304          ;; it'd be wasteful to check again on every AREF.
305          (declare (optimize (safety 0))) 
306          (setf (aref data i) item)))))
307 \f
308 ;;;; utilities
309
310 ;;; Return true if CONT's only use is a non-notinline reference to a
311 ;;; global function with one of the specified NAMES.
312 (defun continuation-function-is (cont names)
313   (declare (type continuation cont) (list names))
314   (let ((use (continuation-use cont)))
315     (and (ref-p use)
316          (let ((leaf (ref-leaf use)))
317            (and (global-var-p leaf)
318                 (eq (global-var-kind leaf) :global-function)
319                 (not (null (member (leaf-source-name leaf) names
320                                    :test #'equal))))))))
321
322 ;;; If CONT is a constant continuation, the return the constant value.
323 ;;; If it is null, then return default, otherwise quietly give up the
324 ;;; IR1 transform.
325 ;;;
326 ;;; ### Probably should take an ARG and flame using the NAME.
327 (defun constant-value-or-lose (cont &optional default)
328   (declare (type (or continuation null) cont))
329   (cond ((not cont) default)
330         ((constant-continuation-p cont)
331          (continuation-value cont))
332         (t
333          (give-up-ir1-transform))))
334
335 #|
336 ;;; This is a frob whose job it is to make it easier to pass around
337 ;;; the arguments to IR1 transforms. It bundles together the name of
338 ;;; the argument (which should be referenced in any expansion), and
339 ;;; the continuation for that argument (or NIL if unsupplied.)
340 (defstruct (arg (:constructor %make-arg (name cont))
341                 (:copier nil))
342   (name nil :type symbol)
343   (cont nil :type (or continuation null)))
344 (defmacro make-arg (name)
345   `(%make-arg ',name ,name))
346
347 ;;; If Arg is null or its CONT is null, then return Default, otherwise
348 ;;; return Arg's NAME.
349 (defun default-arg (arg default)
350   (declare (type (or arg null) arg))
351   (if (and arg (arg-cont arg))
352       (arg-name arg)
353       default))
354
355 ;;; If Arg is null or has no CONT, return the default. Otherwise, Arg's
356 ;;; CONT must be a constant continuation whose value we return. If not, we
357 ;;; give up.
358 (defun arg-constant-value (arg default)
359   (declare (type (or arg null) arg))
360   (if (and arg (arg-cont arg))
361       (let ((cont (arg-cont arg)))
362         (unless (constant-continuation-p cont)
363           (give-up-ir1-transform "Argument is not constant: ~S."
364                                  (arg-name arg)))
365         (continuation-value from-end))
366       default))
367
368 ;;; If Arg is a constant and is EQL to X, then return T, otherwise NIL. If
369 ;;; Arg is NIL or its CONT is NIL, then compare to the default.
370 (defun arg-eql (arg default x)
371   (declare (type (or arg null) x))
372   (if (and arg (arg-cont arg))
373       (let ((cont (arg-cont arg)))
374         (and (constant-continuation-p cont)
375              (eql (continuation-value cont) x)))
376       (eql default x)))
377
378 (defstruct (iterator (:copier nil))
379   ;; The kind of iterator.
380   (kind nil (member :normal :result))
381   ;; A list of LET* bindings to create the initial state.
382   (binds nil :type list)
383   ;; A list of declarations for Binds.
384   (decls nil :type list)
385   ;; A form that returns the current value. This may be set with SETF to set
386   ;; the current value.
387   (current (error "Must specify CURRENT."))
388   ;; In a :Normal iterator, a form that tests whether there is a current value.
389   (done nil)
390   ;; In a :Result iterator, a form that truncates the result at the current
391   ;; position and returns it.
392   (result nil)
393   ;; A form that returns the initial total number of values. The result is
394   ;; undefined after NEXT has been evaluated.
395   (length (error "Must specify LENGTH."))
396   ;; A form that advances the state to the next value. It is an error to call
397   ;; this when the iterator is Done.
398   (next (error "Must specify NEXT.")))
399
400 ;;; Type of an index var that can go negative (in the from-end case.)
401 (deftype neg-index ()
402   `(integer -1 ,most-positive-fixnum))
403
404 ;;; Return an ITERATOR structure describing how to iterate over an arbitrary
405 ;;; sequence. Sequence is a variable bound to the sequence, and Type is the
406 ;;; type of the sequence. If true, INDEX is a variable that should be bound to
407 ;;; the index of the current element in the sequence.
408 ;;;
409 ;;; If we can't tell whether the sequence is a list or a vector, or whether
410 ;;; the iteration is forward or backward, then GIVE-UP.
411 (defun make-sequence-iterator (sequence type &key start end from-end index)
412   (declare (symbol sequence) (type ctype type)
413            (type (or arg null) start end from-end)
414            (type (or symbol null) index))
415   (let ((from-end (arg-constant-value from-end nil)))
416     (cond ((csubtypep type (specifier-type 'vector))
417            (let* ((n-stop (gensym))
418                   (n-idx (or index (gensym)))
419                   (start (default-arg 0 start))
420                   (end (default-arg `(length ,sequence) end)))
421              (make-iterator
422               :kind :normal
423               :binds `((,n-idx ,(if from-end `(1- ,end) ,start))
424                        (,n-stop ,(if from-end `(1- ,start) ,end)))
425               :decls `((type neg-index ,n-idx ,n-stop))
426               :current `(aref ,sequence ,n-idx)
427               :done `(,(if from-end '<= '>=) ,n-idx ,n-stop)
428               :next `(setq ,n-idx
429                            ,(if from-end `(1- ,n-idx) `(1+ ,n-idx)))
430               :length (if from-end
431                           `(- ,n-idx ,n-stop)
432                           `(- ,n-stop ,n-idx)))))
433           ((csubtypep type (specifier-type 'list))
434            (let* ((n-stop (if (and end (not from-end)) (gensym) nil))
435                   (n-current (gensym))
436                   (start-p (not (arg-eql start 0 0)))
437                   (end-p (not (arg-eql end nil nil)))
438                   (start (default-arg start 0))
439                   (end (default-arg end nil)))
440              (make-iterator
441               :binds `((,n-current
442                         ,(if from-end
443                              (if (or start-p end-p)
444                                  `(nreverse (subseq ,sequence ,start
445                                                     ,@(when end `(,end))))
446                                  `(reverse ,sequence))
447                              (if start-p
448                                  `(nthcdr ,start ,sequence)
449                                  sequence)))
450                        ,@(when n-stop
451                            `((,n-stop (nthcdr (the index
452                                                    (- ,end ,start))
453                                               ,n-current))))
454                        ,@(when index
455                            `((,index ,(if from-end `(1- ,end) start)))))
456               :kind :normal
457               :decls `((list ,n-current ,n-end)
458                        ,@(when index `((type neg-index ,index))))
459               :current `(car ,n-current)
460               :done `(eq ,n-current ,n-stop)
461               :length `(- ,(or end `(length ,sequence)) ,start)
462               :next `(progn
463                        (setq ,n-current (cdr ,n-current))
464                        ,@(when index
465                            `((setq ,n-idx
466                                    ,(if from-end
467                                         `(1- ,index)
468                                         `(1+ ,index)))))))))
469           (t
470            (give-up-ir1-transform
471             "can't tell whether sequence is a list or a vector")))))
472
473 ;;; Make an iterator used for constructing result sequences. Name is a
474 ;;; variable to be bound to the result sequence. Type is the type of result
475 ;;; sequence to make. Length is an expression to be evaluated to get the
476 ;;; maximum length of the result (not evaluated in list case.)
477 (defun make-result-sequence-iterator (name type length)
478   (declare (symbol name) (type ctype type))
479
480 ;;; Defines each Name as a local macro that will call the value of the
481 ;;; Fun-Arg with the given arguments. If the argument isn't known to be a
482 ;;; function, give them an efficiency note and reference a coerced version.
483 (defmacro coerce-functions (specs &body body)
484   #!+sb-doc
485   "COERCE-FUNCTIONS ({(Name Fun-Arg Default)}*) Form*"
486   (collect ((binds)
487             (defs))
488     (dolist (spec specs)
489       `(let ((body (progn ,@body))
490              (n-fun (arg-name ,(second spec)))
491              (fun-cont (arg-cont ,(second spec))))
492          (cond ((not fun-cont)
493                 `(macrolet ((,',(first spec) (&rest args)
494                              `(,',',(third spec) ,@args)))
495                    ,body))
496                ((not (csubtypep (continuation-type fun-cont)
497                                 (specifier-type 'function)))
498                 (when (policy *compiler-error-context*
499                               (> speed inhibit-warnings))
500                   (compiler-note
501                    "~S may not be a function, so must coerce at run-time."
502                    n-fun))
503                 (once-only ((n-fun `(if (functionp ,n-fun)
504                                         ,n-fun
505                                         (symbol-function ,n-fun))))
506                   `(macrolet ((,',(first spec) (&rest args)
507                                `(funcall ,',n-fun ,@args)))
508                      ,body)))
509                (t
510                 `(macrolet ((,',(first spec) (&rest args)
511                               `(funcall ,',n-fun ,@args)))
512                    ,body)))))))
513
514 ;;; Wrap code around the result of the body to define Name as a local macro
515 ;;; that returns true when its arguments satisfy the test according to the Args
516 ;;; Test and Test-Not. If both Test and Test-Not are supplied, abort the
517 ;;; transform.
518 (defmacro with-sequence-test ((name test test-not) &body body)
519   `(let ((not-p (arg-cont ,test-not)))
520      (when (and (arg-cont ,test) not-p)
521        (abort-ir1-transform "Both ~S and ~S were supplied."
522                             (arg-name ,test)
523                             (arg-name ,test-not)))
524      (coerce-functions ((,name (if not-p ,test-not ,test) eql))
525        ,@body)))
526 |#
527 \f
528 ;;;; hairy sequence transforms
529
530 ;;; FIXME: no hairy sequence transforms in SBCL?
531 \f
532 ;;;; string operations
533
534 ;;; We transform the case-sensitive string predicates into a non-keyword
535 ;;; version. This is an IR1 transform so that we don't have to worry about
536 ;;; changing the order of evaluation.
537 (macrolet ((def-frob (fun pred*)
538              `(deftransform ,fun ((string1 string2 &key (start1 0) end1
539                                                          (start2 0) end2)
540                                    * *)
541                 `(,',pred* string1 string2 start1 end1 start2 end2))))
542   (def-frob string< string<*)
543   (def-frob string> string>*)
544   (def-frob string<= string<=*)
545   (def-frob string>= string>=*)
546   (def-frob string= string=*)
547   (def-frob string/= string/=*))
548
549 ;;; Return a form that tests the free variables STRING1 and STRING2
550 ;;; for the ordering relationship specified by LESSP and EQUALP. The
551 ;;; start and end are also gotten from the environment. Both strings
552 ;;; must be SIMPLE-STRINGs.
553 (macrolet ((def-frob (name lessp equalp)
554              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
555                                     (simple-string simple-string t t t t) *)
556                 `(let* ((end1 (if (not end1) (length string1) end1))
557                         (end2 (if (not end2) (length string2) end2))
558                         (index (sb!impl::%sp-string-compare
559                                 string1 start1 end1 string2 start2 end2)))
560                   (if index
561                       (cond ((= index ,(if ',lessp 'end1 'end2)) index)
562                             ((= index ,(if ',lessp 'end2 'end1)) nil)
563                             ((,(if ',lessp 'char< 'char>)
564                                (schar string1 index)
565                                (schar string2
566                                       (truly-the index
567                                                  (+ index
568                                                     (truly-the fixnum
569                                                                (- start2 start1))))))
570                              index)
571                             (t nil))
572                       ,(if ',equalp 'end1 nil))))))
573   (def-frob string<* t nil)
574   (def-frob string<=* t t)
575   (def-frob string>* nil nil)
576   (def-frob string>=* nil t))
577
578 (macrolet ((def-frob (name result-fun)
579              `(deftransform ,name ((string1 string2 start1 end1 start2 end2)
580                                    (simple-string simple-string t t t t) *)
581                 `(,',result-fun
582                   (sb!impl::%sp-string-compare
583                    string1 start1 (or end1 (length string1))
584                    string2 start2 (or end2 (length string2)))))))
585   (def-frob string=* not)
586   (def-frob string/=* identity))
587
588 \f
589 ;;;; string-only transforms for sequence functions
590 ;;;;
591 ;;;; Note: CMU CL had more of these, including transforms for
592 ;;;; functions which cons. In SBCL, we've gotten rid of most of the
593 ;;;; transforms for functions which cons, since our GC overhead is
594 ;;;; sufficiently large that it doesn't seem worth it to try to
595 ;;;; economize on function call overhead or on the overhead of runtime
596 ;;;; type dispatch in AREF. The exception is CONCATENATE, since
597 ;;;; a full call to CONCATENATE would have to look up the sequence
598 ;;;; type, which can be really slow.
599 ;;;;
600 ;;;; FIXME: It would be nicer for these transforms to work for any
601 ;;;; calls when all arguments are vectors with the same element type,
602 ;;;; rather than restricting them to STRINGs only.
603
604 ;;; FIXME: Shouldn't we be testing for legality of
605 ;;;   * START1, START2, END1, and END2 indices?
606 ;;;   * size of copied string relative to destination string?
607 ;;; (Either there should be tests conditional on SAFETY>=SPEED, or
608 ;;; the transform should be conditional on SPEED>SAFETY.)
609 ;;;
610 ;;; FIXME: Also, the transform should probably be dependent on
611 ;;; SPEED>SPACE.
612 (deftransform replace ((string1 string2 &key (start1 0) (start2 0)
613                                 end1 end2)
614                        (simple-string simple-string &rest t))
615   `(locally
616      (declare (optimize (safety 0)))
617      (bit-bash-copy string2
618                     (the index
619                          (+ (the index (* start2 sb!vm:n-byte-bits))
620                             ,vector-data-bit-offset))
621                     string1
622                     (the index
623                          (+ (the index (* start1 sb!vm:n-byte-bits))
624                             ,vector-data-bit-offset))
625                     (the index
626                          (* (min (the index (- (or end1 (length string1))
627                                                start1))
628                                  (the index (- (or end2 (length string2))
629                                                start2)))
630                             sb!vm:n-byte-bits)))
631      string1))
632
633 ;;; FIXME: It seems as though it should be possible to make a DEFUN
634 ;;; %CONCATENATE (with a DEFTRANSFORM to translate constant RTYPE to
635 ;;; CTYPE before calling %CONCATENATE) which is comparably efficient,
636 ;;; at least once DYNAMIC-EXTENT works.
637 (deftransform concatenate ((rtype &rest sequences)
638                            (t &rest simple-string)
639                            simple-string)
640   (collect ((lets)
641             (forms)
642             (all-lengths)
643             (args))
644     (dolist (seq sequences)
645       (declare (ignore seq))
646       (let ((n-seq (gensym))
647             (n-length (gensym)))
648         (args n-seq)
649         (lets `(,n-length (the index (* (length ,n-seq) sb!vm:n-byte-bits))))
650         (all-lengths n-length)
651         (forms `(bit-bash-copy ,n-seq ,vector-data-bit-offset
652                                res start
653                                ,n-length))
654         (forms `(setq start (+ start ,n-length)))))
655     `(lambda (rtype ,@(args))
656        (declare (ignore rtype))
657        (let* (,@(lets)
658               (res (make-string (truncate (the index (+ ,@(all-lengths)))
659                                           sb!vm:n-byte-bits)))
660               (start ,vector-data-bit-offset))
661          (declare (type index start ,@(all-lengths)))
662          ,@(forms)
663          res))))
664 \f
665 ;;;; CONS accessor DERIVE-TYPE optimizers
666
667 (defoptimizer (car derive-type) ((cons))
668   (let ((type (continuation-type cons))
669         (null-type (specifier-type 'null)))
670     (cond ((eq type null-type)
671            null-type)
672           ((cons-type-p type)
673            (cons-type-car-type type)))))
674
675 (defoptimizer (cdr derive-type) ((cons))
676   (let ((type (continuation-type cons))
677         (null-type (specifier-type 'null)))
678     (cond ((eq type null-type)
679            null-type)
680           ((cons-type-p type)
681            (cons-type-cdr-type type)))))
682 \f
683 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
684
685 ;;; We want to make sure that %FIND-POSITION is inline-expanded into
686 ;;; %FIND-POSITION-IF only when %FIND-POSITION-IF has an inline
687 ;;; expansion, so we factor out the condition into this function.
688 (defun check-inlineability-of-find-position-if (sequence from-end)
689   (let ((ctype (continuation-type sequence)))
690     (cond ((csubtypep ctype (specifier-type 'vector))
691            ;; It's not worth trying to inline vector code unless we
692            ;; know a fair amount about it at compile time.
693            (upgraded-element-type-specifier-or-give-up sequence)
694            (unless (constant-continuation-p from-end)
695              (give-up-ir1-transform
696               "FROM-END argument value not known at compile time")))
697           ((csubtypep ctype (specifier-type 'list))
698            ;; Inlining on lists is generally worthwhile.
699            ) 
700           (t
701            (give-up-ir1-transform
702             "sequence type not known at compile time")))))
703
704 ;;; %FIND-POSITION-IF for LIST data
705 (deftransform %find-position-if ((predicate sequence from-end start end key)
706                                  (function list t t t function)
707                                  *
708                                  :policy (> speed space)
709                                  :important t)
710   "expand inline"
711   '(let ((index 0)
712          (find nil)
713          (position nil))
714      (declare (type index index))
715      (dolist (i sequence (values find position))
716        (let ((key-i (funcall key i)))
717          (when (and end (>= index end))
718            (return (values find position)))
719          (when (>= index start)
720            (when (funcall predicate key-i)
721              ;; This hack of dealing with non-NIL FROM-END for list
722              ;; data by iterating forward through the list and keeping
723              ;; track of the last time we found a match might be more
724              ;; screwy than what the user expects, but it seems to be
725              ;; allowed by the ANSI standard. (And if the user is
726              ;; screwy enough to ask for FROM-END behavior on list
727              ;; data, turnabout is fair play.)
728              ;;
729              ;; It's also not enormously efficient, calling PREDICATE
730              ;; and KEY more often than necessary; but all the
731              ;; alternatives seem to have their own efficiency
732              ;; problems.
733              (if from-end
734                  (setf find i
735                        position index)
736                  (return (values i index))))))
737        (incf index))))
738
739 ;;; %FIND-POSITION for LIST data can be expanded into %FIND-POSITION-IF
740 ;;; without loss of efficiency. (I.e., the optimizer should be able
741 ;;; to straighten everything out.)
742 (deftransform %find-position ((item sequence from-end start end key test)
743                               (t list t t t t t)
744                               *
745                               :policy (> speed space)
746                               :important t)
747   "expand inline"
748   '(%find-position-if (let ((test-fun (%coerce-callable-to-fun test)))
749                         ;; I'm having difficulty believing I'm
750                         ;; reading it right, but as far as I can see,
751                         ;; the only guidance that ANSI gives for the
752                         ;; order of arguments to asymmetric tests is
753                         ;; the character-set dependent example from
754                         ;; the definition of FIND,
755                         ;;   (find #\d "here are some.." :test #'char>)
756                         ;;     => #\Space
757                         ;; (In ASCII, we have (CHAR> #\d #\SPACE)=>T.)
758                         ;; (Neither the POSITION definition page nor
759                         ;; section 17.2 ("Rules about Test Functions")
760                         ;; seem to consider the possibility of
761                         ;; asymmetry.)
762                         ;;
763                         ;; So, judging from the example, we want to
764                         ;; do (FUNCALL TEST-FUN ITEM I), because
765                         ;; (FUNCALL #'CHAR> #\d #\SPACE)=>T.
766                         ;;
767                         ;; -- WHN (whose attention was drawn to it by
768                         ;;         Alexey Dejneka's bug report/fix)
769                         (lambda (i)
770                           (funcall test-fun item i)))
771                       sequence
772                       from-end
773                       start
774                       end
775                       (%coerce-callable-to-fun key)))
776
777 ;;; The inline expansions for the VECTOR case are saved as macros so
778 ;;; that we can share them between the DEFTRANSFORMs and the default
779 ;;; cases in the DEFUNs. (This isn't needed for the LIST case, because
780 ;;; the DEFTRANSFORMs for LIST are less choosy about when to expand.)
781 (defun %find-position-or-find-position-if-vector-expansion (sequence-arg
782                                                             from-end
783                                                             start
784                                                             end-arg
785                                                             element
786                                                             done-p-expr)
787   (let ((offset (gensym "OFFSET"))
788         (block (gensym "BLOCK"))
789         (index (gensym "INDEX"))
790         (n-sequence (gensym "N-SEQUENCE-"))
791         (sequence (gensym "SEQUENCE"))
792         (n-end (gensym "N-END-"))
793         (end (gensym "END-")))
794     `(let ((,n-sequence ,sequence-arg)
795            (,n-end ,end-arg))
796        (with-array-data ((,sequence ,n-sequence :offset-var ,offset)
797                          (,start ,start)
798                          (,end (or ,n-end (length ,n-sequence))))
799          (block ,block
800            (macrolet ((maybe-return ()
801                         '(let ((,element (aref ,sequence ,index)))
802                            (when ,done-p-expr
803                              (return-from ,block
804                                (values ,element
805                                        (- ,index ,offset)))))))
806              (if ,from-end
807                  (loop for ,index
808                        ;; (If we aren't fastidious about declaring that 
809                        ;; INDEX might be -1, then (FIND 1 #() :FROM-END T)
810                        ;; can send us off into never-never land, since
811                        ;; INDEX is initialized to -1.)
812                        of-type index-or-minus-1
813                        from (1- ,end) downto ,start do
814                        (maybe-return))
815                  (loop for ,index of-type index from ,start below ,end do
816                        (maybe-return))))
817            (values nil nil))))))
818
819 (def!macro %find-position-vector-macro (item sequence
820                                              from-end start end key test)
821   (let ((element (gensym "ELEMENT")))
822     (%find-position-or-find-position-if-vector-expansion
823      sequence
824      from-end
825      start
826      end
827      element
828      ;; (See the LIST transform for a discussion of the correct
829      ;; argument order, i.e. whether the searched-for ,ITEM goes before
830      ;; or after the checked sequence element.)
831      `(funcall ,test ,item (funcall ,key ,element)))))
832
833 (def!macro %find-position-if-vector-macro (predicate sequence
834                                                      from-end start end key)
835   (let ((element (gensym "ELEMENT")))
836     (%find-position-or-find-position-if-vector-expansion
837      sequence
838      from-end
839      start
840      end
841      element
842      `(funcall ,predicate (funcall ,key ,element)))))
843
844 ;;; %FIND-POSITION and %FIND-POSITION-IF for VECTOR data
845 (deftransform %find-position-if ((predicate sequence from-end start end key)
846                                  (function vector t t t function)
847                                  *
848                                  :policy (> speed space)
849                                  :important t)
850   "expand inline"
851   (check-inlineability-of-find-position-if sequence from-end)
852   '(%find-position-if-vector-macro predicate sequence
853                                    from-end start end key))
854 (deftransform %find-position ((item sequence from-end start end key test)
855                               (t vector t t t function function)
856                               *
857                               :policy (> speed space)
858                               :important t)
859   "expand inline"
860   (check-inlineability-of-find-position-if sequence from-end)
861   '(%find-position-vector-macro item sequence
862                                 from-end start end key test))