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