Merge from emacs-24; up to 2012-05-08T14:11:47Z!monnier@iro.umontreal.ca
[emacs.git] / lisp / emacs-lisp / byte-opt.el
bloba4c3e8aac4e2d5ea629146606a243aa2cd0f1148
1 ;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler -*- lexical-binding: t -*-
3 ;; Copyright (C) 1991, 1994, 2000-2012 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 defvared
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-lib))
187 (require 'macroexp)
189 (defun byte-compile-log-lap-1 (format &rest args)
190 ;; Newer byte codes for stack-ref make the slot 0 non-nil again.
191 ;; But the "old disassembler" is *really* ancient by now.
192 ;; (if (aref byte-code-vector 0)
193 ;; (error "The old version of the disassembler is loaded. Reload new-bytecomp as well"))
194 (byte-compile-log-1
195 (apply 'format format
196 (let (c a)
197 (mapcar (lambda (arg)
198 (if (not (consp arg))
199 (if (and (symbolp arg)
200 (string-match "^byte-" (symbol-name arg)))
201 (intern (substring (symbol-name arg) 5))
202 arg)
203 (if (integerp (setq c (car arg)))
204 (error "non-symbolic byte-op %s" c))
205 (if (eq c 'TAG)
206 (setq c arg)
207 (setq a (cond ((memq c byte-goto-ops)
208 (car (cdr (cdr arg))))
209 ((memq c byte-constref-ops)
210 (car (cdr arg)))
211 (t (cdr arg))))
212 (setq c (symbol-name c))
213 (if (string-match "^byte-." c)
214 (setq c (intern (substring c 5)))))
215 (if (eq c 'constant) (setq c 'const))
216 (if (and (eq (cdr arg) 0)
217 (not (memq c '(unbind call const))))
219 (format "(%s %s)" c a))))
220 args)))))
222 (defmacro byte-compile-log-lap (format-string &rest args)
223 `(and (memq byte-optimize-log '(t byte))
224 (byte-compile-log-lap-1 ,format-string ,@args)))
227 ;;; byte-compile optimizers to support inlining
229 (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
231 (defun byte-optimize-inline-handler (form)
232 "byte-optimize-handler for the `inline' special-form."
233 (cons 'progn
234 (mapcar
235 (lambda (sexp)
236 (let ((f (car-safe sexp)))
237 (if (and (symbolp f)
238 (or (cdr (assq f byte-compile-function-environment))
239 (not (or (not (fboundp f))
240 (cdr (assq f byte-compile-macro-environment))
241 (and (consp (setq f (symbol-function f)))
242 (eq (car f) 'macro))
243 (subrp f)))))
244 (byte-compile-inline-expand sexp)
245 sexp)))
246 (cdr form))))
248 (defun byte-compile-inline-expand (form)
249 (let* ((name (car form))
250 (localfn (cdr (assq name byte-compile-function-environment)))
251 (fn (or localfn (and (fboundp name) (symbol-function name)))))
252 (when (autoloadp fn)
253 (autoload-do-load fn)
254 (setq fn (or (and (fboundp name) (symbol-function name))
255 (cdr (assq name byte-compile-function-environment)))))
256 (pcase fn
257 (`nil
258 (byte-compile-warn "attempt to inline `%s' before it was defined"
259 name)
260 form)
261 (`(autoload . ,_)
262 (error "File `%s' didn't define `%s'" (nth 1 fn) name))
263 ((and (pred symbolp) (guard (not (eq fn t)))) ;A function alias.
264 (byte-compile-inline-expand (cons fn (cdr form))))
265 ((pred byte-code-function-p)
266 ;; (message "Inlining byte-code for %S!" name)
267 ;; The byte-code will be really inlined in byte-compile-unfold-bcf.
268 `(,fn ,@(cdr form)))
269 ((or `(lambda . ,_) `(closure . ,_))
270 (if (not (or (eq fn localfn) ;From the same file => same mode.
271 (eq (car fn) ;Same mode.
272 (if lexical-binding 'closure 'lambda))))
273 ;; While byte-compile-unfold-bcf can inline dynbind byte-code into
274 ;; letbind byte-code (or any other combination for that matter), we
275 ;; can only inline dynbind source into dynbind source or letbind
276 ;; source into letbind source.
277 (progn
278 ;; We can of course byte-compile the inlined function
279 ;; first, and then inline its byte-code.
280 (byte-compile name)
281 `(,(symbol-function name) ,@(cdr form)))
282 (let ((newfn (if (eq fn localfn)
283 ;; If `fn' is from the same file, it has already
284 ;; been preprocessed!
285 `(function ,fn)
286 (byte-compile-preprocess
287 (byte-compile--reify-function fn)))))
288 (if (eq (car-safe newfn) 'function)
289 (byte-compile-unfold-lambda `(,(cadr newfn) ,@(cdr form)))
290 (byte-compile-log-warning
291 (format "Inlining closure %S failed" name))
292 form))))
294 (t ;; Give up on inlining.
295 form))))
297 ;; ((lambda ...) ...)
298 (defun byte-compile-unfold-lambda (form &optional name)
299 ;; In lexical-binding mode, let and functions don't bind vars in the same way
300 ;; (let obey special-variable-p, but functions don't). But luckily, this
301 ;; doesn't matter here, because function's behavior is underspecified so it
302 ;; can safely be turned into a `let', even though the reverse is not true.
303 (or name (setq name "anonymous lambda"))
304 (let ((lambda (car form))
305 (values (cdr form)))
306 (let ((arglist (nth 1 lambda))
307 (body (cdr (cdr lambda)))
308 optionalp restp
309 bindings)
310 (if (and (stringp (car body)) (cdr body))
311 (setq body (cdr body)))
312 (if (and (consp (car body)) (eq 'interactive (car (car body))))
313 (setq body (cdr body)))
314 ;; FIXME: The checks below do not belong in an optimization phase.
315 (while arglist
316 (cond ((eq (car arglist) '&optional)
317 ;; ok, I'll let this slide because funcall_lambda() does...
318 ;; (if optionalp (error "multiple &optional keywords in %s" name))
319 (if restp (error "&optional found after &rest in %s" name))
320 (if (null (cdr arglist))
321 (error "nothing after &optional in %s" name))
322 (setq optionalp t))
323 ((eq (car arglist) '&rest)
324 ;; ...but it is by no stretch of the imagination a reasonable
325 ;; thing that funcall_lambda() allows (&rest x y) and
326 ;; (&rest x &optional y) in arglists.
327 (if (null (cdr arglist))
328 (error "nothing after &rest in %s" name))
329 (if (cdr (cdr arglist))
330 (error "multiple vars after &rest in %s" name))
331 (setq restp t))
332 (restp
333 (setq bindings (cons (list (car arglist)
334 (and values (cons 'list values)))
335 bindings)
336 values nil))
337 ((and (not optionalp) (null values))
338 (byte-compile-warn "attempt to open-code `%s' with too few arguments" name)
339 (setq arglist nil values 'too-few))
341 (setq bindings (cons (list (car arglist) (car values))
342 bindings)
343 values (cdr values))))
344 (setq arglist (cdr arglist)))
345 (if values
346 (progn
347 (or (eq values 'too-few)
348 (byte-compile-warn
349 "attempt to open-code `%s' with too many arguments" name))
350 form)
352 ;; The following leads to infinite recursion when loading a
353 ;; file containing `(defsubst f () (f))', and then trying to
354 ;; byte-compile that file.
355 ;(setq body (mapcar 'byte-optimize-form body)))
357 (let ((newform
358 (if bindings
359 (cons 'let (cons (nreverse bindings) body))
360 (cons 'progn body))))
361 (byte-compile-log " %s\t==>\t%s" form newform)
362 newform)))))
365 ;;; implementing source-level optimizers
367 (defun byte-optimize-form-code-walker (form for-effect)
369 ;; For normal function calls, We can just mapcar the optimizer the cdr. But
370 ;; we need to have special knowledge of the syntax of the special forms
371 ;; like let and defun (that's why they're special forms :-). (Actually,
372 ;; the important aspect is that they are subrs that don't evaluate all of
373 ;; their args.)
375 (let ((fn (car-safe form))
376 tmp)
377 (cond ((not (consp form))
378 (if (not (and for-effect
379 (or byte-compile-delete-errors
380 (not (symbolp form))
381 (eq form t))))
382 form))
383 ((eq fn 'quote)
384 (if (cdr (cdr form))
385 (byte-compile-warn "malformed quote form: `%s'"
386 (prin1-to-string form)))
387 ;; map (quote nil) to nil to simplify optimizer logic.
388 ;; map quoted constants to nil if for-effect (just because).
389 (and (nth 1 form)
390 (not for-effect)
391 form))
392 ((eq 'lambda (car-safe fn))
393 (let ((newform (byte-compile-unfold-lambda form)))
394 (if (eq newform form)
395 ;; Some error occurred, avoid infinite recursion
396 form
397 (byte-optimize-form-code-walker newform for-effect))))
398 ((memq fn '(let let*))
399 ;; recursively enter the optimizer for the bindings and body
400 ;; of a let or let*. This for depth-firstness: forms that
401 ;; are more deeply nested are optimized first.
402 (cons fn
403 (cons
404 (mapcar (lambda (binding)
405 (if (symbolp binding)
406 binding
407 (if (cdr (cdr binding))
408 (byte-compile-warn "malformed let binding: `%s'"
409 (prin1-to-string binding)))
410 (list (car binding)
411 (byte-optimize-form (nth 1 binding) nil))))
412 (nth 1 form))
413 (byte-optimize-body (cdr (cdr form)) for-effect))))
414 ((eq fn 'cond)
415 (cons fn
416 (mapcar (lambda (clause)
417 (if (consp clause)
418 (cons
419 (byte-optimize-form (car clause) nil)
420 (byte-optimize-body (cdr clause) for-effect))
421 (byte-compile-warn "malformed cond form: `%s'"
422 (prin1-to-string clause))
423 clause))
424 (cdr form))))
425 ((eq fn 'progn)
426 ;; As an extra added bonus, this simplifies (progn <x>) --> <x>.
427 (if (cdr (cdr form))
428 (macroexp-progn (byte-optimize-body (cdr form) for-effect))
429 (byte-optimize-form (nth 1 form) for-effect)))
430 ((eq fn 'prog1)
431 (if (cdr (cdr form))
432 (cons 'prog1
433 (cons (byte-optimize-form (nth 1 form) for-effect)
434 (byte-optimize-body (cdr (cdr form)) t)))
435 (byte-optimize-form (nth 1 form) for-effect)))
436 ((eq fn 'prog2)
437 (cons 'prog2
438 (cons (byte-optimize-form (nth 1 form) t)
439 (cons (byte-optimize-form (nth 2 form) for-effect)
440 (byte-optimize-body (cdr (cdr (cdr form))) t)))))
442 ((memq fn '(save-excursion save-restriction save-current-buffer))
443 ;; those subrs which have an implicit progn; it's not quite good
444 ;; enough to treat these like normal function calls.
445 ;; This can turn (save-excursion ...) into (save-excursion) which
446 ;; will be optimized away in the lap-optimize pass.
447 (cons fn (byte-optimize-body (cdr form) for-effect)))
449 ((eq fn 'with-output-to-temp-buffer)
450 ;; this is just like the above, except for the first argument.
451 (cons fn
452 (cons
453 (byte-optimize-form (nth 1 form) nil)
454 (byte-optimize-body (cdr (cdr form)) for-effect))))
456 ((eq fn 'if)
457 (when (< (length form) 3)
458 (byte-compile-warn "too few arguments for `if'"))
459 (cons fn
460 (cons (byte-optimize-form (nth 1 form) nil)
461 (cons
462 (byte-optimize-form (nth 2 form) for-effect)
463 (byte-optimize-body (nthcdr 3 form) for-effect)))))
465 ((memq fn '(and or)) ; Remember, and/or are control structures.
466 ;; Take forms off the back until we can't any more.
467 ;; In the future it could conceivably be a problem that the
468 ;; subexpressions of these forms are optimized in the reverse
469 ;; order, but it's ok for now.
470 (if for-effect
471 (let ((backwards (reverse (cdr form))))
472 (while (and backwards
473 (null (setcar backwards
474 (byte-optimize-form (car backwards)
475 for-effect))))
476 (setq backwards (cdr backwards)))
477 (if (and (cdr form) (null backwards))
478 (byte-compile-log
479 " all subforms of %s called for effect; deleted" form))
480 (and backwards
481 (cons fn (nreverse (mapcar 'byte-optimize-form
482 backwards)))))
483 (cons fn (mapcar 'byte-optimize-form (cdr form)))))
485 ((eq fn 'interactive)
486 (byte-compile-warn "misplaced interactive spec: `%s'"
487 (prin1-to-string form))
488 nil)
490 ((memq fn '(function condition-case))
491 ;; These forms are compiled as constants or by breaking out
492 ;; all the subexpressions and compiling them separately.
493 form)
495 ((eq fn 'unwind-protect)
496 ;; the "protected" part of an unwind-protect is compiled (and thus
497 ;; optimized) as a top-level form, so don't do it here. But the
498 ;; non-protected part has the same for-effect status as the
499 ;; unwind-protect itself. (The protected part is always for effect,
500 ;; but that isn't handled properly yet.)
501 (cons fn
502 (cons (byte-optimize-form (nth 1 form) for-effect)
503 (cdr (cdr form)))))
505 ((eq fn 'catch)
506 ;; the body of a catch is compiled (and thus optimized) as a
507 ;; top-level form, so don't do it here. The tag is never
508 ;; for-effect. The body should have the same for-effect status
509 ;; as the catch form itself, but that isn't handled properly yet.
510 (cons fn
511 (cons (byte-optimize-form (nth 1 form) nil)
512 (cdr (cdr form)))))
514 ((eq fn 'ignore)
515 ;; Don't treat the args to `ignore' as being
516 ;; computed for effect. We want to avoid the warnings
517 ;; that might occur if they were treated that way.
518 ;; However, don't actually bother calling `ignore'.
519 `(prog1 nil . ,(mapcar 'byte-optimize-form (cdr form))))
521 ;; Needed as long as we run byte-optimize-form after cconv.
522 ((eq fn 'internal-make-closure) form)
524 ((byte-code-function-p fn)
525 (cons fn (mapcar #'byte-optimize-form (cdr form))))
527 ((not (symbolp fn))
528 (byte-compile-warn "`%s' is a malformed function"
529 (prin1-to-string fn))
530 form)
532 ((and for-effect (setq tmp (get fn 'side-effect-free))
533 (or byte-compile-delete-errors
534 (eq tmp 'error-free)
535 ;; Detect the expansion of (pop foo).
536 ;; There is no need to compile the call to `car' there.
537 (and (eq fn 'car)
538 (eq (car-safe (cadr form)) 'prog1)
539 (let ((var (cadr (cadr form)))
540 (last (nth 2 (cadr form))))
541 (and (symbolp var)
542 (null (nthcdr 3 (cadr form)))
543 (eq (car-safe last) 'setq)
544 (eq (cadr last) var)
545 (eq (car-safe (nth 2 last)) 'cdr)
546 (eq (cadr (nth 2 last)) var))))
547 (progn
548 (byte-compile-warn "value returned from %s is unused"
549 (prin1-to-string form))
550 nil)))
551 (byte-compile-log " %s called for effect; deleted" fn)
552 ;; appending a nil here might not be necessary, but it can't hurt.
553 (byte-optimize-form
554 (cons 'progn (append (cdr form) '(nil))) t))
557 ;; Otherwise, no args can be considered to be for-effect,
558 ;; even if the called function is for-effect, because we
559 ;; don't know anything about that function.
560 (let ((args (mapcar #'byte-optimize-form (cdr form))))
561 (if (and (get fn 'pure)
562 (byte-optimize-all-constp args))
563 (list 'quote (apply fn (mapcar #'eval args)))
564 (cons fn args)))))))
566 (defun byte-optimize-all-constp (list)
567 "Non-nil if all elements of LIST satisfy `macroexp-const-p"
568 (let ((constant t))
569 (while (and list constant)
570 (unless (macroexp-const-p (car list))
571 (setq constant nil))
572 (setq list (cdr list)))
573 constant))
575 (defun byte-optimize-form (form &optional for-effect)
576 "The source-level pass of the optimizer."
578 ;; First, optimize all sub-forms of this one.
579 (setq form (byte-optimize-form-code-walker form for-effect))
581 ;; after optimizing all subforms, optimize this form until it doesn't
582 ;; optimize any further. This means that some forms will be passed through
583 ;; the optimizer many times, but that's necessary to make the for-effect
584 ;; processing do as much as possible.
586 (let (opt new)
587 (if (and (consp form)
588 (symbolp (car form))
589 (or ;; (and for-effect
590 ;; ;; We don't have any of these yet, but we might.
591 ;; (setq opt (get (car form)
592 ;; 'byte-for-effect-optimizer)))
593 (setq opt (function-get (car form) 'byte-optimizer)))
594 (not (eq form (setq new (funcall opt form)))))
595 (progn
596 ;; (if (equal form new) (error "bogus optimizer -- %s" opt))
597 (byte-compile-log " %s\t==>\t%s" form new)
598 (setq new (byte-optimize-form new for-effect))
599 new)
600 form)))
603 (defun byte-optimize-body (forms all-for-effect)
604 ;; Optimize the cdr of a progn or implicit progn; all forms is a list of
605 ;; forms, all but the last of which are optimized with the assumption that
606 ;; they are being called for effect. the last is for-effect as well if
607 ;; all-for-effect is true. returns a new list of forms.
608 (let ((rest forms)
609 (result nil)
610 fe new)
611 (while rest
612 (setq fe (or all-for-effect (cdr rest)))
613 (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
614 (if (or new (not fe))
615 (setq result (cons new result)))
616 (setq rest (cdr rest)))
617 (nreverse result)))
620 ;; some source-level optimizers
622 ;; when writing optimizers, be VERY careful that the optimizer returns
623 ;; something not EQ to its argument if and ONLY if it has made a change.
624 ;; This implies that you cannot simply destructively modify the list;
625 ;; you must return something not EQ to it if you make an optimization.
627 ;; It is now safe to optimize code such that it introduces new bindings.
629 (defsubst byte-compile-trueconstp (form)
630 "Return non-nil if FORM always evaluates to a non-nil value."
631 (while (eq (car-safe form) 'progn)
632 (setq form (car (last (cdr form)))))
633 (cond ((consp form)
634 (pcase (car form)
635 (`quote (cadr form))
636 ;; Can't use recursion in a defsubst.
637 ;; (`progn (byte-compile-trueconstp (car (last (cdr form)))))
639 ((not (symbolp form)))
640 ((eq form t))
641 ((keywordp form))))
643 (defsubst byte-compile-nilconstp (form)
644 "Return non-nil if FORM always evaluates to a nil value."
645 (while (eq (car-safe form) 'progn)
646 (setq form (car (last (cdr form)))))
647 (cond ((consp form)
648 (pcase (car form)
649 (`quote (null (cadr form)))
650 ;; Can't use recursion in a defsubst.
651 ;; (`progn (byte-compile-nilconstp (car (last (cdr form)))))
653 ((not (symbolp form)) nil)
654 ((null form))))
656 ;; If the function is being called with constant numeric args,
657 ;; evaluate as much as possible at compile-time. This optimizer
658 ;; assumes that the function is associative, like + or *.
659 (defun byte-optimize-associative-math (form)
660 (let ((args nil)
661 (constants nil)
662 (rest (cdr form)))
663 (while rest
664 (if (numberp (car rest))
665 (setq constants (cons (car rest) constants))
666 (setq args (cons (car rest) args)))
667 (setq rest (cdr rest)))
668 (if (cdr constants)
669 (if args
670 (list (car form)
671 (apply (car form) constants)
672 (if (cdr args)
673 (cons (car form) (nreverse args))
674 (car args)))
675 (apply (car form) constants))
676 form)))
678 ;; If the function is being called with constant numeric args,
679 ;; evaluate as much as possible at compile-time. This optimizer
680 ;; assumes that the function satisfies
681 ;; (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
682 ;; like - and /.
683 (defun byte-optimize-nonassociative-math (form)
684 (if (or (not (numberp (car (cdr form))))
685 (not (numberp (car (cdr (cdr form))))))
686 form
687 (let ((constant (car (cdr form)))
688 (rest (cdr (cdr form))))
689 (while (numberp (car rest))
690 (setq constant (funcall (car form) constant (car rest))
691 rest (cdr rest)))
692 (if rest
693 (cons (car form) (cons constant rest))
694 constant))))
696 ;;(defun byte-optimize-associative-two-args-math (form)
697 ;; (setq form (byte-optimize-associative-math form))
698 ;; (if (consp form)
699 ;; (byte-optimize-two-args-left form)
700 ;; form))
702 ;;(defun byte-optimize-nonassociative-two-args-math (form)
703 ;; (setq form (byte-optimize-nonassociative-math form))
704 ;; (if (consp form)
705 ;; (byte-optimize-two-args-right form)
706 ;; form))
708 (defun byte-optimize-approx-equal (x y)
709 (<= (* (abs (- x y)) 100) (abs (+ x y))))
711 ;; Collect all the constants from FORM, after the STARTth arg,
712 ;; and apply FUN to them to make one argument at the end.
713 ;; For functions that can handle floats, that optimization
714 ;; can be incorrect because reordering can cause an overflow
715 ;; that would otherwise be avoided by encountering an arg that is a float.
716 ;; We avoid this problem by (1) not moving float constants and
717 ;; (2) not moving anything if it would cause an overflow.
718 (defun byte-optimize-delay-constants-math (form start fun)
719 ;; Merge all FORM's constants from number START, call FUN on them
720 ;; and put the result at the end.
721 (let ((rest (nthcdr (1- start) form))
722 (orig form)
723 ;; t means we must check for overflow.
724 (overflow (memq fun '(+ *))))
725 (while (cdr (setq rest (cdr rest)))
726 (if (integerp (car rest))
727 (let (constants)
728 (setq form (copy-sequence form)
729 rest (nthcdr (1- start) form))
730 (while (setq rest (cdr rest))
731 (cond ((integerp (car rest))
732 (setq constants (cons (car rest) constants))
733 (setcar rest nil))))
734 ;; If necessary, check now for overflow
735 ;; that might be caused by reordering.
736 (if (and overflow
737 ;; We have overflow if the result of doing the arithmetic
738 ;; on floats is not even close to the result
739 ;; of doing it on integers.
740 (not (byte-optimize-approx-equal
741 (apply fun (mapcar 'float constants))
742 (float (apply fun constants)))))
743 (setq form orig)
744 (setq form (nconc (delq nil form)
745 (list (apply fun (nreverse constants)))))))))
746 form))
748 (defsubst byte-compile-butlast (form)
749 (nreverse (cdr (reverse form))))
751 (defun byte-optimize-plus (form)
752 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
753 ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
754 (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
755 ;; For (+ constants...), byte-optimize-predicate does the work.
756 (when (memq nil (mapcar 'numberp (cdr form)))
757 (cond
758 ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
759 ((and (= (length form) 3)
760 (or (memq (nth 1 form) '(1 -1))
761 (memq (nth 2 form) '(1 -1))))
762 (let (integer other)
763 (if (memq (nth 1 form) '(1 -1))
764 (setq integer (nth 1 form) other (nth 2 form))
765 (setq integer (nth 2 form) other (nth 1 form)))
766 (setq form
767 (list (if (eq integer 1) '1+ '1-) other))))
768 ;; Here, we could also do
769 ;; (+ x y ... 1) --> (1+ (+ x y ...))
770 ;; (+ x y ... -1) --> (1- (+ x y ...))
771 ;; The resulting bytecode is smaller, but is it faster? -- cyd
773 (byte-optimize-predicate form))
775 (defun byte-optimize-minus (form)
776 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
777 ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
778 ;; Remove zeros.
779 (when (and (nthcdr 3 form)
780 (memq 0 (cddr form)))
781 (setq form (nconc (list (car form) (cadr form))
782 (delq 0 (copy-sequence (cddr form)))))
783 ;; After the above, we must turn (- x) back into (- x 0)
784 (or (cddr form)
785 (setq form (nconc form (list 0)))))
786 ;; For (- constants..), byte-optimize-predicate does the work.
787 (when (memq nil (mapcar 'numberp (cdr form)))
788 (cond
789 ;; (- x 1) --> (1- x)
790 ((equal (nthcdr 2 form) '(1))
791 (setq form (list '1- (nth 1 form))))
792 ;; (- x -1) --> (1+ x)
793 ((equal (nthcdr 2 form) '(-1))
794 (setq form (list '1+ (nth 1 form))))
795 ;; (- 0 x) --> (- x)
796 ((and (eq (nth 1 form) 0)
797 (= (length form) 3))
798 (setq form (list '- (nth 2 form))))
799 ;; Here, we could also do
800 ;; (- x y ... 1) --> (1- (- x y ...))
801 ;; (- x y ... -1) --> (1+ (- x y ...))
802 ;; The resulting bytecode is smaller, but is it faster? -- cyd
804 (byte-optimize-predicate form))
806 (defun byte-optimize-multiply (form)
807 (setq form (byte-optimize-delay-constants-math form 1 '*))
808 ;; For (* constants..), byte-optimize-predicate does the work.
809 (when (memq nil (mapcar 'numberp (cdr form)))
810 ;; After `byte-optimize-predicate', if there is a INTEGER constant
811 ;; in FORM, it is in the last element.
812 (let ((last (car (reverse (cdr form)))))
813 (cond
814 ;; Would handling (* ... 0) here cause floating point errors?
815 ;; See bug#1334.
816 ((eq 1 last) (setq form (byte-compile-butlast form)))
817 ((eq -1 last)
818 (setq form (list '- (if (nthcdr 3 form)
819 (byte-compile-butlast form)
820 (nth 1 form))))))))
821 (byte-optimize-predicate form))
823 (defun byte-optimize-divide (form)
824 (setq form (byte-optimize-delay-constants-math form 2 '*))
825 ;; After `byte-optimize-predicate', if there is a INTEGER constant
826 ;; in FORM, it is in the last element.
827 (let ((last (car (reverse (cdr (cdr form))))))
828 (cond
829 ;; Runtime error (leave it intact).
830 ((or (null last)
831 (eq last 0)
832 (memql 0.0 (cddr form))))
833 ;; No constants in expression
834 ((not (numberp last)))
835 ;; For (* constants..), byte-optimize-predicate does the work.
836 ((null (memq nil (mapcar 'numberp (cdr form)))))
837 ;; (/ x y.. 1) --> (/ x y..)
838 ((and (eq last 1) (nthcdr 3 form))
839 (setq form (byte-compile-butlast form)))
840 ;; (/ x -1), (/ x .. -1) --> (- x), (- (/ x ..))
841 ((eq last -1)
842 (setq form (list '- (if (nthcdr 3 form)
843 (byte-compile-butlast form)
844 (nth 1 form)))))))
845 (byte-optimize-predicate form))
847 (defun byte-optimize-logmumble (form)
848 (setq form (byte-optimize-delay-constants-math form 1 (car form)))
849 (byte-optimize-predicate
850 (cond ((memq 0 form)
851 (setq form (if (eq (car form) 'logand)
852 (cons 'progn (cdr form))
853 (delq 0 (copy-sequence form)))))
854 ((and (eq (car-safe form) 'logior)
855 (memq -1 form))
856 (cons 'progn (cdr form)))
857 (form))))
860 (defun byte-optimize-binary-predicate (form)
861 (if (macroexp-const-p (nth 1 form))
862 (if (macroexp-const-p (nth 2 form))
863 (condition-case ()
864 (list 'quote (eval form))
865 (error form))
866 ;; This can enable some lapcode optimizations.
867 (list (car form) (nth 2 form) (nth 1 form)))
868 form))
870 (defun byte-optimize-predicate (form)
871 (let ((ok t)
872 (rest (cdr form)))
873 (while (and rest ok)
874 (setq ok (macroexp-const-p (car rest))
875 rest (cdr rest)))
876 (if ok
877 (condition-case ()
878 (list 'quote (eval form))
879 (error form))
880 form)))
882 (defun byte-optimize-identity (form)
883 (if (and (cdr form) (null (cdr (cdr form))))
884 (nth 1 form)
885 (byte-compile-warn "identity called with %d arg%s, but requires 1"
886 (length (cdr form))
887 (if (= 1 (length (cdr form))) "" "s"))
888 form))
890 (put 'identity 'byte-optimizer 'byte-optimize-identity)
892 (put '+ 'byte-optimizer 'byte-optimize-plus)
893 (put '* 'byte-optimizer 'byte-optimize-multiply)
894 (put '- 'byte-optimizer 'byte-optimize-minus)
895 (put '/ 'byte-optimizer 'byte-optimize-divide)
896 (put 'max 'byte-optimizer 'byte-optimize-associative-math)
897 (put 'min 'byte-optimizer 'byte-optimize-associative-math)
899 (put '= 'byte-optimizer 'byte-optimize-binary-predicate)
900 (put 'eq 'byte-optimizer 'byte-optimize-binary-predicate)
901 (put 'equal 'byte-optimizer 'byte-optimize-binary-predicate)
902 (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
903 (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
905 (put '< 'byte-optimizer 'byte-optimize-predicate)
906 (put '> 'byte-optimizer 'byte-optimize-predicate)
907 (put '<= 'byte-optimizer 'byte-optimize-predicate)
908 (put '>= 'byte-optimizer 'byte-optimize-predicate)
909 (put '1+ 'byte-optimizer 'byte-optimize-predicate)
910 (put '1- 'byte-optimizer 'byte-optimize-predicate)
911 (put 'not 'byte-optimizer 'byte-optimize-predicate)
912 (put 'null 'byte-optimizer 'byte-optimize-predicate)
913 (put 'memq 'byte-optimizer 'byte-optimize-predicate)
914 (put 'consp 'byte-optimizer 'byte-optimize-predicate)
915 (put 'listp 'byte-optimizer 'byte-optimize-predicate)
916 (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
917 (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
918 (put 'string< 'byte-optimizer 'byte-optimize-predicate)
919 (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
921 (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
922 (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
923 (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
924 (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
926 (put 'car 'byte-optimizer 'byte-optimize-predicate)
927 (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
928 (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
929 (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
932 ;; I'm not convinced that this is necessary. Doesn't the optimizer loop
933 ;; take care of this? - Jamie
934 ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
935 ;; so arithmetic optimizers recognize the numeric constant. - Hallvard
936 (put 'quote 'byte-optimizer 'byte-optimize-quote)
937 (defun byte-optimize-quote (form)
938 (if (or (consp (nth 1 form))
939 (and (symbolp (nth 1 form))
940 (not (macroexp--const-symbol-p form))))
941 form
942 (nth 1 form)))
944 (defun byte-optimize-zerop (form)
945 (cond ((numberp (nth 1 form))
946 (eval form))
947 (byte-compile-delete-errors
948 (list '= (nth 1 form) 0))
949 (form)))
951 (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
953 (defun byte-optimize-and (form)
954 ;; Simplify if less than 2 args.
955 ;; if there is a literal nil in the args to `and', throw it and following
956 ;; forms away, and surround the `and' with (progn ... nil).
957 (cond ((null (cdr form)))
958 ((memq nil form)
959 (list 'progn
960 (byte-optimize-and
961 (prog1 (setq form (copy-sequence form))
962 (while (nth 1 form)
963 (setq form (cdr form)))
964 (setcdr form nil)))
965 nil))
966 ((null (cdr (cdr form)))
967 (nth 1 form))
968 ((byte-optimize-predicate form))))
970 (defun byte-optimize-or (form)
971 ;; Throw away nil's, and simplify if less than 2 args.
972 ;; If there is a literal non-nil constant in the args to `or', throw away all
973 ;; following forms.
974 (if (memq nil form)
975 (setq form (delq nil (copy-sequence form))))
976 (let ((rest form))
977 (while (cdr (setq rest (cdr rest)))
978 (if (byte-compile-trueconstp (car rest))
979 (setq form (copy-sequence form)
980 rest (setcdr (memq (car rest) form) nil))))
981 (if (cdr (cdr form))
982 (byte-optimize-predicate form)
983 (nth 1 form))))
985 (defun byte-optimize-cond (form)
986 ;; if any clauses have a literal nil as their test, throw them away.
987 ;; if any clause has a literal non-nil constant as its test, throw
988 ;; away all following clauses.
989 (let (rest)
990 ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
991 (while (setq rest (assq nil (cdr form)))
992 (setq form (delq rest (copy-sequence form))))
993 (if (memq nil (cdr form))
994 (setq form (delq nil (copy-sequence form))))
995 (setq rest form)
996 (while (setq rest (cdr rest))
997 (cond ((byte-compile-trueconstp (car-safe (car rest)))
998 ;; This branch will always be taken: kill the subsequent ones.
999 (cond ((eq rest (cdr form)) ;First branch of `cond'.
1000 (setq form `(progn ,@(car rest))))
1001 ((cdr rest)
1002 (setq form (copy-sequence form))
1003 (setcdr (memq (car rest) form) nil)))
1004 (setq rest nil))
1005 ((and (consp (car rest))
1006 (byte-compile-nilconstp (caar rest)))
1007 ;; This branch will never be taken: kill its body.
1008 (setcdr (car rest) nil)))))
1010 ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
1011 (if (eq 'cond (car-safe form))
1012 (let ((clauses (cdr form)))
1013 (if (and (consp (car clauses))
1014 (null (cdr (car clauses))))
1015 (list 'or (car (car clauses))
1016 (byte-optimize-cond
1017 (cons (car form) (cdr (cdr form)))))
1018 form))
1019 form))
1021 (defun byte-optimize-if (form)
1022 ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
1023 ;; (if <true-constant> <then> <else...>) ==> <then>
1024 ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
1025 ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
1026 ;; (if <test> <then> nil) ==> (if <test> <then>)
1027 (let ((clause (nth 1 form)))
1028 (cond ((and (eq (car-safe clause) 'progn)
1029 ;; `clause' is a proper list.
1030 (null (cdr (last clause))))
1031 (if (null (cddr clause))
1032 ;; A trivial `progn'.
1033 (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
1034 (nconc (butlast clause)
1035 (list
1036 (byte-optimize-if
1037 `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
1038 ((byte-compile-trueconstp clause)
1039 `(progn ,clause ,(nth 2 form)))
1040 ((byte-compile-nilconstp clause)
1041 `(progn ,clause ,@(nthcdr 3 form)))
1042 ((nth 2 form)
1043 (if (equal '(nil) (nthcdr 3 form))
1044 (list 'if clause (nth 2 form))
1045 form))
1046 ((or (nth 3 form) (nthcdr 4 form))
1047 (list 'if
1048 ;; Don't make a double negative;
1049 ;; instead, take away the one that is there.
1050 (if (and (consp clause) (memq (car clause) '(not null))
1051 (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
1052 (nth 1 clause)
1053 (list 'not clause))
1054 (if (nthcdr 4 form)
1055 (cons 'progn (nthcdr 3 form))
1056 (nth 3 form))))
1058 (list 'progn clause nil)))))
1060 (defun byte-optimize-while (form)
1061 (when (< (length form) 2)
1062 (byte-compile-warn "too few arguments for `while'"))
1063 (if (nth 1 form)
1064 form))
1066 (put 'and 'byte-optimizer 'byte-optimize-and)
1067 (put 'or 'byte-optimizer 'byte-optimize-or)
1068 (put 'cond 'byte-optimizer 'byte-optimize-cond)
1069 (put 'if 'byte-optimizer 'byte-optimize-if)
1070 (put 'while 'byte-optimizer 'byte-optimize-while)
1072 ;; byte-compile-negation-optimizer lives in bytecomp.el
1073 (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
1074 (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
1075 (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
1078 (defun byte-optimize-funcall (form)
1079 ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
1080 ;; (funcall foo ...) ==> (foo ...)
1081 (let ((fn (nth 1 form)))
1082 (if (memq (car-safe fn) '(quote function))
1083 (cons (nth 1 fn) (cdr (cdr form)))
1084 form)))
1086 (defun byte-optimize-apply (form)
1087 ;; If the last arg is a literal constant, turn this into a funcall.
1088 ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
1089 (let ((fn (nth 1 form))
1090 (last (nth (1- (length form)) form))) ; I think this really is fastest
1091 (or (if (or (null last)
1092 (eq (car-safe last) 'quote))
1093 (if (listp (nth 1 last))
1094 (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
1095 (nconc (list 'funcall fn) butlast
1096 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
1097 (byte-compile-warn
1098 "last arg to apply can't be a literal atom: `%s'"
1099 (prin1-to-string last))
1100 nil))
1101 form)))
1103 (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
1104 (put 'apply 'byte-optimizer 'byte-optimize-apply)
1107 (put 'let 'byte-optimizer 'byte-optimize-letX)
1108 (put 'let* 'byte-optimizer 'byte-optimize-letX)
1109 (defun byte-optimize-letX (form)
1110 (cond ((null (nth 1 form))
1111 ;; No bindings
1112 (cons 'progn (cdr (cdr form))))
1113 ((or (nth 2 form) (nthcdr 3 form))
1114 form)
1115 ;; The body is nil
1116 ((eq (car form) 'let)
1117 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
1118 '(nil)))
1120 (let ((binds (reverse (nth 1 form))))
1121 (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
1124 (put 'nth 'byte-optimizer 'byte-optimize-nth)
1125 (defun byte-optimize-nth (form)
1126 (if (= (safe-length form) 3)
1127 (if (memq (nth 1 form) '(0 1))
1128 (list 'car (if (zerop (nth 1 form))
1129 (nth 2 form)
1130 (list 'cdr (nth 2 form))))
1131 (byte-optimize-predicate form))
1132 form))
1134 (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
1135 (defun byte-optimize-nthcdr (form)
1136 (if (= (safe-length form) 3)
1137 (if (memq (nth 1 form) '(0 1 2))
1138 (let ((count (nth 1 form)))
1139 (setq form (nth 2 form))
1140 (while (>= (setq count (1- count)) 0)
1141 (setq form (list 'cdr form)))
1142 form)
1143 (byte-optimize-predicate form))
1144 form))
1146 ;; Fixme: delete-char -> delete-region (byte-coded)
1147 ;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
1148 ;; string-make-multibyte for constant args.
1150 (put 'set 'byte-optimizer 'byte-optimize-set)
1151 (defun byte-optimize-set (form)
1152 (let ((var (car-safe (cdr-safe form))))
1153 (cond
1154 ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1155 `(setq ,(cadr var) ,@(cddr form)))
1156 ((and (eq (car-safe var) 'make-local-variable)
1157 (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
1158 (consp (cdr var)))
1159 `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
1160 (t form))))
1162 ;; enumerating those functions which need not be called if the returned
1163 ;; value is not used. That is, something like
1164 ;; (progn (list (something-with-side-effects) (yow))
1165 ;; (foo))
1166 ;; may safely be turned into
1167 ;; (progn (progn (something-with-side-effects) (yow))
1168 ;; (foo))
1169 ;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
1171 ;; Some of these functions have the side effect of allocating memory
1172 ;; and it would be incorrect to replace two calls with one.
1173 ;; But we don't try to do those kinds of optimizations,
1174 ;; so it is safe to list such functions here.
1175 ;; Some of these functions return values that depend on environment
1176 ;; state, so that constant folding them would be wrong,
1177 ;; but we don't do constant folding based on this list.
1179 ;; However, at present the only optimization we normally do
1180 ;; is delete calls that need not occur, and we only do that
1181 ;; with the error-free functions.
1183 ;; I wonder if I missed any :-\)
1184 (let ((side-effect-free-fns
1185 '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
1186 assoc assq
1187 boundp buffer-file-name buffer-local-variables buffer-modified-p
1188 buffer-substring byte-code-function-p
1189 capitalize car-less-than-car car cdr ceiling char-after char-before
1190 char-equal char-to-string char-width
1191 compare-strings concat coordinates-in-window-p
1192 copy-alist copy-sequence copy-marker cos count-lines
1193 decode-char
1194 decode-time default-boundp default-value documentation downcase
1195 elt encode-char exp expt encode-time error-message-string
1196 fboundp fceiling featurep ffloor
1197 file-directory-p file-exists-p file-locked-p file-name-absolute-p
1198 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1199 float float-time floor format format-time-string frame-visible-p
1200 fround ftruncate
1201 get gethash get-buffer get-buffer-window getenv get-file-buffer
1202 hash-table-count
1203 int-to-string intern-soft
1204 keymap-parent
1205 length local-variable-if-set-p local-variable-p log log10 logand
1206 logb logior lognot logxor lsh langinfo
1207 make-list make-string make-symbol
1208 marker-buffer max member memq min mod multibyte-char-to-unibyte
1209 next-window nth nthcdr number-to-string
1210 parse-colon-path plist-get plist-member
1211 prefix-numeric-value previous-window prin1-to-string propertize
1212 degrees-to-radians
1213 radians-to-degrees rassq rassoc read-from-string regexp-quote
1214 region-beginning region-end reverse round
1215 sin sqrt string string< string= string-equal string-lessp string-to-char
1216 string-to-int string-to-number substring sxhash symbol-function
1217 symbol-name symbol-plist symbol-value string-make-unibyte
1218 string-make-multibyte string-as-multibyte string-as-unibyte
1219 string-to-multibyte
1220 tan truncate
1221 unibyte-char-to-multibyte upcase user-full-name
1222 user-login-name user-original-login-name custom-variable-p
1223 vconcat
1224 window-buffer window-dedicated-p window-edges window-height
1225 window-hscroll window-minibuffer-p window-width
1226 zerop))
1227 (side-effect-and-error-free-fns
1228 '(arrayp atom
1229 bobp bolp bool-vector-p
1230 buffer-end buffer-list buffer-size buffer-string bufferp
1231 car-safe case-table-p cdr-safe char-or-string-p characterp
1232 charsetp commandp cons consp
1233 current-buffer current-global-map current-indentation
1234 current-local-map current-minor-mode-maps current-time
1235 current-time-string current-time-zone
1236 eobp eolp eq equal eventp
1237 floatp following-char framep
1238 get-largest-window get-lru-window
1239 hash-table-p
1240 identity ignore integerp integer-or-marker-p interactive-p
1241 invocation-directory invocation-name
1242 keymapp
1243 line-beginning-position line-end-position list listp
1244 make-marker mark mark-marker markerp max-char
1245 memory-limit minibuffer-window
1246 mouse-movement-p
1247 natnump nlistp not null number-or-marker-p numberp
1248 one-window-p overlayp
1249 point point-marker point-min point-max preceding-char primary-charset
1250 processp
1251 recent-keys recursion-depth
1252 safe-length selected-frame selected-window sequencep
1253 standard-case-table standard-syntax-table stringp subrp symbolp
1254 syntax-table syntax-table-p
1255 this-command-keys this-command-keys-vector this-single-command-keys
1256 this-single-command-raw-keys
1257 user-real-login-name user-real-uid user-uid
1258 vector vectorp visible-frame-list
1259 wholenump window-configuration-p window-live-p windowp)))
1260 (while side-effect-free-fns
1261 (put (car side-effect-free-fns) 'side-effect-free t)
1262 (setq side-effect-free-fns (cdr side-effect-free-fns)))
1263 (while side-effect-and-error-free-fns
1264 (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
1265 (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
1266 nil)
1269 ;; pure functions are side-effect free functions whose values depend
1270 ;; only on their arguments. For these functions, calls with constant
1271 ;; arguments can be evaluated at compile time. This may shift run time
1272 ;; errors to compile time.
1274 (let ((pure-fns
1275 '(concat symbol-name regexp-opt regexp-quote string-to-syntax)))
1276 (while pure-fns
1277 (put (car pure-fns) 'pure t)
1278 (setq pure-fns (cdr pure-fns)))
1279 nil)
1281 (defconst byte-constref-ops
1282 '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
1284 ;; Used and set dynamically in byte-decompile-bytecode-1.
1285 (defvar bytedecomp-op)
1286 (defvar bytedecomp-ptr)
1288 ;; This function extracts the bitfields from variable-length opcodes.
1289 ;; Originally defined in disass.el (which no longer uses it.)
1290 (defun disassemble-offset (bytes)
1291 "Don't call this!"
1292 ;; Fetch and return the offset for the current opcode.
1293 ;; Return nil if this opcode has no offset.
1294 (cond ((< bytedecomp-op byte-nth)
1295 (let ((tem (logand bytedecomp-op 7)))
1296 (setq bytedecomp-op (logand bytedecomp-op 248))
1297 (cond ((eq tem 6)
1298 ;; Offset in next byte.
1299 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1300 (aref bytes bytedecomp-ptr))
1301 ((eq tem 7)
1302 ;; Offset in next 2 bytes.
1303 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1304 (+ (aref bytes bytedecomp-ptr)
1305 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1306 (lsh (aref bytes bytedecomp-ptr) 8))))
1307 (t tem)))) ;Offset was in opcode.
1308 ((>= bytedecomp-op byte-constant)
1309 (prog1 (- bytedecomp-op byte-constant) ;Offset in opcode.
1310 (setq bytedecomp-op byte-constant)))
1311 ((or (and (>= bytedecomp-op byte-constant2)
1312 (<= bytedecomp-op byte-goto-if-not-nil-else-pop))
1313 (= bytedecomp-op byte-stack-set2))
1314 ;; Offset in next 2 bytes.
1315 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1316 (+ (aref bytes bytedecomp-ptr)
1317 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1318 (lsh (aref bytes bytedecomp-ptr) 8))))
1319 ((and (>= bytedecomp-op byte-listN)
1320 (<= bytedecomp-op byte-discardN))
1321 (setq bytedecomp-ptr (1+ bytedecomp-ptr)) ;Offset in next byte.
1322 (aref bytes bytedecomp-ptr))))
1324 (defvar byte-compile-tag-number)
1326 ;; This de-compiler is used for inline expansion of compiled functions,
1327 ;; and by the disassembler.
1329 ;; This list contains numbers, which are pc values,
1330 ;; before each instruction.
1331 (defun byte-decompile-bytecode (bytes constvec)
1332 "Turn BYTECODE into lapcode, referring to CONSTVEC."
1333 (let ((byte-compile-constants nil)
1334 (byte-compile-variables nil)
1335 (byte-compile-tag-number 0))
1336 (byte-decompile-bytecode-1 bytes constvec)))
1338 ;; As byte-decompile-bytecode, but updates
1339 ;; byte-compile-{constants, variables, tag-number}.
1340 ;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1341 ;; with `goto's destined for the end of the code.
1342 ;; That is for use by the compiler.
1343 ;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
1344 ;; In that case, we put a pc value into the list
1345 ;; before each insn (or its label).
1346 (defun byte-decompile-bytecode-1 (bytes constvec &optional make-spliceable)
1347 (let ((length (length bytes))
1348 (bytedecomp-ptr 0) optr tags bytedecomp-op offset
1349 lap tmp)
1350 (while (not (= bytedecomp-ptr length))
1351 (or make-spliceable
1352 (push bytedecomp-ptr lap))
1353 (setq bytedecomp-op (aref bytes bytedecomp-ptr)
1354 optr bytedecomp-ptr
1355 ;; This uses dynamic-scope magic.
1356 offset (disassemble-offset bytes))
1357 (let ((opcode (aref byte-code-vector bytedecomp-op)))
1358 (cl-assert opcode)
1359 (setq bytedecomp-op opcode))
1360 (cond ((memq bytedecomp-op byte-goto-ops)
1361 ;; It's a pc.
1362 (setq offset
1363 (cdr (or (assq offset tags)
1364 (let ((new (cons offset (byte-compile-make-tag))))
1365 (push new tags)
1366 new)))))
1367 ((cond ((eq bytedecomp-op 'byte-constant2)
1368 (setq bytedecomp-op 'byte-constant) t)
1369 ((memq bytedecomp-op byte-constref-ops)))
1370 (setq tmp (if (>= offset (length constvec))
1371 (list 'out-of-range offset)
1372 (aref constvec offset))
1373 offset (if (eq bytedecomp-op 'byte-constant)
1374 (byte-compile-get-constant tmp)
1375 (or (assq tmp byte-compile-variables)
1376 (let ((new (list tmp)))
1377 (push new byte-compile-variables)
1378 new)))))
1379 ((eq bytedecomp-op 'byte-stack-set2)
1380 (setq bytedecomp-op 'byte-stack-set))
1381 ((and (eq bytedecomp-op 'byte-discardN) (>= offset #x80))
1382 ;; The top bit of the operand for byte-discardN is a flag,
1383 ;; saying whether the top-of-stack is preserved. In
1384 ;; lapcode, we represent this by using a different opcode
1385 ;; (with the flag removed from the operand).
1386 (setq bytedecomp-op 'byte-discardN-preserve-tos)
1387 (setq offset (- offset #x80))))
1388 ;; lap = ( [ (pc . (op . arg)) ]* )
1389 (push (cons optr (cons bytedecomp-op (or offset 0)))
1390 lap)
1391 (setq bytedecomp-ptr (1+ bytedecomp-ptr)))
1392 (let ((rest lap))
1393 (while rest
1394 (cond ((numberp (car rest)))
1395 ((setq tmp (assq (car (car rest)) tags))
1396 ;; This addr is jumped to.
1397 (setcdr rest (cons (cons nil (cdr tmp))
1398 (cdr rest)))
1399 (setq tags (delq tmp tags))
1400 (setq rest (cdr rest))))
1401 (setq rest (cdr rest))))
1402 (if tags (error "optimizer error: missed tags %s" tags))
1403 ;; Remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1404 (mapcar (function (lambda (elt)
1405 (if (numberp elt)
1407 (cdr elt))))
1408 (nreverse lap))))
1411 ;;; peephole optimizer
1413 (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
1415 (defconst byte-conditional-ops
1416 '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
1417 byte-goto-if-not-nil-else-pop))
1419 (defconst byte-after-unbind-ops
1420 '(byte-constant byte-dup
1421 byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
1422 byte-eq byte-not
1423 byte-cons byte-list1 byte-list2 ; byte-list3 byte-list4
1424 byte-interactive-p)
1425 ;; How about other side-effect-free-ops? Is it safe to move an
1426 ;; error invocation (such as from nth) out of an unwind-protect?
1427 ;; No, it is not, because the unwind-protect forms can alter
1428 ;; the inside of the object to which nth would apply.
1429 ;; For the same reason, byte-equal was deleted from this list.
1430 "Byte-codes that can be moved past an unbind.")
1432 (defconst byte-compile-side-effect-and-error-free-ops
1433 '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
1434 byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
1435 byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
1436 byte-point-min byte-following-char byte-preceding-char
1437 byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
1438 byte-current-buffer byte-stack-ref))
1440 (defconst byte-compile-side-effect-free-ops
1441 (nconc
1442 '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
1443 byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
1444 byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
1445 byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
1446 byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
1447 byte-member byte-assq byte-quo byte-rem)
1448 byte-compile-side-effect-and-error-free-ops))
1450 ;; This crock is because of the way DEFVAR_BOOL variables work.
1451 ;; Consider the code
1453 ;; (defun foo (flag)
1454 ;; (let ((old-pop-ups pop-up-windows)
1455 ;; (pop-up-windows flag))
1456 ;; (cond ((not (eq pop-up-windows old-pop-ups))
1457 ;; (setq old-pop-ups pop-up-windows)
1458 ;; ...))))
1460 ;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
1461 ;; something else. But if we optimize
1463 ;; varref flag
1464 ;; varbind pop-up-windows
1465 ;; varref pop-up-windows
1466 ;; not
1467 ;; to
1468 ;; varref flag
1469 ;; dup
1470 ;; varbind pop-up-windows
1471 ;; not
1473 ;; we break the program, because it will appear that pop-up-windows and
1474 ;; old-pop-ups are not EQ when really they are. So we have to know what
1475 ;; the BOOL variables are, and not perform this optimization on them.
1477 ;; The variable `byte-boolean-vars' is now primitive and updated
1478 ;; automatically by DEFVAR_BOOL.
1480 (defun byte-optimize-lapcode (lap &optional _for-effect)
1481 "Simple peephole optimizer. LAP is both modified and returned.
1482 If FOR-EFFECT is non-nil, the return value is assumed to be of no importance."
1483 (let (lap0
1484 lap1
1485 lap2
1486 (keep-going 'first-time)
1487 (add-depth 0)
1488 rest tmp tmp2 tmp3
1489 (side-effect-free (if byte-compile-delete-errors
1490 byte-compile-side-effect-free-ops
1491 byte-compile-side-effect-and-error-free-ops)))
1492 (while keep-going
1493 (or (eq keep-going 'first-time)
1494 (byte-compile-log-lap " ---- next pass"))
1495 (setq rest lap
1496 keep-going nil)
1497 (while rest
1498 (setq lap0 (car rest)
1499 lap1 (nth 1 rest)
1500 lap2 (nth 2 rest))
1502 ;; You may notice that sequences like "dup varset discard" are
1503 ;; optimized but sequences like "dup varset TAG1: discard" are not.
1504 ;; You may be tempted to change this; resist that temptation.
1505 (cond ;;
1506 ;; <side-effect-free> pop --> <deleted>
1507 ;; ...including:
1508 ;; const-X pop --> <deleted>
1509 ;; varref-X pop --> <deleted>
1510 ;; dup pop --> <deleted>
1512 ((and (eq 'byte-discard (car lap1))
1513 (memq (car lap0) side-effect-free))
1514 (setq keep-going t)
1515 (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
1516 (setq rest (cdr rest))
1517 (cond ((= tmp 1)
1518 (byte-compile-log-lap
1519 " %s discard\t-->\t<deleted>" lap0)
1520 (setq lap (delq lap0 (delq lap1 lap))))
1521 ((= tmp 0)
1522 (byte-compile-log-lap
1523 " %s discard\t-->\t<deleted> discard" lap0)
1524 (setq lap (delq lap0 lap)))
1525 ((= tmp -1)
1526 (byte-compile-log-lap
1527 " %s discard\t-->\tdiscard discard" lap0)
1528 (setcar lap0 'byte-discard)
1529 (setcdr lap0 0))
1530 ((error "Optimizer error: too much on the stack"))))
1532 ;; goto*-X X: --> X:
1534 ((and (memq (car lap0) byte-goto-ops)
1535 (eq (cdr lap0) lap1))
1536 (cond ((eq (car lap0) 'byte-goto)
1537 (setq lap (delq lap0 lap))
1538 (setq tmp "<deleted>"))
1539 ((memq (car lap0) byte-goto-always-pop-ops)
1540 (setcar lap0 (setq tmp 'byte-discard))
1541 (setcdr lap0 0))
1542 ((error "Depth conflict at tag %d" (nth 2 lap0))))
1543 (and (memq byte-optimize-log '(t byte))
1544 (byte-compile-log " (goto %s) %s:\t-->\t%s %s:"
1545 (nth 1 lap1) (nth 1 lap1)
1546 tmp (nth 1 lap1)))
1547 (setq keep-going t))
1549 ;; varset-X varref-X --> dup varset-X
1550 ;; varbind-X varref-X --> dup varbind-X
1551 ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
1552 ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
1553 ;; The latter two can enable other optimizations.
1555 ;; For lexical variables, we could do the same
1556 ;; stack-set-X+1 stack-ref-X --> dup stack-set-X+2
1557 ;; but this is a very minor gain, since dup is stack-ref-0,
1558 ;; i.e. it's only better if X>5, and even then it comes
1559 ;; at the cost of an extra stack slot. Let's not bother.
1560 ((and (eq 'byte-varref (car lap2))
1561 (eq (cdr lap1) (cdr lap2))
1562 (memq (car lap1) '(byte-varset byte-varbind)))
1563 (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
1564 (not (eq (car lap0) 'byte-constant)))
1566 (setq keep-going t)
1567 (if (memq (car lap0) '(byte-constant byte-dup))
1568 (progn
1569 (setq tmp (if (or (not tmp)
1570 (macroexp--const-symbol-p
1571 (car (cdr lap0))))
1572 (cdr lap0)
1573 (byte-compile-get-constant t)))
1574 (byte-compile-log-lap " %s %s %s\t-->\t%s %s %s"
1575 lap0 lap1 lap2 lap0 lap1
1576 (cons (car lap0) tmp))
1577 (setcar lap2 (car lap0))
1578 (setcdr lap2 tmp))
1579 (byte-compile-log-lap " %s %s\t-->\tdup %s" lap1 lap2 lap1)
1580 (setcar lap2 (car lap1))
1581 (setcar lap1 'byte-dup)
1582 (setcdr lap1 0)
1583 ;; The stack depth gets locally increased, so we will
1584 ;; increase maxdepth in case depth = maxdepth here.
1585 ;; This can cause the third argument to byte-code to
1586 ;; be larger than necessary.
1587 (setq add-depth 1))))
1589 ;; dup varset-X discard --> varset-X
1590 ;; dup varbind-X discard --> varbind-X
1591 ;; dup stack-set-X discard --> stack-set-X-1
1592 ;; (the varbind variant can emerge from other optimizations)
1594 ((and (eq 'byte-dup (car lap0))
1595 (eq 'byte-discard (car lap2))
1596 (memq (car lap1) '(byte-varset byte-varbind
1597 byte-stack-set)))
1598 (byte-compile-log-lap " dup %s discard\t-->\t%s" lap1 lap1)
1599 (setq keep-going t
1600 rest (cdr rest))
1601 (if (eq 'byte-stack-set (car lap1)) (cl-decf (cdr lap1)))
1602 (setq lap (delq lap0 (delq lap2 lap))))
1604 ;; not goto-X-if-nil --> goto-X-if-non-nil
1605 ;; not goto-X-if-non-nil --> goto-X-if-nil
1607 ;; it is wrong to do the same thing for the -else-pop variants.
1609 ((and (eq 'byte-not (car lap0))
1610 (memq (car lap1) '(byte-goto-if-nil byte-goto-if-not-nil)))
1611 (byte-compile-log-lap " not %s\t-->\t%s"
1612 lap1
1613 (cons
1614 (if (eq (car lap1) 'byte-goto-if-nil)
1615 'byte-goto-if-not-nil
1616 'byte-goto-if-nil)
1617 (cdr lap1)))
1618 (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
1619 'byte-goto-if-not-nil
1620 'byte-goto-if-nil))
1621 (setq lap (delq lap0 lap))
1622 (setq keep-going t))
1624 ;; goto-X-if-nil goto-Y X: --> goto-Y-if-non-nil X:
1625 ;; goto-X-if-non-nil goto-Y X: --> goto-Y-if-nil X:
1627 ;; it is wrong to do the same thing for the -else-pop variants.
1629 ((and (memq (car lap0)
1630 '(byte-goto-if-nil byte-goto-if-not-nil)) ; gotoX
1631 (eq 'byte-goto (car lap1)) ; gotoY
1632 (eq (cdr lap0) lap2)) ; TAG X
1633 (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
1634 'byte-goto-if-not-nil 'byte-goto-if-nil)))
1635 (byte-compile-log-lap " %s %s %s:\t-->\t%s %s:"
1636 lap0 lap1 lap2
1637 (cons inverse (cdr lap1)) lap2)
1638 (setq lap (delq lap0 lap))
1639 (setcar lap1 inverse)
1640 (setq keep-going t)))
1642 ;; const goto-if-* --> whatever
1644 ((and (eq 'byte-constant (car lap0))
1645 (memq (car lap1) byte-conditional-ops)
1646 ;; If the `byte-constant's cdr is not a cons cell, it has
1647 ;; to be an index into the constant pool); even though
1648 ;; it'll be a constant, that constant is not known yet
1649 ;; (it's typically a free variable of a closure, so will
1650 ;; only be known when the closure will be built at
1651 ;; run-time).
1652 (consp (cdr lap0)))
1653 (cond ((if (memq (car lap1) '(byte-goto-if-nil
1654 byte-goto-if-nil-else-pop))
1655 (car (cdr lap0))
1656 (not (car (cdr lap0))))
1657 (byte-compile-log-lap " %s %s\t-->\t<deleted>"
1658 lap0 lap1)
1659 (setq rest (cdr rest)
1660 lap (delq lap0 (delq lap1 lap))))
1662 (byte-compile-log-lap " %s %s\t-->\t%s"
1663 lap0 lap1
1664 (cons 'byte-goto (cdr lap1)))
1665 (when (memq (car lap1) byte-goto-always-pop-ops)
1666 (setq lap (delq lap0 lap)))
1667 (setcar lap1 'byte-goto)))
1668 (setq keep-going t))
1670 ;; varref-X varref-X --> varref-X dup
1671 ;; varref-X [dup ...] varref-X --> varref-X [dup ...] dup
1672 ;; stackref-X [dup ...] stackref-X+N --> stackref-X [dup ...] dup
1673 ;; We don't optimize the const-X variations on this here,
1674 ;; because that would inhibit some goto optimizations; we
1675 ;; optimize the const-X case after all other optimizations.
1677 ((and (memq (car lap0) '(byte-varref byte-stack-ref))
1678 (progn
1679 (setq tmp (cdr rest))
1680 (setq tmp2 0)
1681 (while (eq (car (car tmp)) 'byte-dup)
1682 (setq tmp2 (1+ tmp2))
1683 (setq tmp (cdr tmp)))
1685 (eq (if (eq 'byte-stack-ref (car lap0))
1686 (+ tmp2 1 (cdr lap0))
1687 (cdr lap0))
1688 (cdr (car tmp)))
1689 (eq (car lap0) (car (car tmp))))
1690 (if (memq byte-optimize-log '(t byte))
1691 (let ((str ""))
1692 (setq tmp2 (cdr rest))
1693 (while (not (eq tmp tmp2))
1694 (setq tmp2 (cdr tmp2)
1695 str (concat str " dup")))
1696 (byte-compile-log-lap " %s%s %s\t-->\t%s%s dup"
1697 lap0 str lap0 lap0 str)))
1698 (setq keep-going t)
1699 (setcar (car tmp) 'byte-dup)
1700 (setcdr (car tmp) 0)
1701 (setq rest tmp))
1703 ;; TAG1: TAG2: --> TAG1: <deleted>
1704 ;; (and other references to TAG2 are replaced with TAG1)
1706 ((and (eq (car lap0) 'TAG)
1707 (eq (car lap1) 'TAG))
1708 (and (memq byte-optimize-log '(t byte))
1709 (byte-compile-log " adjacent tags %d and %d merged"
1710 (nth 1 lap1) (nth 1 lap0)))
1711 (setq tmp3 lap)
1712 (while (setq tmp2 (rassq lap0 tmp3))
1713 (setcdr tmp2 lap1)
1714 (setq tmp3 (cdr (memq tmp2 tmp3))))
1715 (setq lap (delq lap0 lap)
1716 keep-going t))
1718 ;; unused-TAG: --> <deleted>
1720 ((and (eq 'TAG (car lap0))
1721 (not (rassq lap0 lap)))
1722 (and (memq byte-optimize-log '(t byte))
1723 (byte-compile-log " unused tag %d removed" (nth 1 lap0)))
1724 (setq lap (delq lap0 lap)
1725 keep-going t))
1727 ;; goto ... --> goto <delete until TAG or end>
1728 ;; return ... --> return <delete until TAG or end>
1730 ((and (memq (car lap0) '(byte-goto byte-return))
1731 (not (memq (car lap1) '(TAG nil))))
1732 (setq tmp rest)
1733 (let ((i 0)
1734 (opt-p (memq byte-optimize-log '(t lap)))
1735 str deleted)
1736 (while (and (setq tmp (cdr tmp))
1737 (not (eq 'TAG (car (car tmp)))))
1738 (if opt-p (setq deleted (cons (car tmp) deleted)
1739 str (concat str " %s")
1740 i (1+ i))))
1741 (if opt-p
1742 (let ((tagstr
1743 (if (eq 'TAG (car (car tmp)))
1744 (format "%d:" (car (cdr (car tmp))))
1745 (or (car tmp) ""))))
1746 (if (< i 6)
1747 (apply 'byte-compile-log-lap-1
1748 (concat " %s" str
1749 " %s\t-->\t%s <deleted> %s")
1750 lap0
1751 (nconc (nreverse deleted)
1752 (list tagstr lap0 tagstr)))
1753 (byte-compile-log-lap
1754 " %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
1755 lap0 i (if (= i 1) "" "s")
1756 tagstr lap0 tagstr))))
1757 (rplacd rest tmp))
1758 (setq keep-going t))
1760 ;; <safe-op> unbind --> unbind <safe-op>
1761 ;; (this may enable other optimizations.)
1763 ((and (eq 'byte-unbind (car lap1))
1764 (memq (car lap0) byte-after-unbind-ops))
1765 (byte-compile-log-lap " %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
1766 (setcar rest lap1)
1767 (setcar (cdr rest) lap0)
1768 (setq keep-going t))
1770 ;; varbind-X unbind-N --> discard unbind-(N-1)
1771 ;; save-excursion unbind-N --> unbind-(N-1)
1772 ;; save-restriction unbind-N --> unbind-(N-1)
1774 ((and (eq 'byte-unbind (car lap1))
1775 (memq (car lap0) '(byte-varbind byte-save-excursion
1776 byte-save-restriction))
1777 (< 0 (cdr lap1)))
1778 (if (zerop (setcdr lap1 (1- (cdr lap1))))
1779 (delq lap1 rest))
1780 (if (eq (car lap0) 'byte-varbind)
1781 (setcar rest (cons 'byte-discard 0))
1782 (setq lap (delq lap0 lap)))
1783 (byte-compile-log-lap " %s %s\t-->\t%s %s"
1784 lap0 (cons (car lap1) (1+ (cdr lap1)))
1785 (if (eq (car lap0) 'byte-varbind)
1786 (car rest)
1787 (car (cdr rest)))
1788 (if (and (/= 0 (cdr lap1))
1789 (eq (car lap0) 'byte-varbind))
1790 (car (cdr rest))
1791 ""))
1792 (setq keep-going t))
1794 ;; goto*-X ... X: goto-Y --> goto*-Y
1795 ;; goto-X ... X: return --> return
1797 ((and (memq (car lap0) byte-goto-ops)
1798 (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
1799 '(byte-goto byte-return)))
1800 (cond ((and (not (eq tmp lap0))
1801 (or (eq (car lap0) 'byte-goto)
1802 (eq (car tmp) 'byte-goto)))
1803 (byte-compile-log-lap " %s [%s]\t-->\t%s"
1804 (car lap0) tmp tmp)
1805 (if (eq (car tmp) 'byte-return)
1806 (setcar lap0 'byte-return))
1807 (setcdr lap0 (cdr tmp))
1808 (setq keep-going t))))
1810 ;; goto-*-else-pop X ... X: goto-if-* --> whatever
1811 ;; goto-*-else-pop X ... X: discard --> whatever
1813 ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
1814 byte-goto-if-not-nil-else-pop))
1815 (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
1816 (eval-when-compile
1817 (cons 'byte-discard byte-conditional-ops)))
1818 (not (eq lap0 (car tmp))))
1819 (setq tmp2 (car tmp))
1820 (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
1821 byte-goto-if-nil)
1822 (byte-goto-if-not-nil-else-pop
1823 byte-goto-if-not-nil))))
1824 (if (memq (car tmp2) tmp3)
1825 (progn (setcar lap0 (car tmp2))
1826 (setcdr lap0 (cdr tmp2))
1827 (byte-compile-log-lap " %s-else-pop [%s]\t-->\t%s"
1828 (car lap0) tmp2 lap0))
1829 ;; Get rid of the -else-pop's and jump one step further.
1830 (or (eq 'TAG (car (nth 1 tmp)))
1831 (setcdr tmp (cons (byte-compile-make-tag)
1832 (cdr tmp))))
1833 (byte-compile-log-lap " %s [%s]\t-->\t%s <skip>"
1834 (car lap0) tmp2 (nth 1 tmp3))
1835 (setcar lap0 (nth 1 tmp3))
1836 (setcdr lap0 (nth 1 tmp)))
1837 (setq keep-going t))
1839 ;; const goto-X ... X: goto-if-* --> whatever
1840 ;; const goto-X ... X: discard --> whatever
1842 ((and (eq (car lap0) 'byte-constant)
1843 (eq (car lap1) 'byte-goto)
1844 (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
1845 (eval-when-compile
1846 (cons 'byte-discard byte-conditional-ops)))
1847 (not (eq lap1 (car tmp))))
1848 (setq tmp2 (car tmp))
1849 (cond ((when (consp (cdr lap0))
1850 (memq (car tmp2)
1851 (if (null (car (cdr lap0)))
1852 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
1853 '(byte-goto-if-not-nil
1854 byte-goto-if-not-nil-else-pop))))
1855 (byte-compile-log-lap " %s goto [%s]\t-->\t%s %s"
1856 lap0 tmp2 lap0 tmp2)
1857 (setcar lap1 (car tmp2))
1858 (setcdr lap1 (cdr tmp2))
1859 ;; Let next step fix the (const,goto-if*) sequence.
1860 (setq rest (cons nil rest))
1861 (setq keep-going t))
1862 ((or (consp (cdr lap0))
1863 (eq (car tmp2) 'byte-discard))
1864 ;; Jump one step further
1865 (byte-compile-log-lap
1866 " %s goto [%s]\t-->\t<deleted> goto <skip>"
1867 lap0 tmp2)
1868 (or (eq 'TAG (car (nth 1 tmp)))
1869 (setcdr tmp (cons (byte-compile-make-tag)
1870 (cdr tmp))))
1871 (setcdr lap1 (car (cdr tmp)))
1872 (setq lap (delq lap0 lap))
1873 (setq keep-going t))))
1875 ;; X: varref-Y ... varset-Y goto-X -->
1876 ;; X: varref-Y Z: ... dup varset-Y goto-Z
1877 ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
1878 ;; (This is so usual for while loops that it is worth handling).
1880 ;; Here again, we could do it for stack-ref/stack-set, but
1881 ;; that's replacing a stack-ref-Y with a stack-ref-0, which
1882 ;; is a very minor improvement (if any), at the cost of
1883 ;; more stack use and more byte-code. Let's not do it.
1885 ((and (eq (car lap1) 'byte-varset)
1886 (eq (car lap2) 'byte-goto)
1887 (not (memq (cdr lap2) rest)) ;Backwards jump
1888 (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
1889 'byte-varref)
1890 (eq (cdr (car tmp)) (cdr lap1))
1891 (not (memq (car (cdr lap1)) byte-boolean-vars)))
1892 ;;(byte-compile-log-lap " Pulled %s to end of loop" (car tmp))
1893 (let ((newtag (byte-compile-make-tag)))
1894 (byte-compile-log-lap
1895 " %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
1896 (nth 1 (cdr lap2)) (car tmp)
1897 lap1 lap2
1898 (nth 1 (cdr lap2)) (car tmp)
1899 (nth 1 newtag) 'byte-dup lap1
1900 (cons 'byte-goto newtag)
1902 (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
1903 (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
1904 (setq add-depth 1)
1905 (setq keep-going t))
1907 ;; goto-X Y: ... X: goto-if*-Y --> goto-if-not-*-X+1 Y:
1908 ;; (This can pull the loop test to the end of the loop)
1910 ((and (eq (car lap0) 'byte-goto)
1911 (eq (car lap1) 'TAG)
1912 (eq lap1
1913 (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
1914 (memq (car (car tmp))
1915 '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
1916 byte-goto-if-nil-else-pop)))
1917 ;; (byte-compile-log-lap " %s %s, %s %s --> moved conditional"
1918 ;; lap0 lap1 (cdr lap0) (car tmp))
1919 (let ((newtag (byte-compile-make-tag)))
1920 (byte-compile-log-lap
1921 "%s %s: ... %s: %s\t-->\t%s ... %s:"
1922 lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
1923 (cons (cdr (assq (car (car tmp))
1924 '((byte-goto-if-nil . byte-goto-if-not-nil)
1925 (byte-goto-if-not-nil . byte-goto-if-nil)
1926 (byte-goto-if-nil-else-pop .
1927 byte-goto-if-not-nil-else-pop)
1928 (byte-goto-if-not-nil-else-pop .
1929 byte-goto-if-nil-else-pop))))
1930 newtag)
1932 (nth 1 newtag)
1934 (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
1935 (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
1936 ;; We can handle this case but not the -if-not-nil case,
1937 ;; because we won't know which non-nil constant to push.
1938 (setcdr rest (cons (cons 'byte-constant
1939 (byte-compile-get-constant nil))
1940 (cdr rest))))
1941 (setcar lap0 (nth 1 (memq (car (car tmp))
1942 '(byte-goto-if-nil-else-pop
1943 byte-goto-if-not-nil
1944 byte-goto-if-nil
1945 byte-goto-if-not-nil
1946 byte-goto byte-goto))))
1948 (setq keep-going t))
1950 (setq rest (cdr rest)))
1952 ;; Cleanup stage:
1953 ;; Rebuild byte-compile-constants / byte-compile-variables.
1954 ;; Simple optimizations that would inhibit other optimizations if they
1955 ;; were done in the optimizing loop, and optimizations which there is no
1956 ;; need to do more than once.
1957 (setq byte-compile-constants nil
1958 byte-compile-variables nil)
1959 (setq rest lap)
1960 (byte-compile-log-lap " ---- final pass")
1961 (while rest
1962 (setq lap0 (car rest)
1963 lap1 (nth 1 rest))
1964 (if (memq (car lap0) byte-constref-ops)
1965 (if (memq (car lap0) '(byte-constant byte-constant2))
1966 (unless (memq (cdr lap0) byte-compile-constants)
1967 (setq byte-compile-constants (cons (cdr lap0)
1968 byte-compile-constants)))
1969 (unless (memq (cdr lap0) byte-compile-variables)
1970 (setq byte-compile-variables (cons (cdr lap0)
1971 byte-compile-variables)))))
1972 (cond (;;
1973 ;; const-C varset-X const-C --> const-C dup varset-X
1974 ;; const-C varbind-X const-C --> const-C dup varbind-X
1976 (and (eq (car lap0) 'byte-constant)
1977 (eq (car (nth 2 rest)) 'byte-constant)
1978 (eq (cdr lap0) (cdr (nth 2 rest)))
1979 (memq (car lap1) '(byte-varbind byte-varset)))
1980 (byte-compile-log-lap " %s %s %s\t-->\t%s dup %s"
1981 lap0 lap1 lap0 lap0 lap1)
1982 (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
1983 (setcar (cdr rest) (cons 'byte-dup 0))
1984 (setq add-depth 1))
1986 ;; const-X [dup/const-X ...] --> const-X [dup ...] dup
1987 ;; varref-X [dup/varref-X ...] --> varref-X [dup ...] dup
1989 ((memq (car lap0) '(byte-constant byte-varref))
1990 (setq tmp rest
1991 tmp2 nil)
1992 (while (progn
1993 (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
1994 (and (eq (cdr lap0) (cdr (car tmp)))
1995 (eq (car lap0) (car (car tmp)))))
1996 (setcar tmp (cons 'byte-dup 0))
1997 (setq tmp2 t))
1998 (if tmp2
1999 (byte-compile-log-lap
2000 " %s [dup/%s]...\t-->\t%s dup..." lap0 lap0 lap0)))
2002 ;; unbind-N unbind-M --> unbind-(N+M)
2004 ((and (eq 'byte-unbind (car lap0))
2005 (eq 'byte-unbind (car lap1)))
2006 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
2007 (cons 'byte-unbind
2008 (+ (cdr lap0) (cdr lap1))))
2009 (setq lap (delq lap0 lap))
2010 (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
2013 ;; stack-set-M [discard/discardN ...] --> discardN-preserve-tos
2014 ;; stack-set-M [discard/discardN ...] --> discardN
2016 ((and (eq (car lap0) 'byte-stack-set)
2017 (memq (car lap1) '(byte-discard byte-discardN))
2018 (progn
2019 ;; See if enough discard operations follow to expose or
2020 ;; destroy the value stored by the stack-set.
2021 (setq tmp (cdr rest))
2022 (setq tmp2 (1- (cdr lap0)))
2023 (setq tmp3 0)
2024 (while (memq (car (car tmp)) '(byte-discard byte-discardN))
2025 (setq tmp3
2026 (+ tmp3 (if (eq (car (car tmp)) 'byte-discard)
2028 (cdr (car tmp)))))
2029 (setq tmp (cdr tmp)))
2030 (>= tmp3 tmp2)))
2031 ;; Do the optimization.
2032 (setq lap (delq lap0 lap))
2033 (setcar lap1
2034 (if (= tmp2 tmp3)
2035 ;; The value stored is the new TOS, so pop one more
2036 ;; value (to get rid of the old value) using the
2037 ;; TOS-preserving discard operator.
2038 'byte-discardN-preserve-tos
2039 ;; Otherwise, the value stored is lost, so just use a
2040 ;; normal discard.
2041 'byte-discardN))
2042 (setcdr lap1 (1+ tmp3))
2043 (setcdr (cdr rest) tmp)
2044 (byte-compile-log-lap " %s [discard/discardN]...\t-->\t%s"
2045 lap0 lap1))
2048 ;; discard/discardN/discardN-preserve-tos-X discard/discardN-Y -->
2049 ;; discardN-(X+Y)
2051 ((and (memq (car lap0)
2052 '(byte-discard byte-discardN
2053 byte-discardN-preserve-tos))
2054 (memq (car lap1) '(byte-discard byte-discardN)))
2055 (setq lap (delq lap0 lap))
2056 (byte-compile-log-lap
2057 " %s %s\t-->\t(discardN %s)"
2058 lap0 lap1
2059 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2060 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2061 (setcdr lap1 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2062 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2063 (setcar lap1 'byte-discardN))
2066 ;; discardN-preserve-tos-X discardN-preserve-tos-Y -->
2067 ;; discardN-preserve-tos-(X+Y)
2069 ((and (eq (car lap0) 'byte-discardN-preserve-tos)
2070 (eq (car lap1) 'byte-discardN-preserve-tos))
2071 (setq lap (delq lap0 lap))
2072 (setcdr lap1 (+ (cdr lap0) (cdr lap1)))
2073 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 (car rest)))
2076 ;; discardN-preserve-tos return --> return
2077 ;; dup return --> return
2078 ;; stack-set-N return --> return ; where N is TOS-1
2080 ((and (eq (car lap1) 'byte-return)
2081 (or (memq (car lap0) '(byte-discardN-preserve-tos byte-dup))
2082 (and (eq (car lap0) 'byte-stack-set)
2083 (= (cdr lap0) 1))))
2084 ;; The byte-code interpreter will pop the stack for us, so
2085 ;; we can just leave stuff on it.
2086 (setq lap (delq lap0 lap))
2087 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 lap1))
2089 (setq rest (cdr rest)))
2090 (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
2091 lap)
2093 (provide 'byte-opt)
2096 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
2097 ;; itself, compile some of its most used recursive functions (at load time).
2099 (eval-when-compile
2100 (or (byte-code-function-p (symbol-function 'byte-optimize-form))
2101 (assq 'byte-code (symbol-function 'byte-optimize-form))
2102 (let ((byte-optimize nil)
2103 (byte-compile-warnings nil))
2104 (mapc (lambda (x)
2105 (or noninteractive (message "compiling %s..." x))
2106 (byte-compile x)
2107 (or noninteractive (message "compiling %s...done" x)))
2108 '(byte-optimize-form
2109 byte-optimize-body
2110 byte-optimize-predicate
2111 byte-optimize-binary-predicate
2112 ;; Inserted some more than necessary, to speed it up.
2113 byte-optimize-form-code-walker
2114 byte-optimize-lapcode))))
2115 nil)
2117 ;;; byte-opt.el ends here