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