byte-opt.el 80.4 KB
Newer Older
1
;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler -*- lexical-binding: t -*-
Jim Blandy's avatar
Jim Blandy committed
2

3
;; Copyright (C) 1991, 1994, 2000-2012  Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6

;; Author: Jamie Zawinski <jwz@lucid.com>
;;	Hallvard Furuseth <hbf@ulrik.uio.no>
Dave Love's avatar
Dave Love committed
7
;; Maintainer: FSF
Jim Blandy's avatar
Jim Blandy committed
8
;; Keywords: internal
9
;; Package: emacs
Jim Blandy's avatar
Jim Blandy committed
10 11 12

;; This file is part of GNU Emacs.

13
;; GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
14
;; it under the terms of the GNU General Public License as published by
15 16
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
17 18 19 20 21 22 23

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
24
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Jim Blandy's avatar
Jim Blandy committed
25

Jim Blandy's avatar
Jim Blandy committed
26 27
;;; Commentary:

Erik Naggum's avatar
Erik Naggum committed
28 29 30 31
;; ========================================================================
;; "No matter how hard you try, you can't make a racehorse out of a pig.
;; You can, however, make a faster pig."
;;
32
;; Or, to put it another way, the Emacs byte compiler is a VW Bug.  This code
33
;; makes it be a VW Bug with fuel injection and a turbocharger...  You're
Erik Naggum's avatar
Erik Naggum committed
34 35 36
;; still not going to make it go faster than 70 mph, but it might be easier
;; to get it there.
;;
Jim Blandy's avatar
Jim Blandy committed
37

Erik Naggum's avatar
Erik Naggum committed
38 39
;; TO DO:
;;
Stefan Monnier's avatar
Stefan Monnier committed
40
;; (apply (lambda (x &rest y) ...) 1 (foo))
Erik Naggum's avatar
Erik Naggum committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
;;
;; maintain a list of functions known not to access any global variables
;; (actually, give them a 'dynamically-safe property) and then
;;   (let ( v1 v2 ... vM vN ) <...dynamically-safe...> )  ==>
;;   (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
;; by recursing on this, we might be able to eliminate the entire let.
;; However certain variables should never have their bindings optimized
;; away, because they affect everything.
;;   (put 'debug-on-error 'binding-is-magic t)
;;   (put 'debug-on-abort 'binding-is-magic t)
;;   (put 'debug-on-next-call 'binding-is-magic t)
;;   (put 'inhibit-quit 'binding-is-magic t)
;;   (put 'quit-flag 'binding-is-magic t)
;;   (put 't 'binding-is-magic t)
;;   (put 'nil 'binding-is-magic t)
;; possibly also
;;   (put 'gc-cons-threshold 'binding-is-magic t)
;;   (put 'track-mouse 'binding-is-magic t)
;; others?
;;
;; Simple defsubsts often produce forms like
;;    (let ((v1 (f1)) (v2 (f2)) ...)
;;       (FN v1 v2 ...))
64
;; It would be nice if we could optimize this to
Erik Naggum's avatar
Erik Naggum committed
65 66 67 68 69
;;    (FN (f1) (f2) ...)
;; but we can't unless FN is dynamically-safe (it might be dynamically
;; referring to the bindings that the lambda arglist established.)
;; One of the uncountable lossages introduced by dynamic scope...
;;
70
;; Maybe there should be a control-structure that says "turn on
Erik Naggum's avatar
Erik Naggum committed
71 72 73
;; fast-and-loose type-assumptive optimizations here."  Then when
;; we see a form like (car foo) we can from then on assume that
;; the variable foo is of type cons, and optimize based on that.
74
;; But, this won't win much because of (you guessed it) dynamic
Erik Naggum's avatar
Erik Naggum committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
;; scope.  Anything down the stack could change the value.
;; (Another reason it doesn't work is that it is perfectly valid
;; to call car with a null argument.)  A better approach might
;; be to allow type-specification of the form
;;   (put 'foo 'arg-types '(float (list integer) dynamic))
;;   (put 'foo 'result-type 'bool)
;; It should be possible to have these types checked to a certain
;; degree.
;;
;; collapse common subexpressions
;;
;; It would be nice if redundant sequences could be factored out as well,
;; when they are known to have no side-effects:
;;   (list (+ a b c) (+ a b c))   -->  a b add c add dup list-2
;; but beware of traps like
;;   (cons (list x y) (list x y))
;;
;; Tail-recursion elimination is not really possible in Emacs Lisp.
;; Tail-recursion elimination is almost always impossible when all variables
;; have dynamic scope, but given that the "return" byteop requires the
;; binding stack to be empty (rather than emptying it itself), there can be
;; no truly tail-recursive Emacs Lisp functions that take any arguments or
;; make any bindings.
;;
;; Here is an example of an Emacs Lisp function which could safely be
;; byte-compiled tail-recursively:
;;
;;  (defun tail-map (fn list)
;;    (cond (list
;;           (funcall fn (car list))
;;           (tail-map fn (cdr list)))))
;;
;; However, if there was even a single let-binding around the COND,
;; it could not be byte-compiled, because there would be an "unbind"
109
;; byte-op between the final "call" and "return."  Adding a
Erik Naggum's avatar
Erik Naggum committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
;; Bunbind_all byteop would fix this.
;;
;;   (defun foo (x y z) ... (foo a b c))
;;   ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
;;   ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
;;   ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
;;
;; this also can be considered tail recursion:
;;
;;   ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
;; could generalize this by doing the optimization
;;   (goto X) ... X: (return)  -->  (return)
;;
;; But this doesn't solve all of the problems: although by doing tail-
;; recursion elimination in this way, the call-stack does not grow, the
;; binding-stack would grow with each recursive step, and would eventually
;; overflow.  I don't believe there is any way around this without lexical
;; scope.
;;
;; Wouldn't it be nice if Emacs Lisp had lexical scope.
;;
131 132
;; Idea: the form (lexical-scope) in a file means that the file may be
;; compiled lexically.  This proclamation is file-local.  Then, within
Erik Naggum's avatar
Erik Naggum committed
133 134 135 136 137
;; that file, "let" would establish lexical bindings, and "let-dynamic"
;; would do things the old way.  (Or we could use CL "declare" forms.)
;; We'd have to notice defvars and defconsts, since those variables should
;; always be dynamic, and attempting to do a lexical binding of them
;; should simply do a dynamic binding instead.
Paul Eggert's avatar
Paul Eggert committed
138
;; But!  We need to know about variables that were not necessarily defvared
Erik Naggum's avatar
Erik Naggum committed
139 140 141
;; in the file being compiled (doing a boundp check isn't good enough.)
;; Fdefvar() would have to be modified to add something to the plist.
;;
142 143
;; A major disadvantage of this scheme is that the interpreter and compiler
;; would have different semantics for files compiled with (dynamic-scope).
Erik Naggum's avatar
Erik Naggum committed
144
;; Since this would be a file-local optimization, there would be no way to
145
;; modify the interpreter to obey this (unless the loader was hacked
Erik Naggum's avatar
Erik Naggum committed
146
;; in some grody way, but that's a really bad idea.)
147 148 149

;; Other things to consider:

Kenichi Handa's avatar
Kenichi Handa committed
150 151 152
;; ;; Associative math should recognize subcalls to identical function:
;; (disassemble (lambda (x) (+ (+ (foo) 1) (+ (bar) 2))))
;; ;; This should generate the same as (1+ x) and (1- x)
153

Kenichi Handa's avatar
Kenichi Handa committed
154 155 156
;; (disassemble (lambda (x) (cons (+ x 1) (- x 1))))
;; ;; An awful lot of functions always return a non-nil value.  If they're
;; ;; error free also they may act as true-constants.
157

Kenichi Handa's avatar
Kenichi Handa committed
158 159 160 161 162 163 164 165
;; (disassemble (lambda (x) (and (point) (foo))))
;; ;; When
;; ;;   - all but one arguments to a function are constant
;; ;;   - the non-constant argument is an if-expression (cond-expression?)
;; ;; then the outer function can be distributed.  If the guarding
;; ;; condition is side-effect-free [assignment-free] then the other
;; ;; arguments may be any expressions.  Since, however, the code size
;; ;; can increase this way they should be "simple".  Compare:
166

Kenichi Handa's avatar
Kenichi Handa committed
167 168
;; (disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
;; (disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))
169

Kenichi Handa's avatar
Kenichi Handa committed
170 171
;; ;; (car (cons A B)) -> (prog1 A B)
;; (disassemble (lambda (x) (car (cons (foo) 42))))
172

Kenichi Handa's avatar
Kenichi Handa committed
173 174
;; ;; (cdr (cons A B)) -> (progn A B)
;; (disassemble (lambda (x) (cdr (cons 42 (foo)))))
175

Kenichi Handa's avatar
Kenichi Handa committed
176 177
;; ;; (car (list A B ...)) -> (prog1 A B ...)
;; (disassemble (lambda (x) (car (list (foo) 42 (bar)))))
178

Kenichi Handa's avatar
Kenichi Handa committed
179 180
;; ;; (cdr (list A B ...)) -> (progn A (list B ...))
;; (disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))
181

Jim Blandy's avatar
Jim Blandy committed
182

Jim Blandy's avatar
Jim Blandy committed
183
;;; Code:
Jim Blandy's avatar
Jim Blandy committed
184

185
(require 'bytecomp)
186
(eval-when-compile (require 'cl))
187

Jim Blandy's avatar
Jim Blandy committed
188
(defun byte-compile-log-lap-1 (format &rest args)
189 190 191 192
  ;; Newer byte codes for stack-ref make the slot 0 non-nil again.
  ;; But the "old disassembler" is *really* ancient by now.
  ;; (if (aref byte-code-vector 0)
  ;;     (error "The old version of the disassembler is loaded.  Reload new-bytecomp as well"))
Jim Blandy's avatar
Jim Blandy committed
193 194 195
  (byte-compile-log-1
   (apply 'format format
     (let (c a)
Stefan Monnier's avatar
Stefan Monnier committed
196
       (mapcar (lambda (arg)
Jim Blandy's avatar
Jim Blandy committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		  (if (not (consp arg))
		      (if (and (symbolp arg)
			       (string-match "^byte-" (symbol-name arg)))
			  (intern (substring (symbol-name arg) 5))
			arg)
		    (if (integerp (setq c (car arg)))
			(error "non-symbolic byte-op %s" c))
		    (if (eq c 'TAG)
			(setq c arg)
		      (setq a (cond ((memq c byte-goto-ops)
				     (car (cdr (cdr arg))))
				    ((memq c byte-constref-ops)
				     (car (cdr arg)))
				    (t (cdr arg))))
		      (setq c (symbol-name c))
		      (if (string-match "^byte-." c)
			  (setq c (intern (substring c 5)))))
		    (if (eq c 'constant) (setq c 'const))
		    (if (and (eq (cdr arg) 0)
			     (not (memq c '(unbind call const))))
			c
		      (format "(%s %s)" c a))))
	       args)))))

(defmacro byte-compile-log-lap (format-string &rest args)
Kenichi Handa's avatar
Kenichi Handa committed
222 223
  `(and (memq byte-optimize-log '(t byte))
	(byte-compile-log-lap-1 ,format-string ,@args)))
Jim Blandy's avatar
Jim Blandy committed
224 225 226 227 228 229 230 231 232 233


;;; byte-compile optimizers to support inlining

(put 'inline 'byte-optimizer 'byte-optimize-inline-handler)

(defun byte-optimize-inline-handler (form)
  "byte-optimize-handler for the `inline' special-form."
  (cons 'progn
	(mapcar
Stefan Monnier's avatar
Stefan Monnier committed
234
	 (lambda (sexp)
235 236 237 238 239 240 241 242 243 244
	   (let ((f (car-safe sexp)))
	     (if (and (symbolp f)
		      (or (cdr (assq f byte-compile-function-environment))
			  (not (or (not (fboundp f))
				   (cdr (assq f byte-compile-macro-environment))
				   (and (consp (setq f (symbol-function f)))
					(eq (car f) 'macro))
				   (subrp f)))))
		 (byte-compile-inline-expand sexp)
	       sexp)))
Jim Blandy's avatar
Jim Blandy committed
245 246 247 248
	 (cdr form))))

(defun byte-compile-inline-expand (form)
  (let* ((name (car form))
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
         (localfn (cdr (assq name byte-compile-function-environment)))
	 (fn (or localfn (and (fboundp name) (symbol-function name)))))
    (when (and (consp fn) (eq (car fn) 'autoload))
      (load (nth 1 fn))
      (setq fn (or (and (fboundp name) (symbol-function name))
                   (cdr (assq name byte-compile-function-environment)))))
    (pcase fn
      (`nil
       (byte-compile-warn "attempt to inline `%s' before it was defined"
                          name)
       form)
      (`(autoload . ,_)
       (error "File `%s' didn't define `%s'" (nth 1 fn) name))
      ((and (pred symbolp) (guard (not (eq fn t)))) ;A function alias.
       (byte-compile-inline-expand (cons fn (cdr form))))
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
      ((pred byte-code-function-p)
       ;; (message "Inlining byte-code for %S!" name)
       ;; The byte-code will be really inlined in byte-compile-unfold-bcf.
       `(,fn ,@(cdr form)))
      ((or (and `(lambda ,args . ,body) (let env nil))
           `(closure ,env ,args . ,body))
       (if (not (or (eq fn localfn)     ;From the same file => same mode.
                    (eq (not lexical-binding) (not env)))) ;Same mode.
           ;; While byte-compile-unfold-bcf can inline dynbind byte-code into
           ;; letbind byte-code (or any other combination for that matter), we
           ;; can only inline dynbind source into dynbind source or letbind
           ;; source into letbind source.
           ;; FIXME: we could of course byte-compile the inlined function
           ;; first, and then inline its byte-code.
           form
         (let ((renv ()))
           ;; Turn the function's closed vars (if any) into local let bindings.
           (dolist (binding env)
             (cond
              ((consp binding)
               ;; We check shadowing by the args, so that the `let' can be
               ;; moved within the lambda, which can then be unfolded.
               ;; FIXME: Some of those bindings might be unused in `body'.
               (unless (memq (car binding) args) ;Shadowed.
                 (push `(,(car binding) ',(cdr binding)) renv)))
              ((eq binding t))
              (t (push `(defvar ,binding) body))))
291 292 293 294 295 296 297 298
           (let ((newfn (if (eq fn localfn)
                            ;; If `fn' is from the same file, it has already
                            ;; been preprocessed!
                            `(function ,fn)
                          (byte-compile-preprocess
                           (if (null renv)
                               `(lambda ,args ,@body)
                             `(lambda ,args (let ,(nreverse renv) ,@body)))))))
299 300 301 302 303
             (if (eq (car-safe newfn) 'function)
                 (byte-compile-unfold-lambda `(,(cadr newfn) ,@(cdr form)))
               (byte-compile-log-warning
                (format "Inlining closure %S failed" name))
               form)))))
304 305 306

      (t ;; Give up on inlining.
       form))))
Jim Blandy's avatar
Jim Blandy committed
307

Kenichi Handa's avatar
Kenichi Handa committed
308
;; ((lambda ...) ...)
Jim Blandy's avatar
Jim Blandy committed
309
(defun byte-compile-unfold-lambda (form &optional name)
310
  ;; In lexical-binding mode, let and functions don't bind vars in the same way
311 312 313
  ;; (let obey special-variable-p, but functions don't).  But luckily, this
  ;; doesn't matter here, because function's behavior is underspecified so it
  ;; can safely be turned into a `let', even though the reverse is not true.
Jim Blandy's avatar
Jim Blandy committed
314 315 316 317 318 319 320 321 322 323 324
  (or name (setq name "anonymous lambda"))
  (let ((lambda (car form))
	(values (cdr form)))
    (let ((arglist (nth 1 lambda))
	  (body (cdr (cdr lambda)))
	  optionalp restp
	  bindings)
      (if (and (stringp (car body)) (cdr body))
	  (setq body (cdr body)))
      (if (and (consp (car body)) (eq 'interactive (car (car body))))
	  (setq body (cdr body)))
325
      ;; FIXME: The checks below do not belong in an optimization phase.
Jim Blandy's avatar
Jim Blandy committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      (while arglist
	(cond ((eq (car arglist) '&optional)
	       ;; ok, I'll let this slide because funcall_lambda() does...
	       ;; (if optionalp (error "multiple &optional keywords in %s" name))
	       (if restp (error "&optional found after &rest in %s" name))
	       (if (null (cdr arglist))
		   (error "nothing after &optional in %s" name))
	       (setq optionalp t))
	      ((eq (car arglist) '&rest)
	       ;; ...but it is by no stretch of the imagination a reasonable
	       ;; thing that funcall_lambda() allows (&rest x y) and
	       ;; (&rest x &optional y) in arglists.
	       (if (null (cdr arglist))
		   (error "nothing after &rest in %s" name))
	       (if (cdr (cdr arglist))
		   (error "multiple vars after &rest in %s" name))
	       (setq restp t))
	      (restp
	       (setq bindings (cons (list (car arglist)
					  (and values (cons 'list values)))
				    bindings)
		     values nil))
	      ((and (not optionalp) (null values))
Gerd Moellmann's avatar
Gerd Moellmann committed
349
	       (byte-compile-warn "attempt to open-code `%s' with too few arguments" name)
Jim Blandy's avatar
Jim Blandy committed
350 351 352 353 354 355 356 357 358 359
	       (setq arglist nil values 'too-few))
	      (t
	       (setq bindings (cons (list (car arglist) (car values))
				    bindings)
		     values (cdr values))))
	(setq arglist (cdr arglist)))
      (if values
	  (progn
	    (or (eq values 'too-few)
		(byte-compile-warn
Gerd Moellmann's avatar
Gerd Moellmann committed
360
		 "attempt to open-code `%s' with too many arguments" name))
Jim Blandy's avatar
Jim Blandy committed
361
	    form)
362

363 364 365 366
	;; The following leads to infinite recursion when loading a
	;; file containing `(defsubst f () (f))', and then trying to
	;; byte-compile that file.
	;(setq body (mapcar 'byte-optimize-form body)))
367 368

	(let ((newform
Jim Blandy's avatar
Jim Blandy committed
369 370 371 372 373 374 375 376 377
	       (if bindings
		   (cons 'let (cons (nreverse bindings) body))
		 (cons 'progn body))))
	  (byte-compile-log "  %s\t==>\t%s" form newform)
	  newform)))))


;;; implementing source-level optimizers

378
(defun byte-optimize-form-code-walker (form for-effect)
Jim Blandy's avatar
Jim Blandy committed
379 380 381 382 383 384 385
  ;;
  ;; For normal function calls, We can just mapcar the optimizer the cdr.  But
  ;; we need to have special knowledge of the syntax of the special forms
  ;; like let and defun (that's why they're special forms :-).  (Actually,
  ;; the important aspect is that they are subrs that don't evaluate all of
  ;; their args.)
  ;;
386
  (let ((fn (car-safe form))
Jim Blandy's avatar
Jim Blandy committed
387 388 389 390 391 392 393 394 395
	tmp)
    (cond ((not (consp form))
	   (if (not (and for-effect
			 (or byte-compile-delete-errors
			     (not (symbolp form))
			     (eq form t))))
	     form))
	  ((eq fn 'quote)
	   (if (cdr (cdr form))
Gerd Moellmann's avatar
Gerd Moellmann committed
396
	       (byte-compile-warn "malformed quote form: `%s'"
Jim Blandy's avatar
Jim Blandy committed
397 398 399 400 401 402
				  (prin1-to-string form)))
	   ;; map (quote nil) to nil to simplify optimizer logic.
	   ;; map quoted constants to nil if for-effect (just because).
	   (and (nth 1 form)
		(not for-effect)
		form))
403
	  ((eq 'lambda (car-safe fn))
404 405
	   (let ((newform (byte-compile-unfold-lambda form)))
	     (if (eq newform form)
406
		 ;; Some error occurred, avoid infinite recursion
407 408
		 form
	       (byte-optimize-form-code-walker newform for-effect))))
Jim Blandy's avatar
Jim Blandy committed
409 410 411 412 413 414
	  ((memq fn '(let let*))
	   ;; recursively enter the optimizer for the bindings and body
	   ;; of a let or let*.  This for depth-firstness: forms that
	   ;; are more deeply nested are optimized first.
	   (cons fn
	     (cons
Stefan Monnier's avatar
Stefan Monnier committed
415
	      (mapcar (lambda (binding)
Jim Blandy's avatar
Jim Blandy committed
416 417 418
			 (if (symbolp binding)
			     binding
			   (if (cdr (cdr binding))
Gerd Moellmann's avatar
Gerd Moellmann committed
419
			       (byte-compile-warn "malformed let binding: `%s'"
Jim Blandy's avatar
Jim Blandy committed
420 421 422 423 424 425 426
						  (prin1-to-string binding)))
			   (list (car binding)
				 (byte-optimize-form (nth 1 binding) nil))))
		      (nth 1 form))
	      (byte-optimize-body (cdr (cdr form)) for-effect))))
	  ((eq fn 'cond)
	   (cons fn
Stefan Monnier's avatar
Stefan Monnier committed
427
		 (mapcar (lambda (clause)
Jim Blandy's avatar
Jim Blandy committed
428 429 430 431
			    (if (consp clause)
				(cons
				 (byte-optimize-form (car clause) nil)
				 (byte-optimize-body (cdr clause) for-effect))
Gerd Moellmann's avatar
Gerd Moellmann committed
432
			      (byte-compile-warn "malformed cond form: `%s'"
Jim Blandy's avatar
Jim Blandy committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
						 (prin1-to-string clause))
			      clause))
			 (cdr form))))
	  ((eq fn 'progn)
	   ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
	   (if (cdr (cdr form))
	       (progn
		 (setq tmp (byte-optimize-body (cdr form) for-effect))
		 (if (cdr tmp) (cons 'progn tmp) (car tmp)))
	     (byte-optimize-form (nth 1 form) for-effect)))
	  ((eq fn 'prog1)
	   (if (cdr (cdr form))
	       (cons 'prog1
		     (cons (byte-optimize-form (nth 1 form) for-effect)
			   (byte-optimize-body (cdr (cdr form)) t)))
	     (byte-optimize-form (nth 1 form) for-effect)))
	  ((eq fn 'prog2)
	   (cons 'prog2
	     (cons (byte-optimize-form (nth 1 form) t)
	       (cons (byte-optimize-form (nth 2 form) for-effect)
		     (byte-optimize-body (cdr (cdr (cdr form))) t)))))
454

455
	  ((memq fn '(save-excursion save-restriction save-current-buffer))
Jim Blandy's avatar
Jim Blandy committed
456 457 458 459 460
	   ;; those subrs which have an implicit progn; it's not quite good
	   ;; enough to treat these like normal function calls.
	   ;; This can turn (save-excursion ...) into (save-excursion) which
	   ;; will be optimized away in the lap-optimize pass.
	   (cons fn (byte-optimize-body (cdr form) for-effect)))
461

Jim Blandy's avatar
Jim Blandy committed
462 463 464 465 466 467
	  ((eq fn 'with-output-to-temp-buffer)
	   ;; this is just like the above, except for the first argument.
	   (cons fn
	     (cons
	      (byte-optimize-form (nth 1 form) nil)
	      (byte-optimize-body (cdr (cdr form)) for-effect))))
468

Jim Blandy's avatar
Jim Blandy committed
469
	  ((eq fn 'if)
Gerd Moellmann's avatar
Gerd Moellmann committed
470
	   (when (< (length form) 3)
Gerd Moellmann's avatar
Gerd Moellmann committed
471
	     (byte-compile-warn "too few arguments for `if'"))
Jim Blandy's avatar
Jim Blandy committed
472 473 474 475 476
	   (cons fn
	     (cons (byte-optimize-form (nth 1 form) nil)
	       (cons
		(byte-optimize-form (nth 2 form) for-effect)
		(byte-optimize-body (nthcdr 3 form) for-effect)))))
477

478 479
	  ((memq fn '(and or))  ; Remember, and/or are control structures.
	   ;; Take forms off the back until we can't any more.
480
	   ;; In the future it could conceivably be a problem that the
Jim Blandy's avatar
Jim Blandy committed
481 482 483 484 485 486 487 488 489 490 491 492 493
	   ;; subexpressions of these forms are optimized in the reverse
	   ;; order, but it's ok for now.
	   (if for-effect
	       (let ((backwards (reverse (cdr form))))
		 (while (and backwards
			     (null (setcar backwards
					   (byte-optimize-form (car backwards)
							       for-effect))))
		   (setq backwards (cdr backwards)))
		 (if (and (cdr form) (null backwards))
		     (byte-compile-log
		      "  all subforms of %s called for effect; deleted" form))
		 (and backwards
494 495
		      (cons fn (nreverse (mapcar 'byte-optimize-form
                                                 backwards)))))
Jim Blandy's avatar
Jim Blandy committed
496 497 498
	     (cons fn (mapcar 'byte-optimize-form (cdr form)))))

	  ((eq fn 'interactive)
Gerd Moellmann's avatar
Gerd Moellmann committed
499
	   (byte-compile-warn "misplaced interactive spec: `%s'"
Jim Blandy's avatar
Jim Blandy committed
500 501
			      (prin1-to-string form))
	   nil)
502

503
	  ((memq fn '(defun defmacro function condition-case))
Jim Blandy's avatar
Jim Blandy committed
504 505 506 507 508 509 510 511 512 513 514 515 516
	   ;; These forms are compiled as constants or by breaking out
	   ;; all the subexpressions and compiling them separately.
	   form)

	  ((eq fn 'unwind-protect)
	   ;; the "protected" part of an unwind-protect is compiled (and thus
	   ;; optimized) as a top-level form, so don't do it here.  But the
	   ;; non-protected part has the same for-effect status as the
	   ;; unwind-protect itself.  (The protected part is always for effect,
	   ;; but that isn't handled properly yet.)
	   (cons fn
		 (cons (byte-optimize-form (nth 1 form) for-effect)
		       (cdr (cdr form)))))
517

Jim Blandy's avatar
Jim Blandy committed
518 519 520 521 522 523 524 525 526
	  ((eq fn 'catch)
	   ;; the body of a catch is compiled (and thus optimized) as a
	   ;; top-level form, so don't do it here.  The tag is never
	   ;; for-effect.  The body should have the same for-effect status
	   ;; as the catch form itself, but that isn't handled properly yet.
	   (cons fn
		 (cons (byte-optimize-form (nth 1 form) nil)
		       (cdr (cdr form)))))

527 528 529 530 531 532 533
	  ((eq fn 'ignore)
	   ;; Don't treat the args to `ignore' as being
	   ;; computed for effect.  We want to avoid the warnings
	   ;; that might occur if they were treated that way.
	   ;; However, don't actually bother calling `ignore'.
	   `(prog1 nil . ,(mapcar 'byte-optimize-form (cdr form))))

Paul Eggert's avatar
Paul Eggert committed
534
          ;; Needed as long as we run byte-optimize-form after cconv.
535
          ((eq fn 'internal-make-closure) form)
536 537 538 539

          ((byte-code-function-p fn)
           (cons fn (mapcar #'byte-optimize-form (cdr form))))

Jim Blandy's avatar
Jim Blandy committed
540
	  ((not (symbolp fn))
541 542
	   (byte-compile-warn "`%s' is a malformed function"
			      (prin1-to-string fn))
Jim Blandy's avatar
Jim Blandy committed
543 544 545 546 547
	   form)

	  ((and for-effect (setq tmp (get fn 'side-effect-free))
		(or byte-compile-delete-errors
		    (eq tmp 'error-free)
548 549 550 551 552 553 554 555 556 557 558 559
		    ;; Detect the expansion of (pop foo).
		    ;; There is no need to compile the call to `car' there.
		    (and (eq fn 'car)
			 (eq (car-safe (cadr form)) 'prog1)
			 (let ((var (cadr (cadr form)))
			       (last (nth 2 (cadr form))))
			   (and (symbolp var)
				(null (nthcdr 3 (cadr form)))
				(eq (car-safe last) 'setq)
				(eq (cadr last) var)
				(eq (car-safe (nth 2 last)) 'cdr)
				(eq (cadr (nth 2 last)) var))))
Jim Blandy's avatar
Jim Blandy committed
560
		    (progn
561 562
		      (byte-compile-warn "value returned from %s is unused"
					 (prin1-to-string form))
Jim Blandy's avatar
Jim Blandy committed
563 564 565 566 567
		      nil)))
	   (byte-compile-log "  %s called for effect; deleted" fn)
	   ;; appending a nil here might not be necessary, but it can't hurt.
	   (byte-optimize-form
	    (cons 'progn (append (cdr form) '(nil))) t))
568

Jim Blandy's avatar
Jim Blandy committed
569 570 571 572
	  (t
	   ;; Otherwise, no args can be considered to be for-effect,
	   ;; even if the called function is for-effect, because we
	   ;; don't know anything about that function.
573 574 575 576 577 578 579
	   (let ((args (mapcar #'byte-optimize-form (cdr form))))
	     (if (and (get fn 'pure)
		      (byte-optimize-all-constp args))
		   (list 'quote (apply fn (mapcar #'eval args)))
	       (cons fn args)))))))

(defun byte-optimize-all-constp (list)
580
  "Non-nil if all elements of LIST satisfy `byte-compile-constp'."
581 582 583 584 585 586
  (let ((constant t))
    (while (and list constant)
      (unless (byte-compile-constp (car list))
	(setq constant nil))
      (setq list (cdr list)))
    constant))
Jim Blandy's avatar
Jim Blandy committed
587

588
(defun byte-optimize-form (form &optional for-effect)
Jim Blandy's avatar
Jim Blandy committed
589 590 591
  "The source-level pass of the optimizer."
  ;;
  ;; First, optimize all sub-forms of this one.
592
  (setq form (byte-optimize-form-code-walker form for-effect))
Jim Blandy's avatar
Jim Blandy committed
593 594 595 596 597 598
  ;;
  ;; after optimizing all subforms, optimize this form until it doesn't
  ;; optimize any further.  This means that some forms will be passed through
  ;; the optimizer many times, but that's necessary to make the for-effect
  ;; processing do as much as possible.
  ;;
599
  (let (opt new)
Jim Blandy's avatar
Jim Blandy committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    (if (and (consp form)
	     (symbolp (car form))
	     (or (and for-effect
		      ;; we don't have any of these yet, but we might.
		      (setq opt (get (car form) 'byte-for-effect-optimizer)))
		 (setq opt (get (car form) 'byte-optimizer)))
	     (not (eq form (setq new (funcall opt form)))))
	(progn
;;	  (if (equal form new) (error "bogus optimizer -- %s" opt))
	  (byte-compile-log "  %s\t==>\t%s" form new)
	  (setq new (byte-optimize-form new for-effect))
	  new)
      form)))


(defun byte-optimize-body (forms all-for-effect)
616
  ;; Optimize the cdr of a progn or implicit progn; all forms is a list of
Jim Blandy's avatar
Jim Blandy committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  ;; forms, all but the last of which are optimized with the assumption that
  ;; they are being called for effect.  the last is for-effect as well if
  ;; all-for-effect is true.  returns a new list of forms.
  (let ((rest forms)
	(result nil)
	fe new)
    (while rest
      (setq fe (or all-for-effect (cdr rest)))
      (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
      (if (or new (not fe))
	  (setq result (cons new result)))
      (setq rest (cdr rest)))
    (nreverse result)))


Kenichi Handa's avatar
Kenichi Handa committed
632 633 634 635 636 637 638 639
;; some source-level optimizers
;;
;; when writing optimizers, be VERY careful that the optimizer returns
;; something not EQ to its argument if and ONLY if it has made a change.
;; This implies that you cannot simply destructively modify the list;
;; you must return something not EQ to it if you make an optimization.
;;
;; It is now safe to optimize code such that it introduces new bindings.
Jim Blandy's avatar
Jim Blandy committed
640

641 642
(defsubst byte-compile-trueconstp (form)
  "Return non-nil if FORM always evaluates to a non-nil value."
643 644
  (while (eq (car-safe form) 'progn)
    (setq form (car (last (cdr form)))))
645 646 647
  (cond ((consp form)
         (case (car form)
           (quote (cadr form))
648 649 650
           ;; Can't use recursion in a defsubst.
           ;; (progn (byte-compile-trueconstp (car (last (cdr form)))))
           ))
651 652 653 654 655 656
        ((not (symbolp form)))
        ((eq form t))
        ((keywordp form))))

(defsubst byte-compile-nilconstp (form)
  "Return non-nil if FORM always evaluates to a nil value."
657 658
  (while (eq (car-safe form) 'progn)
    (setq form (car (last (cdr form)))))
659 660 661
  (cond ((consp form)
         (case (car form)
           (quote (null (cadr form)))
662 663 664
           ;; Can't use recursion in a defsubst.
           ;; (progn (byte-compile-nilconstp (car (last (cdr form)))))
           ))
665 666
        ((not (symbolp form)) nil)
        ((null form))))
Jim Blandy's avatar
Jim Blandy committed
667

668
;; If the function is being called with constant numeric args,
669
;; evaluate as much as possible at compile-time.  This optimizer
670
;; assumes that the function is associative, like + or *.
Jim Blandy's avatar
Jim Blandy committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
(defun byte-optimize-associative-math (form)
  (let ((args nil)
	(constants nil)
	(rest (cdr form)))
    (while rest
      (if (numberp (car rest))
	  (setq constants (cons (car rest) constants))
	  (setq args (cons (car rest) args)))
      (setq rest (cdr rest)))
    (if (cdr constants)
	(if args
	    (list (car form)
		  (apply (car form) constants)
		  (if (cdr args)
		      (cons (car form) (nreverse args))
		      (car args)))
	    (apply (car form) constants))
	form)))

690
;; If the function is being called with constant numeric args,
691 692 693 694
;; evaluate as much as possible at compile-time.  This optimizer
;; assumes that the function satisfies
;;   (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
;; like - and /.
Jim Blandy's avatar
Jim Blandy committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
(defun byte-optimize-nonassociative-math (form)
  (if (or (not (numberp (car (cdr form))))
	  (not (numberp (car (cdr (cdr form))))))
      form
    (let ((constant (car (cdr form)))
	  (rest (cdr (cdr form))))
      (while (numberp (car rest))
	(setq constant (funcall (car form) constant (car rest))
	      rest (cdr rest)))
      (if rest
	  (cons (car form) (cons constant rest))
	  constant))))

;;(defun byte-optimize-associative-two-args-math (form)
;;  (setq form (byte-optimize-associative-math form))
;;  (if (consp form)
;;      (byte-optimize-two-args-left form)
;;      form))

;;(defun byte-optimize-nonassociative-two-args-math (form)
;;  (setq form (byte-optimize-nonassociative-math form))
;;  (if (consp form)
;;      (byte-optimize-two-args-right form)
;;      form))

720
(defun byte-optimize-approx-equal (x y)
721
  (<= (* (abs (- x y)) 100) (abs (+ x y))))
722 723 724 725 726 727 728 729

;; Collect all the constants from FORM, after the STARTth arg,
;; and apply FUN to them to make one argument at the end.
;; For functions that can handle floats, that optimization
;; can be incorrect because reordering can cause an overflow
;; that would otherwise be avoided by encountering an arg that is a float.
;; We avoid this problem by (1) not moving float constants and
;; (2) not moving anything if it would cause an overflow.
Jim Blandy's avatar
Jim Blandy committed
730 731 732
(defun byte-optimize-delay-constants-math (form start fun)
  ;; Merge all FORM's constants from number START, call FUN on them
  ;; and put the result at the end.
733 734 735 736
  (let ((rest (nthcdr (1- start) form))
	(orig form)
	;; t means we must check for overflow.
	(overflow (memq fun '(+ *))))
Jim Blandy's avatar
Jim Blandy committed
737
    (while (cdr (setq rest (cdr rest)))
738
      (if (integerp (car rest))
Jim Blandy's avatar
Jim Blandy committed
739 740 741 742
	  (let (constants)
	    (setq form (copy-sequence form)
		  rest (nthcdr (1- start) form))
	    (while (setq rest (cdr rest))
743
	      (cond ((integerp (car rest))
Jim Blandy's avatar
Jim Blandy committed
744 745
		     (setq constants (cons (car rest) constants))
		     (setcar rest nil))))
746 747 748 749 750 751 752 753 754 755 756 757
	    ;; If necessary, check now for overflow
	    ;; that might be caused by reordering.
	    (if (and overflow
		     ;; We have overflow if the result of doing the arithmetic
		     ;; on floats is not even close to the result
		     ;; of doing it on integers.
		     (not (byte-optimize-approx-equal
			    (apply fun (mapcar 'float constants))
			    (float (apply fun constants)))))
		(setq form orig)
	      (setq form (nconc (delq nil form)
				(list (apply fun (nreverse constants)))))))))
Jim Blandy's avatar
Jim Blandy committed
758 759
    form))

760 761 762
(defsubst byte-compile-butlast (form)
  (nreverse (cdr (reverse form))))

Jim Blandy's avatar
Jim Blandy committed
763
(defun byte-optimize-plus (form)
764 765
  ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
  ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
Jim Blandy's avatar
Jim Blandy committed
766
  (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  ;; For (+ constants...), byte-optimize-predicate does the work.
  (when (memq nil (mapcar 'numberp (cdr form)))
    (cond
     ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
     ((and (= (length form) 3)
	   (or (memq (nth 1 form) '(1 -1))
	       (memq (nth 2 form) '(1 -1))))
      (let (integer other)
	(if (memq (nth 1 form) '(1 -1))
	    (setq integer (nth 1 form) other (nth 2 form))
	  (setq integer (nth 2 form) other (nth 1 form)))
	(setq form
	      (list (if (eq integer 1) '1+ '1-) other))))
     ;; Here, we could also do
     ;;  (+ x y ... 1) --> (1+ (+ x y ...))
     ;;  (+ x y ... -1) --> (1- (+ x y ...))
     ;; The resulting bytecode is smaller, but is it faster? -- cyd
     ))
  (byte-optimize-predicate form))
Jim Blandy's avatar
Jim Blandy committed
786 787

(defun byte-optimize-minus (form)
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
  ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
  ;; Remove zeros.
  (when (and (nthcdr 3 form)
	     (memq 0 (cddr form)))
    (setq form (nconc (list (car form) (cadr form))
		      (delq 0 (copy-sequence (cddr form)))))
    ;; After the above, we must turn (- x) back into (- x 0)
    (or (cddr form)
	(setq form (nconc form (list 0)))))
  ;; For (- constants..), byte-optimize-predicate does the work.
  (when (memq nil (mapcar 'numberp (cdr form)))
    (cond
     ;; (- x 1) --> (1- x)
     ((equal (nthcdr 2 form) '(1))
      (setq form (list '1- (nth 1 form))))
     ;; (- x -1) --> (1+ x)
     ((equal (nthcdr 2 form) '(-1))
      (setq form (list '1+ (nth 1 form))))
     ;; (- 0 x) --> (- x)
     ((and (eq (nth 1 form) 0)
	   (= (length form) 3))
      (setq form (list '- (nth 2 form))))
     ;; Here, we could also do
     ;;  (- x y ... 1) --> (1- (- x y ...))
     ;;  (- x y ... -1) --> (1+ (- x y ...))
     ;; The resulting bytecode is smaller, but is it faster? -- cyd
     ))
  (byte-optimize-predicate form))
Jim Blandy's avatar
Jim Blandy committed
817 818 819

(defun byte-optimize-multiply (form)
  (setq form (byte-optimize-delay-constants-math form 1 '*))
820 821 822 823 824 825 826 827 828 829 830 831 832 833
  ;; For (* constants..), byte-optimize-predicate does the work.
  (when (memq nil (mapcar 'numberp (cdr form)))
    ;; After `byte-optimize-predicate', if there is a INTEGER constant
    ;; in FORM, it is in the last element.
    (let ((last (car (reverse (cdr form)))))
      (cond
       ;; Would handling (* ... 0) here cause floating point errors?
       ;; See bug#1334.
       ((eq 1 last) (setq form (byte-compile-butlast form)))
       ((eq -1 last)
	(setq form (list '- (if (nthcdr 3 form)
				(byte-compile-butlast form)
			      (nth 1 form))))))))
  (byte-optimize-predicate form))
Jim Blandy's avatar
Jim Blandy committed
834 835 836

(defun byte-optimize-divide (form)
  (setq form (byte-optimize-delay-constants-math form 2 '*))
837 838
  ;; After `byte-optimize-predicate', if there is a INTEGER constant
  ;; in FORM, it is in the last element.
Jim Blandy's avatar
Jim Blandy committed
839
  (let ((last (car (reverse (cdr (cdr form))))))
840
    (cond
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
     ;; Runtime error (leave it intact).
     ((or (null last)
	  (eq last 0)
	  (memql 0.0 (cddr form))))
     ;; No constants in expression
     ((not (numberp last)))
     ;; For (* constants..), byte-optimize-predicate does the work.
     ((null (memq nil (mapcar 'numberp (cdr form)))))
     ;; (/ x y.. 1) --> (/ x y..)
     ((and (eq last 1) (nthcdr 3 form))
      (setq form (byte-compile-butlast form)))
     ;; (/ x -1), (/ x .. -1)  --> (- x), (- (/ x ..))
     ((eq last -1)
      (setq form (list '- (if (nthcdr 3 form)
			      (byte-compile-butlast form)
			    (nth 1 form)))))))
  (byte-optimize-predicate form))
Jim Blandy's avatar
Jim Blandy committed
858 859 860 861 862 863 864 865 866 867

(defun byte-optimize-logmumble (form)
  (setq form (byte-optimize-delay-constants-math form 1 (car form)))
  (byte-optimize-predicate
   (cond ((memq 0 form)
	  (setq form (if (eq (car form) 'logand)
			 (cons 'progn (cdr form))
		       (delq 0 (copy-sequence form)))))
	 ((and (eq (car-safe form) 'logior)
	       (memq -1 form))
868
	  (cons 'progn (cdr form)))
Jim Blandy's avatar
Jim Blandy committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
	 (form))))


(defun byte-optimize-binary-predicate (form)
  (if (byte-compile-constp (nth 1 form))
      (if (byte-compile-constp (nth 2 form))
	  (condition-case ()
	      (list 'quote (eval form))
	    (error form))
	;; This can enable some lapcode optimizations.
	(list (car form) (nth 2 form) (nth 1 form)))
    form))

(defun byte-optimize-predicate (form)
  (let ((ok t)
	(rest (cdr form)))
    (while (and rest ok)
      (setq ok (byte-compile-constp (car rest))
	    rest (cdr rest)))
    (if ok
	(condition-case ()
	    (list 'quote (eval form))
	  (error form))
	form)))

(defun byte-optimize-identity (form)
  (if (and (cdr form) (null (cdr (cdr form))))
      (nth 1 form)
Gerd Moellmann's avatar
Gerd Moellmann committed
897
    (byte-compile-warn "identity called with %d arg%s, but requires 1"
Jim Blandy's avatar
Jim Blandy committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
		       (length (cdr form))
		       (if (= 1 (length (cdr form))) "" "s"))
    form))

(put 'identity 'byte-optimizer 'byte-optimize-identity)

(put '+   'byte-optimizer 'byte-optimize-plus)
(put '*   'byte-optimizer 'byte-optimize-multiply)
(put '-   'byte-optimizer 'byte-optimize-minus)
(put '/   'byte-optimizer 'byte-optimize-divide)
(put 'max 'byte-optimizer 'byte-optimize-associative-math)
(put 'min 'byte-optimizer 'byte-optimize-associative-math)

(put '=   'byte-optimizer 'byte-optimize-binary-predicate)
(put 'eq  'byte-optimizer 'byte-optimize-binary-predicate)
(put 'equal   'byte-optimizer 'byte-optimize-binary-predicate)
(put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
(put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)

(put '<   'byte-optimizer 'byte-optimize-predicate)
(put '>   'byte-optimizer 'byte-optimize-predicate)
(put '<=  'byte-optimizer 'byte-optimize-predicate)
(put '>=  'byte-optimizer 'byte-optimize-predicate)
(put '1+  'byte-optimizer 'byte-optimize-predicate)
(put '1-  'byte-optimizer 'byte-optimize-predicate)
(put 'not 'byte-optimizer 'byte-optimize-predicate)
(put 'null  'byte-optimizer 'byte-optimize-predicate)
(put 'memq  'byte-optimizer 'byte-optimize-predicate)
(put 'consp 'byte-optimizer 'byte-optimize-predicate)
(put 'listp 'byte-optimizer 'byte-optimize-predicate)
(put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
(put 'stringp 'byte-optimizer 'byte-optimize-predicate)
(put 'string< 'byte-optimizer 'byte-optimize-predicate)
(put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)

(put 'logand 'byte-optimizer 'byte-optimize-logmumble)
(put 'logior 'byte-optimizer 'byte-optimize-logmumble)
(put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
(put 'lognot 'byte-optimizer 'byte-optimize-predicate)

(put 'car 'byte-optimizer 'byte-optimize-predicate)
(put 'cdr 'byte-optimizer 'byte-optimize-predicate)
(put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
(put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)


944
;; I'm not convinced that this is necessary.  Doesn't the optimizer loop
Jim Blandy's avatar
Jim Blandy committed
945 946
;; take care of this? - Jamie
;; I think this may some times be necessary to reduce ie (quote 5) to 5,
947
;; so arithmetic optimizers recognize the numeric constant.  - Hallvard
Jim Blandy's avatar
Jim Blandy committed
948 949 950 951
(put 'quote 'byte-optimizer 'byte-optimize-quote)
(defun byte-optimize-quote (form)
  (if (or (consp (nth 1 form))
	  (and (symbolp (nth 1 form))
Dave Love's avatar
Dave Love committed
952
	       (not (byte-compile-const-symbol-p form))))
Jim Blandy's avatar
Jim Blandy committed
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
      form
    (nth 1 form)))

(defun byte-optimize-zerop (form)
  (cond ((numberp (nth 1 form))
	 (eval form))
	(byte-compile-delete-errors
	 (list '= (nth 1 form) 0))
	(form)))

(put 'zerop 'byte-optimizer 'byte-optimize-zerop)

(defun byte-optimize-and (form)
  ;; Simplify if less than 2 args.
  ;; if there is a literal nil in the args to `and', throw it and following
  ;; forms away, and surround the `and' with (progn ... nil).
  (cond ((null (cdr form)))
	((memq nil form)
	 (list 'progn
	       (byte-optimize-and
		(prog1 (setq form (copy-sequence form))
		  (while (nth 1 form)
		    (setq form (cdr form)))
		  (setcdr form nil)))
	       nil))
	((null (cdr (cdr form)))
	 (nth 1 form))
	((byte-optimize-predicate form))))

(defun byte-optimize-or (form)
  ;; Throw away nil's, and simplify if less than 2 args.
  ;; If there is a literal non-nil constant in the args to `or', throw away all
  ;; following forms.
  (if (memq nil form)
      (setq form (delq nil (copy-sequence form))))
  (let ((rest form))
    (while (cdr (setq rest (cdr rest)))
      (if (byte-compile-trueconstp (car rest))
	  (setq form (copy-sequence form)
		rest (setcdr (memq (car rest) form) nil))))
    (if (cdr (cdr form))
	(byte-optimize-predicate form)
      (nth 1 form))))

(defun byte-optimize-cond (form)
  ;; if any clauses have a literal nil as their test, throw them away.
  ;; if any clause has a literal non-nil constant as its test, throw
  ;; away all following clauses.
  (let (rest)
    ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
    (while (setq rest (assq nil (cdr form)))
      (setq form (delq rest (copy-sequence form))))
    (if (memq nil (cdr form))
	(setq form (delq nil (copy-sequence form))))
    (setq rest form)
    (while (setq rest (cdr rest))
      (cond ((byte-compile-trueconstp (car-safe (car rest)))
1010 1011 1012
             ;; This branch will always be taken: kill the subsequent ones.
	     (cond ((eq rest (cdr form)) ;First branch of `cond'.
		    (setq form `(progn ,@(car rest))))
Jim Blandy's avatar
Jim Blandy committed
1013 1014 1015
		   ((cdr rest)
		    (setq form (copy-sequence form))
		    (setcdr (memq (car rest) form) nil)))
1016 1017 1018 1019 1020
	     (setq rest nil))
            ((and (consp (car rest))
                  (byte-compile-nilconstp (caar rest)))
             ;; This branch will never be taken: kill its body.
             (setcdr (car rest) nil)))))
Jim Blandy's avatar
Jim Blandy committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
  ;;
  ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
  (if (eq 'cond (car-safe form))
      (let ((clauses (cdr form)))
	(if (and (consp (car clauses))
		 (null (cdr (car clauses))))
	    (list 'or (car (car clauses))
		  (byte-optimize-cond
		   (cons (car form) (cdr (cdr form)))))
	  form))
    form))

(defun byte-optimize-if (form)
1034
  ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
Jim Blandy's avatar
Jim Blandy committed
1035 1036 1037 1038 1039
  ;; (if <true-constant> <then> <else...>) ==> <then>
  ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
  ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
  ;; (if <test> <then> nil) ==> (if <test> <then>)
  (let ((clause (nth 1 form)))
1040 1041 1042
    (cond ((and (eq (car-safe clause) 'progn)
                ;; `clause' is a proper list.
                (null (cdr (last clause))))
1043 1044 1045 1046 1047 1048 1049 1050
           (if (null (cddr clause))
               ;; A trivial `progn'.
               (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
             (nconc (butlast clause)
                    (list
                     (byte-optimize-if
                      `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
          ((byte-compile-trueconstp clause)
1051 1052 1053
	   `(progn ,clause ,(nth 2 form)))
	  ((byte-compile-nilconstp clause)
           `(progn ,clause ,@(nthcdr 3 form)))
Jim Blandy's avatar
Jim Blandy committed
1054 1055 1056 1057 1058
	  ((nth 2 form)
	   (if (equal '(nil) (nthcdr 3 form))
	       (list 'if clause (nth 2 form))
	     form))
	  ((or (nth 3 form) (nthcdr 4 form))
1059 1060 1061 1062 1063 1064 1065
	   (list 'if
		 ;; Don't make a double negative;
		 ;; instead, take away the one that is there.
		 (if (and (consp clause) (memq (car clause) '(not null))
			  (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
		     (nth 1 clause)
		   (list 'not clause))
Jim Blandy's avatar
Jim Blandy committed
1066 1067 1068 1069 1070 1071 1072
		 (if (nthcdr 4 form)
		     (cons 'progn (nthcdr 3 form))
		   (nth 3 form))))
	  (t
	   (list 'progn clause nil)))))

(defun byte-optimize-while (form)
Gerd Moellmann's avatar
Gerd Moellmann committed
1073
  (when (< (length form) 2)
Gerd Moellmann's avatar
Gerd Moellmann committed
1074
    (byte-compile-warn "too few arguments for `while'"))
Jim Blandy's avatar
Jim Blandy committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  (if (nth 1 form)
      form))

(put 'and   'byte-optimizer 'byte-optimize-and)
(put 'or    'byte-optimizer 'byte-optimize-or)
(put 'cond  'byte-optimizer 'byte-optimize-cond)
(put 'if    'byte-optimizer 'byte-optimize-if)
(put 'while 'byte-optimizer 'byte-optimize-while)

;; byte-compile-negation-optimizer lives in bytecomp.el
(put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
(put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
(put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)


(defun byte-optimize-funcall (form)
Stefan Monnier's avatar
Stefan Monnier committed
1091 1092
  ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
  ;; (funcall foo ...) ==> (foo ...)
Jim Blandy's avatar
Jim Blandy committed
1093 1094 1095
  (let ((fn (nth 1 form)))
    (if (memq (car-safe fn) '(quote function))
	(cons (nth 1 fn) (cdr (cdr form)))
1096
      form)))
Jim Blandy's avatar
Jim Blandy committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

(defun byte-optimize-apply (form)
  ;; If the last arg is a literal constant, turn this into a funcall.
  ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
  (let ((fn (nth 1 form))
	(last (nth (1- (length form)) form))) ; I think this really is fastest
    (or (if (or (null last)
		(eq (car-safe last) 'quote))
	    (if (listp (nth 1 last))
		(let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
Jim Blandy's avatar
Jim Blandy committed
1107
		  (nconc (list 'funcall fn) butlast
Stefan Monnier's avatar
Stefan Monnier committed
1108
			 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
Jim Blandy's avatar
Jim Blandy committed
1109
	      (byte-compile-warn
Gerd Moellmann's avatar
Gerd Moellmann committed
1110
	       "last arg to apply can't be a literal atom: `%s'"
Jim Blandy's avatar
Jim Blandy committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	       (prin1-to-string last))
	      nil))
	form)))

(put 'funcall 'byte-optimizer 'byte-optimize-funcall)
(put 'apply   'byte-optimizer 'byte-optimize-apply)


(put 'let 'byte-optimizer 'byte-optimize-letX)
(put 'let* 'byte-optimizer 'byte-optimize-letX)
(defun byte-optimize-letX (form)
  (cond ((null (nth 1 form))
	 ;; No bindings
	 (cons 'progn (cdr (cdr form))))
	((or (nth 2 form) (nthcdr 3 form))
	 form)
	 ;; The body is nil
	((eq (car form) 'let)
1129 1130
	 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
		 '(nil)))
Jim Blandy's avatar
Jim Blandy committed
1131 1132 1133 1134 1135 1136 1137
	(t
	 (let ((binds (reverse (nth 1 form))))
	   (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))


(put 'nth 'byte-optimizer 'byte-optimize-nth)
(defun byte-optimize-nth (form)
Dave Love's avatar
Dave Love committed
1138 1139 1140 1141 1142 1143 1144
  (if (= (safe-length form) 3)
      (if (memq (nth 1 form) '(0 1))
	  (list 'car (if (zerop (nth 1 form))
			 (nth 2 form)
		       (list 'cdr (nth 2 form))))
	(byte-optimize-predicate form))
    form))
Jim Blandy's avatar
Jim Blandy committed
1145 1146 1147

(put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
(defun byte-optimize-nthcdr (form)
Dave Love's avatar
Dave Love committed
1148 1149 1150 1151 1152 1153 1154 1155 1156
  (if (= (safe-length form) 3)
      (if (memq (nth 1 form) '(0 1 2))
	  (let ((count (nth 1 form)))
	    (setq form (nth 2 form))
	    (while (>= (setq count (1- count)) 0)
	      (setq form (list 'cdr form)))
	    form)
	(byte-optimize-predicate form))
    form))
1157

Dave Love's avatar
Dave Love committed
1158 1159 1160 1161 1162 1163
;; Fixme: delete-char -> delete-region (byte-coded)
;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
;; string-make-multibyte for constant args.

(put 'featurep 'byte-optimizer 'byte-optimize-featurep)
(defun byte-optimize-featurep (form)
1164 1165
  ;; Emacs-21's byte-code doesn't run under XEmacs or SXEmacs anyway, so we
  ;; can safely optimize away this test.
1166
  (if (member (cdr-safe form) '(((quote xemacs)) ((quote sxemacs))))
Dave Love's avatar
Dave Love committed
1167
      nil
1168 1169 1170
    (if (member (cdr-safe form) '(((quote emacs))))
	t
      form)))
1171 1172 1173 1174 1175 1176

(put 'set 'byte-optimizer 'byte-optimize-set)
(defun byte-optimize-set (form)
  (let ((var (car-safe (cdr-safe form))))
    (cond
     ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1177
      `(setq ,(cadr var) ,@(cddr form)))
1178 1179 1180 1181 1182
     ((and (eq (car-safe var) 'make-local-variable)
	   (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
	   (consp (cdr var)))
      `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
     (t form))))
Jim Blandy's avatar
Jim Blandy committed
1183

Kenichi Handa's avatar
Kenichi Handa committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
;; enumerating those functions which need not be called if the returned
;; value is not used.  That is, something like
;;    (progn (list (something-with-side-effects) (yow))
;;           (foo))
;; may safely be turned into
;;    (progn (progn (something-with-side-effects) (yow))
;;           (foo))
;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.

;; Some of these functions have the side effect of allocating memory
;; and it would be incorrect to replace two calls with one.
;; But we don't try to do those kinds of optimizations,
;; so it is safe to list such functions here.
;; Some of these functions return values that depend on environment
;; state, so that constant folding them would be wrong,
;; but we don't do constant folding based on this list.

;; However, at present the only optimization we normally do
;; is delete calls that need not occur, and we only do that
;; with the error-free functions.

;; I wonder if I missed any :-\)
Jim Blandy's avatar
Jim Blandy committed
1206
(let ((side-effect-free-fns
1207 1208 1209
       '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
	 assoc assq
	 boundp buffer-file-name buffer-local-variables buffer-modified-p
1210
	 buffer-substring byte-code-function-p
1211
	 capitalize car-less-than-car car cdr ceiling char-after char-before
1212 1213 1214
	 char-equal char-to-string char-width
	 compare-strings concat coordinates-in-window-p
	 copy-alist copy-sequence copy-marker cos count-lines
1215
	 decode-char
1216
	 decode-time default-boundp default-value documentation downcase
Kenichi Handa's avatar
Kenichi Handa committed
1217
	 elt encode-char exp expt encode-time error-message-string
1218
	 fboundp fceiling featurep ffloor
Jim Blandy's avatar
Jim Blandy committed
1219 1220
	 file-directory-p file-exists-p file-locked-p file-name-absolute-p
	 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1221 1222
	 float float-time floor format format-time-string frame-visible-p
	 fround ftruncate