* src/term.c (init_tty) [HAVE_GPM]: Move mouse settings after set_tty_hooks.
[emacs.git] / lisp / emacs-lisp / byte-opt.el
blob7b98ade24220702596a8cd06b1d22c0a407d12b7
1 ;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler -*- lexical-binding: t -*-
3 ;; Copyright (C) 1991, 1994, 2000-2011 Free Software Foundation, Inc.
5 ;; Author: Jamie Zawinski <jwz@lucid.com>
6 ;; Hallvard Furuseth <hbf@ulrik.uio.no>
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9 ;; Package: emacs
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; 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/>.
26 ;;; Commentary:
28 ;; ========================================================================
29 ;; "No matter how hard you try, you can't make a racehorse out of a pig.
30 ;; 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
34 ;; still not going to make it go faster than 70 mph, but it might be easier
35 ;; to get it there.
38 ;; TO DO:
40 ;; (apply (lambda (x &rest y) ...) 1 (foo))
42 ;; maintain a list of functions known not to access any global variables
43 ;; (actually, give them a 'dynamically-safe property) and then
44 ;; (let ( v1 v2 ... vM vN ) <...dynamically-safe...> ) ==>
45 ;; (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
46 ;; by recursing on this, we might be able to eliminate the entire let.
47 ;; However certain variables should never have their bindings optimized
48 ;; away, because they affect everything.
49 ;; (put 'debug-on-error 'binding-is-magic t)
50 ;; (put 'debug-on-abort 'binding-is-magic t)
51 ;; (put 'debug-on-next-call 'binding-is-magic t)
52 ;; (put 'inhibit-quit 'binding-is-magic t)
53 ;; (put 'quit-flag 'binding-is-magic t)
54 ;; (put 't 'binding-is-magic t)
55 ;; (put 'nil 'binding-is-magic t)
56 ;; possibly also
57 ;; (put 'gc-cons-threshold 'binding-is-magic t)
58 ;; (put 'track-mouse 'binding-is-magic t)
59 ;; others?
61 ;; Simple defsubsts often produce forms like
62 ;; (let ((v1 (f1)) (v2 (f2)) ...)
63 ;; (FN v1 v2 ...))
64 ;; It would be nice if we could optimize this to
65 ;; (FN (f1) (f2) ...)
66 ;; but we can't unless FN is dynamically-safe (it might be dynamically
67 ;; referring to the bindings that the lambda arglist established.)
68 ;; One of the uncountable lossages introduced by dynamic scope...
70 ;; Maybe there should be a control-structure that says "turn on
71 ;; fast-and-loose type-assumptive optimizations here." Then when
72 ;; we see a form like (car foo) we can from then on assume that
73 ;; 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
75 ;; scope. Anything down the stack could change the value.
76 ;; (Another reason it doesn't work is that it is perfectly valid
77 ;; to call car with a null argument.) A better approach might
78 ;; be to allow type-specification of the form
79 ;; (put 'foo 'arg-types '(float (list integer) dynamic))
80 ;; (put 'foo 'result-type 'bool)
81 ;; It should be possible to have these types checked to a certain
82 ;; degree.
84 ;; collapse common subexpressions
86 ;; It would be nice if redundant sequences could be factored out as well,
87 ;; when they are known to have no side-effects:
88 ;; (list (+ a b c) (+ a b c)) --> a b add c add dup list-2
89 ;; but beware of traps like
90 ;; (cons (list x y) (list x y))
92 ;; Tail-recursion elimination is not really possible in Emacs Lisp.
93 ;; Tail-recursion elimination is almost always impossible when all variables
94 ;; have dynamic scope, but given that the "return" byteop requires the
95 ;; binding stack to be empty (rather than emptying it itself), there can be
96 ;; no truly tail-recursive Emacs Lisp functions that take any arguments or
97 ;; make any bindings.
99 ;; Here is an example of an Emacs Lisp function which could safely be
100 ;; byte-compiled tail-recursively:
102 ;; (defun tail-map (fn list)
103 ;; (cond (list
104 ;; (funcall fn (car list))
105 ;; (tail-map fn (cdr list)))))
107 ;; However, if there was even a single let-binding around the COND,
108 ;; it could not be byte-compiled, because there would be an "unbind"
109 ;; byte-op between the final "call" and "return." Adding a
110 ;; Bunbind_all byteop would fix this.
112 ;; (defun foo (x y z) ... (foo a b c))
113 ;; ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
114 ;; ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
115 ;; ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
117 ;; this also can be considered tail recursion:
119 ;; ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
120 ;; could generalize this by doing the optimization
121 ;; (goto X) ... X: (return) --> (return)
123 ;; But this doesn't solve all of the problems: although by doing tail-
124 ;; recursion elimination in this way, the call-stack does not grow, the
125 ;; binding-stack would grow with each recursive step, and would eventually
126 ;; overflow. I don't believe there is any way around this without lexical
127 ;; scope.
129 ;; Wouldn't it be nice if Emacs Lisp had lexical scope.
131 ;; Idea: the form (lexical-scope) in a file means that the file may be
132 ;; compiled lexically. This proclamation is file-local. Then, within
133 ;; that file, "let" would establish lexical bindings, and "let-dynamic"
134 ;; would do things the old way. (Or we could use CL "declare" forms.)
135 ;; We'd have to notice defvars and defconsts, since those variables should
136 ;; always be dynamic, and attempting to do a lexical binding of them
137 ;; should simply do a dynamic binding instead.
138 ;; But! We need to know about variables that were not necessarily defvarred
139 ;; in the file being compiled (doing a boundp check isn't good enough.)
140 ;; Fdefvar() would have to be modified to add something to the plist.
142 ;; A major disadvantage of this scheme is that the interpreter and compiler
143 ;; would have different semantics for files compiled with (dynamic-scope).
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
146 ;; in some grody way, but that's a really bad idea.)
148 ;; Other things to consider:
150 ;; ;; Associative math should recognize subcalls to identical function:
151 ;; (disassemble (lambda (x) (+ (+ (foo) 1) (+ (bar) 2))))
152 ;; ;; This should generate the same as (1+ x) and (1- x)
154 ;; (disassemble (lambda (x) (cons (+ x 1) (- x 1))))
155 ;; ;; An awful lot of functions always return a non-nil value. If they're
156 ;; ;; error free also they may act as true-constants.
158 ;; (disassemble (lambda (x) (and (point) (foo))))
159 ;; ;; When
160 ;; ;; - all but one arguments to a function are constant
161 ;; ;; - the non-constant argument is an if-expression (cond-expression?)
162 ;; ;; then the outer function can be distributed. If the guarding
163 ;; ;; condition is side-effect-free [assignment-free] then the other
164 ;; ;; arguments may be any expressions. Since, however, the code size
165 ;; ;; can increase this way they should be "simple". Compare:
167 ;; (disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
168 ;; (disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))
170 ;; ;; (car (cons A B)) -> (prog1 A B)
171 ;; (disassemble (lambda (x) (car (cons (foo) 42))))
173 ;; ;; (cdr (cons A B)) -> (progn A B)
174 ;; (disassemble (lambda (x) (cdr (cons 42 (foo)))))
176 ;; ;; (car (list A B ...)) -> (prog1 A B ...)
177 ;; (disassemble (lambda (x) (car (list (foo) 42 (bar)))))
179 ;; ;; (cdr (list A B ...)) -> (progn A (list B ...))
180 ;; (disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))
183 ;;; Code:
185 (require 'bytecomp)
186 (eval-when-compile (require 'cl))
188 (defun byte-compile-log-lap-1 (format &rest args)
189 ;; Newer byte codes for stack-ref make the slot 0 non-nil again.
190 ;; But the "old disassembler" is *really* ancient by now.
191 ;; (if (aref byte-code-vector 0)
192 ;; (error "The old version of the disassembler is loaded. Reload new-bytecomp as well"))
193 (byte-compile-log-1
194 (apply 'format format
195 (let (c a)
196 (mapcar (lambda (arg)
197 (if (not (consp arg))
198 (if (and (symbolp arg)
199 (string-match "^byte-" (symbol-name arg)))
200 (intern (substring (symbol-name arg) 5))
201 arg)
202 (if (integerp (setq c (car arg)))
203 (error "non-symbolic byte-op %s" c))
204 (if (eq c 'TAG)
205 (setq c arg)
206 (setq a (cond ((memq c byte-goto-ops)
207 (car (cdr (cdr arg))))
208 ((memq c byte-constref-ops)
209 (car (cdr arg)))
210 (t (cdr arg))))
211 (setq c (symbol-name c))
212 (if (string-match "^byte-." c)
213 (setq c (intern (substring c 5)))))
214 (if (eq c 'constant) (setq c 'const))
215 (if (and (eq (cdr arg) 0)
216 (not (memq c '(unbind call const))))
218 (format "(%s %s)" c a))))
219 args)))))
221 (defmacro byte-compile-log-lap (format-string &rest args)
222 `(and (memq byte-optimize-log '(t byte))
223 (byte-compile-log-lap-1 ,format-string ,@args)))
226 ;;; byte-compile optimizers to support inlining
228 (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
230 (defun byte-optimize-inline-handler (form)
231 "byte-optimize-handler for the `inline' special-form."
232 (cons 'progn
233 (mapcar
234 (lambda (sexp)
235 (let ((f (car-safe sexp)))
236 (if (and (symbolp f)
237 (or (cdr (assq f byte-compile-function-environment))
238 (not (or (not (fboundp f))
239 (cdr (assq f byte-compile-macro-environment))
240 (and (consp (setq f (symbol-function f)))
241 (eq (car f) 'macro))
242 (subrp f)))))
243 (byte-compile-inline-expand sexp)
244 sexp)))
245 (cdr form))))
247 (defun byte-compile-inline-expand (form)
248 (let* ((name (car form))
249 (localfn (cdr (assq name byte-compile-function-environment)))
250 (fn (or localfn (and (fboundp name) (symbol-function name)))))
251 (when (and (consp fn) (eq (car fn) 'autoload))
252 (load (nth 1 fn))
253 (setq fn (or (and (fboundp name) (symbol-function name))
254 (cdr (assq name byte-compile-function-environment)))))
255 (pcase fn
256 (`nil
257 (byte-compile-warn "attempt to inline `%s' before it was defined"
258 name)
259 form)
260 (`(autoload . ,_)
261 (error "File `%s' didn't define `%s'" (nth 1 fn) name))
262 ((and (pred symbolp) (guard (not (eq fn t)))) ;A function alias.
263 (byte-compile-inline-expand (cons fn (cdr form))))
264 ((pred byte-code-function-p)
265 ;; (message "Inlining byte-code for %S!" name)
266 ;; The byte-code will be really inlined in byte-compile-unfold-bcf.
267 `(,fn ,@(cdr form)))
268 ((or (and `(lambda ,args . ,body) (let env nil))
269 `(closure ,env ,args . ,body))
270 (if (not (or (eq fn localfn) ;From the same file => same mode.
271 (eq (not lexical-binding) (not env)))) ;Same mode.
272 ;; While byte-compile-unfold-bcf can inline dynbind byte-code into
273 ;; letbind byte-code (or any other combination for that matter), we
274 ;; can only inline dynbind source into dynbind source or letbind
275 ;; source into letbind source.
276 ;; FIXME: we could of course byte-compile the inlined function
277 ;; first, and then inline its byte-code.
278 form
279 (let ((renv ()))
280 ;; Turn the function's closed vars (if any) into local let bindings.
281 (dolist (binding env)
282 (cond
283 ((consp binding)
284 ;; We check shadowing by the args, so that the `let' can be
285 ;; moved within the lambda, which can then be unfolded.
286 ;; FIXME: Some of those bindings might be unused in `body'.
287 (unless (memq (car binding) args) ;Shadowed.
288 (push `(,(car binding) ',(cdr binding)) renv)))
289 ((eq binding t))
290 (t (push `(defvar ,binding) body))))
291 (let ((newfn (byte-compile-preprocess
292 (if (null renv)
293 `(lambda ,args ,@body)
294 `(lambda ,args (let ,(nreverse renv) ,@body))))))
295 (if (eq (car-safe newfn) 'function)
296 (byte-compile-unfold-lambda `(,(cadr newfn) ,@(cdr form)))
297 (byte-compile-log-warning
298 (format "Inlining closure %S failed" name))
299 form)))))
301 (t ;; Give up on inlining.
302 form))))
304 ;; ((lambda ...) ...)
305 (defun byte-compile-unfold-lambda (form &optional name)
306 ;; In lexical-binding mode, let and functions don't bind vars in the same way
307 ;; (let obey special-variable-p, but functions don't). But luckily, this
308 ;; doesn't matter here, because function's behavior is underspecified so it
309 ;; can safely be turned into a `let', even though the reverse is not true.
310 (or name (setq name "anonymous lambda"))
311 (let ((lambda (car form))
312 (values (cdr form)))
313 (let ((arglist (nth 1 lambda))
314 (body (cdr (cdr lambda)))
315 optionalp restp
316 bindings)
317 (if (and (stringp (car body)) (cdr body))
318 (setq body (cdr body)))
319 (if (and (consp (car body)) (eq 'interactive (car (car body))))
320 (setq body (cdr body)))
321 ;; FIXME: The checks below do not belong in an optimization phase.
322 (while arglist
323 (cond ((eq (car arglist) '&optional)
324 ;; ok, I'll let this slide because funcall_lambda() does...
325 ;; (if optionalp (error "multiple &optional keywords in %s" name))
326 (if restp (error "&optional found after &rest in %s" name))
327 (if (null (cdr arglist))
328 (error "nothing after &optional in %s" name))
329 (setq optionalp t))
330 ((eq (car arglist) '&rest)
331 ;; ...but it is by no stretch of the imagination a reasonable
332 ;; thing that funcall_lambda() allows (&rest x y) and
333 ;; (&rest x &optional y) in arglists.
334 (if (null (cdr arglist))
335 (error "nothing after &rest in %s" name))
336 (if (cdr (cdr arglist))
337 (error "multiple vars after &rest in %s" name))
338 (setq restp t))
339 (restp
340 (setq bindings (cons (list (car arglist)
341 (and values (cons 'list values)))
342 bindings)
343 values nil))
344 ((and (not optionalp) (null values))
345 (byte-compile-warn "attempt to open-code `%s' with too few arguments" name)
346 (setq arglist nil values 'too-few))
348 (setq bindings (cons (list (car arglist) (car values))
349 bindings)
350 values (cdr values))))
351 (setq arglist (cdr arglist)))
352 (if values
353 (progn
354 (or (eq values 'too-few)
355 (byte-compile-warn
356 "attempt to open-code `%s' with too many arguments" name))
357 form)
359 ;; The following leads to infinite recursion when loading a
360 ;; file containing `(defsubst f () (f))', and then trying to
361 ;; byte-compile that file.
362 ;(setq body (mapcar 'byte-optimize-form body)))
364 (let ((newform
365 (if bindings
366 (cons 'let (cons (nreverse bindings) body))
367 (cons 'progn body))))
368 (byte-compile-log " %s\t==>\t%s" form newform)
369 newform)))))
372 ;;; implementing source-level optimizers
374 (defun byte-optimize-form-code-walker (form for-effect)
376 ;; For normal function calls, We can just mapcar the optimizer the cdr. But
377 ;; we need to have special knowledge of the syntax of the special forms
378 ;; like let and defun (that's why they're special forms :-). (Actually,
379 ;; the important aspect is that they are subrs that don't evaluate all of
380 ;; their args.)
382 (let ((fn (car-safe form))
383 tmp)
384 (cond ((not (consp form))
385 (if (not (and for-effect
386 (or byte-compile-delete-errors
387 (not (symbolp form))
388 (eq form t))))
389 form))
390 ((eq fn 'quote)
391 (if (cdr (cdr form))
392 (byte-compile-warn "malformed quote form: `%s'"
393 (prin1-to-string form)))
394 ;; map (quote nil) to nil to simplify optimizer logic.
395 ;; map quoted constants to nil if for-effect (just because).
396 (and (nth 1 form)
397 (not for-effect)
398 form))
399 ((eq 'lambda (car-safe fn))
400 (let ((newform (byte-compile-unfold-lambda form)))
401 (if (eq newform form)
402 ;; Some error occurred, avoid infinite recursion
403 form
404 (byte-optimize-form-code-walker newform for-effect))))
405 ((memq fn '(let let*))
406 ;; recursively enter the optimizer for the bindings and body
407 ;; of a let or let*. This for depth-firstness: forms that
408 ;; are more deeply nested are optimized first.
409 (cons fn
410 (cons
411 (mapcar (lambda (binding)
412 (if (symbolp binding)
413 binding
414 (if (cdr (cdr binding))
415 (byte-compile-warn "malformed let binding: `%s'"
416 (prin1-to-string binding)))
417 (list (car binding)
418 (byte-optimize-form (nth 1 binding) nil))))
419 (nth 1 form))
420 (byte-optimize-body (cdr (cdr form)) for-effect))))
421 ((eq fn 'cond)
422 (cons fn
423 (mapcar (lambda (clause)
424 (if (consp clause)
425 (cons
426 (byte-optimize-form (car clause) nil)
427 (byte-optimize-body (cdr clause) for-effect))
428 (byte-compile-warn "malformed cond form: `%s'"
429 (prin1-to-string clause))
430 clause))
431 (cdr form))))
432 ((eq fn 'progn)
433 ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
434 (if (cdr (cdr form))
435 (progn
436 (setq tmp (byte-optimize-body (cdr form) for-effect))
437 (if (cdr tmp) (cons 'progn tmp) (car tmp)))
438 (byte-optimize-form (nth 1 form) for-effect)))
439 ((eq fn 'prog1)
440 (if (cdr (cdr form))
441 (cons 'prog1
442 (cons (byte-optimize-form (nth 1 form) for-effect)
443 (byte-optimize-body (cdr (cdr form)) t)))
444 (byte-optimize-form (nth 1 form) for-effect)))
445 ((eq fn 'prog2)
446 (cons 'prog2
447 (cons (byte-optimize-form (nth 1 form) t)
448 (cons (byte-optimize-form (nth 2 form) for-effect)
449 (byte-optimize-body (cdr (cdr (cdr form))) t)))))
451 ((memq fn '(save-excursion save-restriction save-current-buffer))
452 ;; those subrs which have an implicit progn; it's not quite good
453 ;; enough to treat these like normal function calls.
454 ;; This can turn (save-excursion ...) into (save-excursion) which
455 ;; will be optimized away in the lap-optimize pass.
456 (cons fn (byte-optimize-body (cdr form) for-effect)))
458 ((eq fn 'with-output-to-temp-buffer)
459 ;; this is just like the above, except for the first argument.
460 (cons fn
461 (cons
462 (byte-optimize-form (nth 1 form) nil)
463 (byte-optimize-body (cdr (cdr form)) for-effect))))
465 ((eq fn 'if)
466 (when (< (length form) 3)
467 (byte-compile-warn "too few arguments for `if'"))
468 (cons fn
469 (cons (byte-optimize-form (nth 1 form) nil)
470 (cons
471 (byte-optimize-form (nth 2 form) for-effect)
472 (byte-optimize-body (nthcdr 3 form) for-effect)))))
474 ((memq fn '(and or)) ; Remember, and/or are control structures.
475 ;; Take forms off the back until we can't any more.
476 ;; In the future it could conceivably be a problem that the
477 ;; subexpressions of these forms are optimized in the reverse
478 ;; order, but it's ok for now.
479 (if for-effect
480 (let ((backwards (reverse (cdr form))))
481 (while (and backwards
482 (null (setcar backwards
483 (byte-optimize-form (car backwards)
484 for-effect))))
485 (setq backwards (cdr backwards)))
486 (if (and (cdr form) (null backwards))
487 (byte-compile-log
488 " all subforms of %s called for effect; deleted" form))
489 (and backwards
490 (cons fn (nreverse (mapcar 'byte-optimize-form
491 backwards)))))
492 (cons fn (mapcar 'byte-optimize-form (cdr form)))))
494 ((eq fn 'interactive)
495 (byte-compile-warn "misplaced interactive spec: `%s'"
496 (prin1-to-string form))
497 nil)
499 ((memq fn '(defun defmacro function condition-case))
500 ;; These forms are compiled as constants or by breaking out
501 ;; all the subexpressions and compiling them separately.
502 form)
504 ((eq fn 'unwind-protect)
505 ;; the "protected" part of an unwind-protect is compiled (and thus
506 ;; optimized) as a top-level form, so don't do it here. But the
507 ;; non-protected part has the same for-effect status as the
508 ;; unwind-protect itself. (The protected part is always for effect,
509 ;; but that isn't handled properly yet.)
510 (cons fn
511 (cons (byte-optimize-form (nth 1 form) for-effect)
512 (cdr (cdr form)))))
514 ((eq fn 'catch)
515 ;; the body of a catch is compiled (and thus optimized) as a
516 ;; top-level form, so don't do it here. The tag is never
517 ;; for-effect. The body should have the same for-effect status
518 ;; as the catch form itself, but that isn't handled properly yet.
519 (cons fn
520 (cons (byte-optimize-form (nth 1 form) nil)
521 (cdr (cdr form)))))
523 ((eq fn 'ignore)
524 ;; Don't treat the args to `ignore' as being
525 ;; computed for effect. We want to avoid the warnings
526 ;; that might occur if they were treated that way.
527 ;; However, don't actually bother calling `ignore'.
528 `(prog1 nil . ,(mapcar 'byte-optimize-form (cdr form))))
530 ;; Neeeded as long as we run byte-optimize-form after cconv.
531 ((eq fn 'internal-make-closure) form)
533 ((byte-code-function-p fn)
534 (cons fn (mapcar #'byte-optimize-form (cdr form))))
536 ((not (symbolp fn))
537 (byte-compile-warn "`%s' is a malformed function"
538 (prin1-to-string fn))
539 form)
541 ((and for-effect (setq tmp (get fn 'side-effect-free))
542 (or byte-compile-delete-errors
543 (eq tmp 'error-free)
544 ;; Detect the expansion of (pop foo).
545 ;; There is no need to compile the call to `car' there.
546 (and (eq fn 'car)
547 (eq (car-safe (cadr form)) 'prog1)
548 (let ((var (cadr (cadr form)))
549 (last (nth 2 (cadr form))))
550 (and (symbolp var)
551 (null (nthcdr 3 (cadr form)))
552 (eq (car-safe last) 'setq)
553 (eq (cadr last) var)
554 (eq (car-safe (nth 2 last)) 'cdr)
555 (eq (cadr (nth 2 last)) var))))
556 (progn
557 (byte-compile-warn "value returned from %s is unused"
558 (prin1-to-string form))
559 nil)))
560 (byte-compile-log " %s called for effect; deleted" fn)
561 ;; appending a nil here might not be necessary, but it can't hurt.
562 (byte-optimize-form
563 (cons 'progn (append (cdr form) '(nil))) t))
566 ;; Otherwise, no args can be considered to be for-effect,
567 ;; even if the called function is for-effect, because we
568 ;; don't know anything about that function.
569 (let ((args (mapcar #'byte-optimize-form (cdr form))))
570 (if (and (get fn 'pure)
571 (byte-optimize-all-constp args))
572 (list 'quote (apply fn (mapcar #'eval args)))
573 (cons fn args)))))))
575 (defun byte-optimize-all-constp (list)
576 "Non-nil if all elements of LIST satisfy `byte-compile-constp'."
577 (let ((constant t))
578 (while (and list constant)
579 (unless (byte-compile-constp (car list))
580 (setq constant nil))
581 (setq list (cdr list)))
582 constant))
584 (defun byte-optimize-form (form &optional for-effect)
585 "The source-level pass of the optimizer."
587 ;; First, optimize all sub-forms of this one.
588 (setq form (byte-optimize-form-code-walker form for-effect))
590 ;; after optimizing all subforms, optimize this form until it doesn't
591 ;; optimize any further. This means that some forms will be passed through
592 ;; the optimizer many times, but that's necessary to make the for-effect
593 ;; processing do as much as possible.
595 (let (opt new)
596 (if (and (consp form)
597 (symbolp (car form))
598 (or (and for-effect
599 ;; we don't have any of these yet, but we might.
600 (setq opt (get (car form) 'byte-for-effect-optimizer)))
601 (setq opt (get (car form) 'byte-optimizer)))
602 (not (eq form (setq new (funcall opt form)))))
603 (progn
604 ;; (if (equal form new) (error "bogus optimizer -- %s" opt))
605 (byte-compile-log " %s\t==>\t%s" form new)
606 (setq new (byte-optimize-form new for-effect))
607 new)
608 form)))
611 (defun byte-optimize-body (forms all-for-effect)
612 ;; Optimize the cdr of a progn or implicit progn; all forms is a list of
613 ;; forms, all but the last of which are optimized with the assumption that
614 ;; they are being called for effect. the last is for-effect as well if
615 ;; all-for-effect is true. returns a new list of forms.
616 (let ((rest forms)
617 (result nil)
618 fe new)
619 (while rest
620 (setq fe (or all-for-effect (cdr rest)))
621 (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
622 (if (or new (not fe))
623 (setq result (cons new result)))
624 (setq rest (cdr rest)))
625 (nreverse result)))
628 ;; some source-level optimizers
630 ;; when writing optimizers, be VERY careful that the optimizer returns
631 ;; something not EQ to its argument if and ONLY if it has made a change.
632 ;; This implies that you cannot simply destructively modify the list;
633 ;; you must return something not EQ to it if you make an optimization.
635 ;; It is now safe to optimize code such that it introduces new bindings.
637 (defsubst byte-compile-trueconstp (form)
638 "Return non-nil if FORM always evaluates to a non-nil value."
639 (while (eq (car-safe form) 'progn)
640 (setq form (car (last (cdr form)))))
641 (cond ((consp form)
642 (case (car form)
643 (quote (cadr form))
644 ;; Can't use recursion in a defsubst.
645 ;; (progn (byte-compile-trueconstp (car (last (cdr form)))))
647 ((not (symbolp form)))
648 ((eq form t))
649 ((keywordp form))))
651 (defsubst byte-compile-nilconstp (form)
652 "Return non-nil if FORM always evaluates to a nil value."
653 (while (eq (car-safe form) 'progn)
654 (setq form (car (last (cdr form)))))
655 (cond ((consp form)
656 (case (car form)
657 (quote (null (cadr form)))
658 ;; Can't use recursion in a defsubst.
659 ;; (progn (byte-compile-nilconstp (car (last (cdr form)))))
661 ((not (symbolp form)) nil)
662 ((null form))))
664 ;; If the function is being called with constant numeric args,
665 ;; evaluate as much as possible at compile-time. This optimizer
666 ;; assumes that the function is associative, like + or *.
667 (defun byte-optimize-associative-math (form)
668 (let ((args nil)
669 (constants nil)
670 (rest (cdr form)))
671 (while rest
672 (if (numberp (car rest))
673 (setq constants (cons (car rest) constants))
674 (setq args (cons (car rest) args)))
675 (setq rest (cdr rest)))
676 (if (cdr constants)
677 (if args
678 (list (car form)
679 (apply (car form) constants)
680 (if (cdr args)
681 (cons (car form) (nreverse args))
682 (car args)))
683 (apply (car form) constants))
684 form)))
686 ;; If the function is being called with constant numeric args,
687 ;; evaluate as much as possible at compile-time. This optimizer
688 ;; assumes that the function satisfies
689 ;; (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
690 ;; like - and /.
691 (defun byte-optimize-nonassociative-math (form)
692 (if (or (not (numberp (car (cdr form))))
693 (not (numberp (car (cdr (cdr form))))))
694 form
695 (let ((constant (car (cdr form)))
696 (rest (cdr (cdr form))))
697 (while (numberp (car rest))
698 (setq constant (funcall (car form) constant (car rest))
699 rest (cdr rest)))
700 (if rest
701 (cons (car form) (cons constant rest))
702 constant))))
704 ;;(defun byte-optimize-associative-two-args-math (form)
705 ;; (setq form (byte-optimize-associative-math form))
706 ;; (if (consp form)
707 ;; (byte-optimize-two-args-left form)
708 ;; form))
710 ;;(defun byte-optimize-nonassociative-two-args-math (form)
711 ;; (setq form (byte-optimize-nonassociative-math form))
712 ;; (if (consp form)
713 ;; (byte-optimize-two-args-right form)
714 ;; form))
716 (defun byte-optimize-approx-equal (x y)
717 (<= (* (abs (- x y)) 100) (abs (+ x y))))
719 ;; Collect all the constants from FORM, after the STARTth arg,
720 ;; and apply FUN to them to make one argument at the end.
721 ;; For functions that can handle floats, that optimization
722 ;; can be incorrect because reordering can cause an overflow
723 ;; that would otherwise be avoided by encountering an arg that is a float.
724 ;; We avoid this problem by (1) not moving float constants and
725 ;; (2) not moving anything if it would cause an overflow.
726 (defun byte-optimize-delay-constants-math (form start fun)
727 ;; Merge all FORM's constants from number START, call FUN on them
728 ;; and put the result at the end.
729 (let ((rest (nthcdr (1- start) form))
730 (orig form)
731 ;; t means we must check for overflow.
732 (overflow (memq fun '(+ *))))
733 (while (cdr (setq rest (cdr rest)))
734 (if (integerp (car rest))
735 (let (constants)
736 (setq form (copy-sequence form)
737 rest (nthcdr (1- start) form))
738 (while (setq rest (cdr rest))
739 (cond ((integerp (car rest))
740 (setq constants (cons (car rest) constants))
741 (setcar rest nil))))
742 ;; If necessary, check now for overflow
743 ;; that might be caused by reordering.
744 (if (and overflow
745 ;; We have overflow if the result of doing the arithmetic
746 ;; on floats is not even close to the result
747 ;; of doing it on integers.
748 (not (byte-optimize-approx-equal
749 (apply fun (mapcar 'float constants))
750 (float (apply fun constants)))))
751 (setq form orig)
752 (setq form (nconc (delq nil form)
753 (list (apply fun (nreverse constants)))))))))
754 form))
756 (defsubst byte-compile-butlast (form)
757 (nreverse (cdr (reverse form))))
759 (defun byte-optimize-plus (form)
760 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
761 ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
762 (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
763 ;; For (+ constants...), byte-optimize-predicate does the work.
764 (when (memq nil (mapcar 'numberp (cdr form)))
765 (cond
766 ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
767 ((and (= (length form) 3)
768 (or (memq (nth 1 form) '(1 -1))
769 (memq (nth 2 form) '(1 -1))))
770 (let (integer other)
771 (if (memq (nth 1 form) '(1 -1))
772 (setq integer (nth 1 form) other (nth 2 form))
773 (setq integer (nth 2 form) other (nth 1 form)))
774 (setq form
775 (list (if (eq integer 1) '1+ '1-) other))))
776 ;; Here, we could also do
777 ;; (+ x y ... 1) --> (1+ (+ x y ...))
778 ;; (+ x y ... -1) --> (1- (+ x y ...))
779 ;; The resulting bytecode is smaller, but is it faster? -- cyd
781 (byte-optimize-predicate form))
783 (defun byte-optimize-minus (form)
784 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
785 ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
786 ;; Remove zeros.
787 (when (and (nthcdr 3 form)
788 (memq 0 (cddr form)))
789 (setq form (nconc (list (car form) (cadr form))
790 (delq 0 (copy-sequence (cddr form)))))
791 ;; After the above, we must turn (- x) back into (- x 0)
792 (or (cddr form)
793 (setq form (nconc form (list 0)))))
794 ;; For (- constants..), byte-optimize-predicate does the work.
795 (when (memq nil (mapcar 'numberp (cdr form)))
796 (cond
797 ;; (- x 1) --> (1- x)
798 ((equal (nthcdr 2 form) '(1))
799 (setq form (list '1- (nth 1 form))))
800 ;; (- x -1) --> (1+ x)
801 ((equal (nthcdr 2 form) '(-1))
802 (setq form (list '1+ (nth 1 form))))
803 ;; (- 0 x) --> (- x)
804 ((and (eq (nth 1 form) 0)
805 (= (length form) 3))
806 (setq form (list '- (nth 2 form))))
807 ;; Here, we could also do
808 ;; (- x y ... 1) --> (1- (- x y ...))
809 ;; (- x y ... -1) --> (1+ (- x y ...))
810 ;; The resulting bytecode is smaller, but is it faster? -- cyd
812 (byte-optimize-predicate form))
814 (defun byte-optimize-multiply (form)
815 (setq form (byte-optimize-delay-constants-math form 1 '*))
816 ;; For (* constants..), byte-optimize-predicate does the work.
817 (when (memq nil (mapcar 'numberp (cdr form)))
818 ;; After `byte-optimize-predicate', if there is a INTEGER constant
819 ;; in FORM, it is in the last element.
820 (let ((last (car (reverse (cdr form)))))
821 (cond
822 ;; Would handling (* ... 0) here cause floating point errors?
823 ;; See bug#1334.
824 ((eq 1 last) (setq form (byte-compile-butlast form)))
825 ((eq -1 last)
826 (setq form (list '- (if (nthcdr 3 form)
827 (byte-compile-butlast form)
828 (nth 1 form))))))))
829 (byte-optimize-predicate form))
831 (defun byte-optimize-divide (form)
832 (setq form (byte-optimize-delay-constants-math form 2 '*))
833 ;; After `byte-optimize-predicate', if there is a INTEGER constant
834 ;; in FORM, it is in the last element.
835 (let ((last (car (reverse (cdr (cdr form))))))
836 (cond
837 ;; Runtime error (leave it intact).
838 ((or (null last)
839 (eq last 0)
840 (memql 0.0 (cddr form))))
841 ;; No constants in expression
842 ((not (numberp last)))
843 ;; For (* constants..), byte-optimize-predicate does the work.
844 ((null (memq nil (mapcar 'numberp (cdr form)))))
845 ;; (/ x y.. 1) --> (/ x y..)
846 ((and (eq last 1) (nthcdr 3 form))
847 (setq form (byte-compile-butlast form)))
848 ;; (/ x -1), (/ x .. -1) --> (- x), (- (/ x ..))
849 ((eq last -1)
850 (setq form (list '- (if (nthcdr 3 form)
851 (byte-compile-butlast form)
852 (nth 1 form)))))))
853 (byte-optimize-predicate form))
855 (defun byte-optimize-logmumble (form)
856 (setq form (byte-optimize-delay-constants-math form 1 (car form)))
857 (byte-optimize-predicate
858 (cond ((memq 0 form)
859 (setq form (if (eq (car form) 'logand)
860 (cons 'progn (cdr form))
861 (delq 0 (copy-sequence form)))))
862 ((and (eq (car-safe form) 'logior)
863 (memq -1 form))
864 (cons 'progn (cdr form)))
865 (form))))
868 (defun byte-optimize-binary-predicate (form)
869 (if (byte-compile-constp (nth 1 form))
870 (if (byte-compile-constp (nth 2 form))
871 (condition-case ()
872 (list 'quote (eval form))
873 (error form))
874 ;; This can enable some lapcode optimizations.
875 (list (car form) (nth 2 form) (nth 1 form)))
876 form))
878 (defun byte-optimize-predicate (form)
879 (let ((ok t)
880 (rest (cdr form)))
881 (while (and rest ok)
882 (setq ok (byte-compile-constp (car rest))
883 rest (cdr rest)))
884 (if ok
885 (condition-case ()
886 (list 'quote (eval form))
887 (error form))
888 form)))
890 (defun byte-optimize-identity (form)
891 (if (and (cdr form) (null (cdr (cdr form))))
892 (nth 1 form)
893 (byte-compile-warn "identity called with %d arg%s, but requires 1"
894 (length (cdr form))
895 (if (= 1 (length (cdr form))) "" "s"))
896 form))
898 (put 'identity 'byte-optimizer 'byte-optimize-identity)
900 (put '+ 'byte-optimizer 'byte-optimize-plus)
901 (put '* 'byte-optimizer 'byte-optimize-multiply)
902 (put '- 'byte-optimizer 'byte-optimize-minus)
903 (put '/ 'byte-optimizer 'byte-optimize-divide)
904 (put 'max 'byte-optimizer 'byte-optimize-associative-math)
905 (put 'min 'byte-optimizer 'byte-optimize-associative-math)
907 (put '= 'byte-optimizer 'byte-optimize-binary-predicate)
908 (put 'eq 'byte-optimizer 'byte-optimize-binary-predicate)
909 (put 'equal 'byte-optimizer 'byte-optimize-binary-predicate)
910 (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
911 (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
913 (put '< 'byte-optimizer 'byte-optimize-predicate)
914 (put '> 'byte-optimizer 'byte-optimize-predicate)
915 (put '<= 'byte-optimizer 'byte-optimize-predicate)
916 (put '>= 'byte-optimizer 'byte-optimize-predicate)
917 (put '1+ 'byte-optimizer 'byte-optimize-predicate)
918 (put '1- 'byte-optimizer 'byte-optimize-predicate)
919 (put 'not 'byte-optimizer 'byte-optimize-predicate)
920 (put 'null 'byte-optimizer 'byte-optimize-predicate)
921 (put 'memq 'byte-optimizer 'byte-optimize-predicate)
922 (put 'consp 'byte-optimizer 'byte-optimize-predicate)
923 (put 'listp 'byte-optimizer 'byte-optimize-predicate)
924 (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
925 (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
926 (put 'string< 'byte-optimizer 'byte-optimize-predicate)
927 (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
929 (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
930 (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
931 (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
932 (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
934 (put 'car 'byte-optimizer 'byte-optimize-predicate)
935 (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
936 (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
937 (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
940 ;; I'm not convinced that this is necessary. Doesn't the optimizer loop
941 ;; take care of this? - Jamie
942 ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
943 ;; so arithmetic optimizers recognize the numeric constant. - Hallvard
944 (put 'quote 'byte-optimizer 'byte-optimize-quote)
945 (defun byte-optimize-quote (form)
946 (if (or (consp (nth 1 form))
947 (and (symbolp (nth 1 form))
948 (not (byte-compile-const-symbol-p form))))
949 form
950 (nth 1 form)))
952 (defun byte-optimize-zerop (form)
953 (cond ((numberp (nth 1 form))
954 (eval form))
955 (byte-compile-delete-errors
956 (list '= (nth 1 form) 0))
957 (form)))
959 (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
961 (defun byte-optimize-and (form)
962 ;; Simplify if less than 2 args.
963 ;; if there is a literal nil in the args to `and', throw it and following
964 ;; forms away, and surround the `and' with (progn ... nil).
965 (cond ((null (cdr form)))
966 ((memq nil form)
967 (list 'progn
968 (byte-optimize-and
969 (prog1 (setq form (copy-sequence form))
970 (while (nth 1 form)
971 (setq form (cdr form)))
972 (setcdr form nil)))
973 nil))
974 ((null (cdr (cdr form)))
975 (nth 1 form))
976 ((byte-optimize-predicate form))))
978 (defun byte-optimize-or (form)
979 ;; Throw away nil's, and simplify if less than 2 args.
980 ;; If there is a literal non-nil constant in the args to `or', throw away all
981 ;; following forms.
982 (if (memq nil form)
983 (setq form (delq nil (copy-sequence form))))
984 (let ((rest form))
985 (while (cdr (setq rest (cdr rest)))
986 (if (byte-compile-trueconstp (car rest))
987 (setq form (copy-sequence form)
988 rest (setcdr (memq (car rest) form) nil))))
989 (if (cdr (cdr form))
990 (byte-optimize-predicate form)
991 (nth 1 form))))
993 (defun byte-optimize-cond (form)
994 ;; if any clauses have a literal nil as their test, throw them away.
995 ;; if any clause has a literal non-nil constant as its test, throw
996 ;; away all following clauses.
997 (let (rest)
998 ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
999 (while (setq rest (assq nil (cdr form)))
1000 (setq form (delq rest (copy-sequence form))))
1001 (if (memq nil (cdr form))
1002 (setq form (delq nil (copy-sequence form))))
1003 (setq rest form)
1004 (while (setq rest (cdr rest))
1005 (cond ((byte-compile-trueconstp (car-safe (car rest)))
1006 ;; This branch will always be taken: kill the subsequent ones.
1007 (cond ((eq rest (cdr form)) ;First branch of `cond'.
1008 (setq form `(progn ,@(car rest))))
1009 ((cdr rest)
1010 (setq form (copy-sequence form))
1011 (setcdr (memq (car rest) form) nil)))
1012 (setq rest nil))
1013 ((and (consp (car rest))
1014 (byte-compile-nilconstp (caar rest)))
1015 ;; This branch will never be taken: kill its body.
1016 (setcdr (car rest) nil)))))
1018 ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
1019 (if (eq 'cond (car-safe form))
1020 (let ((clauses (cdr form)))
1021 (if (and (consp (car clauses))
1022 (null (cdr (car clauses))))
1023 (list 'or (car (car clauses))
1024 (byte-optimize-cond
1025 (cons (car form) (cdr (cdr form)))))
1026 form))
1027 form))
1029 (defun byte-optimize-if (form)
1030 ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
1031 ;; (if <true-constant> <then> <else...>) ==> <then>
1032 ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
1033 ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
1034 ;; (if <test> <then> nil) ==> (if <test> <then>)
1035 (let ((clause (nth 1 form)))
1036 (cond ((and (eq (car-safe clause) 'progn)
1037 ;; `clause' is a proper list.
1038 (null (cdr (last clause))))
1039 (if (null (cddr clause))
1040 ;; A trivial `progn'.
1041 (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
1042 (nconc (butlast clause)
1043 (list
1044 (byte-optimize-if
1045 `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
1046 ((byte-compile-trueconstp clause)
1047 `(progn ,clause ,(nth 2 form)))
1048 ((byte-compile-nilconstp clause)
1049 `(progn ,clause ,@(nthcdr 3 form)))
1050 ((nth 2 form)
1051 (if (equal '(nil) (nthcdr 3 form))
1052 (list 'if clause (nth 2 form))
1053 form))
1054 ((or (nth 3 form) (nthcdr 4 form))
1055 (list 'if
1056 ;; Don't make a double negative;
1057 ;; instead, take away the one that is there.
1058 (if (and (consp clause) (memq (car clause) '(not null))
1059 (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
1060 (nth 1 clause)
1061 (list 'not clause))
1062 (if (nthcdr 4 form)
1063 (cons 'progn (nthcdr 3 form))
1064 (nth 3 form))))
1066 (list 'progn clause nil)))))
1068 (defun byte-optimize-while (form)
1069 (when (< (length form) 2)
1070 (byte-compile-warn "too few arguments for `while'"))
1071 (if (nth 1 form)
1072 form))
1074 (put 'and 'byte-optimizer 'byte-optimize-and)
1075 (put 'or 'byte-optimizer 'byte-optimize-or)
1076 (put 'cond 'byte-optimizer 'byte-optimize-cond)
1077 (put 'if 'byte-optimizer 'byte-optimize-if)
1078 (put 'while 'byte-optimizer 'byte-optimize-while)
1080 ;; byte-compile-negation-optimizer lives in bytecomp.el
1081 (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
1082 (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
1083 (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
1086 (defun byte-optimize-funcall (form)
1087 ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
1088 ;; (funcall foo ...) ==> (foo ...)
1089 (let ((fn (nth 1 form)))
1090 (if (memq (car-safe fn) '(quote function))
1091 (cons (nth 1 fn) (cdr (cdr form)))
1092 form)))
1094 (defun byte-optimize-apply (form)
1095 ;; If the last arg is a literal constant, turn this into a funcall.
1096 ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
1097 (let ((fn (nth 1 form))
1098 (last (nth (1- (length form)) form))) ; I think this really is fastest
1099 (or (if (or (null last)
1100 (eq (car-safe last) 'quote))
1101 (if (listp (nth 1 last))
1102 (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
1103 (nconc (list 'funcall fn) butlast
1104 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
1105 (byte-compile-warn
1106 "last arg to apply can't be a literal atom: `%s'"
1107 (prin1-to-string last))
1108 nil))
1109 form)))
1111 (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
1112 (put 'apply 'byte-optimizer 'byte-optimize-apply)
1115 (put 'let 'byte-optimizer 'byte-optimize-letX)
1116 (put 'let* 'byte-optimizer 'byte-optimize-letX)
1117 (defun byte-optimize-letX (form)
1118 (cond ((null (nth 1 form))
1119 ;; No bindings
1120 (cons 'progn (cdr (cdr form))))
1121 ((or (nth 2 form) (nthcdr 3 form))
1122 form)
1123 ;; The body is nil
1124 ((eq (car form) 'let)
1125 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
1126 '(nil)))
1128 (let ((binds (reverse (nth 1 form))))
1129 (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
1132 (put 'nth 'byte-optimizer 'byte-optimize-nth)
1133 (defun byte-optimize-nth (form)
1134 (if (= (safe-length form) 3)
1135 (if (memq (nth 1 form) '(0 1))
1136 (list 'car (if (zerop (nth 1 form))
1137 (nth 2 form)
1138 (list 'cdr (nth 2 form))))
1139 (byte-optimize-predicate form))
1140 form))
1142 (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
1143 (defun byte-optimize-nthcdr (form)
1144 (if (= (safe-length form) 3)
1145 (if (memq (nth 1 form) '(0 1 2))
1146 (let ((count (nth 1 form)))
1147 (setq form (nth 2 form))
1148 (while (>= (setq count (1- count)) 0)
1149 (setq form (list 'cdr form)))
1150 form)
1151 (byte-optimize-predicate form))
1152 form))
1154 ;; Fixme: delete-char -> delete-region (byte-coded)
1155 ;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
1156 ;; string-make-multibyte for constant args.
1158 (put 'featurep 'byte-optimizer 'byte-optimize-featurep)
1159 (defun byte-optimize-featurep (form)
1160 ;; Emacs-21's byte-code doesn't run under XEmacs or SXEmacs anyway, so we
1161 ;; can safely optimize away this test.
1162 (if (member (cdr-safe form) '(((quote xemacs)) ((quote sxemacs))))
1164 (if (member (cdr-safe form) '(((quote emacs))))
1166 form)))
1168 (put 'set 'byte-optimizer 'byte-optimize-set)
1169 (defun byte-optimize-set (form)
1170 (let ((var (car-safe (cdr-safe form))))
1171 (cond
1172 ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1173 `(setq ,(cadr var) ,@(cddr form)))
1174 ((and (eq (car-safe var) 'make-local-variable)
1175 (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
1176 (consp (cdr var)))
1177 `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
1178 (t form))))
1180 ;; enumerating those functions which need not be called if the returned
1181 ;; value is not used. That is, something like
1182 ;; (progn (list (something-with-side-effects) (yow))
1183 ;; (foo))
1184 ;; may safely be turned into
1185 ;; (progn (progn (something-with-side-effects) (yow))
1186 ;; (foo))
1187 ;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
1189 ;; Some of these functions have the side effect of allocating memory
1190 ;; and it would be incorrect to replace two calls with one.
1191 ;; But we don't try to do those kinds of optimizations,
1192 ;; so it is safe to list such functions here.
1193 ;; Some of these functions return values that depend on environment
1194 ;; state, so that constant folding them would be wrong,
1195 ;; but we don't do constant folding based on this list.
1197 ;; However, at present the only optimization we normally do
1198 ;; is delete calls that need not occur, and we only do that
1199 ;; with the error-free functions.
1201 ;; I wonder if I missed any :-\)
1202 (let ((side-effect-free-fns
1203 '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
1204 assoc assq
1205 boundp buffer-file-name buffer-local-variables buffer-modified-p
1206 buffer-substring byte-code-function-p
1207 capitalize car-less-than-car car cdr ceiling char-after char-before
1208 char-equal char-to-string char-width
1209 compare-strings concat coordinates-in-window-p
1210 copy-alist copy-sequence copy-marker cos count-lines
1211 decode-char
1212 decode-time default-boundp default-value documentation downcase
1213 elt encode-char exp expt encode-time error-message-string
1214 fboundp fceiling featurep ffloor
1215 file-directory-p file-exists-p file-locked-p file-name-absolute-p
1216 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1217 float float-time floor format format-time-string frame-visible-p
1218 fround ftruncate
1219 get gethash get-buffer get-buffer-window getenv get-file-buffer
1220 hash-table-count
1221 int-to-string intern-soft
1222 keymap-parent
1223 length local-variable-if-set-p local-variable-p log log10 logand
1224 logb logior lognot logxor lsh langinfo
1225 make-list make-string make-symbol
1226 marker-buffer max member memq min mod multibyte-char-to-unibyte
1227 next-window nth nthcdr number-to-string
1228 parse-colon-path plist-get plist-member
1229 prefix-numeric-value previous-window prin1-to-string propertize
1230 degrees-to-radians
1231 radians-to-degrees rassq rassoc read-from-string regexp-quote
1232 region-beginning region-end reverse round
1233 sin sqrt string string< string= string-equal string-lessp string-to-char
1234 string-to-int string-to-number substring sxhash symbol-function
1235 symbol-name symbol-plist symbol-value string-make-unibyte
1236 string-make-multibyte string-as-multibyte string-as-unibyte
1237 string-to-multibyte
1238 tan truncate
1239 unibyte-char-to-multibyte upcase user-full-name
1240 user-login-name user-original-login-name user-variable-p
1241 vconcat
1242 window-buffer window-dedicated-p window-edges window-height
1243 window-hscroll window-minibuffer-p window-width
1244 zerop))
1245 (side-effect-and-error-free-fns
1246 '(arrayp atom
1247 bobp bolp bool-vector-p
1248 buffer-end buffer-list buffer-size buffer-string bufferp
1249 car-safe case-table-p cdr-safe char-or-string-p characterp
1250 charsetp commandp cons consp
1251 current-buffer current-global-map current-indentation
1252 current-local-map current-minor-mode-maps current-time
1253 current-time-string current-time-zone
1254 eobp eolp eq equal eventp
1255 floatp following-char framep
1256 get-largest-window get-lru-window
1257 hash-table-p
1258 identity ignore integerp integer-or-marker-p interactive-p
1259 invocation-directory invocation-name
1260 keymapp
1261 line-beginning-position line-end-position list listp
1262 make-marker mark mark-marker markerp max-char
1263 memory-limit minibuffer-window
1264 mouse-movement-p
1265 natnump nlistp not null number-or-marker-p numberp
1266 one-window-p overlayp
1267 point point-marker point-min point-max preceding-char primary-charset
1268 processp
1269 recent-keys recursion-depth
1270 safe-length selected-frame selected-window sequencep
1271 standard-case-table standard-syntax-table stringp subrp symbolp
1272 syntax-table syntax-table-p
1273 this-command-keys this-command-keys-vector this-single-command-keys
1274 this-single-command-raw-keys
1275 user-real-login-name user-real-uid user-uid
1276 vector vectorp visible-frame-list
1277 wholenump window-configuration-p window-live-p windowp)))
1278 (while side-effect-free-fns
1279 (put (car side-effect-free-fns) 'side-effect-free t)
1280 (setq side-effect-free-fns (cdr side-effect-free-fns)))
1281 (while side-effect-and-error-free-fns
1282 (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
1283 (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
1284 nil)
1287 ;; pure functions are side-effect free functions whose values depend
1288 ;; only on their arguments. For these functions, calls with constant
1289 ;; arguments can be evaluated at compile time. This may shift run time
1290 ;; errors to compile time.
1292 (let ((pure-fns
1293 '(concat symbol-name regexp-opt regexp-quote string-to-syntax)))
1294 (while pure-fns
1295 (put (car pure-fns) 'pure t)
1296 (setq pure-fns (cdr pure-fns)))
1297 nil)
1299 (defconst byte-constref-ops
1300 '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
1302 ;; Used and set dynamically in byte-decompile-bytecode-1.
1303 (defvar bytedecomp-op)
1304 (defvar bytedecomp-ptr)
1306 ;; This function extracts the bitfields from variable-length opcodes.
1307 ;; Originally defined in disass.el (which no longer uses it.)
1308 (defun disassemble-offset (bytes)
1309 "Don't call this!"
1310 ;; Fetch and return the offset for the current opcode.
1311 ;; Return nil if this opcode has no offset.
1312 (cond ((< bytedecomp-op byte-nth)
1313 (let ((tem (logand bytedecomp-op 7)))
1314 (setq bytedecomp-op (logand bytedecomp-op 248))
1315 (cond ((eq tem 6)
1316 ;; Offset in next byte.
1317 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1318 (aref bytes bytedecomp-ptr))
1319 ((eq tem 7)
1320 ;; Offset in next 2 bytes.
1321 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1322 (+ (aref bytes bytedecomp-ptr)
1323 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1324 (lsh (aref bytes bytedecomp-ptr) 8))))
1325 (t tem)))) ;Offset was in opcode.
1326 ((>= bytedecomp-op byte-constant)
1327 (prog1 (- bytedecomp-op byte-constant) ;Offset in opcode.
1328 (setq bytedecomp-op byte-constant)))
1329 ((or (and (>= bytedecomp-op byte-constant2)
1330 (<= bytedecomp-op byte-goto-if-not-nil-else-pop))
1331 (= bytedecomp-op byte-stack-set2))
1332 ;; Offset in next 2 bytes.
1333 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1334 (+ (aref bytes bytedecomp-ptr)
1335 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1336 (lsh (aref bytes bytedecomp-ptr) 8))))
1337 ((and (>= bytedecomp-op byte-listN)
1338 (<= bytedecomp-op byte-discardN))
1339 (setq bytedecomp-ptr (1+ bytedecomp-ptr)) ;Offset in next byte.
1340 (aref bytes bytedecomp-ptr))))
1342 (defvar byte-compile-tag-number)
1344 ;; This de-compiler is used for inline expansion of compiled functions,
1345 ;; and by the disassembler.
1347 ;; This list contains numbers, which are pc values,
1348 ;; before each instruction.
1349 (defun byte-decompile-bytecode (bytes constvec)
1350 "Turn BYTECODE into lapcode, referring to CONSTVEC."
1351 (let ((byte-compile-constants nil)
1352 (byte-compile-variables nil)
1353 (byte-compile-tag-number 0))
1354 (byte-decompile-bytecode-1 bytes constvec)))
1356 ;; As byte-decompile-bytecode, but updates
1357 ;; byte-compile-{constants, variables, tag-number}.
1358 ;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1359 ;; with `goto's destined for the end of the code.
1360 ;; That is for use by the compiler.
1361 ;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
1362 ;; In that case, we put a pc value into the list
1363 ;; before each insn (or its label).
1364 (defun byte-decompile-bytecode-1 (bytes constvec &optional make-spliceable)
1365 (let ((length (length bytes))
1366 (bytedecomp-ptr 0) optr tags bytedecomp-op offset
1367 lap tmp)
1368 (while (not (= bytedecomp-ptr length))
1369 (or make-spliceable
1370 (push bytedecomp-ptr lap))
1371 (setq bytedecomp-op (aref bytes bytedecomp-ptr)
1372 optr bytedecomp-ptr
1373 ;; This uses dynamic-scope magic.
1374 offset (disassemble-offset bytes))
1375 (let ((opcode (aref byte-code-vector bytedecomp-op)))
1376 (assert opcode)
1377 (setq bytedecomp-op opcode))
1378 (cond ((memq bytedecomp-op byte-goto-ops)
1379 ;; It's a pc.
1380 (setq offset
1381 (cdr (or (assq offset tags)
1382 (let ((new (cons offset (byte-compile-make-tag))))
1383 (push new tags)
1384 new)))))
1385 ((cond ((eq bytedecomp-op 'byte-constant2)
1386 (setq bytedecomp-op 'byte-constant) t)
1387 ((memq bytedecomp-op byte-constref-ops)))
1388 (setq tmp (if (>= offset (length constvec))
1389 (list 'out-of-range offset)
1390 (aref constvec offset))
1391 offset (if (eq bytedecomp-op 'byte-constant)
1392 (byte-compile-get-constant tmp)
1393 (or (assq tmp byte-compile-variables)
1394 (let ((new (list tmp)))
1395 (push new byte-compile-variables)
1396 new)))))
1397 ((eq bytedecomp-op 'byte-stack-set2)
1398 (setq bytedecomp-op 'byte-stack-set))
1399 ((and (eq bytedecomp-op 'byte-discardN) (>= offset #x80))
1400 ;; The top bit of the operand for byte-discardN is a flag,
1401 ;; saying whether the top-of-stack is preserved. In
1402 ;; lapcode, we represent this by using a different opcode
1403 ;; (with the flag removed from the operand).
1404 (setq bytedecomp-op 'byte-discardN-preserve-tos)
1405 (setq offset (- offset #x80))))
1406 ;; lap = ( [ (pc . (op . arg)) ]* )
1407 (push (cons optr (cons bytedecomp-op (or offset 0)))
1408 lap)
1409 (setq bytedecomp-ptr (1+ bytedecomp-ptr)))
1410 (let ((rest lap))
1411 (while rest
1412 (cond ((numberp (car rest)))
1413 ((setq tmp (assq (car (car rest)) tags))
1414 ;; This addr is jumped to.
1415 (setcdr rest (cons (cons nil (cdr tmp))
1416 (cdr rest)))
1417 (setq tags (delq tmp tags))
1418 (setq rest (cdr rest))))
1419 (setq rest (cdr rest))))
1420 (if tags (error "optimizer error: missed tags %s" tags))
1421 ;; Remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1422 (mapcar (function (lambda (elt)
1423 (if (numberp elt)
1425 (cdr elt))))
1426 (nreverse lap))))
1429 ;;; peephole optimizer
1431 (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
1433 (defconst byte-conditional-ops
1434 '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
1435 byte-goto-if-not-nil-else-pop))
1437 (defconst byte-after-unbind-ops
1438 '(byte-constant byte-dup
1439 byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
1440 byte-eq byte-not
1441 byte-cons byte-list1 byte-list2 ; byte-list3 byte-list4
1442 byte-interactive-p)
1443 ;; How about other side-effect-free-ops? Is it safe to move an
1444 ;; error invocation (such as from nth) out of an unwind-protect?
1445 ;; No, it is not, because the unwind-protect forms can alter
1446 ;; the inside of the object to which nth would apply.
1447 ;; For the same reason, byte-equal was deleted from this list.
1448 "Byte-codes that can be moved past an unbind.")
1450 (defconst byte-compile-side-effect-and-error-free-ops
1451 '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
1452 byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
1453 byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
1454 byte-point-min byte-following-char byte-preceding-char
1455 byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
1456 byte-current-buffer byte-stack-ref))
1458 (defconst byte-compile-side-effect-free-ops
1459 (nconc
1460 '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
1461 byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
1462 byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
1463 byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
1464 byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
1465 byte-member byte-assq byte-quo byte-rem)
1466 byte-compile-side-effect-and-error-free-ops))
1468 ;; This crock is because of the way DEFVAR_BOOL variables work.
1469 ;; Consider the code
1471 ;; (defun foo (flag)
1472 ;; (let ((old-pop-ups pop-up-windows)
1473 ;; (pop-up-windows flag))
1474 ;; (cond ((not (eq pop-up-windows old-pop-ups))
1475 ;; (setq old-pop-ups pop-up-windows)
1476 ;; ...))))
1478 ;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
1479 ;; something else. But if we optimize
1481 ;; varref flag
1482 ;; varbind pop-up-windows
1483 ;; varref pop-up-windows
1484 ;; not
1485 ;; to
1486 ;; varref flag
1487 ;; dup
1488 ;; varbind pop-up-windows
1489 ;; not
1491 ;; we break the program, because it will appear that pop-up-windows and
1492 ;; old-pop-ups are not EQ when really they are. So we have to know what
1493 ;; the BOOL variables are, and not perform this optimization on them.
1495 ;; The variable `byte-boolean-vars' is now primitive and updated
1496 ;; automatically by DEFVAR_BOOL.
1498 (defun byte-optimize-lapcode (lap &optional _for-effect)
1499 "Simple peephole optimizer. LAP is both modified and returned.
1500 If FOR-EFFECT is non-nil, the return value is assumed to be of no importance."
1501 (let (lap0
1502 lap1
1503 lap2
1504 (keep-going 'first-time)
1505 (add-depth 0)
1506 rest tmp tmp2 tmp3
1507 (side-effect-free (if byte-compile-delete-errors
1508 byte-compile-side-effect-free-ops
1509 byte-compile-side-effect-and-error-free-ops)))
1510 (while keep-going
1511 (or (eq keep-going 'first-time)
1512 (byte-compile-log-lap " ---- next pass"))
1513 (setq rest lap
1514 keep-going nil)
1515 (while rest
1516 (setq lap0 (car rest)
1517 lap1 (nth 1 rest)
1518 lap2 (nth 2 rest))
1520 ;; You may notice that sequences like "dup varset discard" are
1521 ;; optimized but sequences like "dup varset TAG1: discard" are not.
1522 ;; You may be tempted to change this; resist that temptation.
1523 (cond ;;
1524 ;; <side-effect-free> pop --> <deleted>
1525 ;; ...including:
1526 ;; const-X pop --> <deleted>
1527 ;; varref-X pop --> <deleted>
1528 ;; dup pop --> <deleted>
1530 ((and (eq 'byte-discard (car lap1))
1531 (memq (car lap0) side-effect-free))
1532 (setq keep-going t)
1533 (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
1534 (setq rest (cdr rest))
1535 (cond ((= tmp 1)
1536 (byte-compile-log-lap
1537 " %s discard\t-->\t<deleted>" lap0)
1538 (setq lap (delq lap0 (delq lap1 lap))))
1539 ((= tmp 0)
1540 (byte-compile-log-lap
1541 " %s discard\t-->\t<deleted> discard" lap0)
1542 (setq lap (delq lap0 lap)))
1543 ((= tmp -1)
1544 (byte-compile-log-lap
1545 " %s discard\t-->\tdiscard discard" lap0)
1546 (setcar lap0 'byte-discard)
1547 (setcdr lap0 0))
1548 ((error "Optimizer error: too much on the stack"))))
1550 ;; goto*-X X: --> X:
1552 ((and (memq (car lap0) byte-goto-ops)
1553 (eq (cdr lap0) lap1))
1554 (cond ((eq (car lap0) 'byte-goto)
1555 (setq lap (delq lap0 lap))
1556 (setq tmp "<deleted>"))
1557 ((memq (car lap0) byte-goto-always-pop-ops)
1558 (setcar lap0 (setq tmp 'byte-discard))
1559 (setcdr lap0 0))
1560 ((error "Depth conflict at tag %d" (nth 2 lap0))))
1561 (and (memq byte-optimize-log '(t byte))
1562 (byte-compile-log " (goto %s) %s:\t-->\t%s %s:"
1563 (nth 1 lap1) (nth 1 lap1)
1564 tmp (nth 1 lap1)))
1565 (setq keep-going t))
1567 ;; varset-X varref-X --> dup varset-X
1568 ;; varbind-X varref-X --> dup varbind-X
1569 ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
1570 ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
1571 ;; The latter two can enable other optimizations.
1573 ;; For lexical variables, we could do the same
1574 ;; stack-set-X+1 stack-ref-X --> dup stack-set-X+2
1575 ;; but this is a very minor gain, since dup is stack-ref-0,
1576 ;; i.e. it's only better if X>5, and even then it comes
1577 ;; at the cost cost of an extra stack slot. Let's not bother.
1578 ((and (eq 'byte-varref (car lap2))
1579 (eq (cdr lap1) (cdr lap2))
1580 (memq (car lap1) '(byte-varset byte-varbind)))
1581 (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
1582 (not (eq (car lap0) 'byte-constant)))
1584 (setq keep-going t)
1585 (if (memq (car lap0) '(byte-constant byte-dup))
1586 (progn
1587 (setq tmp (if (or (not tmp)
1588 (byte-compile-const-symbol-p
1589 (car (cdr lap0))))
1590 (cdr lap0)
1591 (byte-compile-get-constant t)))
1592 (byte-compile-log-lap " %s %s %s\t-->\t%s %s %s"
1593 lap0 lap1 lap2 lap0 lap1
1594 (cons (car lap0) tmp))
1595 (setcar lap2 (car lap0))
1596 (setcdr lap2 tmp))
1597 (byte-compile-log-lap " %s %s\t-->\tdup %s" lap1 lap2 lap1)
1598 (setcar lap2 (car lap1))
1599 (setcar lap1 'byte-dup)
1600 (setcdr lap1 0)
1601 ;; The stack depth gets locally increased, so we will
1602 ;; increase maxdepth in case depth = maxdepth here.
1603 ;; This can cause the third argument to byte-code to
1604 ;; be larger than necessary.
1605 (setq add-depth 1))))
1607 ;; dup varset-X discard --> varset-X
1608 ;; dup varbind-X discard --> varbind-X
1609 ;; dup stack-set-X discard --> stack-set-X-1
1610 ;; (the varbind variant can emerge from other optimizations)
1612 ((and (eq 'byte-dup (car lap0))
1613 (eq 'byte-discard (car lap2))
1614 (memq (car lap1) '(byte-varset byte-varbind
1615 byte-stack-set)))
1616 (byte-compile-log-lap " dup %s discard\t-->\t%s" lap1 lap1)
1617 (setq keep-going t
1618 rest (cdr rest))
1619 (if (eq 'byte-stack-set (car lap1)) (decf (cdr lap1)))
1620 (setq lap (delq lap0 (delq lap2 lap))))
1622 ;; not goto-X-if-nil --> goto-X-if-non-nil
1623 ;; not goto-X-if-non-nil --> goto-X-if-nil
1625 ;; it is wrong to do the same thing for the -else-pop variants.
1627 ((and (eq 'byte-not (car lap0))
1628 (memq (car lap1) '(byte-goto-if-nil byte-goto-if-not-nil)))
1629 (byte-compile-log-lap " not %s\t-->\t%s"
1630 lap1
1631 (cons
1632 (if (eq (car lap1) 'byte-goto-if-nil)
1633 'byte-goto-if-not-nil
1634 'byte-goto-if-nil)
1635 (cdr lap1)))
1636 (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
1637 'byte-goto-if-not-nil
1638 'byte-goto-if-nil))
1639 (setq lap (delq lap0 lap))
1640 (setq keep-going t))
1642 ;; goto-X-if-nil goto-Y X: --> goto-Y-if-non-nil X:
1643 ;; goto-X-if-non-nil goto-Y X: --> goto-Y-if-nil X:
1645 ;; it is wrong to do the same thing for the -else-pop variants.
1647 ((and (memq (car lap0)
1648 '(byte-goto-if-nil byte-goto-if-not-nil)) ; gotoX
1649 (eq 'byte-goto (car lap1)) ; gotoY
1650 (eq (cdr lap0) lap2)) ; TAG X
1651 (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
1652 'byte-goto-if-not-nil 'byte-goto-if-nil)))
1653 (byte-compile-log-lap " %s %s %s:\t-->\t%s %s:"
1654 lap0 lap1 lap2
1655 (cons inverse (cdr lap1)) lap2)
1656 (setq lap (delq lap0 lap))
1657 (setcar lap1 inverse)
1658 (setq keep-going t)))
1660 ;; const goto-if-* --> whatever
1662 ((and (eq 'byte-constant (car lap0))
1663 (memq (car lap1) byte-conditional-ops)
1664 ;; If the `byte-constant's cdr is not a cons cell, it has
1665 ;; to be an index into the constant pool); even though
1666 ;; it'll be a constant, that constant is not known yet
1667 ;; (it's typically a free variable of a closure, so will
1668 ;; only be known when the closure will be built at
1669 ;; run-time).
1670 (consp (cdr lap0)))
1671 (cond ((if (memq (car lap1) '(byte-goto-if-nil
1672 byte-goto-if-nil-else-pop))
1673 (car (cdr lap0))
1674 (not (car (cdr lap0))))
1675 (byte-compile-log-lap " %s %s\t-->\t<deleted>"
1676 lap0 lap1)
1677 (setq rest (cdr rest)
1678 lap (delq lap0 (delq lap1 lap))))
1680 (byte-compile-log-lap " %s %s\t-->\t%s"
1681 lap0 lap1
1682 (cons 'byte-goto (cdr lap1)))
1683 (when (memq (car lap1) byte-goto-always-pop-ops)
1684 (setq lap (delq lap0 lap)))
1685 (setcar lap1 'byte-goto)))
1686 (setq keep-going t))
1688 ;; varref-X varref-X --> varref-X dup
1689 ;; varref-X [dup ...] varref-X --> varref-X [dup ...] dup
1690 ;; stackref-X [dup ...] stackref-X+N --> stackref-X [dup ...] dup
1691 ;; We don't optimize the const-X variations on this here,
1692 ;; because that would inhibit some goto optimizations; we
1693 ;; optimize the const-X case after all other optimizations.
1695 ((and (memq (car lap0) '(byte-varref byte-stack-ref))
1696 (progn
1697 (setq tmp (cdr rest))
1698 (setq tmp2 0)
1699 (while (eq (car (car tmp)) 'byte-dup)
1700 (setq tmp2 (1+ tmp2))
1701 (setq tmp (cdr tmp)))
1703 (eq (if (eq 'byte-stack-ref (car lap0))
1704 (+ tmp2 1 (cdr lap0))
1705 (cdr lap0))
1706 (cdr (car tmp)))
1707 (eq (car lap0) (car (car tmp))))
1708 (if (memq byte-optimize-log '(t byte))
1709 (let ((str ""))
1710 (setq tmp2 (cdr rest))
1711 (while (not (eq tmp tmp2))
1712 (setq tmp2 (cdr tmp2)
1713 str (concat str " dup")))
1714 (byte-compile-log-lap " %s%s %s\t-->\t%s%s dup"
1715 lap0 str lap0 lap0 str)))
1716 (setq keep-going t)
1717 (setcar (car tmp) 'byte-dup)
1718 (setcdr (car tmp) 0)
1719 (setq rest tmp))
1721 ;; TAG1: TAG2: --> TAG1: <deleted>
1722 ;; (and other references to TAG2 are replaced with TAG1)
1724 ((and (eq (car lap0) 'TAG)
1725 (eq (car lap1) 'TAG))
1726 (and (memq byte-optimize-log '(t byte))
1727 (byte-compile-log " adjacent tags %d and %d merged"
1728 (nth 1 lap1) (nth 1 lap0)))
1729 (setq tmp3 lap)
1730 (while (setq tmp2 (rassq lap0 tmp3))
1731 (setcdr tmp2 lap1)
1732 (setq tmp3 (cdr (memq tmp2 tmp3))))
1733 (setq lap (delq lap0 lap)
1734 keep-going t))
1736 ;; unused-TAG: --> <deleted>
1738 ((and (eq 'TAG (car lap0))
1739 (not (rassq lap0 lap)))
1740 (and (memq byte-optimize-log '(t byte))
1741 (byte-compile-log " unused tag %d removed" (nth 1 lap0)))
1742 (setq lap (delq lap0 lap)
1743 keep-going t))
1745 ;; goto ... --> goto <delete until TAG or end>
1746 ;; return ... --> return <delete until TAG or end>
1748 ((and (memq (car lap0) '(byte-goto byte-return))
1749 (not (memq (car lap1) '(TAG nil))))
1750 (setq tmp rest)
1751 (let ((i 0)
1752 (opt-p (memq byte-optimize-log '(t lap)))
1753 str deleted)
1754 (while (and (setq tmp (cdr tmp))
1755 (not (eq 'TAG (car (car tmp)))))
1756 (if opt-p (setq deleted (cons (car tmp) deleted)
1757 str (concat str " %s")
1758 i (1+ i))))
1759 (if opt-p
1760 (let ((tagstr
1761 (if (eq 'TAG (car (car tmp)))
1762 (format "%d:" (car (cdr (car tmp))))
1763 (or (car tmp) ""))))
1764 (if (< i 6)
1765 (apply 'byte-compile-log-lap-1
1766 (concat " %s" str
1767 " %s\t-->\t%s <deleted> %s")
1768 lap0
1769 (nconc (nreverse deleted)
1770 (list tagstr lap0 tagstr)))
1771 (byte-compile-log-lap
1772 " %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
1773 lap0 i (if (= i 1) "" "s")
1774 tagstr lap0 tagstr))))
1775 (rplacd rest tmp))
1776 (setq keep-going t))
1778 ;; <safe-op> unbind --> unbind <safe-op>
1779 ;; (this may enable other optimizations.)
1781 ((and (eq 'byte-unbind (car lap1))
1782 (memq (car lap0) byte-after-unbind-ops))
1783 (byte-compile-log-lap " %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
1784 (setcar rest lap1)
1785 (setcar (cdr rest) lap0)
1786 (setq keep-going t))
1788 ;; varbind-X unbind-N --> discard unbind-(N-1)
1789 ;; save-excursion unbind-N --> unbind-(N-1)
1790 ;; save-restriction unbind-N --> unbind-(N-1)
1792 ((and (eq 'byte-unbind (car lap1))
1793 (memq (car lap0) '(byte-varbind byte-save-excursion
1794 byte-save-restriction))
1795 (< 0 (cdr lap1)))
1796 (if (zerop (setcdr lap1 (1- (cdr lap1))))
1797 (delq lap1 rest))
1798 (if (eq (car lap0) 'byte-varbind)
1799 (setcar rest (cons 'byte-discard 0))
1800 (setq lap (delq lap0 lap)))
1801 (byte-compile-log-lap " %s %s\t-->\t%s %s"
1802 lap0 (cons (car lap1) (1+ (cdr lap1)))
1803 (if (eq (car lap0) 'byte-varbind)
1804 (car rest)
1805 (car (cdr rest)))
1806 (if (and (/= 0 (cdr lap1))
1807 (eq (car lap0) 'byte-varbind))
1808 (car (cdr rest))
1809 ""))
1810 (setq keep-going t))
1812 ;; goto*-X ... X: goto-Y --> goto*-Y
1813 ;; goto-X ... X: return --> return
1815 ((and (memq (car lap0) byte-goto-ops)
1816 (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
1817 '(byte-goto byte-return)))
1818 (cond ((and (not (eq tmp lap0))
1819 (or (eq (car lap0) 'byte-goto)
1820 (eq (car tmp) 'byte-goto)))
1821 (byte-compile-log-lap " %s [%s]\t-->\t%s"
1822 (car lap0) tmp tmp)
1823 (if (eq (car tmp) 'byte-return)
1824 (setcar lap0 'byte-return))
1825 (setcdr lap0 (cdr tmp))
1826 (setq keep-going t))))
1828 ;; goto-*-else-pop X ... X: goto-if-* --> whatever
1829 ;; goto-*-else-pop X ... X: discard --> whatever
1831 ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
1832 byte-goto-if-not-nil-else-pop))
1833 (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
1834 (eval-when-compile
1835 (cons 'byte-discard byte-conditional-ops)))
1836 (not (eq lap0 (car tmp))))
1837 (setq tmp2 (car tmp))
1838 (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
1839 byte-goto-if-nil)
1840 (byte-goto-if-not-nil-else-pop
1841 byte-goto-if-not-nil))))
1842 (if (memq (car tmp2) tmp3)
1843 (progn (setcar lap0 (car tmp2))
1844 (setcdr lap0 (cdr tmp2))
1845 (byte-compile-log-lap " %s-else-pop [%s]\t-->\t%s"
1846 (car lap0) tmp2 lap0))
1847 ;; Get rid of the -else-pop's and jump one step further.
1848 (or (eq 'TAG (car (nth 1 tmp)))
1849 (setcdr tmp (cons (byte-compile-make-tag)
1850 (cdr tmp))))
1851 (byte-compile-log-lap " %s [%s]\t-->\t%s <skip>"
1852 (car lap0) tmp2 (nth 1 tmp3))
1853 (setcar lap0 (nth 1 tmp3))
1854 (setcdr lap0 (nth 1 tmp)))
1855 (setq keep-going t))
1857 ;; const goto-X ... X: goto-if-* --> whatever
1858 ;; const goto-X ... X: discard --> whatever
1860 ((and (eq (car lap0) 'byte-constant)
1861 (eq (car lap1) 'byte-goto)
1862 (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
1863 (eval-when-compile
1864 (cons 'byte-discard byte-conditional-ops)))
1865 (not (eq lap1 (car tmp))))
1866 (setq tmp2 (car tmp))
1867 (cond ((when (consp (cdr lap0))
1868 (memq (car tmp2)
1869 (if (null (car (cdr lap0)))
1870 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
1871 '(byte-goto-if-not-nil
1872 byte-goto-if-not-nil-else-pop))))
1873 (byte-compile-log-lap " %s goto [%s]\t-->\t%s %s"
1874 lap0 tmp2 lap0 tmp2)
1875 (setcar lap1 (car tmp2))
1876 (setcdr lap1 (cdr tmp2))
1877 ;; Let next step fix the (const,goto-if*) sequence.
1878 (setq rest (cons nil rest))
1879 (setq keep-going t))
1880 ((or (consp (cdr lap0))
1881 (eq (car tmp2) 'byte-discard))
1882 ;; Jump one step further
1883 (byte-compile-log-lap
1884 " %s goto [%s]\t-->\t<deleted> goto <skip>"
1885 lap0 tmp2)
1886 (or (eq 'TAG (car (nth 1 tmp)))
1887 (setcdr tmp (cons (byte-compile-make-tag)
1888 (cdr tmp))))
1889 (setcdr lap1 (car (cdr tmp)))
1890 (setq lap (delq lap0 lap))
1891 (setq keep-going t))))
1893 ;; X: varref-Y ... varset-Y goto-X -->
1894 ;; X: varref-Y Z: ... dup varset-Y goto-Z
1895 ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
1896 ;; (This is so usual for while loops that it is worth handling).
1898 ;; Here again, we could do it for stack-ref/stack-set, but
1899 ;; that's replacing a stack-ref-Y with a stack-ref-0, which
1900 ;; is a very minor improvement (if any), at the cost of
1901 ;; more stack use and more byte-code. Let's not do it.
1903 ((and (eq (car lap1) 'byte-varset)
1904 (eq (car lap2) 'byte-goto)
1905 (not (memq (cdr lap2) rest)) ;Backwards jump
1906 (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
1907 'byte-varref)
1908 (eq (cdr (car tmp)) (cdr lap1))
1909 (not (memq (car (cdr lap1)) byte-boolean-vars)))
1910 ;;(byte-compile-log-lap " Pulled %s to end of loop" (car tmp))
1911 (let ((newtag (byte-compile-make-tag)))
1912 (byte-compile-log-lap
1913 " %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
1914 (nth 1 (cdr lap2)) (car tmp)
1915 lap1 lap2
1916 (nth 1 (cdr lap2)) (car tmp)
1917 (nth 1 newtag) 'byte-dup lap1
1918 (cons 'byte-goto newtag)
1920 (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
1921 (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
1922 (setq add-depth 1)
1923 (setq keep-going t))
1925 ;; goto-X Y: ... X: goto-if*-Y --> goto-if-not-*-X+1 Y:
1926 ;; (This can pull the loop test to the end of the loop)
1928 ((and (eq (car lap0) 'byte-goto)
1929 (eq (car lap1) 'TAG)
1930 (eq lap1
1931 (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
1932 (memq (car (car tmp))
1933 '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
1934 byte-goto-if-nil-else-pop)))
1935 ;; (byte-compile-log-lap " %s %s, %s %s --> moved conditional"
1936 ;; lap0 lap1 (cdr lap0) (car tmp))
1937 (let ((newtag (byte-compile-make-tag)))
1938 (byte-compile-log-lap
1939 "%s %s: ... %s: %s\t-->\t%s ... %s:"
1940 lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
1941 (cons (cdr (assq (car (car tmp))
1942 '((byte-goto-if-nil . byte-goto-if-not-nil)
1943 (byte-goto-if-not-nil . byte-goto-if-nil)
1944 (byte-goto-if-nil-else-pop .
1945 byte-goto-if-not-nil-else-pop)
1946 (byte-goto-if-not-nil-else-pop .
1947 byte-goto-if-nil-else-pop))))
1948 newtag)
1950 (nth 1 newtag)
1952 (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
1953 (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
1954 ;; We can handle this case but not the -if-not-nil case,
1955 ;; because we won't know which non-nil constant to push.
1956 (setcdr rest (cons (cons 'byte-constant
1957 (byte-compile-get-constant nil))
1958 (cdr rest))))
1959 (setcar lap0 (nth 1 (memq (car (car tmp))
1960 '(byte-goto-if-nil-else-pop
1961 byte-goto-if-not-nil
1962 byte-goto-if-nil
1963 byte-goto-if-not-nil
1964 byte-goto byte-goto))))
1966 (setq keep-going t))
1968 (setq rest (cdr rest)))
1970 ;; Cleanup stage:
1971 ;; Rebuild byte-compile-constants / byte-compile-variables.
1972 ;; Simple optimizations that would inhibit other optimizations if they
1973 ;; were done in the optimizing loop, and optimizations which there is no
1974 ;; need to do more than once.
1975 (setq byte-compile-constants nil
1976 byte-compile-variables nil)
1977 (setq rest lap)
1978 (byte-compile-log-lap " ---- final pass")
1979 (while rest
1980 (setq lap0 (car rest)
1981 lap1 (nth 1 rest))
1982 (if (memq (car lap0) byte-constref-ops)
1983 (if (memq (car lap0) '(byte-constant byte-constant2))
1984 (unless (memq (cdr lap0) byte-compile-constants)
1985 (setq byte-compile-constants (cons (cdr lap0)
1986 byte-compile-constants)))
1987 (unless (memq (cdr lap0) byte-compile-variables)
1988 (setq byte-compile-variables (cons (cdr lap0)
1989 byte-compile-variables)))))
1990 (cond (;;
1991 ;; const-C varset-X const-C --> const-C dup varset-X
1992 ;; const-C varbind-X const-C --> const-C dup varbind-X
1994 (and (eq (car lap0) 'byte-constant)
1995 (eq (car (nth 2 rest)) 'byte-constant)
1996 (eq (cdr lap0) (cdr (nth 2 rest)))
1997 (memq (car lap1) '(byte-varbind byte-varset)))
1998 (byte-compile-log-lap " %s %s %s\t-->\t%s dup %s"
1999 lap0 lap1 lap0 lap0 lap1)
2000 (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
2001 (setcar (cdr rest) (cons 'byte-dup 0))
2002 (setq add-depth 1))
2004 ;; const-X [dup/const-X ...] --> const-X [dup ...] dup
2005 ;; varref-X [dup/varref-X ...] --> varref-X [dup ...] dup
2007 ((memq (car lap0) '(byte-constant byte-varref))
2008 (setq tmp rest
2009 tmp2 nil)
2010 (while (progn
2011 (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
2012 (and (eq (cdr lap0) (cdr (car tmp)))
2013 (eq (car lap0) (car (car tmp)))))
2014 (setcar tmp (cons 'byte-dup 0))
2015 (setq tmp2 t))
2016 (if tmp2
2017 (byte-compile-log-lap
2018 " %s [dup/%s]...\t-->\t%s dup..." lap0 lap0 lap0)))
2020 ;; unbind-N unbind-M --> unbind-(N+M)
2022 ((and (eq 'byte-unbind (car lap0))
2023 (eq 'byte-unbind (car lap1)))
2024 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
2025 (cons 'byte-unbind
2026 (+ (cdr lap0) (cdr lap1))))
2027 (setq lap (delq lap0 lap))
2028 (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
2031 ;; stack-set-M [discard/discardN ...] --> discardN-preserve-tos
2032 ;; stack-set-M [discard/discardN ...] --> discardN
2034 ((and (eq (car lap0) 'byte-stack-set)
2035 (memq (car lap1) '(byte-discard byte-discardN))
2036 (progn
2037 ;; See if enough discard operations follow to expose or
2038 ;; destroy the value stored by the stack-set.
2039 (setq tmp (cdr rest))
2040 (setq tmp2 (1- (cdr lap0)))
2041 (setq tmp3 0)
2042 (while (memq (car (car tmp)) '(byte-discard byte-discardN))
2043 (setq tmp3
2044 (+ tmp3 (if (eq (car (car tmp)) 'byte-discard)
2046 (cdr (car tmp)))))
2047 (setq tmp (cdr tmp)))
2048 (>= tmp3 tmp2)))
2049 ;; Do the optimization.
2050 (setq lap (delq lap0 lap))
2051 (setcar lap1
2052 (if (= tmp2 tmp3)
2053 ;; The value stored is the new TOS, so pop one more
2054 ;; value (to get rid of the old value) using the
2055 ;; TOS-preserving discard operator.
2056 'byte-discardN-preserve-tos
2057 ;; Otherwise, the value stored is lost, so just use a
2058 ;; normal discard.
2059 'byte-discardN))
2060 (setcdr lap1 (1+ tmp3))
2061 (setcdr (cdr rest) tmp)
2062 (byte-compile-log-lap " %s [discard/discardN]...\t-->\t%s"
2063 lap0 lap1))
2066 ;; discard/discardN/discardN-preserve-tos-X discard/discardN-Y -->
2067 ;; discardN-(X+Y)
2069 ((and (memq (car lap0)
2070 '(byte-discard byte-discardN
2071 byte-discardN-preserve-tos))
2072 (memq (car lap1) '(byte-discard byte-discardN)))
2073 (setq lap (delq lap0 lap))
2074 (byte-compile-log-lap
2075 " %s %s\t-->\t(discardN %s)"
2076 lap0 lap1
2077 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2078 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2079 (setcdr lap1 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2080 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2081 (setcar lap1 'byte-discardN))
2084 ;; discardN-preserve-tos-X discardN-preserve-tos-Y -->
2085 ;; discardN-preserve-tos-(X+Y)
2087 ((and (eq (car lap0) 'byte-discardN-preserve-tos)
2088 (eq (car lap1) 'byte-discardN-preserve-tos))
2089 (setq lap (delq lap0 lap))
2090 (setcdr lap1 (+ (cdr lap0) (cdr lap1)))
2091 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 (car rest)))
2094 ;; discardN-preserve-tos return --> return
2095 ;; dup return --> return
2096 ;; stack-set-N return --> return ; where N is TOS-1
2098 ((and (eq (car lap1) 'byte-return)
2099 (or (memq (car lap0) '(byte-discardN-preserve-tos byte-dup))
2100 (and (eq (car lap0) 'byte-stack-set)
2101 (= (cdr lap0) 1))))
2102 ;; The byte-code interpreter will pop the stack for us, so
2103 ;; we can just leave stuff on it.
2104 (setq lap (delq lap0 lap))
2105 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 lap1))
2107 (setq rest (cdr rest)))
2108 (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
2109 lap)
2111 (provide 'byte-opt)
2114 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
2115 ;; itself, compile some of its most used recursive functions (at load time).
2117 (eval-when-compile
2118 (or (byte-code-function-p (symbol-function 'byte-optimize-form))
2119 (assq 'byte-code (symbol-function 'byte-optimize-form))
2120 (let ((byte-optimize nil)
2121 (byte-compile-warnings nil))
2122 (mapc (lambda (x)
2123 (or noninteractive (message "compiling %s..." x))
2124 (byte-compile x)
2125 (or noninteractive (message "compiling %s...done" x)))
2126 '(byte-optimize-form
2127 byte-optimize-body
2128 byte-optimize-predicate
2129 byte-optimize-binary-predicate
2130 ;; Inserted some more than necessary, to speed it up.
2131 byte-optimize-form-code-walker
2132 byte-optimize-lapcode))))
2133 nil)
2135 ;;; byte-opt.el ends here