]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/byte-opt.el
Reduce use of (require 'cl).
[gnu-emacs] / lisp / emacs-lisp / byte-opt.el
1 ;;; byte-opt.el --- the optimization passes of the emacs-lisp byte compiler -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1991, 1994, 2000-2012 Free Software Foundation, Inc.
4
5 ;; Author: Jamie Zawinski <jwz@lucid.com>
6 ;; Hallvard Furuseth <hbf@ulrik.uio.no>
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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."
31 ;;
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.
36 ;;
37
38 ;; TO DO:
39 ;;
40 ;; (apply (lambda (x &rest y) ...) 1 (foo))
41 ;;
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?
60 ;;
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...
69 ;;
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.
83 ;;
84 ;; collapse common subexpressions
85 ;;
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))
91 ;;
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.
98 ;;
99 ;; Here is an example of an Emacs Lisp function which could safely be
100 ;; byte-compiled tail-recursively:
101 ;;
102 ;; (defun tail-map (fn list)
103 ;; (cond (list
104 ;; (funcall fn (car list))
105 ;; (tail-map fn (cdr list)))))
106 ;;
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.
111 ;;
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)
116 ;;
117 ;; this also can be considered tail recursion:
118 ;;
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)
122 ;;
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.
128 ;;
129 ;; Wouldn't it be nice if Emacs Lisp had lexical scope.
130 ;;
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.
141 ;;
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.)
147
148 ;; Other things to consider:
149
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)
153
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.
157
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:
166
167 ;; (disassemble (lambda (x) (eq (if (point) 'a 'b) 'c)))
168 ;; (disassemble (lambda (x) (if (point) (eq 'a 'c) (eq 'b 'c))))
169
170 ;; ;; (car (cons A B)) -> (prog1 A B)
171 ;; (disassemble (lambda (x) (car (cons (foo) 42))))
172
173 ;; ;; (cdr (cons A B)) -> (progn A B)
174 ;; (disassemble (lambda (x) (cdr (cons 42 (foo)))))
175
176 ;; ;; (car (list A B ...)) -> (prog1 A B ...)
177 ;; (disassemble (lambda (x) (car (list (foo) 42 (bar)))))
178
179 ;; ;; (cdr (list A B ...)) -> (progn A (list B ...))
180 ;; (disassemble (lambda (x) (cdr (list 42 (foo) (bar)))))
181
182
183 ;;; Code:
184
185 (require 'bytecomp)
186 (eval-when-compile (require 'cl-lib))
187 (require 'macroexp)
188
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))))
218 c
219 (format "(%s %s)" c a))))
220 args)))))
221
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)))
225
226 \f
227 ;;; byte-compile optimizers to support inlining
228
229 (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
230
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))))
247
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 (and (consp fn) (eq (car fn) 'autoload))
253 (load (nth 1 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))))
293
294 (t ;; Give up on inlining.
295 form))))
296
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))
340 (t
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)
351
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)))
356
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)))))
363
364 \f
365 ;;; implementing source-level optimizers
366
367 (defun byte-optimize-form-code-walker (form for-effect)
368 ;;
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.)
374 ;;
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)))))
441
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)))
448
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))))
455
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)))))
464
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)))))
484
485 ((eq fn 'interactive)
486 (byte-compile-warn "misplaced interactive spec: `%s'"
487 (prin1-to-string form))
488 nil)
489
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)
494
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)))))
504
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)))))
513
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))))
520
521 ;; Needed as long as we run byte-optimize-form after cconv.
522 ((eq fn 'internal-make-closure) form)
523
524 ((byte-code-function-p fn)
525 (cons fn (mapcar #'byte-optimize-form (cdr form))))
526
527 ((not (symbolp fn))
528 (byte-compile-warn "`%s' is a malformed function"
529 (prin1-to-string fn))
530 form)
531
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))
555
556 (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)))))))
565
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))
574
575 (defun byte-optimize-form (form &optional for-effect)
576 "The source-level pass of the optimizer."
577 ;;
578 ;; First, optimize all sub-forms of this one.
579 (setq form (byte-optimize-form-code-walker form for-effect))
580 ;;
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.
585 ;;
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) 'byte-for-effect-optimizer)))
592 (setq opt (get (car form) 'byte-optimizer)))
593 (not (eq form (setq new (funcall opt form)))))
594 (progn
595 ;; (if (equal form new) (error "bogus optimizer -- %s" opt))
596 (byte-compile-log " %s\t==>\t%s" form new)
597 (setq new (byte-optimize-form new for-effect))
598 new)
599 form)))
600
601
602 (defun byte-optimize-body (forms all-for-effect)
603 ;; Optimize the cdr of a progn or implicit progn; all forms is a list of
604 ;; forms, all but the last of which are optimized with the assumption that
605 ;; they are being called for effect. the last is for-effect as well if
606 ;; all-for-effect is true. returns a new list of forms.
607 (let ((rest forms)
608 (result nil)
609 fe new)
610 (while rest
611 (setq fe (or all-for-effect (cdr rest)))
612 (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
613 (if (or new (not fe))
614 (setq result (cons new result)))
615 (setq rest (cdr rest)))
616 (nreverse result)))
617
618 \f
619 ;; some source-level optimizers
620 ;;
621 ;; when writing optimizers, be VERY careful that the optimizer returns
622 ;; something not EQ to its argument if and ONLY if it has made a change.
623 ;; This implies that you cannot simply destructively modify the list;
624 ;; you must return something not EQ to it if you make an optimization.
625 ;;
626 ;; It is now safe to optimize code such that it introduces new bindings.
627
628 (defsubst byte-compile-trueconstp (form)
629 "Return non-nil if FORM always evaluates to a non-nil value."
630 (while (eq (car-safe form) 'progn)
631 (setq form (car (last (cdr form)))))
632 (cond ((consp form)
633 (pcase (car form)
634 (`quote (cadr form))
635 ;; Can't use recursion in a defsubst.
636 ;; (`progn (byte-compile-trueconstp (car (last (cdr form)))))
637 ))
638 ((not (symbolp form)))
639 ((eq form t))
640 ((keywordp form))))
641
642 (defsubst byte-compile-nilconstp (form)
643 "Return non-nil if FORM always evaluates to a nil value."
644 (while (eq (car-safe form) 'progn)
645 (setq form (car (last (cdr form)))))
646 (cond ((consp form)
647 (pcase (car form)
648 (`quote (null (cadr form)))
649 ;; Can't use recursion in a defsubst.
650 ;; (`progn (byte-compile-nilconstp (car (last (cdr form)))))
651 ))
652 ((not (symbolp form)) nil)
653 ((null form))))
654
655 ;; If the function is being called with constant numeric args,
656 ;; evaluate as much as possible at compile-time. This optimizer
657 ;; assumes that the function is associative, like + or *.
658 (defun byte-optimize-associative-math (form)
659 (let ((args nil)
660 (constants nil)
661 (rest (cdr form)))
662 (while rest
663 (if (numberp (car rest))
664 (setq constants (cons (car rest) constants))
665 (setq args (cons (car rest) args)))
666 (setq rest (cdr rest)))
667 (if (cdr constants)
668 (if args
669 (list (car form)
670 (apply (car form) constants)
671 (if (cdr args)
672 (cons (car form) (nreverse args))
673 (car args)))
674 (apply (car form) constants))
675 form)))
676
677 ;; If the function is being called with constant numeric args,
678 ;; evaluate as much as possible at compile-time. This optimizer
679 ;; assumes that the function satisfies
680 ;; (op x1 x2 ... xn) == (op ...(op (op x1 x2) x3) ...xn)
681 ;; like - and /.
682 (defun byte-optimize-nonassociative-math (form)
683 (if (or (not (numberp (car (cdr form))))
684 (not (numberp (car (cdr (cdr form))))))
685 form
686 (let ((constant (car (cdr form)))
687 (rest (cdr (cdr form))))
688 (while (numberp (car rest))
689 (setq constant (funcall (car form) constant (car rest))
690 rest (cdr rest)))
691 (if rest
692 (cons (car form) (cons constant rest))
693 constant))))
694
695 ;;(defun byte-optimize-associative-two-args-math (form)
696 ;; (setq form (byte-optimize-associative-math form))
697 ;; (if (consp form)
698 ;; (byte-optimize-two-args-left form)
699 ;; form))
700
701 ;;(defun byte-optimize-nonassociative-two-args-math (form)
702 ;; (setq form (byte-optimize-nonassociative-math form))
703 ;; (if (consp form)
704 ;; (byte-optimize-two-args-right form)
705 ;; form))
706
707 (defun byte-optimize-approx-equal (x y)
708 (<= (* (abs (- x y)) 100) (abs (+ x y))))
709
710 ;; Collect all the constants from FORM, after the STARTth arg,
711 ;; and apply FUN to them to make one argument at the end.
712 ;; For functions that can handle floats, that optimization
713 ;; can be incorrect because reordering can cause an overflow
714 ;; that would otherwise be avoided by encountering an arg that is a float.
715 ;; We avoid this problem by (1) not moving float constants and
716 ;; (2) not moving anything if it would cause an overflow.
717 (defun byte-optimize-delay-constants-math (form start fun)
718 ;; Merge all FORM's constants from number START, call FUN on them
719 ;; and put the result at the end.
720 (let ((rest (nthcdr (1- start) form))
721 (orig form)
722 ;; t means we must check for overflow.
723 (overflow (memq fun '(+ *))))
724 (while (cdr (setq rest (cdr rest)))
725 (if (integerp (car rest))
726 (let (constants)
727 (setq form (copy-sequence form)
728 rest (nthcdr (1- start) form))
729 (while (setq rest (cdr rest))
730 (cond ((integerp (car rest))
731 (setq constants (cons (car rest) constants))
732 (setcar rest nil))))
733 ;; If necessary, check now for overflow
734 ;; that might be caused by reordering.
735 (if (and overflow
736 ;; We have overflow if the result of doing the arithmetic
737 ;; on floats is not even close to the result
738 ;; of doing it on integers.
739 (not (byte-optimize-approx-equal
740 (apply fun (mapcar 'float constants))
741 (float (apply fun constants)))))
742 (setq form orig)
743 (setq form (nconc (delq nil form)
744 (list (apply fun (nreverse constants)))))))))
745 form))
746
747 (defsubst byte-compile-butlast (form)
748 (nreverse (cdr (reverse form))))
749
750 (defun byte-optimize-plus (form)
751 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
752 ;;(setq form (byte-optimize-delay-constants-math form 1 '+))
753 (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
754 ;; For (+ constants...), byte-optimize-predicate does the work.
755 (when (memq nil (mapcar 'numberp (cdr form)))
756 (cond
757 ;; (+ x 1) --> (1+ x) and (+ x -1) --> (1- x).
758 ((and (= (length form) 3)
759 (or (memq (nth 1 form) '(1 -1))
760 (memq (nth 2 form) '(1 -1))))
761 (let (integer other)
762 (if (memq (nth 1 form) '(1 -1))
763 (setq integer (nth 1 form) other (nth 2 form))
764 (setq integer (nth 2 form) other (nth 1 form)))
765 (setq form
766 (list (if (eq integer 1) '1+ '1-) other))))
767 ;; Here, we could also do
768 ;; (+ x y ... 1) --> (1+ (+ x y ...))
769 ;; (+ x y ... -1) --> (1- (+ x y ...))
770 ;; The resulting bytecode is smaller, but is it faster? -- cyd
771 ))
772 (byte-optimize-predicate form))
773
774 (defun byte-optimize-minus (form)
775 ;; Don't call `byte-optimize-delay-constants-math' (bug#1334).
776 ;;(setq form (byte-optimize-delay-constants-math form 2 '+))
777 ;; Remove zeros.
778 (when (and (nthcdr 3 form)
779 (memq 0 (cddr form)))
780 (setq form (nconc (list (car form) (cadr form))
781 (delq 0 (copy-sequence (cddr form)))))
782 ;; After the above, we must turn (- x) back into (- x 0)
783 (or (cddr form)
784 (setq form (nconc form (list 0)))))
785 ;; For (- constants..), byte-optimize-predicate does the work.
786 (when (memq nil (mapcar 'numberp (cdr form)))
787 (cond
788 ;; (- x 1) --> (1- x)
789 ((equal (nthcdr 2 form) '(1))
790 (setq form (list '1- (nth 1 form))))
791 ;; (- x -1) --> (1+ x)
792 ((equal (nthcdr 2 form) '(-1))
793 (setq form (list '1+ (nth 1 form))))
794 ;; (- 0 x) --> (- x)
795 ((and (eq (nth 1 form) 0)
796 (= (length form) 3))
797 (setq form (list '- (nth 2 form))))
798 ;; Here, we could also do
799 ;; (- x y ... 1) --> (1- (- x y ...))
800 ;; (- x y ... -1) --> (1+ (- x y ...))
801 ;; The resulting bytecode is smaller, but is it faster? -- cyd
802 ))
803 (byte-optimize-predicate form))
804
805 (defun byte-optimize-multiply (form)
806 (setq form (byte-optimize-delay-constants-math form 1 '*))
807 ;; For (* constants..), byte-optimize-predicate does the work.
808 (when (memq nil (mapcar 'numberp (cdr form)))
809 ;; After `byte-optimize-predicate', if there is a INTEGER constant
810 ;; in FORM, it is in the last element.
811 (let ((last (car (reverse (cdr form)))))
812 (cond
813 ;; Would handling (* ... 0) here cause floating point errors?
814 ;; See bug#1334.
815 ((eq 1 last) (setq form (byte-compile-butlast form)))
816 ((eq -1 last)
817 (setq form (list '- (if (nthcdr 3 form)
818 (byte-compile-butlast form)
819 (nth 1 form))))))))
820 (byte-optimize-predicate form))
821
822 (defun byte-optimize-divide (form)
823 (setq form (byte-optimize-delay-constants-math form 2 '*))
824 ;; After `byte-optimize-predicate', if there is a INTEGER constant
825 ;; in FORM, it is in the last element.
826 (let ((last (car (reverse (cdr (cdr form))))))
827 (cond
828 ;; Runtime error (leave it intact).
829 ((or (null last)
830 (eq last 0)
831 (memql 0.0 (cddr form))))
832 ;; No constants in expression
833 ((not (numberp last)))
834 ;; For (* constants..), byte-optimize-predicate does the work.
835 ((null (memq nil (mapcar 'numberp (cdr form)))))
836 ;; (/ x y.. 1) --> (/ x y..)
837 ((and (eq last 1) (nthcdr 3 form))
838 (setq form (byte-compile-butlast form)))
839 ;; (/ x -1), (/ x .. -1) --> (- x), (- (/ x ..))
840 ((eq last -1)
841 (setq form (list '- (if (nthcdr 3 form)
842 (byte-compile-butlast form)
843 (nth 1 form)))))))
844 (byte-optimize-predicate form))
845
846 (defun byte-optimize-logmumble (form)
847 (setq form (byte-optimize-delay-constants-math form 1 (car form)))
848 (byte-optimize-predicate
849 (cond ((memq 0 form)
850 (setq form (if (eq (car form) 'logand)
851 (cons 'progn (cdr form))
852 (delq 0 (copy-sequence form)))))
853 ((and (eq (car-safe form) 'logior)
854 (memq -1 form))
855 (cons 'progn (cdr form)))
856 (form))))
857
858
859 (defun byte-optimize-binary-predicate (form)
860 (if (macroexp-const-p (nth 1 form))
861 (if (macroexp-const-p (nth 2 form))
862 (condition-case ()
863 (list 'quote (eval form))
864 (error form))
865 ;; This can enable some lapcode optimizations.
866 (list (car form) (nth 2 form) (nth 1 form)))
867 form))
868
869 (defun byte-optimize-predicate (form)
870 (let ((ok t)
871 (rest (cdr form)))
872 (while (and rest ok)
873 (setq ok (macroexp-const-p (car rest))
874 rest (cdr rest)))
875 (if ok
876 (condition-case ()
877 (list 'quote (eval form))
878 (error form))
879 form)))
880
881 (defun byte-optimize-identity (form)
882 (if (and (cdr form) (null (cdr (cdr form))))
883 (nth 1 form)
884 (byte-compile-warn "identity called with %d arg%s, but requires 1"
885 (length (cdr form))
886 (if (= 1 (length (cdr form))) "" "s"))
887 form))
888
889 (put 'identity 'byte-optimizer 'byte-optimize-identity)
890
891 (put '+ 'byte-optimizer 'byte-optimize-plus)
892 (put '* 'byte-optimizer 'byte-optimize-multiply)
893 (put '- 'byte-optimizer 'byte-optimize-minus)
894 (put '/ 'byte-optimizer 'byte-optimize-divide)
895 (put 'max 'byte-optimizer 'byte-optimize-associative-math)
896 (put 'min 'byte-optimizer 'byte-optimize-associative-math)
897
898 (put '= 'byte-optimizer 'byte-optimize-binary-predicate)
899 (put 'eq 'byte-optimizer 'byte-optimize-binary-predicate)
900 (put 'equal 'byte-optimizer 'byte-optimize-binary-predicate)
901 (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
902 (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
903
904 (put '< 'byte-optimizer 'byte-optimize-predicate)
905 (put '> 'byte-optimizer 'byte-optimize-predicate)
906 (put '<= 'byte-optimizer 'byte-optimize-predicate)
907 (put '>= 'byte-optimizer 'byte-optimize-predicate)
908 (put '1+ 'byte-optimizer 'byte-optimize-predicate)
909 (put '1- 'byte-optimizer 'byte-optimize-predicate)
910 (put 'not 'byte-optimizer 'byte-optimize-predicate)
911 (put 'null 'byte-optimizer 'byte-optimize-predicate)
912 (put 'memq 'byte-optimizer 'byte-optimize-predicate)
913 (put 'consp 'byte-optimizer 'byte-optimize-predicate)
914 (put 'listp 'byte-optimizer 'byte-optimize-predicate)
915 (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
916 (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
917 (put 'string< 'byte-optimizer 'byte-optimize-predicate)
918 (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
919
920 (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
921 (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
922 (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
923 (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
924
925 (put 'car 'byte-optimizer 'byte-optimize-predicate)
926 (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
927 (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
928 (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
929
930
931 ;; I'm not convinced that this is necessary. Doesn't the optimizer loop
932 ;; take care of this? - Jamie
933 ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
934 ;; so arithmetic optimizers recognize the numeric constant. - Hallvard
935 (put 'quote 'byte-optimizer 'byte-optimize-quote)
936 (defun byte-optimize-quote (form)
937 (if (or (consp (nth 1 form))
938 (and (symbolp (nth 1 form))
939 (not (macroexp--const-symbol-p form))))
940 form
941 (nth 1 form)))
942
943 (defun byte-optimize-zerop (form)
944 (cond ((numberp (nth 1 form))
945 (eval form))
946 (byte-compile-delete-errors
947 (list '= (nth 1 form) 0))
948 (form)))
949
950 (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
951
952 (defun byte-optimize-and (form)
953 ;; Simplify if less than 2 args.
954 ;; if there is a literal nil in the args to `and', throw it and following
955 ;; forms away, and surround the `and' with (progn ... nil).
956 (cond ((null (cdr form)))
957 ((memq nil form)
958 (list 'progn
959 (byte-optimize-and
960 (prog1 (setq form (copy-sequence form))
961 (while (nth 1 form)
962 (setq form (cdr form)))
963 (setcdr form nil)))
964 nil))
965 ((null (cdr (cdr form)))
966 (nth 1 form))
967 ((byte-optimize-predicate form))))
968
969 (defun byte-optimize-or (form)
970 ;; Throw away nil's, and simplify if less than 2 args.
971 ;; If there is a literal non-nil constant in the args to `or', throw away all
972 ;; following forms.
973 (if (memq nil form)
974 (setq form (delq nil (copy-sequence form))))
975 (let ((rest form))
976 (while (cdr (setq rest (cdr rest)))
977 (if (byte-compile-trueconstp (car rest))
978 (setq form (copy-sequence form)
979 rest (setcdr (memq (car rest) form) nil))))
980 (if (cdr (cdr form))
981 (byte-optimize-predicate form)
982 (nth 1 form))))
983
984 (defun byte-optimize-cond (form)
985 ;; if any clauses have a literal nil as their test, throw them away.
986 ;; if any clause has a literal non-nil constant as its test, throw
987 ;; away all following clauses.
988 (let (rest)
989 ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
990 (while (setq rest (assq nil (cdr form)))
991 (setq form (delq rest (copy-sequence form))))
992 (if (memq nil (cdr form))
993 (setq form (delq nil (copy-sequence form))))
994 (setq rest form)
995 (while (setq rest (cdr rest))
996 (cond ((byte-compile-trueconstp (car-safe (car rest)))
997 ;; This branch will always be taken: kill the subsequent ones.
998 (cond ((eq rest (cdr form)) ;First branch of `cond'.
999 (setq form `(progn ,@(car rest))))
1000 ((cdr rest)
1001 (setq form (copy-sequence form))
1002 (setcdr (memq (car rest) form) nil)))
1003 (setq rest nil))
1004 ((and (consp (car rest))
1005 (byte-compile-nilconstp (caar rest)))
1006 ;; This branch will never be taken: kill its body.
1007 (setcdr (car rest) nil)))))
1008 ;;
1009 ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
1010 (if (eq 'cond (car-safe form))
1011 (let ((clauses (cdr form)))
1012 (if (and (consp (car clauses))
1013 (null (cdr (car clauses))))
1014 (list 'or (car (car clauses))
1015 (byte-optimize-cond
1016 (cons (car form) (cdr (cdr form)))))
1017 form))
1018 form))
1019
1020 (defun byte-optimize-if (form)
1021 ;; (if (progn <insts> <test>) <rest>) ==> (progn <insts> (if <test> <rest>))
1022 ;; (if <true-constant> <then> <else...>) ==> <then>
1023 ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
1024 ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
1025 ;; (if <test> <then> nil) ==> (if <test> <then>)
1026 (let ((clause (nth 1 form)))
1027 (cond ((and (eq (car-safe clause) 'progn)
1028 ;; `clause' is a proper list.
1029 (null (cdr (last clause))))
1030 (if (null (cddr clause))
1031 ;; A trivial `progn'.
1032 (byte-optimize-if `(if ,(cadr clause) ,@(nthcdr 2 form)))
1033 (nconc (butlast clause)
1034 (list
1035 (byte-optimize-if
1036 `(if ,(car (last clause)) ,@(nthcdr 2 form)))))))
1037 ((byte-compile-trueconstp clause)
1038 `(progn ,clause ,(nth 2 form)))
1039 ((byte-compile-nilconstp clause)
1040 `(progn ,clause ,@(nthcdr 3 form)))
1041 ((nth 2 form)
1042 (if (equal '(nil) (nthcdr 3 form))
1043 (list 'if clause (nth 2 form))
1044 form))
1045 ((or (nth 3 form) (nthcdr 4 form))
1046 (list 'if
1047 ;; Don't make a double negative;
1048 ;; instead, take away the one that is there.
1049 (if (and (consp clause) (memq (car clause) '(not null))
1050 (= (length clause) 2)) ; (not xxxx) or (not (xxxx))
1051 (nth 1 clause)
1052 (list 'not clause))
1053 (if (nthcdr 4 form)
1054 (cons 'progn (nthcdr 3 form))
1055 (nth 3 form))))
1056 (t
1057 (list 'progn clause nil)))))
1058
1059 (defun byte-optimize-while (form)
1060 (when (< (length form) 2)
1061 (byte-compile-warn "too few arguments for `while'"))
1062 (if (nth 1 form)
1063 form))
1064
1065 (put 'and 'byte-optimizer 'byte-optimize-and)
1066 (put 'or 'byte-optimizer 'byte-optimize-or)
1067 (put 'cond 'byte-optimizer 'byte-optimize-cond)
1068 (put 'if 'byte-optimizer 'byte-optimize-if)
1069 (put 'while 'byte-optimizer 'byte-optimize-while)
1070
1071 ;; byte-compile-negation-optimizer lives in bytecomp.el
1072 (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
1073 (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
1074 (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
1075
1076
1077 (defun byte-optimize-funcall (form)
1078 ;; (funcall (lambda ...) ...) ==> ((lambda ...) ...)
1079 ;; (funcall foo ...) ==> (foo ...)
1080 (let ((fn (nth 1 form)))
1081 (if (memq (car-safe fn) '(quote function))
1082 (cons (nth 1 fn) (cdr (cdr form)))
1083 form)))
1084
1085 (defun byte-optimize-apply (form)
1086 ;; If the last arg is a literal constant, turn this into a funcall.
1087 ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
1088 (let ((fn (nth 1 form))
1089 (last (nth (1- (length form)) form))) ; I think this really is fastest
1090 (or (if (or (null last)
1091 (eq (car-safe last) 'quote))
1092 (if (listp (nth 1 last))
1093 (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
1094 (nconc (list 'funcall fn) butlast
1095 (mapcar (lambda (x) (list 'quote x)) (nth 1 last))))
1096 (byte-compile-warn
1097 "last arg to apply can't be a literal atom: `%s'"
1098 (prin1-to-string last))
1099 nil))
1100 form)))
1101
1102 (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
1103 (put 'apply 'byte-optimizer 'byte-optimize-apply)
1104
1105
1106 (put 'let 'byte-optimizer 'byte-optimize-letX)
1107 (put 'let* 'byte-optimizer 'byte-optimize-letX)
1108 (defun byte-optimize-letX (form)
1109 (cond ((null (nth 1 form))
1110 ;; No bindings
1111 (cons 'progn (cdr (cdr form))))
1112 ((or (nth 2 form) (nthcdr 3 form))
1113 form)
1114 ;; The body is nil
1115 ((eq (car form) 'let)
1116 (append '(progn) (mapcar 'car-safe (mapcar 'cdr-safe (nth 1 form)))
1117 '(nil)))
1118 (t
1119 (let ((binds (reverse (nth 1 form))))
1120 (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
1121
1122
1123 (put 'nth 'byte-optimizer 'byte-optimize-nth)
1124 (defun byte-optimize-nth (form)
1125 (if (= (safe-length form) 3)
1126 (if (memq (nth 1 form) '(0 1))
1127 (list 'car (if (zerop (nth 1 form))
1128 (nth 2 form)
1129 (list 'cdr (nth 2 form))))
1130 (byte-optimize-predicate form))
1131 form))
1132
1133 (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
1134 (defun byte-optimize-nthcdr (form)
1135 (if (= (safe-length form) 3)
1136 (if (memq (nth 1 form) '(0 1 2))
1137 (let ((count (nth 1 form)))
1138 (setq form (nth 2 form))
1139 (while (>= (setq count (1- count)) 0)
1140 (setq form (list 'cdr form)))
1141 form)
1142 (byte-optimize-predicate form))
1143 form))
1144
1145 ;; Fixme: delete-char -> delete-region (byte-coded)
1146 ;; optimize string-as-unibyte, string-as-multibyte, string-make-unibyte,
1147 ;; string-make-multibyte for constant args.
1148
1149 (put 'set 'byte-optimizer 'byte-optimize-set)
1150 (defun byte-optimize-set (form)
1151 (let ((var (car-safe (cdr-safe form))))
1152 (cond
1153 ((and (eq (car-safe var) 'quote) (consp (cdr var)))
1154 `(setq ,(cadr var) ,@(cddr form)))
1155 ((and (eq (car-safe var) 'make-local-variable)
1156 (eq (car-safe (setq var (car-safe (cdr var)))) 'quote)
1157 (consp (cdr var)))
1158 `(progn ,(cadr form) (setq ,(cadr var) ,@(cddr form))))
1159 (t form))))
1160 \f
1161 ;; enumerating those functions which need not be called if the returned
1162 ;; value is not used. That is, something like
1163 ;; (progn (list (something-with-side-effects) (yow))
1164 ;; (foo))
1165 ;; may safely be turned into
1166 ;; (progn (progn (something-with-side-effects) (yow))
1167 ;; (foo))
1168 ;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
1169
1170 ;; Some of these functions have the side effect of allocating memory
1171 ;; and it would be incorrect to replace two calls with one.
1172 ;; But we don't try to do those kinds of optimizations,
1173 ;; so it is safe to list such functions here.
1174 ;; Some of these functions return values that depend on environment
1175 ;; state, so that constant folding them would be wrong,
1176 ;; but we don't do constant folding based on this list.
1177
1178 ;; However, at present the only optimization we normally do
1179 ;; is delete calls that need not occur, and we only do that
1180 ;; with the error-free functions.
1181
1182 ;; I wonder if I missed any :-\)
1183 (let ((side-effect-free-fns
1184 '(% * + - / /= 1+ 1- < <= = > >= abs acos append aref ash asin atan
1185 assoc assq
1186 boundp buffer-file-name buffer-local-variables buffer-modified-p
1187 buffer-substring byte-code-function-p
1188 capitalize car-less-than-car car cdr ceiling char-after char-before
1189 char-equal char-to-string char-width
1190 compare-strings concat coordinates-in-window-p
1191 copy-alist copy-sequence copy-marker cos count-lines
1192 decode-char
1193 decode-time default-boundp default-value documentation downcase
1194 elt encode-char exp expt encode-time error-message-string
1195 fboundp fceiling featurep ffloor
1196 file-directory-p file-exists-p file-locked-p file-name-absolute-p
1197 file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
1198 float float-time floor format format-time-string frame-visible-p
1199 fround ftruncate
1200 get gethash get-buffer get-buffer-window getenv get-file-buffer
1201 hash-table-count
1202 int-to-string intern-soft
1203 keymap-parent
1204 length local-variable-if-set-p local-variable-p log log10 logand
1205 logb logior lognot logxor lsh langinfo
1206 make-list make-string make-symbol
1207 marker-buffer max member memq min mod multibyte-char-to-unibyte
1208 next-window nth nthcdr number-to-string
1209 parse-colon-path plist-get plist-member
1210 prefix-numeric-value previous-window prin1-to-string propertize
1211 degrees-to-radians
1212 radians-to-degrees rassq rassoc read-from-string regexp-quote
1213 region-beginning region-end reverse round
1214 sin sqrt string string< string= string-equal string-lessp string-to-char
1215 string-to-int string-to-number substring sxhash symbol-function
1216 symbol-name symbol-plist symbol-value string-make-unibyte
1217 string-make-multibyte string-as-multibyte string-as-unibyte
1218 string-to-multibyte
1219 tan truncate
1220 unibyte-char-to-multibyte upcase user-full-name
1221 user-login-name user-original-login-name custom-variable-p
1222 vconcat
1223 window-buffer window-dedicated-p window-edges window-height
1224 window-hscroll window-minibuffer-p window-width
1225 zerop))
1226 (side-effect-and-error-free-fns
1227 '(arrayp atom
1228 bobp bolp bool-vector-p
1229 buffer-end buffer-list buffer-size buffer-string bufferp
1230 car-safe case-table-p cdr-safe char-or-string-p characterp
1231 charsetp commandp cons consp
1232 current-buffer current-global-map current-indentation
1233 current-local-map current-minor-mode-maps current-time
1234 current-time-string current-time-zone
1235 eobp eolp eq equal eventp
1236 floatp following-char framep
1237 get-largest-window get-lru-window
1238 hash-table-p
1239 identity ignore integerp integer-or-marker-p interactive-p
1240 invocation-directory invocation-name
1241 keymapp
1242 line-beginning-position line-end-position list listp
1243 make-marker mark mark-marker markerp max-char
1244 memory-limit minibuffer-window
1245 mouse-movement-p
1246 natnump nlistp not null number-or-marker-p numberp
1247 one-window-p overlayp
1248 point point-marker point-min point-max preceding-char primary-charset
1249 processp
1250 recent-keys recursion-depth
1251 safe-length selected-frame selected-window sequencep
1252 standard-case-table standard-syntax-table stringp subrp symbolp
1253 syntax-table syntax-table-p
1254 this-command-keys this-command-keys-vector this-single-command-keys
1255 this-single-command-raw-keys
1256 user-real-login-name user-real-uid user-uid
1257 vector vectorp visible-frame-list
1258 wholenump window-configuration-p window-live-p windowp)))
1259 (while side-effect-free-fns
1260 (put (car side-effect-free-fns) 'side-effect-free t)
1261 (setq side-effect-free-fns (cdr side-effect-free-fns)))
1262 (while side-effect-and-error-free-fns
1263 (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
1264 (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
1265 nil)
1266
1267 \f
1268 ;; pure functions are side-effect free functions whose values depend
1269 ;; only on their arguments. For these functions, calls with constant
1270 ;; arguments can be evaluated at compile time. This may shift run time
1271 ;; errors to compile time.
1272
1273 (let ((pure-fns
1274 '(concat symbol-name regexp-opt regexp-quote string-to-syntax)))
1275 (while pure-fns
1276 (put (car pure-fns) 'pure t)
1277 (setq pure-fns (cdr pure-fns)))
1278 nil)
1279 \f
1280 (defconst byte-constref-ops
1281 '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
1282
1283 ;; Used and set dynamically in byte-decompile-bytecode-1.
1284 (defvar bytedecomp-op)
1285 (defvar bytedecomp-ptr)
1286
1287 ;; This function extracts the bitfields from variable-length opcodes.
1288 ;; Originally defined in disass.el (which no longer uses it.)
1289 (defun disassemble-offset (bytes)
1290 "Don't call this!"
1291 ;; Fetch and return the offset for the current opcode.
1292 ;; Return nil if this opcode has no offset.
1293 (cond ((< bytedecomp-op byte-nth)
1294 (let ((tem (logand bytedecomp-op 7)))
1295 (setq bytedecomp-op (logand bytedecomp-op 248))
1296 (cond ((eq tem 6)
1297 ;; Offset in next byte.
1298 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1299 (aref bytes bytedecomp-ptr))
1300 ((eq tem 7)
1301 ;; Offset in next 2 bytes.
1302 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1303 (+ (aref bytes bytedecomp-ptr)
1304 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1305 (lsh (aref bytes bytedecomp-ptr) 8))))
1306 (t tem)))) ;Offset was in opcode.
1307 ((>= bytedecomp-op byte-constant)
1308 (prog1 (- bytedecomp-op byte-constant) ;Offset in opcode.
1309 (setq bytedecomp-op byte-constant)))
1310 ((or (and (>= bytedecomp-op byte-constant2)
1311 (<= bytedecomp-op byte-goto-if-not-nil-else-pop))
1312 (= bytedecomp-op byte-stack-set2))
1313 ;; Offset in next 2 bytes.
1314 (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1315 (+ (aref bytes bytedecomp-ptr)
1316 (progn (setq bytedecomp-ptr (1+ bytedecomp-ptr))
1317 (lsh (aref bytes bytedecomp-ptr) 8))))
1318 ((and (>= bytedecomp-op byte-listN)
1319 (<= bytedecomp-op byte-discardN))
1320 (setq bytedecomp-ptr (1+ bytedecomp-ptr)) ;Offset in next byte.
1321 (aref bytes bytedecomp-ptr))))
1322
1323 (defvar byte-compile-tag-number)
1324
1325 ;; This de-compiler is used for inline expansion of compiled functions,
1326 ;; and by the disassembler.
1327 ;;
1328 ;; This list contains numbers, which are pc values,
1329 ;; before each instruction.
1330 (defun byte-decompile-bytecode (bytes constvec)
1331 "Turn BYTECODE into lapcode, referring to CONSTVEC."
1332 (let ((byte-compile-constants nil)
1333 (byte-compile-variables nil)
1334 (byte-compile-tag-number 0))
1335 (byte-decompile-bytecode-1 bytes constvec)))
1336
1337 ;; As byte-decompile-bytecode, but updates
1338 ;; byte-compile-{constants, variables, tag-number}.
1339 ;; If MAKE-SPLICEABLE is true, then `return' opcodes are replaced
1340 ;; with `goto's destined for the end of the code.
1341 ;; That is for use by the compiler.
1342 ;; If MAKE-SPLICEABLE is nil, we are being called for the disassembler.
1343 ;; In that case, we put a pc value into the list
1344 ;; before each insn (or its label).
1345 (defun byte-decompile-bytecode-1 (bytes constvec &optional make-spliceable)
1346 (let ((length (length bytes))
1347 (bytedecomp-ptr 0) optr tags bytedecomp-op offset
1348 lap tmp)
1349 (while (not (= bytedecomp-ptr length))
1350 (or make-spliceable
1351 (push bytedecomp-ptr lap))
1352 (setq bytedecomp-op (aref bytes bytedecomp-ptr)
1353 optr bytedecomp-ptr
1354 ;; This uses dynamic-scope magic.
1355 offset (disassemble-offset bytes))
1356 (let ((opcode (aref byte-code-vector bytedecomp-op)))
1357 (cl-assert opcode)
1358 (setq bytedecomp-op opcode))
1359 (cond ((memq bytedecomp-op byte-goto-ops)
1360 ;; It's a pc.
1361 (setq offset
1362 (cdr (or (assq offset tags)
1363 (let ((new (cons offset (byte-compile-make-tag))))
1364 (push new tags)
1365 new)))))
1366 ((cond ((eq bytedecomp-op 'byte-constant2)
1367 (setq bytedecomp-op 'byte-constant) t)
1368 ((memq bytedecomp-op byte-constref-ops)))
1369 (setq tmp (if (>= offset (length constvec))
1370 (list 'out-of-range offset)
1371 (aref constvec offset))
1372 offset (if (eq bytedecomp-op 'byte-constant)
1373 (byte-compile-get-constant tmp)
1374 (or (assq tmp byte-compile-variables)
1375 (let ((new (list tmp)))
1376 (push new byte-compile-variables)
1377 new)))))
1378 ((eq bytedecomp-op 'byte-stack-set2)
1379 (setq bytedecomp-op 'byte-stack-set))
1380 ((and (eq bytedecomp-op 'byte-discardN) (>= offset #x80))
1381 ;; The top bit of the operand for byte-discardN is a flag,
1382 ;; saying whether the top-of-stack is preserved. In
1383 ;; lapcode, we represent this by using a different opcode
1384 ;; (with the flag removed from the operand).
1385 (setq bytedecomp-op 'byte-discardN-preserve-tos)
1386 (setq offset (- offset #x80))))
1387 ;; lap = ( [ (pc . (op . arg)) ]* )
1388 (push (cons optr (cons bytedecomp-op (or offset 0)))
1389 lap)
1390 (setq bytedecomp-ptr (1+ bytedecomp-ptr)))
1391 (let ((rest lap))
1392 (while rest
1393 (cond ((numberp (car rest)))
1394 ((setq tmp (assq (car (car rest)) tags))
1395 ;; This addr is jumped to.
1396 (setcdr rest (cons (cons nil (cdr tmp))
1397 (cdr rest)))
1398 (setq tags (delq tmp tags))
1399 (setq rest (cdr rest))))
1400 (setq rest (cdr rest))))
1401 (if tags (error "optimizer error: missed tags %s" tags))
1402 ;; Remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
1403 (mapcar (function (lambda (elt)
1404 (if (numberp elt)
1405 elt
1406 (cdr elt))))
1407 (nreverse lap))))
1408
1409 \f
1410 ;;; peephole optimizer
1411
1412 (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
1413
1414 (defconst byte-conditional-ops
1415 '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
1416 byte-goto-if-not-nil-else-pop))
1417
1418 (defconst byte-after-unbind-ops
1419 '(byte-constant byte-dup
1420 byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
1421 byte-eq byte-not
1422 byte-cons byte-list1 byte-list2 ; byte-list3 byte-list4
1423 byte-interactive-p)
1424 ;; How about other side-effect-free-ops? Is it safe to move an
1425 ;; error invocation (such as from nth) out of an unwind-protect?
1426 ;; No, it is not, because the unwind-protect forms can alter
1427 ;; the inside of the object to which nth would apply.
1428 ;; For the same reason, byte-equal was deleted from this list.
1429 "Byte-codes that can be moved past an unbind.")
1430
1431 (defconst byte-compile-side-effect-and-error-free-ops
1432 '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
1433 byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
1434 byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
1435 byte-point-min byte-following-char byte-preceding-char
1436 byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
1437 byte-current-buffer byte-stack-ref))
1438
1439 (defconst byte-compile-side-effect-free-ops
1440 (nconc
1441 '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
1442 byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
1443 byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
1444 byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
1445 byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
1446 byte-member byte-assq byte-quo byte-rem)
1447 byte-compile-side-effect-and-error-free-ops))
1448
1449 ;; This crock is because of the way DEFVAR_BOOL variables work.
1450 ;; Consider the code
1451 ;;
1452 ;; (defun foo (flag)
1453 ;; (let ((old-pop-ups pop-up-windows)
1454 ;; (pop-up-windows flag))
1455 ;; (cond ((not (eq pop-up-windows old-pop-ups))
1456 ;; (setq old-pop-ups pop-up-windows)
1457 ;; ...))))
1458 ;;
1459 ;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
1460 ;; something else. But if we optimize
1461 ;;
1462 ;; varref flag
1463 ;; varbind pop-up-windows
1464 ;; varref pop-up-windows
1465 ;; not
1466 ;; to
1467 ;; varref flag
1468 ;; dup
1469 ;; varbind pop-up-windows
1470 ;; not
1471 ;;
1472 ;; we break the program, because it will appear that pop-up-windows and
1473 ;; old-pop-ups are not EQ when really they are. So we have to know what
1474 ;; the BOOL variables are, and not perform this optimization on them.
1475
1476 ;; The variable `byte-boolean-vars' is now primitive and updated
1477 ;; automatically by DEFVAR_BOOL.
1478
1479 (defun byte-optimize-lapcode (lap &optional _for-effect)
1480 "Simple peephole optimizer. LAP is both modified and returned.
1481 If FOR-EFFECT is non-nil, the return value is assumed to be of no importance."
1482 (let (lap0
1483 lap1
1484 lap2
1485 (keep-going 'first-time)
1486 (add-depth 0)
1487 rest tmp tmp2 tmp3
1488 (side-effect-free (if byte-compile-delete-errors
1489 byte-compile-side-effect-free-ops
1490 byte-compile-side-effect-and-error-free-ops)))
1491 (while keep-going
1492 (or (eq keep-going 'first-time)
1493 (byte-compile-log-lap " ---- next pass"))
1494 (setq rest lap
1495 keep-going nil)
1496 (while rest
1497 (setq lap0 (car rest)
1498 lap1 (nth 1 rest)
1499 lap2 (nth 2 rest))
1500
1501 ;; You may notice that sequences like "dup varset discard" are
1502 ;; optimized but sequences like "dup varset TAG1: discard" are not.
1503 ;; You may be tempted to change this; resist that temptation.
1504 (cond ;;
1505 ;; <side-effect-free> pop --> <deleted>
1506 ;; ...including:
1507 ;; const-X pop --> <deleted>
1508 ;; varref-X pop --> <deleted>
1509 ;; dup pop --> <deleted>
1510 ;;
1511 ((and (eq 'byte-discard (car lap1))
1512 (memq (car lap0) side-effect-free))
1513 (setq keep-going t)
1514 (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
1515 (setq rest (cdr rest))
1516 (cond ((= tmp 1)
1517 (byte-compile-log-lap
1518 " %s discard\t-->\t<deleted>" lap0)
1519 (setq lap (delq lap0 (delq lap1 lap))))
1520 ((= tmp 0)
1521 (byte-compile-log-lap
1522 " %s discard\t-->\t<deleted> discard" lap0)
1523 (setq lap (delq lap0 lap)))
1524 ((= tmp -1)
1525 (byte-compile-log-lap
1526 " %s discard\t-->\tdiscard discard" lap0)
1527 (setcar lap0 'byte-discard)
1528 (setcdr lap0 0))
1529 ((error "Optimizer error: too much on the stack"))))
1530 ;;
1531 ;; goto*-X X: --> X:
1532 ;;
1533 ((and (memq (car lap0) byte-goto-ops)
1534 (eq (cdr lap0) lap1))
1535 (cond ((eq (car lap0) 'byte-goto)
1536 (setq lap (delq lap0 lap))
1537 (setq tmp "<deleted>"))
1538 ((memq (car lap0) byte-goto-always-pop-ops)
1539 (setcar lap0 (setq tmp 'byte-discard))
1540 (setcdr lap0 0))
1541 ((error "Depth conflict at tag %d" (nth 2 lap0))))
1542 (and (memq byte-optimize-log '(t byte))
1543 (byte-compile-log " (goto %s) %s:\t-->\t%s %s:"
1544 (nth 1 lap1) (nth 1 lap1)
1545 tmp (nth 1 lap1)))
1546 (setq keep-going t))
1547 ;;
1548 ;; varset-X varref-X --> dup varset-X
1549 ;; varbind-X varref-X --> dup varbind-X
1550 ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
1551 ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
1552 ;; The latter two can enable other optimizations.
1553 ;;
1554 ;; For lexical variables, we could do the same
1555 ;; stack-set-X+1 stack-ref-X --> dup stack-set-X+2
1556 ;; but this is a very minor gain, since dup is stack-ref-0,
1557 ;; i.e. it's only better if X>5, and even then it comes
1558 ;; at the cost of an extra stack slot. Let's not bother.
1559 ((and (eq 'byte-varref (car lap2))
1560 (eq (cdr lap1) (cdr lap2))
1561 (memq (car lap1) '(byte-varset byte-varbind)))
1562 (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
1563 (not (eq (car lap0) 'byte-constant)))
1564 nil
1565 (setq keep-going t)
1566 (if (memq (car lap0) '(byte-constant byte-dup))
1567 (progn
1568 (setq tmp (if (or (not tmp)
1569 (macroexp--const-symbol-p
1570 (car (cdr lap0))))
1571 (cdr lap0)
1572 (byte-compile-get-constant t)))
1573 (byte-compile-log-lap " %s %s %s\t-->\t%s %s %s"
1574 lap0 lap1 lap2 lap0 lap1
1575 (cons (car lap0) tmp))
1576 (setcar lap2 (car lap0))
1577 (setcdr lap2 tmp))
1578 (byte-compile-log-lap " %s %s\t-->\tdup %s" lap1 lap2 lap1)
1579 (setcar lap2 (car lap1))
1580 (setcar lap1 'byte-dup)
1581 (setcdr lap1 0)
1582 ;; The stack depth gets locally increased, so we will
1583 ;; increase maxdepth in case depth = maxdepth here.
1584 ;; This can cause the third argument to byte-code to
1585 ;; be larger than necessary.
1586 (setq add-depth 1))))
1587 ;;
1588 ;; dup varset-X discard --> varset-X
1589 ;; dup varbind-X discard --> varbind-X
1590 ;; dup stack-set-X discard --> stack-set-X-1
1591 ;; (the varbind variant can emerge from other optimizations)
1592 ;;
1593 ((and (eq 'byte-dup (car lap0))
1594 (eq 'byte-discard (car lap2))
1595 (memq (car lap1) '(byte-varset byte-varbind
1596 byte-stack-set)))
1597 (byte-compile-log-lap " dup %s discard\t-->\t%s" lap1 lap1)
1598 (setq keep-going t
1599 rest (cdr rest))
1600 (if (eq 'byte-stack-set (car lap1)) (cl-decf (cdr lap1)))
1601 (setq lap (delq lap0 (delq lap2 lap))))
1602 ;;
1603 ;; not goto-X-if-nil --> goto-X-if-non-nil
1604 ;; not goto-X-if-non-nil --> goto-X-if-nil
1605 ;;
1606 ;; it is wrong to do the same thing for the -else-pop variants.
1607 ;;
1608 ((and (eq 'byte-not (car lap0))
1609 (memq (car lap1) '(byte-goto-if-nil byte-goto-if-not-nil)))
1610 (byte-compile-log-lap " not %s\t-->\t%s"
1611 lap1
1612 (cons
1613 (if (eq (car lap1) 'byte-goto-if-nil)
1614 'byte-goto-if-not-nil
1615 'byte-goto-if-nil)
1616 (cdr lap1)))
1617 (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
1618 'byte-goto-if-not-nil
1619 'byte-goto-if-nil))
1620 (setq lap (delq lap0 lap))
1621 (setq keep-going t))
1622 ;;
1623 ;; goto-X-if-nil goto-Y X: --> goto-Y-if-non-nil X:
1624 ;; goto-X-if-non-nil goto-Y X: --> goto-Y-if-nil X:
1625 ;;
1626 ;; it is wrong to do the same thing for the -else-pop variants.
1627 ;;
1628 ((and (memq (car lap0)
1629 '(byte-goto-if-nil byte-goto-if-not-nil)) ; gotoX
1630 (eq 'byte-goto (car lap1)) ; gotoY
1631 (eq (cdr lap0) lap2)) ; TAG X
1632 (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
1633 'byte-goto-if-not-nil 'byte-goto-if-nil)))
1634 (byte-compile-log-lap " %s %s %s:\t-->\t%s %s:"
1635 lap0 lap1 lap2
1636 (cons inverse (cdr lap1)) lap2)
1637 (setq lap (delq lap0 lap))
1638 (setcar lap1 inverse)
1639 (setq keep-going t)))
1640 ;;
1641 ;; const goto-if-* --> whatever
1642 ;;
1643 ((and (eq 'byte-constant (car lap0))
1644 (memq (car lap1) byte-conditional-ops)
1645 ;; If the `byte-constant's cdr is not a cons cell, it has
1646 ;; to be an index into the constant pool); even though
1647 ;; it'll be a constant, that constant is not known yet
1648 ;; (it's typically a free variable of a closure, so will
1649 ;; only be known when the closure will be built at
1650 ;; run-time).
1651 (consp (cdr lap0)))
1652 (cond ((if (memq (car lap1) '(byte-goto-if-nil
1653 byte-goto-if-nil-else-pop))
1654 (car (cdr lap0))
1655 (not (car (cdr lap0))))
1656 (byte-compile-log-lap " %s %s\t-->\t<deleted>"
1657 lap0 lap1)
1658 (setq rest (cdr rest)
1659 lap (delq lap0 (delq lap1 lap))))
1660 (t
1661 (byte-compile-log-lap " %s %s\t-->\t%s"
1662 lap0 lap1
1663 (cons 'byte-goto (cdr lap1)))
1664 (when (memq (car lap1) byte-goto-always-pop-ops)
1665 (setq lap (delq lap0 lap)))
1666 (setcar lap1 'byte-goto)))
1667 (setq keep-going t))
1668 ;;
1669 ;; varref-X varref-X --> varref-X dup
1670 ;; varref-X [dup ...] varref-X --> varref-X [dup ...] dup
1671 ;; stackref-X [dup ...] stackref-X+N --> stackref-X [dup ...] dup
1672 ;; We don't optimize the const-X variations on this here,
1673 ;; because that would inhibit some goto optimizations; we
1674 ;; optimize the const-X case after all other optimizations.
1675 ;;
1676 ((and (memq (car lap0) '(byte-varref byte-stack-ref))
1677 (progn
1678 (setq tmp (cdr rest))
1679 (setq tmp2 0)
1680 (while (eq (car (car tmp)) 'byte-dup)
1681 (setq tmp2 (1+ tmp2))
1682 (setq tmp (cdr tmp)))
1683 t)
1684 (eq (if (eq 'byte-stack-ref (car lap0))
1685 (+ tmp2 1 (cdr lap0))
1686 (cdr lap0))
1687 (cdr (car tmp)))
1688 (eq (car lap0) (car (car tmp))))
1689 (if (memq byte-optimize-log '(t byte))
1690 (let ((str ""))
1691 (setq tmp2 (cdr rest))
1692 (while (not (eq tmp tmp2))
1693 (setq tmp2 (cdr tmp2)
1694 str (concat str " dup")))
1695 (byte-compile-log-lap " %s%s %s\t-->\t%s%s dup"
1696 lap0 str lap0 lap0 str)))
1697 (setq keep-going t)
1698 (setcar (car tmp) 'byte-dup)
1699 (setcdr (car tmp) 0)
1700 (setq rest tmp))
1701 ;;
1702 ;; TAG1: TAG2: --> TAG1: <deleted>
1703 ;; (and other references to TAG2 are replaced with TAG1)
1704 ;;
1705 ((and (eq (car lap0) 'TAG)
1706 (eq (car lap1) 'TAG))
1707 (and (memq byte-optimize-log '(t byte))
1708 (byte-compile-log " adjacent tags %d and %d merged"
1709 (nth 1 lap1) (nth 1 lap0)))
1710 (setq tmp3 lap)
1711 (while (setq tmp2 (rassq lap0 tmp3))
1712 (setcdr tmp2 lap1)
1713 (setq tmp3 (cdr (memq tmp2 tmp3))))
1714 (setq lap (delq lap0 lap)
1715 keep-going t))
1716 ;;
1717 ;; unused-TAG: --> <deleted>
1718 ;;
1719 ((and (eq 'TAG (car lap0))
1720 (not (rassq lap0 lap)))
1721 (and (memq byte-optimize-log '(t byte))
1722 (byte-compile-log " unused tag %d removed" (nth 1 lap0)))
1723 (setq lap (delq lap0 lap)
1724 keep-going t))
1725 ;;
1726 ;; goto ... --> goto <delete until TAG or end>
1727 ;; return ... --> return <delete until TAG or end>
1728 ;;
1729 ((and (memq (car lap0) '(byte-goto byte-return))
1730 (not (memq (car lap1) '(TAG nil))))
1731 (setq tmp rest)
1732 (let ((i 0)
1733 (opt-p (memq byte-optimize-log '(t lap)))
1734 str deleted)
1735 (while (and (setq tmp (cdr tmp))
1736 (not (eq 'TAG (car (car tmp)))))
1737 (if opt-p (setq deleted (cons (car tmp) deleted)
1738 str (concat str " %s")
1739 i (1+ i))))
1740 (if opt-p
1741 (let ((tagstr
1742 (if (eq 'TAG (car (car tmp)))
1743 (format "%d:" (car (cdr (car tmp))))
1744 (or (car tmp) ""))))
1745 (if (< i 6)
1746 (apply 'byte-compile-log-lap-1
1747 (concat " %s" str
1748 " %s\t-->\t%s <deleted> %s")
1749 lap0
1750 (nconc (nreverse deleted)
1751 (list tagstr lap0 tagstr)))
1752 (byte-compile-log-lap
1753 " %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
1754 lap0 i (if (= i 1) "" "s")
1755 tagstr lap0 tagstr))))
1756 (rplacd rest tmp))
1757 (setq keep-going t))
1758 ;;
1759 ;; <safe-op> unbind --> unbind <safe-op>
1760 ;; (this may enable other optimizations.)
1761 ;;
1762 ((and (eq 'byte-unbind (car lap1))
1763 (memq (car lap0) byte-after-unbind-ops))
1764 (byte-compile-log-lap " %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
1765 (setcar rest lap1)
1766 (setcar (cdr rest) lap0)
1767 (setq keep-going t))
1768 ;;
1769 ;; varbind-X unbind-N --> discard unbind-(N-1)
1770 ;; save-excursion unbind-N --> unbind-(N-1)
1771 ;; save-restriction unbind-N --> unbind-(N-1)
1772 ;;
1773 ((and (eq 'byte-unbind (car lap1))
1774 (memq (car lap0) '(byte-varbind byte-save-excursion
1775 byte-save-restriction))
1776 (< 0 (cdr lap1)))
1777 (if (zerop (setcdr lap1 (1- (cdr lap1))))
1778 (delq lap1 rest))
1779 (if (eq (car lap0) 'byte-varbind)
1780 (setcar rest (cons 'byte-discard 0))
1781 (setq lap (delq lap0 lap)))
1782 (byte-compile-log-lap " %s %s\t-->\t%s %s"
1783 lap0 (cons (car lap1) (1+ (cdr lap1)))
1784 (if (eq (car lap0) 'byte-varbind)
1785 (car rest)
1786 (car (cdr rest)))
1787 (if (and (/= 0 (cdr lap1))
1788 (eq (car lap0) 'byte-varbind))
1789 (car (cdr rest))
1790 ""))
1791 (setq keep-going t))
1792 ;;
1793 ;; goto*-X ... X: goto-Y --> goto*-Y
1794 ;; goto-X ... X: return --> return
1795 ;;
1796 ((and (memq (car lap0) byte-goto-ops)
1797 (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
1798 '(byte-goto byte-return)))
1799 (cond ((and (not (eq tmp lap0))
1800 (or (eq (car lap0) 'byte-goto)
1801 (eq (car tmp) 'byte-goto)))
1802 (byte-compile-log-lap " %s [%s]\t-->\t%s"
1803 (car lap0) tmp tmp)
1804 (if (eq (car tmp) 'byte-return)
1805 (setcar lap0 'byte-return))
1806 (setcdr lap0 (cdr tmp))
1807 (setq keep-going t))))
1808 ;;
1809 ;; goto-*-else-pop X ... X: goto-if-* --> whatever
1810 ;; goto-*-else-pop X ... X: discard --> whatever
1811 ;;
1812 ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
1813 byte-goto-if-not-nil-else-pop))
1814 (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
1815 (eval-when-compile
1816 (cons 'byte-discard byte-conditional-ops)))
1817 (not (eq lap0 (car tmp))))
1818 (setq tmp2 (car tmp))
1819 (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
1820 byte-goto-if-nil)
1821 (byte-goto-if-not-nil-else-pop
1822 byte-goto-if-not-nil))))
1823 (if (memq (car tmp2) tmp3)
1824 (progn (setcar lap0 (car tmp2))
1825 (setcdr lap0 (cdr tmp2))
1826 (byte-compile-log-lap " %s-else-pop [%s]\t-->\t%s"
1827 (car lap0) tmp2 lap0))
1828 ;; Get rid of the -else-pop's and jump one step further.
1829 (or (eq 'TAG (car (nth 1 tmp)))
1830 (setcdr tmp (cons (byte-compile-make-tag)
1831 (cdr tmp))))
1832 (byte-compile-log-lap " %s [%s]\t-->\t%s <skip>"
1833 (car lap0) tmp2 (nth 1 tmp3))
1834 (setcar lap0 (nth 1 tmp3))
1835 (setcdr lap0 (nth 1 tmp)))
1836 (setq keep-going t))
1837 ;;
1838 ;; const goto-X ... X: goto-if-* --> whatever
1839 ;; const goto-X ... X: discard --> whatever
1840 ;;
1841 ((and (eq (car lap0) 'byte-constant)
1842 (eq (car lap1) 'byte-goto)
1843 (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
1844 (eval-when-compile
1845 (cons 'byte-discard byte-conditional-ops)))
1846 (not (eq lap1 (car tmp))))
1847 (setq tmp2 (car tmp))
1848 (cond ((when (consp (cdr lap0))
1849 (memq (car tmp2)
1850 (if (null (car (cdr lap0)))
1851 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
1852 '(byte-goto-if-not-nil
1853 byte-goto-if-not-nil-else-pop))))
1854 (byte-compile-log-lap " %s goto [%s]\t-->\t%s %s"
1855 lap0 tmp2 lap0 tmp2)
1856 (setcar lap1 (car tmp2))
1857 (setcdr lap1 (cdr tmp2))
1858 ;; Let next step fix the (const,goto-if*) sequence.
1859 (setq rest (cons nil rest))
1860 (setq keep-going t))
1861 ((or (consp (cdr lap0))
1862 (eq (car tmp2) 'byte-discard))
1863 ;; Jump one step further
1864 (byte-compile-log-lap
1865 " %s goto [%s]\t-->\t<deleted> goto <skip>"
1866 lap0 tmp2)
1867 (or (eq 'TAG (car (nth 1 tmp)))
1868 (setcdr tmp (cons (byte-compile-make-tag)
1869 (cdr tmp))))
1870 (setcdr lap1 (car (cdr tmp)))
1871 (setq lap (delq lap0 lap))
1872 (setq keep-going t))))
1873 ;;
1874 ;; X: varref-Y ... varset-Y goto-X -->
1875 ;; X: varref-Y Z: ... dup varset-Y goto-Z
1876 ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
1877 ;; (This is so usual for while loops that it is worth handling).
1878 ;;
1879 ;; Here again, we could do it for stack-ref/stack-set, but
1880 ;; that's replacing a stack-ref-Y with a stack-ref-0, which
1881 ;; is a very minor improvement (if any), at the cost of
1882 ;; more stack use and more byte-code. Let's not do it.
1883 ;;
1884 ((and (eq (car lap1) 'byte-varset)
1885 (eq (car lap2) 'byte-goto)
1886 (not (memq (cdr lap2) rest)) ;Backwards jump
1887 (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
1888 'byte-varref)
1889 (eq (cdr (car tmp)) (cdr lap1))
1890 (not (memq (car (cdr lap1)) byte-boolean-vars)))
1891 ;;(byte-compile-log-lap " Pulled %s to end of loop" (car tmp))
1892 (let ((newtag (byte-compile-make-tag)))
1893 (byte-compile-log-lap
1894 " %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
1895 (nth 1 (cdr lap2)) (car tmp)
1896 lap1 lap2
1897 (nth 1 (cdr lap2)) (car tmp)
1898 (nth 1 newtag) 'byte-dup lap1
1899 (cons 'byte-goto newtag)
1900 )
1901 (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
1902 (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
1903 (setq add-depth 1)
1904 (setq keep-going t))
1905 ;;
1906 ;; goto-X Y: ... X: goto-if*-Y --> goto-if-not-*-X+1 Y:
1907 ;; (This can pull the loop test to the end of the loop)
1908 ;;
1909 ((and (eq (car lap0) 'byte-goto)
1910 (eq (car lap1) 'TAG)
1911 (eq lap1
1912 (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
1913 (memq (car (car tmp))
1914 '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
1915 byte-goto-if-nil-else-pop)))
1916 ;; (byte-compile-log-lap " %s %s, %s %s --> moved conditional"
1917 ;; lap0 lap1 (cdr lap0) (car tmp))
1918 (let ((newtag (byte-compile-make-tag)))
1919 (byte-compile-log-lap
1920 "%s %s: ... %s: %s\t-->\t%s ... %s:"
1921 lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
1922 (cons (cdr (assq (car (car tmp))
1923 '((byte-goto-if-nil . byte-goto-if-not-nil)
1924 (byte-goto-if-not-nil . byte-goto-if-nil)
1925 (byte-goto-if-nil-else-pop .
1926 byte-goto-if-not-nil-else-pop)
1927 (byte-goto-if-not-nil-else-pop .
1928 byte-goto-if-nil-else-pop))))
1929 newtag)
1930
1931 (nth 1 newtag)
1932 )
1933 (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
1934 (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
1935 ;; We can handle this case but not the -if-not-nil case,
1936 ;; because we won't know which non-nil constant to push.
1937 (setcdr rest (cons (cons 'byte-constant
1938 (byte-compile-get-constant nil))
1939 (cdr rest))))
1940 (setcar lap0 (nth 1 (memq (car (car tmp))
1941 '(byte-goto-if-nil-else-pop
1942 byte-goto-if-not-nil
1943 byte-goto-if-nil
1944 byte-goto-if-not-nil
1945 byte-goto byte-goto))))
1946 )
1947 (setq keep-going t))
1948 )
1949 (setq rest (cdr rest)))
1950 )
1951 ;; Cleanup stage:
1952 ;; Rebuild byte-compile-constants / byte-compile-variables.
1953 ;; Simple optimizations that would inhibit other optimizations if they
1954 ;; were done in the optimizing loop, and optimizations which there is no
1955 ;; need to do more than once.
1956 (setq byte-compile-constants nil
1957 byte-compile-variables nil)
1958 (setq rest lap)
1959 (byte-compile-log-lap " ---- final pass")
1960 (while rest
1961 (setq lap0 (car rest)
1962 lap1 (nth 1 rest))
1963 (if (memq (car lap0) byte-constref-ops)
1964 (if (memq (car lap0) '(byte-constant byte-constant2))
1965 (unless (memq (cdr lap0) byte-compile-constants)
1966 (setq byte-compile-constants (cons (cdr lap0)
1967 byte-compile-constants)))
1968 (unless (memq (cdr lap0) byte-compile-variables)
1969 (setq byte-compile-variables (cons (cdr lap0)
1970 byte-compile-variables)))))
1971 (cond (;;
1972 ;; const-C varset-X const-C --> const-C dup varset-X
1973 ;; const-C varbind-X const-C --> const-C dup varbind-X
1974 ;;
1975 (and (eq (car lap0) 'byte-constant)
1976 (eq (car (nth 2 rest)) 'byte-constant)
1977 (eq (cdr lap0) (cdr (nth 2 rest)))
1978 (memq (car lap1) '(byte-varbind byte-varset)))
1979 (byte-compile-log-lap " %s %s %s\t-->\t%s dup %s"
1980 lap0 lap1 lap0 lap0 lap1)
1981 (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
1982 (setcar (cdr rest) (cons 'byte-dup 0))
1983 (setq add-depth 1))
1984 ;;
1985 ;; const-X [dup/const-X ...] --> const-X [dup ...] dup
1986 ;; varref-X [dup/varref-X ...] --> varref-X [dup ...] dup
1987 ;;
1988 ((memq (car lap0) '(byte-constant byte-varref))
1989 (setq tmp rest
1990 tmp2 nil)
1991 (while (progn
1992 (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
1993 (and (eq (cdr lap0) (cdr (car tmp)))
1994 (eq (car lap0) (car (car tmp)))))
1995 (setcar tmp (cons 'byte-dup 0))
1996 (setq tmp2 t))
1997 (if tmp2
1998 (byte-compile-log-lap
1999 " %s [dup/%s]...\t-->\t%s dup..." lap0 lap0 lap0)))
2000 ;;
2001 ;; unbind-N unbind-M --> unbind-(N+M)
2002 ;;
2003 ((and (eq 'byte-unbind (car lap0))
2004 (eq 'byte-unbind (car lap1)))
2005 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1
2006 (cons 'byte-unbind
2007 (+ (cdr lap0) (cdr lap1))))
2008 (setq lap (delq lap0 lap))
2009 (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
2010
2011 ;;
2012 ;; stack-set-M [discard/discardN ...] --> discardN-preserve-tos
2013 ;; stack-set-M [discard/discardN ...] --> discardN
2014 ;;
2015 ((and (eq (car lap0) 'byte-stack-set)
2016 (memq (car lap1) '(byte-discard byte-discardN))
2017 (progn
2018 ;; See if enough discard operations follow to expose or
2019 ;; destroy the value stored by the stack-set.
2020 (setq tmp (cdr rest))
2021 (setq tmp2 (1- (cdr lap0)))
2022 (setq tmp3 0)
2023 (while (memq (car (car tmp)) '(byte-discard byte-discardN))
2024 (setq tmp3
2025 (+ tmp3 (if (eq (car (car tmp)) 'byte-discard)
2026 1
2027 (cdr (car tmp)))))
2028 (setq tmp (cdr tmp)))
2029 (>= tmp3 tmp2)))
2030 ;; Do the optimization.
2031 (setq lap (delq lap0 lap))
2032 (setcar lap1
2033 (if (= tmp2 tmp3)
2034 ;; The value stored is the new TOS, so pop one more
2035 ;; value (to get rid of the old value) using the
2036 ;; TOS-preserving discard operator.
2037 'byte-discardN-preserve-tos
2038 ;; Otherwise, the value stored is lost, so just use a
2039 ;; normal discard.
2040 'byte-discardN))
2041 (setcdr lap1 (1+ tmp3))
2042 (setcdr (cdr rest) tmp)
2043 (byte-compile-log-lap " %s [discard/discardN]...\t-->\t%s"
2044 lap0 lap1))
2045
2046 ;;
2047 ;; discard/discardN/discardN-preserve-tos-X discard/discardN-Y -->
2048 ;; discardN-(X+Y)
2049 ;;
2050 ((and (memq (car lap0)
2051 '(byte-discard byte-discardN
2052 byte-discardN-preserve-tos))
2053 (memq (car lap1) '(byte-discard byte-discardN)))
2054 (setq lap (delq lap0 lap))
2055 (byte-compile-log-lap
2056 " %s %s\t-->\t(discardN %s)"
2057 lap0 lap1
2058 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2059 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2060 (setcdr lap1 (+ (if (eq (car lap0) 'byte-discard) 1 (cdr lap0))
2061 (if (eq (car lap1) 'byte-discard) 1 (cdr lap1))))
2062 (setcar lap1 'byte-discardN))
2063
2064 ;;
2065 ;; discardN-preserve-tos-X discardN-preserve-tos-Y -->
2066 ;; discardN-preserve-tos-(X+Y)
2067 ;;
2068 ((and (eq (car lap0) 'byte-discardN-preserve-tos)
2069 (eq (car lap1) 'byte-discardN-preserve-tos))
2070 (setq lap (delq lap0 lap))
2071 (setcdr lap1 (+ (cdr lap0) (cdr lap1)))
2072 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 (car rest)))
2073
2074 ;;
2075 ;; discardN-preserve-tos return --> return
2076 ;; dup return --> return
2077 ;; stack-set-N return --> return ; where N is TOS-1
2078 ;;
2079 ((and (eq (car lap1) 'byte-return)
2080 (or (memq (car lap0) '(byte-discardN-preserve-tos byte-dup))
2081 (and (eq (car lap0) 'byte-stack-set)
2082 (= (cdr lap0) 1))))
2083 ;; The byte-code interpreter will pop the stack for us, so
2084 ;; we can just leave stuff on it.
2085 (setq lap (delq lap0 lap))
2086 (byte-compile-log-lap " %s %s\t-->\t%s" lap0 lap1 lap1))
2087 )
2088 (setq rest (cdr rest)))
2089 (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
2090 lap)
2091
2092 (provide 'byte-opt)
2093
2094 \f
2095 ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
2096 ;; itself, compile some of its most used recursive functions (at load time).
2097 ;;
2098 (eval-when-compile
2099 (or (byte-code-function-p (symbol-function 'byte-optimize-form))
2100 (assq 'byte-code (symbol-function 'byte-optimize-form))
2101 (let ((byte-optimize nil)
2102 (byte-compile-warnings nil))
2103 (mapc (lambda (x)
2104 (or noninteractive (message "compiling %s..." x))
2105 (byte-compile x)
2106 (or noninteractive (message "compiling %s...done" x)))
2107 '(byte-optimize-form
2108 byte-optimize-body
2109 byte-optimize-predicate
2110 byte-optimize-binary-predicate
2111 ;; Inserted some more than necessary, to speed it up.
2112 byte-optimize-form-code-walker
2113 byte-optimize-lapcode))))
2114 nil)
2115
2116 ;;; byte-opt.el ends here