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