byte-opt.el 84 KB

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