home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / elisp / packages / bytecomp / byte-optimize.el next >
Encoding:
Text File  |  1992-07-02  |  62.7 KB  |  1,732 lines

  1. ;;; -*- Mode:Emacs-Lisp -*-
  2. ;;; The optimization passes of the emacs-lisp byte compiler.
  3.  
  4. ;; By Jamie Zawinski <jwz@lucid.com> and Hallvard Furuseth <hbf@ulrik.uio.no>.
  5. ;; last modified  2-jun-92.
  6.  
  7. ;; This file is part of GNU Emacs.
  8.  
  9. ;; GNU Emacs is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 1, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. ;; GNU General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  21. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; ========================================================================
  24. ;;; "No matter how hard you try, you can't make a racehorse out of a pig.
  25. ;;; you can, however, make a faster pig."
  26. ;;;
  27. ;;; Or, to put it another way, the emacs byte compiler is a VW Bug.  This code
  28. ;;; makes it be a VW Bug with fuel injection and a turbocharger...  You're 
  29. ;;; still not going to make it go faster than 70 mph, but it might be easier
  30. ;;; to get it there.
  31. ;;;
  32.  
  33. ;;; TO DO:
  34. ;;;
  35. ;;; (apply '(lambda (x &rest y) ...) 1 (foo))
  36. ;;;
  37. ;;; collapse common subexpressions
  38. ;;;
  39. ;;; maintain a list of functions known not to access any global variables
  40. ;;; (actually, give them a 'dynamically-safe property) and then
  41. ;;;   (let ( v1 v2 ... vM vN ) <...dynamically-safe...> )  ==>
  42. ;;;   (let ( v1 v2 ... vM ) vN <...dynamically-safe...> )
  43. ;;; by recursing on this, we might be able to eliminate the entire let.
  44. ;;; However certain variables should never have their bindings optimized
  45. ;;; away, because they affect everything.
  46. ;;;   (put 'debug-on-error 'binding-is-magic t)
  47. ;;;   (put 'debug-on-abort 'binding-is-magic t)
  48. ;;;   (put 'inhibit-quit 'binding-is-magic t)
  49. ;;;   (put 'quit-flag 'binding-is-magic t)
  50. ;;; others?
  51. ;;;
  52. ;;; Simple defsubsts often produce forms like
  53. ;;;    (let ((v1 (f1)) (v2 (f2)) ...)
  54. ;;;       (FN v1 v2 ...))
  55. ;;; It would be nice if we could optimize this to 
  56. ;;;    (FN (f1) (f2) ...)
  57. ;;; but we can't unless FN is dynamically-safe (it might be dynamically
  58. ;;; referring to the bindings that the lambda arglist established.)
  59. ;;; One of the uncountable lossages introduced by dynamic scope...
  60. ;;;
  61. ;;; Maybe there should be a control-structure that says "turn on 
  62. ;;; fast-and-loose type-assumptive optimizations here."  Then when
  63. ;;; we see a form like (car foo) we can from then on assume that
  64. ;;; the variable foo is of type cons, and optimize based on that.
  65. ;;; But, this won't win much because of (you guessed it) dynamic 
  66. ;;; scope.  Anything down the stack could change the value.
  67. ;;;
  68. ;;; It would be nice if redundant sequences could be factored out as well,
  69. ;;; when they are known to have no side-effects:
  70. ;;;   (list (+ a b c) (+ a b c))   -->  a b add c add dup list-2
  71. ;;; but beware of traps like
  72. ;;;   (cons (list x y) (list x y))
  73. ;;;
  74. ;;; Tail-recursion elimination is not really possible in elisp.  Tail-recursion
  75. ;;; elimination is almost always impossible when all variables have dynamic
  76. ;;; scope, but given that the "return" byteop requires the binding stack to be
  77. ;;; empty (rather than emptying it itself), there can be no truly tail-
  78. ;;; recursive elisp functions that take any arguments or make any bindings.
  79. ;;;
  80. ;;; Here is an example of an elisp function which could safely be
  81. ;;; byte-compiled tail-recursively:
  82. ;;;
  83. ;;;  (defun tail-map (fn list)
  84. ;;;    (cond (list
  85. ;;;           (funcall fn (car list))
  86. ;;;           (tail-map fn (cdr list)))))
  87. ;;;
  88. ;;; However, if there was even a single let-binding around the COND,
  89. ;;; it could not be byte-compiled, because there would be an "unbind"
  90. ;;; byte-op between the final "call" and "return."  Adding a 
  91. ;;; Bunbind_all byteop would fix this.
  92. ;;;
  93. ;;;   (defun foo (x y z) ... (foo a b c))
  94. ;;;   ... (const foo) (varref a) (varref b) (varref c) (call 3) END: (return)
  95. ;;;   ... (varref a) (varbind x) (varref b) (varbind y) (varref c) (varbind z) (goto 0) END: (unbind-all) (return)
  96. ;;;   ... (varref a) (varset x) (varref b) (varset y) (varref c) (varset z) (goto 0) END: (return)
  97. ;;;
  98. ;;; this also can be considered tail recursion:
  99. ;;;
  100. ;;;   ... (const foo) (varref a) (call 1) (goto X) ... X: (return)
  101. ;;; could generalize this by doing the optimization
  102. ;;;   (goto X) ... X: (return)  -->  (return)
  103. ;;;
  104. ;;; But this doesn't solve all of the problems: although by doing tail-
  105. ;;; recursion elimination in this way, the call-stack does not grow, the
  106. ;;; binding-stack would grow with each recursive step, and would eventually
  107. ;;; overflow.  I don't believe there is any way around this without lexical
  108. ;;; scope.
  109. ;;;
  110. ;;; Wouldn't it be nice if elisp had lexical scope.
  111. ;;;
  112. ;;; Idea: the form (lexical-scope) in a file means that the file may be 
  113. ;;; compiled lexically.  This proclamation is file-local.  Then, within 
  114. ;;; that file, "let" would establish lexical bindings, and "let-dynamic"
  115. ;;; would do things the old way.  (Or we could use CL "declare" forms.)
  116. ;;; We'd have to notice defvars and defconsts, since those variables should
  117. ;;; always be dynamic, and attempting to do a lexical binding of them
  118. ;;; should simply do a dynamic binding instead.
  119. ;;; But!  We need to know about variables that were not necessarily defvarred
  120. ;;; in the file being compiled (doing a boundp check isn't good enough.)
  121. ;;; Fdefvar() would have to be modified to add something to the plist.
  122. ;;;
  123. ;;; A major disadvantage of this scheme is that the interpreter and compiler 
  124. ;;; would have different semantics for files compiled with (dynamic-scope).  
  125. ;;; Since this would be a file-local optimization, there would be no way to
  126. ;;; modify the interpreter to obey this (unless the loader was hacked 
  127. ;;; in some grody way, but that's a really bad idea.)
  128. ;;;
  129. ;;; Really the Right Thing is to make lexical scope the default across
  130. ;;; the board, in the interpreter and compiler, and just FIX all of 
  131. ;;; the code that relies on dynamic scope of non-defvarred variables.
  132.  
  133.  
  134. (require 'byte-compile "bytecomp")
  135.  
  136. (or (fboundp 'byte-compile-lapcode)
  137.     (error "loading bytecomp got the wrong version of the compiler."))
  138.  
  139. (defun byte-compile-log-lap-1 (format &rest args)
  140.   (if (aref byte-code-vector 0)
  141.       (error "The old version of the disassembler is loaded.  Reload new-bytecomp as well."))
  142.   (byte-compile-log-1
  143.    (apply 'format format
  144.      (let (c a)
  145.        (mapcar '(lambda (arg)
  146.           (if (not (consp arg))
  147.               (if (and (symbolp arg)
  148.                    (string-match "^byte-" (symbol-name arg)))
  149.               (intern (substring (symbol-name arg) 5))
  150.             arg)
  151.             (if (integerp (setq c (car arg)))
  152.             (error "non-symbolic byte-op %s" c))
  153.             (if (eq c 'TAG)
  154.             (setq c arg)
  155.               (setq a (cond ((memq c byte-goto-ops)
  156.                      (car (cdr (cdr arg))))
  157.                     ((memq c byte-constref-ops)
  158.                      (car (cdr arg)))
  159.                     (t (cdr arg))))
  160.               (setq c (symbol-name c))
  161.               (if (string-match "^byte-." c)
  162.               (setq c (intern (substring c 5)))))
  163.             (if (eq c 'constant) (setq c 'const))
  164.             (if (and (eq (cdr arg) 0)
  165.                  (not (memq c '(unbind call const))))
  166.             c
  167.               (format "(%s %s)" c a))))
  168.            args)))))
  169.  
  170. (defmacro byte-compile-log-lap (format-string &rest args)
  171.   (list 'and
  172.     '(memq byte-optimize-log '(t byte))
  173.     (cons 'byte-compile-log-lap-1
  174.           (cons format-string args))))
  175.  
  176.  
  177. ;;; byte-compile optimizers to support inlining
  178.  
  179. (put 'inline 'byte-optimizer 'byte-optimize-inline-handler)
  180.  
  181. (defun byte-optimize-inline-handler (form)
  182.   "byte-optimize-handler for the `inline' special-form."
  183.   (cons 'progn
  184.     (mapcar
  185.      '(lambda (sexp)
  186.         (let ((fn (car-safe sexp)))
  187.           (if (and (symbolp fn)
  188.             (or (cdr (assq fn byte-compile-function-environment))
  189.               (and (fboundp fn)
  190.             (not (or (cdr (assq fn byte-compile-macro-environment))
  191.                  (and (consp (setq fn (symbol-function fn)))
  192.                       (eq (car fn) 'macro))
  193.                  (subrp fn))))))
  194.           (byte-compile-inline-expand sexp)
  195.         sexp)))
  196.      (cdr form))))
  197.  
  198.  
  199. (defun byte-inline-lapcode (lap)
  200.   "splice the given lap code into the current instruction stream.
  201. If it has any labels in it, you're responsible for making sure there
  202. are no collisions, and that byte-compile-tag-number is reasonable
  203. after this is spliced in.  the provided list is destroyed."
  204.   (setq byte-compile-output (nconc (nreverse lap) byte-compile-output)))
  205.  
  206.  
  207. (defun byte-compile-inline-expand (form)
  208.   (let* ((name (car form))
  209.      (fn (or (cdr (assq name byte-compile-function-environment))
  210.          (and (fboundp name) (symbol-function name)))))
  211.     (if (null fn)
  212.     (progn
  213.       (byte-compile-warn "attempt to inline %s before it was defined" name)
  214.       form)
  215.       ;; else
  216.       (if (and (consp fn) (eq (car fn) 'autoload))
  217.       (load (nth 1 fn)))
  218.       (if (and (consp fn) (eq (car fn) 'autoload))
  219.       (error "file \"%s\" didn't define \"%s\"" (nth 1 fn) name))
  220.       (if (symbolp fn)
  221.       (byte-compile-inline-expand (cons fn (cdr form)))
  222.     (if (compiled-function-p fn)
  223.         (cons (list 'lambda (aref fn 0)
  224.             (list 'byte-code (aref fn 1) (aref fn 2) (aref fn 3)))
  225.           (cdr form))
  226.       (if (not (eq (car fn) 'lambda)) (error "%s is not a lambda" name))
  227.       (cons fn (cdr form)))))))
  228.  
  229. ;;; ((lambda ...) ...)
  230. ;;; 
  231. (defun byte-compile-unfold-lambda (form &optional name)
  232.   (or name (setq name "anonymous lambda"))
  233.   (let ((lambda (car form))
  234.     (values (cdr form)))
  235.     (if (compiled-function-p lambda)
  236.     (setq lambda (list 'lambda (nth 0 form)
  237.                (list 'byte-code
  238.                  (nth 1 form) (nth 2 form) (nth 3 form)))))
  239.     (let ((arglist (nth 1 lambda))
  240.       (body (cdr (cdr lambda)))
  241.       optionalp restp
  242.       bindings)
  243.       (if (and (stringp (car body)) (cdr body))
  244.       (setq body (cdr body)))
  245.       (if (and (consp (car body)) (eq 'interactive (car (car body))))
  246.       (setq body (cdr body)))
  247.       (while arglist
  248.     (cond ((eq (car arglist) '&optional)
  249.            ;; ok, I'll let this slide because funcall_lambda() does...
  250.            ;; (if optionalp (error "multiple &optional keywords in %s" name))
  251.            (if restp (error "&optional found after &rest in %s" name))
  252.            (if (null (cdr arglist))
  253.            (error "nothing after &optional in %s" name))
  254.            (setq optionalp t))
  255.           ((eq (car arglist) '&rest)
  256.            ;; ...but it is by no stretch of the imagination a reasonable
  257.            ;; thing that funcall_lambda() allows (&rest x y) and
  258.            ;; (&rest x &optional y) in arglists.
  259.            (if (null (cdr arglist))
  260.            (error "nothing after &rest in %s" name))
  261.            (if (cdr (cdr arglist))
  262.            (error "multiple vars after &rest in %s" name))
  263.            (setq restp t))
  264.           (restp
  265.            (setq bindings (cons (list (car arglist)
  266.                       (and values (cons 'list values)))
  267.                     bindings)
  268.              values nil))
  269.           ((and (not optionalp) (null values))
  270.            (byte-compile-warn "attempt to open-code %s with too few arguments" name)
  271.            (setq arglist nil values 'too-few))
  272.           (t
  273.            (setq bindings (cons (list (car arglist) (car values))
  274.                     bindings)
  275.              values (cdr values))))
  276.     (setq arglist (cdr arglist)))
  277.       (if values
  278.       (progn
  279.         (or (eq values 'too-few)
  280.         (byte-compile-warn
  281.          "attempt to open-code %s with too many arguments" name))
  282.         form)
  283.     (let ((newform 
  284.            (if bindings
  285.            (cons 'let (cons (nreverse bindings) body))
  286.          (cons 'progn body))))
  287.       (byte-compile-log "  %s\t==>\t%s" form newform)
  288.       newform)))))
  289.  
  290.  
  291. ;;; implementing source-level optimizers
  292.  
  293. (defun byte-optimize-form-code-walker (form for-effect)
  294.   ;;
  295.   ;; For normal function calls, We can just mapcar the optimizer the cdr.  But
  296.   ;; we need to have special knowledge of the syntax of the special forms
  297.   ;; like let and defun (that's why they're special forms :-).  (Actually,
  298.   ;; the important aspect is that they are subrs that don't evaluate all of
  299.   ;; their args.)
  300.   ;;
  301.   (let ((fn (car-safe form))
  302.     tmp)
  303.     (cond ((not (consp form))
  304.        (if (not (and for-effect
  305.              (or byte-compile-delete-errors
  306.                  (not (symbolp form))
  307.                  (eq form t))))
  308.          form))
  309.       ((eq fn 'quote)
  310.        (if (cdr (cdr form))
  311.            (byte-compile-warn "malformed quote form: %s"
  312.                   (prin1-to-string form)))
  313.        ;; map (quote nil) to nil to simplify optimizer logic.
  314.        ;; map quoted constants to nil if for-effect (just because).
  315.        (and (nth 1 form)
  316.         (not for-effect)
  317.         form))
  318.       ((or (compiled-function-p fn)
  319.            (eq 'lambda (car-safe fn)))
  320.        (byte-compile-unfold-lambda form))
  321.       ((memq fn '(let let*))
  322.        ;; recursively enter the optimizer for the bindings and body
  323.        ;; of a let or let*.  This for depth-firstness: forms that
  324.        ;; are more deeply nested are optimized first.
  325.        (cons fn
  326.          (cons
  327.           (mapcar '(lambda (binding)
  328.              (if (symbolp binding)
  329.                  binding
  330.                (if (cdr (cdr binding))
  331.                    (byte-compile-warn "malformed let binding: %s"
  332.                           (prin1-to-string binding)))
  333.                (list (car binding)
  334.                  (byte-optimize-form (nth 1 binding) nil))))
  335.               (nth 1 form))
  336.           (byte-optimize-body (cdr (cdr form)) for-effect))))
  337.       ((eq fn 'cond)
  338.        (cons fn
  339.          (mapcar '(lambda (clause)
  340.                 (if (consp clause)
  341.                 (cons
  342.                  (byte-optimize-form (car clause) nil)
  343.                  (byte-optimize-body (cdr clause) for-effect))
  344.                   (byte-compile-warn "malformed cond form: %s"
  345.                          (prin1-to-string clause))
  346.                   clause))
  347.              (cdr form))))
  348.       ((eq fn 'progn)
  349.        ;; as an extra added bonus, this simplifies (progn <x>) --> <x>
  350.        (if (cdr (cdr form))
  351.            (progn
  352.          (setq tmp (byte-optimize-body (cdr form) for-effect))
  353.          (if (cdr tmp) (cons 'progn tmp) (car tmp)))
  354.          (byte-optimize-form (nth 1 form) for-effect)))
  355.       ((eq fn 'prog1)
  356.        (if (cdr (cdr form))
  357.            (cons 'prog1
  358.              (cons (byte-optimize-form (nth 1 form) for-effect)
  359.                (byte-optimize-body (cdr (cdr form)) t)))
  360.          (byte-optimize-form (nth 1 form) for-effect)))
  361.       ((eq fn 'prog2)
  362.        (cons 'prog2
  363.          (cons (byte-optimize-form (nth 1 form) t)
  364.            (cons (byte-optimize-form (nth 2 form) for-effect)
  365.              (byte-optimize-body (cdr (cdr (cdr form))) t)))))
  366.       
  367.       ((memq fn '(save-excursion save-restriction))
  368.        ;; those subrs which have an implicit progn; it's not quite good
  369.        ;; enough to treat these like normal function calls.
  370.        ;; This can turn (save-excursion ...) into (save-excursion) which
  371.        ;; will be optimized away in the lap-optimize pass.
  372.        (cons fn (byte-optimize-body (cdr form) for-effect)))
  373.       
  374.       ((eq fn 'with-output-to-temp-buffer)
  375.        ;; this is just like the above, except for the first argument.
  376.        (cons fn
  377.          (cons
  378.           (byte-optimize-form (nth 1 form) nil)
  379.           (byte-optimize-body (cdr (cdr form)) for-effect))))
  380.       
  381.       ((eq fn 'if)
  382.        (cons fn
  383.          (cons (byte-optimize-form (nth 1 form) nil)
  384.            (cons
  385.         (byte-optimize-form (nth 2 form) for-effect)
  386.         (byte-optimize-body (nthcdr 3 form) for-effect)))))
  387.       
  388.       ((memq fn '(and or))  ; remember, and/or are control structures.
  389.        ;; take forms off the back until we can't any more.
  390.        ;; In the future it could concievably be a problem that the
  391.        ;; subexpressions of these forms are optimized in the reverse
  392.        ;; order, but it's ok for now.
  393.        (if for-effect
  394.            (let ((backwards (reverse (cdr form))))
  395.          (while (and backwards
  396.                  (null (setcar backwards
  397.                        (byte-optimize-form (car backwards)
  398.                                    for-effect))))
  399.            (setq backwards (cdr backwards)))
  400.          (if (and (cdr form) (null backwards))
  401.              (byte-compile-log
  402.               "  all subforms of %s called for effect; deleted" form))
  403.          (and backwards
  404.               (cons fn (nreverse backwards))))
  405.          (cons fn (mapcar 'byte-optimize-form (cdr form)))))
  406.  
  407.       ((eq fn 'interactive)
  408.        (byte-compile-warn "misplaced interactive spec: %s"
  409.                   (prin1-to-string form))
  410.        nil)
  411.       
  412.       ((memq fn '(defun defmacro function
  413.               condition-case save-window-excursion))
  414.        ;; These forms are compiled as constants or by breaking out
  415.        ;; all the subexpressions and compiling them separately.
  416.        form)
  417.  
  418.       ((eq fn 'unwind-protect)
  419.        ;; the "protected" part of an unwind-protect is compiled (and thus
  420.        ;; optimized) as a top-level form, so don't do it here.  But the
  421.        ;; non-protected part has the same for-effect status as the
  422.        ;; unwind-protect itself.  (The protected part is always for effect,
  423.        ;; but that isn't handled properly yet.)
  424.        (cons fn
  425.          (cons (byte-optimize-form (nth 1 form) for-effect)
  426.                (cdr (cdr form)))))
  427.        
  428.       ((eq fn 'catch)
  429.        ;; the body of a catch is compiled (and thus optimized) as a
  430.        ;; top-level form, so don't do it here.  The tag is never
  431.        ;; for-effect.  The body should have the same for-effect status
  432.        ;; as the catch form itself, but that isn't handled properly yet.
  433.        (cons fn
  434.          (cons (byte-optimize-form (nth 1 form) nil)
  435.                (cdr (cdr form)))))
  436.  
  437.       ;; If optimization is on, this is the only place that macros are
  438.       ;; expanded.  If optimization is off, then macroexpansion happens
  439.       ;; in byte-compile-form.  Otherwise, the macros are already expanded
  440.       ;; by the time that is reached.
  441.       ((not (eq form
  442.             (setq form (macroexpand form
  443.                         byte-compile-macro-environment))))
  444.        (byte-optimize-form form for-effect))
  445.       
  446.       ((not (symbolp fn))
  447.        (or (eq 'mocklisp (car-safe fn)) ; ha!
  448.            (byte-compile-warn "%s is a malformed function"
  449.                   (prin1-to-string fn)))
  450.        form)
  451.  
  452.       ((and for-effect (setq tmp (get fn 'side-effect-free))
  453.         (or byte-compile-delete-errors
  454.             (eq tmp 'error-free)
  455.             (progn
  456.               (byte-compile-warn "%s called for effect"
  457.                      (prin1-to-string form))
  458.               nil)))
  459.        (byte-compile-log "  %s called for effect; deleted" fn)
  460.        ;; appending a nil here might not be necessary, but it can't hurt.
  461.        (byte-optimize-form
  462.         (cons 'progn (append (cdr form) '(nil))) t))
  463.       
  464.       (t
  465.        ;; Otherwise, no args can be considered to be for-effect,
  466.        ;; even if the called function is for-effect, because we
  467.        ;; don't know anything about that function.
  468.        (cons fn (mapcar 'byte-optimize-form (cdr form)))))))
  469.  
  470.  
  471. (defun byte-optimize-form (form &optional for-effect)
  472.   "The source-level pass of the optimizer."
  473.   ;;
  474.   ;; First, optimize all sub-forms of this one.
  475.   (setq form (byte-optimize-form-code-walker form for-effect))
  476.   ;;
  477.   ;; after optimizing all subforms, optimize this form until it doesn't
  478.   ;; optimize any further.  This means that some forms will be passed through
  479.   ;; the optimizer many times, but that's necessary to make the for-effect
  480.   ;; processing do as much as possible.
  481.   ;;
  482.   (let (opt new)
  483.     (if (and (consp form)
  484.          (symbolp (car form))
  485.          (or (and for-effect
  486.               ;; we don't have any of these yet, but we might.
  487.               (setq opt (get (car form) 'byte-for-effect-optimizer)))
  488.          (setq opt (get (car form) 'byte-optimizer)))
  489.          (not (eq form (setq new (funcall opt form)))))
  490.     (progn
  491. ;;      (if (equal form new) (error "bogus optimizer -- %s" opt))
  492.       (byte-compile-log "  %s\t==>\t%s" form new)
  493.       (setq new (byte-optimize-form new for-effect))
  494.       new)
  495.       form)))
  496.  
  497.  
  498. (defun byte-optimize-body (forms all-for-effect)
  499.   ;; optimize the cdr of a progn or implicit progn; all forms is a list of
  500.   ;; forms, all but the last of which are optimized with the assumption that
  501.   ;; they are being called for effect.  the last is for-effect as well if
  502.   ;; all-for-effect is true.  returns a new list of forms.
  503.   (let ((rest forms)
  504.     (result nil)
  505.     fe new)
  506.     (while rest
  507.       (setq fe (or all-for-effect (cdr rest)))
  508.       (setq new (and (car rest) (byte-optimize-form (car rest) fe)))
  509.       (if (or new (not fe))
  510.       (setq result (cons new result)))
  511.       (setq rest (cdr rest)))
  512.     (nreverse result)))
  513.  
  514.  
  515. ;;; some source-level optimizers
  516. ;;;
  517. ;;; when writing optimizers, be VERY careful that the optimizer returns
  518. ;;; something not EQ to its argument if and ONLY if it has made a change.
  519. ;;; This implies that you cannot simply destructively modify the list;
  520. ;;; you must return something not EQ to it if you make an optimization.
  521. ;;;
  522. ;;; It is now safe to optimize code such that it introduces new bindings.
  523.  
  524. ;; I'd like this to be a defsubst, but let's not be self-referental...
  525. (defmacro byte-compile-trueconstp (form)
  526.   ;; Returns non-nil if FORM is a non-nil constant.
  527.   (` (cond ((consp (, form)) (eq (car (, form)) 'quote))
  528.        ((not (symbolp (, form))))
  529.        ((eq (, form) t)))))
  530.  
  531. (defun byte-optimize-associative-math (form)
  532.   "If the function is being called with constant numeric args,
  533. evaluate as much as possible at compile-time.  This optimizer 
  534. assumes that the function is associative, like + or *."
  535.   (let ((args nil)
  536.     (constants nil)
  537.     (rest (cdr form)))
  538.     (while rest
  539.       (if (numberp (car rest))
  540.       (setq constants (cons (car rest) constants))
  541.       (setq args (cons (car rest) args)))
  542.       (setq rest (cdr rest)))
  543.     (if (cdr constants)
  544.     (if args
  545.         (list (car form)
  546.           (apply (car form) constants)
  547.           (if (cdr args)
  548.               (cons (car form) (nreverse args))
  549.               (car args)))
  550.         (apply (car form) constants))
  551.     form)))
  552.  
  553. (defun byte-optimize-nonassociative-math (form)
  554.   "If the function is being called with constant numeric args,
  555. evaluate as much as possible at compile-time.  This optimizer 
  556. assumes that the function is nonassociative, like - or /."
  557.   (if (or (not (numberp (car (cdr form))))
  558.       (not (numberp (car (cdr (cdr form))))))
  559.       form
  560.     (let ((constant (car (cdr form)))
  561.       (rest (cdr (cdr form))))
  562.       (while (numberp (car rest))
  563.     (setq constant (funcall (car form) constant (car rest))
  564.           rest (cdr rest)))
  565.       (if rest
  566.       (cons (car form) (cons constant rest))
  567.       constant))))
  568.  
  569. ;;(defun byte-optimize-associative-two-args-math (form)
  570. ;;  (setq form (byte-optimize-associative-math form))
  571. ;;  (if (consp form)
  572. ;;      (byte-optimize-two-args-left form)
  573. ;;      form))
  574.  
  575. ;;(defun byte-optimize-nonassociative-two-args-math (form)
  576. ;;  (setq form (byte-optimize-nonassociative-math form))
  577. ;;  (if (consp form)
  578. ;;      (byte-optimize-two-args-right form)
  579. ;;      form))
  580.  
  581. (defun byte-optimize-delay-constants-math (form start fun)
  582.   ;; Merge all FORM's constants from number START, call FUN on them
  583.   ;; and put the result at the end.
  584.   (let ((rest (nthcdr (1- start) form)))
  585.     (while (cdr (setq rest (cdr rest)))
  586.       (if (numberp (car rest))
  587.       (let (constants)
  588.         (setq form (copy-sequence form)
  589.           rest (nthcdr (1- start) form))
  590.         (while (setq rest (cdr rest))
  591.           (cond ((numberp (car rest))
  592.              (setq constants (cons (car rest) constants))
  593.              (setcar rest nil))))
  594.         (setq form (nconc (delq nil form)
  595.                   (list (apply fun (nreverse constants))))))))
  596.     form))
  597.  
  598. (defun byte-optimize-plus (form)
  599.   (setq form (byte-optimize-delay-constants-math form 1 '+))
  600.   (if (memq 0 form) (setq form (delq 0 (copy-sequence form))))
  601.   ;;(setq form (byte-optimize-associative-two-args-math form))
  602.   (cond ((null (cdr form))
  603.      (condition-case ()
  604.          (eval form)
  605.        (error form)))
  606.     ((null (cdr (cdr form))) (nth 1 form))
  607.     (t form)))
  608.  
  609. (defun byte-optimize-minus (form)
  610.   ;; Put constants at the end, except the last constant.
  611.   (setq form (byte-optimize-delay-constants-math form 2 '+))
  612.   ;; Now only first and last element can be a number.
  613.   (let ((last (car (reverse (nthcdr 3 form)))))
  614.     (cond ((eq 0 last)
  615.        ;; (- x y ... 0)  --> (- x y ...)
  616.        (setq form (copy-sequence form))
  617.        (setcdr (cdr (cdr form)) (delq 0 (nthcdr 3 form))))
  618.       ;; If form is (- CONST foo... CONST), merge first and last.
  619.       ((and (numberp (nth 1 form))
  620.         (numberp last))
  621.        (setq form (nconc (list '- (- (nth 1 form) last) (nth 2 form))
  622.                  (delq last (copy-sequence (nthcdr 3 form))))))))
  623.   (if (eq (nth 2 form) 0)
  624.       (nth 1 form)            ; (- x 0)  -->  x
  625.     (byte-optimize-predicate
  626.      (if (and (null (cdr (cdr (cdr form))))
  627.           (eq (nth 1 form) 0))    ; (- 0 x)  -->  (- x)
  628.      (cons (car form) (cdr (cdr form)))
  629.        form))))
  630.  
  631. (defun byte-optimize-multiply (form)
  632.   (setq form (byte-optimize-delay-constants-math form 1 '*))
  633.   ;; If there is a constant in FORM, it is now the last element.
  634.   (cond ((null (cdr form)) 1)
  635.     ((null (cdr (cdr form))) (nth 1 form))
  636.     ((let ((last (car (reverse form))))
  637.        (cond ((eq 0 last)  (list 'progn (cdr form)))
  638.          ((eq 1 last)  (delq 1 (copy-sequence form)))
  639.          ((eq -1 last) (list '- (delq -1 (copy-sequence form))))
  640.          ((and (eq 2 last)
  641.                (memq t (mapcar 'symbolp (cdr form))))
  642.           (prog1 (setq form (delq 2 (copy-sequence form)))
  643.             (while (not (symbolp (car (setq form (cdr form))))))
  644.             (setcar form (list '+ (car form) (car form)))))
  645.          (form))))))
  646.  
  647. (defsubst byte-compile-butlast (form)
  648.   (nreverse (cdr (reverse form))))
  649.  
  650. (defun byte-optimize-divide (form)
  651.   (setq form (byte-optimize-delay-constants-math form 2 '*))
  652.   (let ((last (car (reverse (cdr (cdr form))))))
  653.     (if (numberp last)
  654.     (cond ((= last 1)
  655.            (setq form (byte-compile-butlast form)))
  656.           ((numberp (nth 1 form))
  657.            (setq form (cons (car form)
  658.                 (cons (/ (nth 1 form) last)
  659.                       (byte-compile-butlast (cdr (cdr form)))))
  660.              last nil))))
  661.     (cond ((null (cdr (cdr form)))
  662.        (nth 1 form))
  663.       ((eq (nth 1 form) 0)
  664.        (append '(progn) (cdr (cdr form)) '(0)))
  665.       ((eq last -1)
  666.        (list '- (if (nthcdr 3 form)
  667.             (byte-compile-butlast form)
  668.               (nth 1 form))))
  669.       (form))))
  670.  
  671. (defun byte-optimize-logmumble (form)
  672.   (setq form (byte-optimize-delay-constants-math form 1 (car form)))
  673.   (byte-optimize-predicate
  674.    (cond ((memq 0 form)
  675.       (setq form (if (eq (car form) 'logand)
  676.              (cons 'progn (cdr form))
  677.                (delq 0 (copy-sequence form)))))
  678.      ((and (eq (car-safe form) 'logior)
  679.            (memq -1 form))
  680.       (delq -1 (copy-sequence form)))
  681.      (form))))
  682.  
  683.  
  684. (defun byte-optimize-binary-predicate (form)
  685.   (if (byte-compile-constp (nth 1 form))
  686.       (if (byte-compile-constp (nth 2 form))
  687.       (condition-case ()
  688.           (list 'quote (eval form))
  689.         (error form))
  690.     ;; This can enable some lapcode optimizations.
  691.     (list (car form) (nth 2 form) (nth 1 form)))
  692.     form))
  693.  
  694. (defun byte-optimize-predicate (form)
  695.   (let ((ok t)
  696.     (rest (cdr form)))
  697.     (while (and rest ok)
  698.       (setq ok (byte-compile-constp (car rest))
  699.         rest (cdr rest)))
  700.     (if ok
  701.     (condition-case ()
  702.         (list 'quote (eval form))
  703.       (error form))
  704.     form)))
  705.  
  706. (defun byte-optimize-identity (form)
  707.   (if (and (cdr form) (null (cdr (cdr form))))
  708.       (nth 1 form)
  709.     (byte-compile-warn "identity called with %d arg%s, but requires 1"
  710.                (length (cdr form))
  711.                (if (= 1 (length (cdr form))) "" "s"))
  712.     form))
  713.  
  714. (put 'identity 'byte-optimizer 'byte-optimize-identity)
  715.  
  716. (put '+   'byte-optimizer 'byte-optimize-plus)
  717. (put '*   'byte-optimizer 'byte-optimize-multiply)
  718. (put '-   'byte-optimizer 'byte-optimize-minus)
  719. (put '/   'byte-optimizer 'byte-optimize-divide)
  720. (put 'max 'byte-optimizer 'byte-optimize-associative-math)
  721. (put 'min 'byte-optimizer 'byte-optimize-associative-math)
  722.  
  723. (put '=   'byte-optimizer 'byte-optimize-binary-predicate)
  724. (put 'eq  'byte-optimizer 'byte-optimize-binary-predicate)
  725. (put 'eql 'byte-optimizer 'byte-optimize-binary-predicate)
  726. (put 'equal   'byte-optimizer 'byte-optimize-binary-predicate)
  727. (put 'string= 'byte-optimizer 'byte-optimize-binary-predicate)
  728. (put 'string-equal 'byte-optimizer 'byte-optimize-binary-predicate)
  729.  
  730. (put '<   'byte-optimizer 'byte-optimize-predicate)
  731. (put '>   'byte-optimizer 'byte-optimize-predicate)
  732. (put '<=  'byte-optimizer 'byte-optimize-predicate)
  733. (put '>=  'byte-optimizer 'byte-optimize-predicate)
  734. (put '1+  'byte-optimizer 'byte-optimize-predicate)
  735. (put '1-  'byte-optimizer 'byte-optimize-predicate)
  736. (put 'not 'byte-optimizer 'byte-optimize-predicate)
  737. (put 'null  'byte-optimizer 'byte-optimize-predicate)
  738. (put 'memq  'byte-optimizer 'byte-optimize-predicate)
  739. (put 'consp 'byte-optimizer 'byte-optimize-predicate)
  740. (put 'listp 'byte-optimizer 'byte-optimize-predicate)
  741. (put 'symbolp 'byte-optimizer 'byte-optimize-predicate)
  742. (put 'stringp 'byte-optimizer 'byte-optimize-predicate)
  743. (put 'string< 'byte-optimizer 'byte-optimize-predicate)
  744. (put 'string-lessp 'byte-optimizer 'byte-optimize-predicate)
  745.  
  746. (put 'logand 'byte-optimizer 'byte-optimize-logmumble)
  747. (put 'logior 'byte-optimizer 'byte-optimize-logmumble)
  748. (put 'logxor 'byte-optimizer 'byte-optimize-logmumble)
  749. (put 'lognot 'byte-optimizer 'byte-optimize-predicate)
  750.  
  751. (put 'car 'byte-optimizer 'byte-optimize-predicate)
  752. (put 'cdr 'byte-optimizer 'byte-optimize-predicate)
  753. (put 'car-safe 'byte-optimizer 'byte-optimize-predicate)
  754. (put 'cdr-safe 'byte-optimizer 'byte-optimize-predicate)
  755.  
  756.  
  757. ;; I'm not convinced that this is necessary.  Doesn't the optimizer loop 
  758. ;; take care of this? - Jamie
  759. ;; I think this may some times be necessary to reduce ie (quote 5) to 5,
  760. ;; so arithmetic optimizers recognize the numerinc constant.  - Hallvard
  761. (put 'quote 'byte-optimizer 'byte-optimize-quote)
  762. (defun byte-optimize-quote (form)
  763.   (if (or (consp (nth 1 form))
  764.       (and (symbolp (nth 1 form))
  765.            (not (memq (nth 1 form) '(nil t)))))
  766.       form
  767.     (nth 1 form)))
  768.  
  769. (defun byte-optimize-zerop (form)
  770.   (cond ((numberp (nth 1 form))
  771.      (eval form))
  772.     (byte-compile-delete-errors
  773.      (list '= (nth 1 form) 0))
  774.     (form)))
  775.  
  776. (put 'zerop 'byte-optimizer 'byte-optimize-zerop)
  777.  
  778. (defun byte-optimize-and (form)
  779.   ;; Simplify if less than 2 args.
  780.   ;; if there is a literal nil in the args to `and', throw it and following
  781.   ;; forms away, and surround the `and' with (progn ... nil).
  782.   (cond ((null (cdr form)))
  783.     ((memq nil form)
  784.      (list 'progn
  785.            (byte-optimize-and
  786.         (prog1 (setq form (copy-sequence form))
  787.           (while (nth 1 form)
  788.             (setq form (cdr form)))
  789.           (setcdr form nil)))
  790.            nil))
  791.     ((null (cdr (cdr form)))
  792.      (nth 1 form))
  793.     ((byte-optimize-predicate form))))
  794.  
  795. (defun byte-optimize-or (form)
  796.   ;; Throw away nil's, and simplify if less than 2 args.
  797.   ;; If there is a literal non-nil constant in the args to `or', throw away all
  798.   ;; following forms.
  799.   (if (memq nil form)
  800.       (setq form (delq nil (copy-sequence form))))
  801.   (let ((rest form))
  802.     (while (cdr (setq rest (cdr rest)))
  803.       (if (byte-compile-trueconstp (car rest))
  804.       (setq form (copy-sequence form)
  805.         rest (setcdr (memq (car rest) form) nil))))
  806.     (if (cdr (cdr form))
  807.     (byte-optimize-predicate form)
  808.       (nth 1 form))))
  809.  
  810. (defun byte-optimize-cond (form)
  811.   ;; if any clauses have a literal nil as their test, throw them away.
  812.   ;; if any clause has a literal non-nil constant as its test, throw
  813.   ;; away all following clauses.
  814.   (let (rest)
  815.     ;; This must be first, to reduce (cond (t ...) (nil)) to (progn t ...)
  816.     (while (setq rest (assq nil (cdr form)))
  817.       (setq form (delq rest (copy-sequence form))))
  818.     (if (memq nil (cdr form))
  819.     (setq form (delq nil (copy-sequence form))))
  820.     (setq rest form)
  821.     (while (setq rest (cdr rest))
  822.       (cond ((byte-compile-trueconstp (car-safe (car rest)))
  823.          (cond ((eq rest (cdr form))
  824.             (setq form
  825.               (if (cdr (car rest))
  826.                   (if (cdr (cdr (car rest)))
  827.                   (cons 'progn (cdr (car rest)))
  828.                 (nth 1 (car rest)))
  829.                 (car (car rest)))))
  830.            ((cdr rest)
  831.             (setq form (copy-sequence form))
  832.             (setcdr (memq (car rest) form) nil)))
  833.          (setq rest nil)))))
  834.   ;;
  835.   ;; Turn (cond (( <x> )) ... ) into (or <x> (cond ... ))
  836.   (if (eq 'cond (car-safe form))
  837.       (let ((clauses (cdr form)))
  838.     (if (and (consp (car clauses))
  839.          (null (cdr (car clauses))))
  840.         (list 'or (car (car clauses))
  841.           (byte-optimize-cond
  842.            (cons (car form) (cdr (cdr form)))))
  843.       form))
  844.     form))
  845.  
  846. (defun byte-optimize-if (form)
  847.   ;; (if <true-constant> <then> <else...>) ==> <then>
  848.   ;; (if <false-constant> <then> <else...>) ==> (progn <else...>)
  849.   ;; (if <test> nil <else...>) ==> (if (not <test>) (progn <else...>))
  850.   ;; (if <test> <then> nil) ==> (if <test> <then>)
  851.   (let ((clause (nth 1 form)))
  852.     (cond ((byte-compile-trueconstp clause)
  853.        (nth 2 form))
  854.       ((null clause)
  855.        (if (nthcdr 4 form)
  856.            (cons 'progn (nthcdr 3 form))
  857.          (nth 3 form)))
  858.       ((nth 2 form)
  859.        (if (equal '(nil) (nthcdr 3 form))
  860.            (list 'if clause (nth 2 form))
  861.          form))
  862.       ((or (nth 3 form) (nthcdr 4 form))
  863.        (list 'if (list 'not clause)
  864.          (if (nthcdr 4 form)
  865.              (cons 'progn (nthcdr 3 form))
  866.            (nth 3 form))))
  867.       (t
  868.        (list 'progn clause nil)))))
  869.  
  870. (defun byte-optimize-while (form)
  871.   (if (nth 1 form)
  872.       form))
  873.  
  874. (put 'and   'byte-optimizer 'byte-optimize-and)
  875. (put 'or    'byte-optimizer 'byte-optimize-or)
  876. (put 'cond  'byte-optimizer 'byte-optimize-cond)
  877. (put 'if    'byte-optimizer 'byte-optimize-if)
  878. (put 'while 'byte-optimizer 'byte-optimize-while)
  879.  
  880. ;; byte-compile-negation-optimizer lives in bytecomp.el
  881. (put '/= 'byte-optimizer 'byte-compile-negation-optimizer)
  882. (put 'atom 'byte-optimizer 'byte-compile-negation-optimizer)
  883. (put 'nlistp 'byte-optimizer 'byte-compile-negation-optimizer)
  884.  
  885.  
  886. (defun byte-optimize-funcall (form)
  887.   ;; (funcall '(lambda ...) ...) ==> ((lambda ...) ...)
  888.   ;; (funcall 'foo ...) ==> (foo ...)
  889.   (let ((fn (nth 1 form)))
  890.     (if (memq (car-safe fn) '(quote function))
  891.     (cons (nth 1 fn) (cdr (cdr form)))
  892.     form)))
  893.  
  894. (defun byte-optimize-apply (form)
  895.   ;; If the last arg is a literal constant, turn this into a funcall.
  896.   ;; The funcall optimizer can then transform (funcall 'foo ...) -> (foo ...).
  897.   (let ((fn (nth 1 form))
  898.     (last (nth (1- (length form)) form))) ; I think this really is fastest
  899.     (or (if (or (null last)
  900.         (eq (car-safe last) 'quote))
  901.         (if (listp (nth 1 last))
  902.         (let ((butlast (nreverse (cdr (reverse (cdr (cdr form)))))))
  903.           (nconc (list 'funcall fn) butlast
  904.              (mapcar '(lambda (x) (list 'quote x)) (nth 1 last))))
  905.           (byte-compile-warn
  906.            "last arg to apply can't be a literal atom: %s"
  907.            (prin1-to-string last))
  908.           nil))
  909.     form)))
  910.  
  911. (put 'funcall 'byte-optimizer 'byte-optimize-funcall)
  912. (put 'apply   'byte-optimizer 'byte-optimize-apply)
  913.  
  914.  
  915. (put 'let 'byte-optimizer 'byte-optimize-letX)
  916. (put 'let* 'byte-optimizer 'byte-optimize-letX)
  917. (defun byte-optimize-letX (form)
  918.   (cond ((null (nth 1 form))
  919.      ;; No bindings
  920.      (cons 'progn (cdr (cdr form))))
  921.     ((or (nth 2 form) (nthcdr 3 form))
  922.      form)
  923.      ;; The body is nil
  924.     ((eq (car form) 'let)
  925.      (append '(progn) (mapcar 'car (mapcar 'cdr (nth 1 form))) '(nil)))
  926.     (t
  927.      (let ((binds (reverse (nth 1 form))))
  928.        (list 'let* (reverse (cdr binds)) (nth 1 (car binds)) nil)))))
  929.  
  930.  
  931. (put 'nth 'byte-optimizer 'byte-optimize-nth)
  932. (defun byte-optimize-nth (form)
  933.   (if (memq (nth 1 form) '(0 1))
  934.       (list 'car (if (zerop (nth 1 form))
  935.              (nth 2 form)
  936.            (list 'cdr (nth 2 form))))
  937.     (byte-optimize-predicate form)))
  938.  
  939. (put 'nthcdr 'byte-optimizer 'byte-optimize-nthcdr)
  940. (defun byte-optimize-nthcdr (form)
  941.   (let ((count (nth 1 form)))
  942.     (if (not (memq count '(0 1 2)))
  943.     (byte-optimize-predicate form)
  944.       (setq form (nth 2 form))
  945.       (while (natnump (setq count (1- count)))
  946.     (setq form (list 'cdr form)))
  947.       form)))
  948.  
  949. ;;; enumerating those functions which need not be called if the returned 
  950. ;;; value is not used.  That is, something like
  951. ;;;    (progn (list (something-with-side-effects) (yow))
  952. ;;;           (foo))
  953. ;;; may safely be turned into
  954. ;;;    (progn (progn (something-with-side-effects) (yow))
  955. ;;;           (foo))
  956. ;;; Further optimizations will turn (progn (list 1 2 3) 'foo) into 'foo.
  957.  
  958. ;;; I wonder if I missed any :-\)
  959. (let ((side-effect-free-fns
  960.        '(% * + / /= 1+ < <= = > >= append aref ash assoc assq boundp
  961.      buffer-file-name buffer-local-variables buffer-modified-p
  962.      buffer-substring capitalize car cdr concat coordinates-in-window-p
  963.      copy-marker count-lines documentation downcase elt fboundp featurep
  964.      file-directory-p file-exists-p file-locked-p file-name-absolute-p
  965.      file-newer-than-file-p file-readable-p file-symlink-p file-writable-p
  966.      format get get-buffer get-buffer-window getenv get-file-buffer length
  967.      logand logior lognot logxor lsh marker-buffer max member memq min mod
  968.      next-window nth nthcdr previous-window rassq regexp-quote reverse
  969.      string< string= string-lessp string-equal substring user-variable-p
  970.      window-buffer window-edges window-height window-hscroll window-width
  971.      zerop))
  972.       ;; could also add plusp, minusp, signum.  If anyone ever defines
  973.       ;; these, they will certainly be side-effect free.
  974.       (side-effect-and-error-free-fns
  975.        '(arrayp atom bobp bolp buffer-end buffer-list buffer-size
  976.      buffer-string bufferp char-or-string-p commandp cons consp
  977.      current-buffer dot dot-marker eobp eolp eq eql equal
  978.      get-largest-window identity integerp integer-or-marker-p
  979.      interactive-p keymapp list listp make-marker mark mark-marker
  980.      markerp minibuffer-window natnump nlistp not null numberp
  981.      one-window-p point point-marker processp selected-window sequencep
  982.      stringp subrp symbolp syntax-table-p vector vectorp windowp)))
  983.   (while side-effect-free-fns
  984.     (put (car side-effect-free-fns) 'side-effect-free t)
  985.     (setq side-effect-free-fns (cdr side-effect-free-fns)))
  986.   (while side-effect-and-error-free-fns
  987.     (put (car side-effect-and-error-free-fns) 'side-effect-free 'error-free)
  988.     (setq side-effect-and-error-free-fns (cdr side-effect-and-error-free-fns)))
  989.   nil)
  990.  
  991.  
  992. (defun byte-compile-splice-in-already-compiled-code (form)
  993.   ;; form is (byte-code "..." [...] n)
  994.   (if (not (memq byte-optimize '(t lap)))
  995.       (byte-compile-normal-call form)
  996.     (byte-inline-lapcode
  997.      (byte-decompile-bytecode-1 (nth 1 form) (nth 2 form) t))
  998.     (setq byte-compile-maxdepth (max (+ byte-compile-depth (nth 3 form))
  999.                      byte-compile-maxdepth))
  1000.     (setq byte-compile-depth (1+ byte-compile-depth))))
  1001.  
  1002. (put 'byte-code 'byte-compile 'byte-compile-splice-in-already-compiled-code)
  1003.  
  1004.  
  1005. (defconst byte-constref-ops
  1006.   '(byte-constant byte-constant2 byte-varref byte-varset byte-varbind))
  1007.  
  1008. ;;; This function extracts the bitfields from variable-length opcodes.
  1009. ;;; Originally defined in disass.el (which no longer uses it.)
  1010.  
  1011. (defun disassemble-offset ()
  1012.   "Don't call this!"
  1013.   ;; fetch and return the offset for the current opcode.
  1014.   ;; return NIL if this opcode has no offset
  1015.   ;; OP, PTR and BYTES are used and set dynamically
  1016.   (defvar op)
  1017.   (defvar ptr)
  1018.   (defvar bytes)
  1019.   (cond ((< op byte-nth)
  1020.      (let ((tem (logand op 7)))
  1021.        (setq op (logand op 248))
  1022.        (cond ((eq tem 6)
  1023.           (setq ptr (1+ ptr))    ;offset in next byte
  1024.           (aref bytes ptr))
  1025.          ((eq tem 7)
  1026.           (setq ptr (1+ ptr))    ;offset in next 2 bytes
  1027.           (+ (aref bytes ptr)
  1028.              (progn (setq ptr (1+ ptr))
  1029.                 (lsh (aref bytes ptr) 8))))
  1030.          (t tem))))        ;offset was in opcode
  1031.     ((>= op byte-constant)
  1032.      (prog1 (- op byte-constant)    ;offset in opcode
  1033.        (setq op byte-constant)))
  1034.     ((and (>= op byte-constant2)
  1035.           (<= op byte-goto-if-not-nil-else-pop))
  1036.      (setq ptr (1+ ptr))        ;offset in next 2 bytes
  1037.      (+ (aref bytes ptr)
  1038.         (progn (setq ptr (1+ ptr))
  1039.            (lsh (aref bytes ptr) 8))))
  1040.     ((and (>= op byte-rel-goto)
  1041.           (<= op byte-insertN))
  1042.      (setq ptr (1+ ptr))        ;offset in next byte
  1043.      (aref bytes ptr))))
  1044.  
  1045.  
  1046. ;;; This de-compiler is used for inline expansion of compiled functions,
  1047. ;;; and by the disassembler.
  1048. ;;;
  1049. (defun byte-decompile-bytecode (bytes constvec)
  1050.   "Turns BYTECODE into lapcode, refering to CONSTVEC."
  1051.   (let ((byte-compile-constants nil)
  1052.     (byte-compile-variables nil)
  1053.     (byte-compile-tag-number 0))
  1054.     (byte-decompile-bytecode-1 bytes constvec)))
  1055.  
  1056. (defun byte-decompile-bytecode-1 (bytes constvec &optional make-splicable)
  1057.   "As byte-decompile-bytecode, but updates
  1058. byte-compile-{constants, variables, tag-number}.
  1059. If the optional 3rd arg is true, then `return' opcodes are replaced
  1060. with `goto's destined for the end of the code."
  1061.   (let ((length (length bytes))
  1062.     (ptr 0) optr tag tags op offset
  1063.     lap tmp
  1064.     endtag
  1065.     (retcount 0))
  1066.     (while (not (= ptr length))
  1067.       (setq op (aref bytes ptr)
  1068.         optr ptr
  1069.         offset (disassemble-offset)) ; this does dynamic-scope magic
  1070.       (setq op (aref byte-code-vector op))
  1071.       (cond ((or (memq op byte-goto-ops)
  1072.          (cond ((memq op byte-rel-goto-ops)
  1073.             (setq op (aref byte-code-vector
  1074.                        (- (symbol-value op)
  1075.                       (- byte-rel-goto byte-goto))))
  1076.             (setq offset (+ ptr (- offset 127)))
  1077.             t)))
  1078.          ;; it's a pc
  1079.          (setq offset
  1080.            (cdr (or (assq offset tags)
  1081.                 (car (setq tags
  1082.                        (cons (cons offset
  1083.                            (byte-compile-make-tag))
  1084.                          tags)))))))
  1085.         ((cond ((eq op 'byte-constant2) (setq op 'byte-constant) t)
  1086.            ((memq op byte-constref-ops)))
  1087.          (setq tmp (aref constvec offset)
  1088.            offset (if (eq op 'byte-constant)
  1089.                   (byte-compile-get-constant tmp)
  1090.                 (or (assq tmp byte-compile-variables)
  1091.                 (car (setq byte-compile-variables
  1092.                        (cons (list tmp)
  1093.                          byte-compile-variables)))))))
  1094.         ((and make-splicable
  1095.           (eq op 'byte-return))
  1096.          (if (= ptr (1- length))
  1097.          (setq op nil)
  1098.            (setq offset (or endtag (setq endtag (byte-compile-make-tag)))
  1099.              op 'byte-goto))))
  1100.       ;; lap = ( [ (pc . (op . arg)) ]* )
  1101.       (setq lap (cons (cons optr (cons op (or offset 0)))
  1102.               lap))
  1103.       (setq ptr (1+ ptr)))
  1104.     ;; take off the dummy nil op that we replaced a trailing "return" with.
  1105.     (let ((rest lap))
  1106.       (while rest
  1107.     (cond ((setq tmp (assq (car (car rest)) tags))
  1108.            ;; this addr is jumped to
  1109.            (setcdr rest (cons (cons nil (cdr tmp))
  1110.                   (cdr rest)))
  1111.            (setq tags (delq tmp tags))
  1112.            (setq rest (cdr rest))))
  1113.     (setq rest (cdr rest))))
  1114.     (if tags (error "optimizer error: missed tags %s" tags))
  1115.     (if (null (car (cdr (car lap))))
  1116.     (setq lap (cdr lap)))
  1117.     (if endtag
  1118.     (setq lap (cons (cons nil endtag) lap)))
  1119.     ;; remove addrs, lap = ( [ (op . arg) | (TAG tagno) ]* )
  1120.     (mapcar 'cdr (nreverse lap))))
  1121.  
  1122.  
  1123. ;;; peephole optimizer
  1124.  
  1125. (defconst byte-tagref-ops (cons 'TAG byte-goto-ops))
  1126.  
  1127. (defconst byte-conditional-ops
  1128.   '(byte-goto-if-nil byte-goto-if-not-nil byte-goto-if-nil-else-pop
  1129.     byte-goto-if-not-nil-else-pop))
  1130.  
  1131. (defconst byte-after-unbind-ops
  1132.    '(byte-constant byte-dup
  1133.      byte-symbolp byte-consp byte-stringp byte-listp byte-numberp byte-integerp
  1134.      byte-eq byte-equal byte-not
  1135.      byte-cons byte-list1 byte-list2    ; byte-list3 byte-list4
  1136.      byte-interactive-p
  1137.      ;; How about other side-effect-free-ops?  Is it safe to move an
  1138.      ;; error invocation (such as from nth) out of an unwind-protect?
  1139.      "Byte-codes that can be moved past an unbind."))
  1140.  
  1141. (defconst byte-compile-side-effect-and-error-free-ops
  1142.   '(byte-constant byte-dup byte-symbolp byte-consp byte-stringp byte-listp
  1143.     byte-integerp byte-numberp byte-eq byte-equal byte-not byte-car-safe
  1144.     byte-cdr-safe byte-cons byte-list1 byte-list2 byte-point byte-point-max
  1145.     byte-point-min byte-following-char byte-preceding-char
  1146.     byte-current-column byte-eolp byte-eobp byte-bolp byte-bobp
  1147.     byte-current-buffer byte-interactive-p))
  1148.  
  1149. (defconst byte-compile-side-effect-free-ops
  1150.   (nconc 
  1151.    '(byte-varref byte-nth byte-memq byte-car byte-cdr byte-length byte-aref
  1152.      byte-symbol-value byte-get byte-concat2 byte-concat3 byte-sub1 byte-add1
  1153.      byte-eqlsign byte-gtr byte-lss byte-leq byte-geq byte-diff byte-negate
  1154.      byte-plus byte-max byte-min byte-mult byte-char-after byte-char-syntax
  1155.      byte-buffer-substring byte-string= byte-string< byte-nthcdr byte-elt
  1156.      byte-member byte-assq byte-quo byte-rem)
  1157.    byte-compile-side-effect-and-error-free-ops))
  1158.  
  1159. ;;; This piece of shit is because of the way DEFVAR_BOOL() variables work.
  1160. ;;; Consider the code
  1161. ;;;
  1162. ;;;    (defun foo (flag)
  1163. ;;;      (let ((old-pop-ups pop-up-windows)
  1164. ;;;        (pop-up-windows flag))
  1165. ;;;        (cond ((not (eq pop-up-windows old-pop-ups))
  1166. ;;;           (setq old-pop-ups pop-up-windows)
  1167. ;;;           ...))))
  1168. ;;;
  1169. ;;; Uncompiled, old-pop-ups will always be set to nil or t, even if FLAG is
  1170. ;;; something else.  But if we optimize
  1171. ;;;
  1172. ;;;    varref flag
  1173. ;;;    varbind pop-up-windows
  1174. ;;;    varref pop-up-windows
  1175. ;;;    not
  1176. ;;; to
  1177. ;;;    varref flag
  1178. ;;;    dup
  1179. ;;;    varbind pop-up-windows
  1180. ;;;    not
  1181. ;;;
  1182. ;;; we break the program, because it will appear that pop-up-windows and 
  1183. ;;; old-pop-ups are not EQ when really they are.  So we have to know what
  1184. ;;; the BOOL variables are, and not perform this optimization on them.
  1185. ;;;
  1186. (defconst byte-boolean-vars
  1187.   '(abbrevs-changed abbrev-all-caps inverse-video visible-bell
  1188.     check-protected-fields no-redraw-on-reenter cursor-in-echo-area
  1189.     noninteractive stack-trace-on-error debug-on-error debug-on-quit
  1190.     debug-on-next-call insert-default-directory vms-stmlf-recfm
  1191.     indent-tabs-mode meta-flag load-in-progress defining-kbd-macro
  1192.     completion-auto-help completion-ignore-case enable-recursive-minibuffers
  1193.     print-escape-newlines delete-exited-processes parse-sexp-ignore-comments
  1194.     words-include-escapes pop-up-windows 
  1195.     reset-terminal-on-clear truncate-partial-width-windows
  1196.     mode-line-inverse-video)
  1197.   "DEFVAR_BOOL variables.  Giving these any non-nil value sets them to t.
  1198. If this does not enumerate all DEFVAR_BOOL variables, the byte-optimizer
  1199. may generate incorrect code.")
  1200.  
  1201. (defun byte-optimize-lapcode (lap &optional for-effect)
  1202.   "Simple peephole optimizer.  LAP is both modified and returned."
  1203.   (let (lap0 off0
  1204.     lap1 off1
  1205.     lap2 off2
  1206.     (keep-going 'first-time)
  1207.     (add-depth 0)
  1208.     rest tmp tmp2 tmp3
  1209.     (side-effect-free (if byte-compile-delete-errors
  1210.                   byte-compile-side-effect-free-ops
  1211.                 byte-compile-side-effect-and-error-free-ops)))
  1212.     (while keep-going
  1213.       (or (eq keep-going 'first-time)
  1214.       (byte-compile-log-lap "  ---- next pass"))
  1215.       (setq rest lap
  1216.         keep-going nil)
  1217.       (while rest
  1218.     (setq lap0 (car rest)
  1219.           lap1 (nth 1 rest)
  1220.           lap2 (nth 2 rest))
  1221.  
  1222.     ;; You may notice that sequences like "dup varset discard" are
  1223.     ;; optimized but sequences like "dup varset TAG1: discard" are not.
  1224.     ;; You may be tempted to change this; resist that temptation.
  1225.     (cond ;;
  1226.           ;; <side-effect-free> pop -->  <deleted>
  1227.           ;;  ...including:
  1228.           ;; const-X pop   -->  <deleted>
  1229.           ;; varref-X pop  -->  <deleted>
  1230.           ;; dup pop       -->  <deleted>
  1231.           ;;
  1232.           ((and (eq 'byte-discard (car lap1))
  1233.             (memq (car lap0) side-effect-free))
  1234.            (setq keep-going t)
  1235.            (setq tmp (aref byte-stack+-info (symbol-value (car lap0))))
  1236.            (setq rest (cdr rest))
  1237.            (cond ((= tmp 1)
  1238.               (byte-compile-log-lap
  1239.                 "  %s discard\t-->\t<deleted>" lap0)
  1240.               (setq lap (delq lap0 (delq lap1 lap))))
  1241.              ((= tmp 0)
  1242.               (byte-compile-log-lap
  1243.                "  %s discard\t-->\t<deleted> discard" lap0)
  1244.               (setq lap (delq lap0 lap)))
  1245.              ((= tmp -1)
  1246.               (byte-compile-log-lap
  1247.                "  %s discard\t-->\tdiscard discard" lap0)
  1248.               (setcar lap0 'byte-discard)
  1249.               (setcdr lap0 0))
  1250.              ((error "Optimizer error: too much on the stack"))))
  1251.           ;;
  1252.           ;; goto*-X X:  -->  X:
  1253.           ;;
  1254.           ((and (memq (car lap0) byte-goto-ops)
  1255.             (eq (cdr lap0) lap1))
  1256.            (cond ((eq (car lap0) 'byte-goto)
  1257.               (setq lap (delq lap0 lap))
  1258.               (setq tmp "<deleted>"))
  1259.              ((memq (car lap0) byte-goto-always-pop-ops)
  1260.               (setcar lap0 (setq tmp 'byte-discard))
  1261.               (setcdr lap0 0))
  1262.              ((error "Depth conflict at tag %d" (nth 2 lap0))))
  1263.            (and (memq byte-optimize-log '(t byte))
  1264.             (byte-compile-log "  (goto %s) %s:\t-->\t%s %s:"
  1265.                       (nth 1 lap1) (nth 1 lap1)
  1266.                       tmp (nth 1 lap1)))
  1267.            (setq keep-going t))
  1268.           ;;
  1269.           ;; varset-X varref-X  -->  dup varset-X
  1270.           ;; varbind-X varref-X  -->  dup varbind-X
  1271.           ;; const/dup varset-X varref-X --> const/dup varset-X const/dup
  1272.           ;; const/dup varbind-X varref-X --> const/dup varbind-X const/dup
  1273.           ;; The latter two can enable other optimizations.
  1274.           ;;
  1275.           ((and (eq 'byte-varref (car lap2))
  1276.             (eq (cdr lap1) (cdr lap2))
  1277.             (memq (car lap1) '(byte-varset byte-varbind)))
  1278.            (if (and (setq tmp (memq (car (cdr lap2)) byte-boolean-vars))
  1279.             (not (eq (car lap0) 'byte-constant)))
  1280.            nil
  1281.          (setq keep-going t)
  1282.          (if (memq (car lap0) '(byte-constant byte-dup))
  1283.              (progn
  1284.                (setq tmp (if (or (not tmp)
  1285.                      (memq (car (cdr lap0)) '(nil t)))
  1286.                      (cdr lap0)
  1287.                    (byte-compile-get-constant t)))
  1288.                (byte-compile-log-lap "  %s %s %s\t-->\t%s %s %s"
  1289.                          lap0 lap1 lap2 lap0 lap1
  1290.                          (cons (car lap0) tmp))
  1291.                (setcar lap2 (car lap0))
  1292.                (setcdr lap2 tmp))
  1293.            (byte-compile-log-lap "  %s %s\t-->\tdup %s" lap1 lap2 lap1)
  1294.            (setcar lap2 (car lap1))
  1295.            (setcar lap1 'byte-dup)
  1296.            (setcdr lap1 0)
  1297.            ;; The stack depth gets locally increased, so we will
  1298.            ;; increase maxdepth in case depth = maxdepth here.
  1299.            ;; This can cause the third argument to byte-code to
  1300.            ;; be larger than necessary.
  1301.            (setq add-depth 1))))
  1302.           ;;
  1303.           ;; dup varset-X discard  -->  varset-X
  1304.           ;; dup varbind-X discard  -->  varbind-X
  1305.           ;; (the varbind variant can emerge from other optimizations)
  1306.           ;;
  1307.           ((and (eq 'byte-dup (car lap0))
  1308.             (eq 'byte-discard (car lap2))
  1309.             (memq (car lap1) '(byte-varset byte-varbind)))
  1310.            (byte-compile-log-lap "  dup %s discard\t-->\t%s" lap1 lap1)
  1311.            (setq keep-going t
  1312.              rest (cdr rest))
  1313.            (setq lap (delq lap0 (delq lap2 lap))))
  1314.           ;;
  1315.           ;; not goto-X-if-nil              -->  goto-X-if-non-nil
  1316.           ;; not goto-X-if-non-nil          -->  goto-X-if-nil
  1317.           ;;
  1318.           ;; it is wrong to do the same thing for the -else-pop variants.
  1319.           ;;
  1320.           ((and (eq 'byte-not (car lap0))
  1321.             (or (eq 'byte-goto-if-nil (car lap1))
  1322.             (eq 'byte-goto-if-not-nil (car lap1))))
  1323.            (byte-compile-log-lap "  not %s\t-->\t%s"
  1324.                      lap1
  1325.                      (cons
  1326.                       (if (eq (car lap1) 'byte-goto-if-nil)
  1327.                       'byte-goto-if-not-nil
  1328.                     'byte-goto-if-nil)
  1329.                       (cdr lap1)))
  1330.            (setcar lap1 (if (eq (car lap1) 'byte-goto-if-nil)
  1331.                 'byte-goto-if-not-nil
  1332.                 'byte-goto-if-nil))
  1333.            (setq lap (delq lap0 lap))
  1334.            (setq keep-going t))
  1335.           ;;
  1336.           ;; goto-X-if-nil     goto-Y X:  -->  goto-Y-if-non-nil X:
  1337.           ;; goto-X-if-non-nil goto-Y X:  -->  goto-Y-if-nil     X:
  1338.           ;;
  1339.           ;; it is wrong to do the same thing for the -else-pop variants.
  1340.           ;; 
  1341.           ((and (or (eq 'byte-goto-if-nil (car lap0))
  1342.             (eq 'byte-goto-if-not-nil (car lap0)))    ; gotoX
  1343.             (eq 'byte-goto (car lap1))            ; gotoY
  1344.             (eq (cdr lap0) lap2))            ; TAG X
  1345.            (let ((inverse (if (eq 'byte-goto-if-nil (car lap0))
  1346.                   'byte-goto-if-not-nil 'byte-goto-if-nil)))
  1347.          (byte-compile-log-lap "  %s %s %s:\t-->\t%s %s:"
  1348.                        lap0 lap1 lap2
  1349.                        (cons inverse (cdr lap1)) lap2)
  1350.          (setq lap (delq lap0 lap))
  1351.          (setcar lap1 inverse)
  1352.          (setq keep-going t)))
  1353.           ;;
  1354.           ;; const goto-if-* --> whatever
  1355.           ;;
  1356.           ((and (eq 'byte-constant (car lap0))
  1357.             (memq (car lap1) byte-conditional-ops))
  1358.            (cond ((if (or (eq (car lap1) 'byte-goto-if-nil)
  1359.                   (eq (car lap1) 'byte-goto-if-nil-else-pop))
  1360.               (car (cdr lap0))
  1361.             (not (car (cdr lap0))))
  1362.               (byte-compile-log-lap "  %s %s\t-->\t<deleted>"
  1363.                         lap0 lap1)
  1364.               (setq rest (cdr rest)
  1365.                 lap (delq lap0 (delq lap1 lap))))
  1366.              (t
  1367.               (if (memq (car lap1) byte-goto-always-pop-ops)
  1368.               (progn
  1369.                 (byte-compile-log-lap "  %s %s\t-->\t%s"
  1370.                  lap0 lap1 (cons 'byte-goto (cdr lap1)))
  1371.                 (setq lap (delq lap0 lap)))
  1372.             (byte-compile-log-lap "  %s %s\t-->\t%s" lap0 lap1
  1373.              (cons 'byte-goto (cdr lap1))))
  1374.               (setcar lap1 'byte-goto)))
  1375.            (setq keep-going t))
  1376.           ;;
  1377.           ;; varref-X varref-X  -->  varref-X dup
  1378.           ;; varref-X [dup ...] varref-X  -->  varref-X [dup ...] dup
  1379.           ;; We don't optimize the const-X variations on this here,
  1380.           ;; because that would inhibit some goto optimizations; we
  1381.           ;; optimize the const-X case after all other optimizations.
  1382.           ;;
  1383.           ((and (eq 'byte-varref (car lap0))
  1384.             (progn
  1385.               (setq tmp (cdr rest))
  1386.               (while (eq (car (car tmp)) 'byte-dup)
  1387.             (setq tmp (cdr tmp)))
  1388.               t)
  1389.             (eq (cdr lap0) (cdr (car tmp)))
  1390.             (eq 'byte-varref (car (car tmp))))
  1391.            (if (memq byte-optimize-log '(t byte))
  1392.            (let ((str ""))
  1393.              (setq tmp2 (cdr rest))
  1394.              (while (not (eq tmp tmp2))
  1395.                (setq tmp2 (cdr tmp2)
  1396.                  str (concat str " dup")))
  1397.              (byte-compile-log-lap "  %s%s %s\t-->\t%s%s dup"
  1398.                        lap0 str lap0 lap0 str)))
  1399.            (setq keep-going t)
  1400.            (setcar (car tmp) 'byte-dup)
  1401.            (setcdr (car tmp) 0)
  1402.            (setq rest tmp))
  1403.           ;;
  1404.           ;; TAG1: TAG2: --> TAG1: <deleted>
  1405.           ;; (and other references to TAG2 are replaced with TAG1)
  1406.           ;;
  1407.           ((and (eq (car lap0) 'TAG)
  1408.             (eq (car lap1) 'TAG))
  1409.            (and (memq byte-optimize-log '(t byte))
  1410.             (byte-compile-log "  adjascent tags %d and %d merged"
  1411.                       (nth 1 lap1) (nth 1 lap0)))
  1412.            (setq tmp3 lap)
  1413.            (while (setq tmp2 (rassq lap0 tmp3))
  1414.          (setcdr tmp2 lap1)
  1415.          (setq tmp3 (cdr (memq tmp2 tmp3))))
  1416.            (setq lap (delq lap0 lap)
  1417.              keep-going t))
  1418.           ;;
  1419.           ;; unused-TAG: --> <deleted>
  1420.           ;;
  1421.           ((and (eq 'TAG (car lap0))
  1422.             (not (rassq lap0 lap)))
  1423.            (and (memq byte-optimize-log '(t byte))
  1424.             (byte-compile-log "  unused tag %d removed" (nth 1 lap0)))
  1425.            (setq lap (delq lap0 lap)
  1426.              keep-going t))
  1427.           ;;
  1428.           ;; goto   ... --> goto   <delete until TAG or end>
  1429.           ;; return ... --> return <delete until TAG or end>
  1430.           ;;
  1431.           ((and (memq (car lap0) '(byte-goto byte-return))
  1432.             (not (memq (car lap1) '(TAG nil))))
  1433.            (setq tmp rest)
  1434.            (let ((i 0)
  1435.              (opt-p (memq byte-optimize-log '(t lap)))
  1436.              str deleted)
  1437.          (while (and (setq tmp (cdr tmp))
  1438.                  (not (eq 'TAG (car (car tmp)))))
  1439.            (if opt-p (setq deleted (cons (car tmp) deleted)
  1440.                    str (concat str " %s")
  1441.                    i (1+ i))))
  1442.          (if opt-p
  1443.              (let ((tagstr 
  1444.                 (if (eq 'TAG (car (car tmp)))
  1445.                 (format "%d:" (cdr (car tmp)))
  1446.                   (or (car tmp) ""))))
  1447.                (if (< i 6)
  1448.                (apply 'byte-compile-log-lap-1
  1449.                   (concat "  %s" str
  1450.                       " %s\t-->\t%s <deleted> %s")
  1451.                   lap0
  1452.                   (nconc (nreverse deleted)
  1453.                      (list tagstr lap0 tagstr)))
  1454.              (byte-compile-log-lap
  1455.               "  %s <%d unreachable op%s> %s\t-->\t%s <deleted> %s"
  1456.               lap0 i (if (= i 1) "" "s")
  1457.               tagstr lap0 tagstr))))
  1458.          (rplacd rest tmp))
  1459.            (setq keep-going t))
  1460.           ;;
  1461.           ;; <safe-op> unbind --> unbind <safe-op>
  1462.           ;; (this may enable other optimizations.)
  1463.           ;;
  1464.           ((and (eq 'byte-unbind (car lap1))
  1465.             (memq (car lap0) byte-after-unbind-ops))
  1466.            (byte-compile-log-lap "  %s %s\t-->\t%s %s" lap0 lap1 lap1 lap0)
  1467.            (setcar rest lap1)
  1468.            (setcar (cdr rest) lap0)
  1469.            (setq keep-going t))
  1470.           ;;
  1471.           ;; varbind-X unbind-N         -->  discard unbind-(N-1)
  1472.           ;; save-excursion unbind-N    -->  unbind-(N-1)
  1473.           ;; save-restriction unbind-N  -->  unbind-(N-1)
  1474.           ;;
  1475.           ((and (eq 'byte-unbind (car lap1))
  1476.             (memq (car lap0) '(byte-varbind byte-save-excursion
  1477.                        byte-save-restriction))
  1478.             (< 0 (cdr lap1)))
  1479.            (if (zerop (setcdr lap1 (1- (cdr lap1))))
  1480.            (delq lap1 rest))
  1481.            (if (eq (car lap0) 'byte-varbind)
  1482.            (setcar rest (cons 'byte-discard 0))
  1483.          (setq lap (delq lap0 lap)))
  1484.            (byte-compile-log-lap "  %s %s\t-->\t%s %s"
  1485.          lap0 (cons (car lap1) (1+ (cdr lap1)))
  1486.          (if (eq (car lap0) 'byte-varbind)
  1487.              (car rest)
  1488.            (car (cdr rest)))
  1489.          (if (and (/= 0 (cdr lap1))
  1490.               (eq (car lap0) 'byte-varbind))
  1491.              (car (cdr rest))
  1492.            ""))
  1493.            (setq keep-going t))
  1494.           ;;
  1495.           ;; goto*-X ... X: goto-Y  --> goto*-Y
  1496.           ;; goto-X ...  X: return  --> return
  1497.           ;;
  1498.           ((and (memq (car lap0) byte-goto-ops)
  1499.             (memq (car (setq tmp (nth 1 (memq (cdr lap0) lap))))
  1500.               '(byte-goto byte-return)))
  1501.            (cond ((and (not (eq tmp lap0))
  1502.                (or (eq (car lap0) 'byte-goto)
  1503.                    (eq (car tmp) 'byte-goto)))
  1504.               (byte-compile-log-lap "  %s [%s]\t-->\t%s"
  1505.                         (car lap0) tmp tmp)
  1506.               (if (eq (car tmp) 'byte-return)
  1507.               (setcar lap0 'byte-return))
  1508.               (setcdr lap0 (cdr tmp))
  1509.               (setq keep-going t))))
  1510.           ;;
  1511.           ;; goto-*-else-pop X ... X: goto-if-* --> whatever
  1512.           ;; goto-*-else-pop X ... X: discard --> whatever
  1513.           ;;
  1514.           ((and (memq (car lap0) '(byte-goto-if-nil-else-pop
  1515.                        byte-goto-if-not-nil-else-pop))
  1516.             (memq (car (car (setq tmp (cdr (memq (cdr lap0) lap)))))
  1517.               (eval-when-compile
  1518.                (cons 'byte-discard byte-conditional-ops)))
  1519.             (not (eq lap0 (car tmp))))
  1520.            (setq tmp2 (car tmp))
  1521.            (setq tmp3 (assq (car lap0) '((byte-goto-if-nil-else-pop
  1522.                           byte-goto-if-nil)
  1523.                          (byte-goto-if-not-nil-else-pop
  1524.                           byte-goto-if-not-nil))))
  1525.            (if (memq (car tmp2) tmp3)
  1526.            (progn (setcar lap0 (car tmp2))
  1527.               (setcdr lap0 (cdr tmp2))
  1528.               (byte-compile-log-lap "  %s-else-pop [%s]\t-->\t%s"
  1529.                         (car lap0) tmp2 lap0))
  1530.          ;; Get rid of the -else-pop's and jump one step further.
  1531.          (or (eq 'TAG (car (nth 1 tmp)))
  1532.              (setcdr tmp (cons (byte-compile-make-tag)
  1533.                        (cdr tmp))))
  1534.          (byte-compile-log-lap "  %s [%s]\t-->\t%s <skip>"
  1535.                        (car lap0) tmp2 (nth 1 tmp3))
  1536.          (setcar lap0 (nth 1 tmp3))
  1537.          (setcdr lap0 (nth 1 tmp)))
  1538.            (setq keep-going t))
  1539.           ;;
  1540.           ;; const goto-X ... X: goto-if-* --> whatever
  1541.           ;; const goto-X ... X: discard   --> whatever
  1542.           ;;
  1543.           ((and (eq (car lap0) 'byte-constant)
  1544.             (eq (car lap1) 'byte-goto)
  1545.             (memq (car (car (setq tmp (cdr (memq (cdr lap1) lap)))))
  1546.               (eval-when-compile
  1547.                 (cons 'byte-discard byte-conditional-ops)))
  1548.             (not (eq lap1 (car tmp))))
  1549.            (setq tmp2 (car tmp))
  1550.            (cond ((memq (car tmp2)
  1551.                 (if (null (car (cdr lap0)))
  1552.                 '(byte-goto-if-nil byte-goto-if-nil-else-pop)
  1553.                   '(byte-goto-if-not-nil
  1554.                 byte-goto-if-not-nil-else-pop)))
  1555.               (byte-compile-log-lap "  %s goto [%s]\t-->\t%s %s"
  1556.                         lap0 tmp2 lap0 tmp2)
  1557.               (setcar lap1 (car tmp2))
  1558.               (setcdr lap1 (cdr tmp2))
  1559.               ;; Let next step fix the (const,goto-if*) sequence.
  1560.               (setq rest (cons nil rest)))
  1561.              (t
  1562.               ;; Jump one step further
  1563.               (byte-compile-log-lap
  1564.                "  %s goto [%s]\t-->\t<deleted> goto <skip>"
  1565.                lap0 tmp2)
  1566.               (or (eq 'TAG (car (nth 1 tmp)))
  1567.               (setcdr tmp (cons (byte-compile-make-tag)
  1568.                         (cdr tmp))))
  1569.               (setcdr lap1 (car (cdr tmp)))
  1570.               (setq lap (delq lap0 lap))))
  1571.            (setq keep-going t))
  1572.           ;;
  1573.           ;; X: varref-Y    ...     varset-Y goto-X  -->
  1574.           ;; X: varref-Y Z: ... dup varset-Y goto-Z
  1575.           ;; (varset-X goto-BACK, BACK: varref-X --> copy the varref down.)
  1576.           ;; (This is so usual for while loops that it is worth handling).
  1577.           ;;
  1578.           ((and (eq (car lap1) 'byte-varset)
  1579.             (eq (car lap2) 'byte-goto)
  1580.             (not (memq (cdr lap2) rest)) ;Backwards jump
  1581.             (eq (car (car (setq tmp (cdr (memq (cdr lap2) lap)))))
  1582.             'byte-varref)
  1583.             (eq (cdr (car tmp)) (cdr lap1))
  1584.             (not (memq (car (cdr lap1)) byte-boolean-vars)))
  1585.            ;;(byte-compile-log-lap "  Pulled %s to end of loop" (car tmp))
  1586.            (let ((newtag (byte-compile-make-tag)))
  1587.          (byte-compile-log-lap
  1588.           "  %s: %s ... %s %s\t-->\t%s: %s %s: ... %s %s %s"
  1589.           (nth 1 (cdr lap2)) (car tmp)
  1590.                   lap1 lap2
  1591.           (nth 1 (cdr lap2)) (car tmp)
  1592.           (nth 1 newtag) 'byte-dup lap1
  1593.           (cons 'byte-goto newtag)
  1594.           )
  1595.          (setcdr rest (cons (cons 'byte-dup 0) (cdr rest)))
  1596.          (setcdr tmp (cons (setcdr lap2 newtag) (cdr tmp))))
  1597.            (setq add-depth 1)
  1598.            (setq keep-going t))
  1599.           ;;
  1600.           ;; goto-X Y: ... X: goto-if*-Y  -->  goto-if-not-*-X+1 Y:
  1601.           ;; (This can pull the loop test to the end of the loop)
  1602.           ;;
  1603.           ((and (eq (car lap0) 'byte-goto)
  1604.             (eq (car lap1) 'TAG)
  1605.             (eq lap1
  1606.             (cdr (car (setq tmp (cdr (memq (cdr lap0) lap))))))
  1607.             (memq (car (car tmp))
  1608.               '(byte-goto byte-goto-if-nil byte-goto-if-not-nil
  1609.                       byte-goto-if-nil-else-pop)))
  1610. ;;           (byte-compile-log-lap "  %s %s, %s %s  --> moved conditional"
  1611. ;;                     lap0 lap1 (cdr lap0) (car tmp))
  1612.            (let ((newtag (byte-compile-make-tag)))
  1613.          (byte-compile-log-lap
  1614.           "%s %s: ... %s: %s\t-->\t%s ... %s:"
  1615.           lap0 (nth 1 lap1) (nth 1 (cdr lap0)) (car tmp)
  1616.           (cons (cdr (assq (car (car tmp))
  1617.                    '((byte-goto-if-nil . byte-goto-if-not-nil)
  1618.                      (byte-goto-if-not-nil . byte-goto-if-nil)
  1619.                      (byte-goto-if-nil-else-pop .
  1620.                       byte-goto-if-not-nil-else-pop)
  1621.                      (byte-goto-if-not-nil-else-pop .
  1622.                       byte-goto-if-nil-else-pop))))
  1623.             newtag)
  1624.           
  1625.           (nth 1 newtag)
  1626.           )
  1627.          (setcdr tmp (cons (setcdr lap0 newtag) (cdr tmp)))
  1628.          (if (eq (car (car tmp)) 'byte-goto-if-nil-else-pop)
  1629.              ;; We can handle this case but not the -if-not-nil case,
  1630.              ;; because we won't know which non-nil constant to push.
  1631.            (setcdr rest (cons (cons 'byte-constant
  1632.                         (byte-compile-get-constant nil))
  1633.                       (cdr rest))))
  1634.            (setcar lap0 (nth 1 (memq (car (car tmp))
  1635.                      '(byte-goto-if-nil-else-pop
  1636.                        byte-goto-if-not-nil
  1637.                        byte-goto-if-nil
  1638.                        byte-goto-if-not-nil
  1639.                        byte-goto byte-goto))))
  1640.            )
  1641.            (setq keep-going t))
  1642.           )
  1643.     (setq rest (cdr rest)))
  1644.       )
  1645.     ;; Cleanup stage:
  1646.     ;; Rebuild byte-compile-constants / byte-compile-variables.
  1647.     ;; Simple optimizations that would inhibit other optimizations if they
  1648.     ;; were done in the optimizing loop, and optimizations which there is no
  1649.     ;;  need to do more than once.
  1650.     (setq byte-compile-constants nil
  1651.       byte-compile-variables nil)
  1652.     (setq rest lap)
  1653.     (while rest
  1654.       (setq lap0 (car rest)
  1655.         lap1 (nth 1 rest))
  1656.       (if (memq (car lap0) byte-constref-ops)
  1657.       (if (eq (cdr lap0) 'byte-constant)
  1658.           (or (memq (cdr lap0) byte-compile-variables)
  1659.           (setq byte-compile-variables (cons (cdr lap0)
  1660.                              byte-compile-variables)))
  1661.         (or (memq (cdr lap0) byte-compile-constants)
  1662.         (setq byte-compile-constants (cons (cdr lap0)
  1663.                            byte-compile-constants)))))
  1664.       (cond (;;
  1665.          ;; const-C varset-X const-C  -->  const-C dup varset-X
  1666.          ;; const-C varbind-X const-C  -->  const-C dup varbind-X
  1667.          ;;
  1668.          (and (eq (car lap0) 'byte-constant)
  1669.           (eq (car (nth 2 rest)) 'byte-constant)
  1670.           (eq (cdr lap0) (car (nth 2 rest)))
  1671.           (memq (car lap1) '(byte-varbind byte-varset)))
  1672.          (byte-compile-log-lap "  %s %s %s\t-->\t%s dup %s"
  1673.                    lap0 lap1 lap0 lap0 lap1)
  1674.          (setcar (cdr (cdr rest)) (cons (car lap1) (cdr lap1)))
  1675.          (setcar (cdr rest) (cons 'byte-dup 0))
  1676.          (setq add-depth 1))
  1677.         ;;
  1678.         ;; const-X  [dup/const-X ...]   -->  const-X  [dup ...] dup
  1679.         ;; varref-X [dup/varref-X ...]  -->  varref-X [dup ...] dup
  1680.         ;;
  1681.         ((memq (car lap0) '(byte-constant byte-varref))
  1682.          (setq tmp rest
  1683.            tmp2 nil)
  1684.          (while (progn
  1685.               (while (eq 'byte-dup (car (car (setq tmp (cdr tmp))))))
  1686.               (and (eq (cdr lap0) (cdr (car tmp)))
  1687.                (eq (car lap0) (car (car tmp)))))
  1688.            (setcar tmp (cons 'byte-dup 0))
  1689.            (setq tmp2 t))
  1690.          (if tmp2
  1691.          (byte-compile-log-lap
  1692.           "  %s [dup/%s]... %s\t-->\t%s dup..." lap0 lap0 lap0)))
  1693.         ;;
  1694.         ;; unbind-N unbind-M  -->  unbind-(N+M)
  1695.         ;;
  1696.         ((and (eq 'byte-unbind (car lap0))
  1697.           (eq 'byte-unbind (car lap1)))
  1698.          (byte-compile-log-lap "  %s %s\t-->\t%s" lap0 lap1
  1699.                    (cons 'byte-unbind
  1700.                      (+ (cdr lap0) (cdr lap1))))
  1701.          (setq keep-going t)
  1702.          (setq lap (delq lap0 lap))
  1703.          (setcdr lap1 (+ (cdr lap1) (cdr lap0))))
  1704.         )
  1705.       (setq rest (cdr rest)))
  1706.     (setq byte-compile-maxdepth (+ byte-compile-maxdepth add-depth)))
  1707.   lap)
  1708.  
  1709. (provide 'byte-optimize)
  1710.  
  1711.  
  1712. ;; To avoid "lisp nesting exceeds max-lisp-eval-depth" when this file compiles
  1713. ;; itself, compile some of its most used recursive functions (at load time).
  1714. ;;
  1715. (eval-when-compile
  1716.  (or (compiled-function-p (symbol-function 'byte-optimize-form))
  1717.      (assq 'byte-code (symbol-function 'byte-optimize-form))
  1718.      (let ((byte-optimize nil)
  1719.        (byte-compile-warnings nil))
  1720.        (mapcar '(lambda (x)
  1721.           (or noninteractive (message "compiling %s..." x))
  1722.           (byte-compile x)
  1723.           (or noninteractive (message "compiling %s...done" x)))
  1724.            '(byte-optimize-form
  1725.          byte-optimize-body
  1726.          byte-optimize-predicate
  1727.          byte-optimize-binary-predicate
  1728.          ;; Inserted some more than necessary, to speed it up.
  1729.          byte-optimize-form-code-walker
  1730.          byte-optimize-lapcode))))
  1731.  nil)
  1732.