peval.scm 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  1. ;;; Tree-IL partial evaluator
  2. ;; Copyright (C) 2011-2014,2017,2019-2024 Free Software Foundation, Inc.
  3. ;;;; This library is free software; you can redistribute it and/or
  4. ;;;; modify it under the terms of the GNU Lesser General Public
  5. ;;;; License as published by the Free Software Foundation; either
  6. ;;;; version 3 of the License, or (at your option) any later version.
  7. ;;;;
  8. ;;;; This library is distributed in the hope that it will be useful,
  9. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. ;;;; Lesser General Public License for more details.
  12. ;;;;
  13. ;;;; You should have received a copy of the GNU Lesser General Public
  14. ;;;; License along with this library; if not, write to the Free Software
  15. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. (define-module (language tree-il peval)
  17. #:use-module (language tree-il)
  18. #:use-module (language tree-il primitives)
  19. #:use-module (language tree-il effects)
  20. #:use-module (ice-9 vlist)
  21. #:use-module (ice-9 match)
  22. #:use-module (srfi srfi-1)
  23. #:use-module (srfi srfi-9)
  24. #:use-module (srfi srfi-11)
  25. #:use-module (srfi srfi-26)
  26. #:use-module (system base target)
  27. #:use-module (ice-9 control)
  28. #:export (peval))
  29. ;;;
  30. ;;; Partial evaluation is Guile's most important source-to-source
  31. ;;; optimization pass. It performs copy propagation, dead code
  32. ;;; elimination, inlining, and constant folding, all while preserving
  33. ;;; the order of effects in the residual program.
  34. ;;;
  35. ;;; For more on partial evaluation, see William Cook’s excellent
  36. ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
  37. ;;; partial evaluator in 90 minutes”[0].
  38. ;;;
  39. ;;; Our implementation of this algorithm was heavily influenced by
  40. ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
  41. ;;; IU CS Dept. TR 484.
  42. ;;;
  43. ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
  44. ;;;
  45. ;; First, some helpers.
  46. ;;
  47. (define-syntax *logging* (identifier-syntax #f))
  48. ;; For efficiency we define *logging* to inline to #f, so that the call
  49. ;; to log* gets optimized out. If you want to log, uncomment these
  50. ;; lines:
  51. ;;
  52. ;; (define %logging #f)
  53. ;; (define-syntax *logging* (identifier-syntax %logging))
  54. ;;
  55. ;; Then you can change %logging at runtime.
  56. (define-syntax log
  57. (syntax-rules (quote)
  58. ((log 'event arg ...)
  59. (if (and *logging*
  60. (or (eq? *logging* #t)
  61. (memq 'event *logging*)))
  62. (log* 'event arg ...)))))
  63. (define (log* event . args)
  64. (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
  65. 'pretty-print)))
  66. (pp `(log ,event . ,args))
  67. (newline)
  68. (values)))
  69. (define (tree-il-any proc exp)
  70. (let/ec k
  71. (tree-il-fold (lambda (exp res)
  72. (let ((res (proc exp)))
  73. (if res (k res) #f)))
  74. (lambda (exp res) #f)
  75. #f exp)))
  76. (define (vlist-any proc vlist)
  77. (let ((len (vlist-length vlist)))
  78. (let lp ((i 0))
  79. (and (< i len)
  80. (or (proc (vlist-ref vlist i))
  81. (lp (1+ i)))))))
  82. (define (singly-valued-expression? exp)
  83. (match exp
  84. (($ <const>) #t)
  85. (($ <void>) #t)
  86. (($ <lexical-ref>) #t)
  87. (($ <primitive-ref>) #t)
  88. (($ <module-ref>) #t)
  89. (($ <toplevel-ref>) #t)
  90. (($ <primcall> _ (? singly-valued-primitive?)) #t)
  91. (($ <primcall> _ 'values (val)) #t)
  92. (($ <lambda>) #t)
  93. (($ <conditional> _ test consequent alternate)
  94. (and (singly-valued-expression? consequent)
  95. (singly-valued-expression? alternate)))
  96. (else #f)))
  97. (define (truncate-values x)
  98. "Discard all but the first value of X."
  99. (if (singly-valued-expression? x)
  100. x
  101. (make-primcall (tree-il-srcv x) 'values (list x))))
  102. ;; Peval will do a one-pass analysis on the source program to determine
  103. ;; the set of assigned lexicals, and to identify unreferenced and
  104. ;; singly-referenced lexicals.
  105. ;;
  106. (define-record-type <var>
  107. (make-var name gensym refcount set?)
  108. var?
  109. (name var-name)
  110. (gensym var-gensym)
  111. (refcount var-refcount set-var-refcount!)
  112. (set? var-set? set-var-set?!))
  113. (define* (build-var-table exp #:optional (table vlist-null))
  114. (tree-il-fold
  115. (lambda (exp res)
  116. (match exp
  117. (($ <lexical-ref> src name gensym)
  118. (let ((var (cdr (vhash-assq gensym res))))
  119. (set-var-refcount! var (1+ (var-refcount var)))
  120. res))
  121. (($ <lambda-case> src req opt rest kw init gensyms body alt)
  122. (fold (lambda (name sym res)
  123. (vhash-consq sym (make-var name sym 0 #f) res))
  124. res
  125. (append req (or opt '()) (if rest (list rest) '())
  126. (match kw
  127. ((aok? (kw name sym) ...) name)
  128. (_ '())))
  129. gensyms))
  130. (($ <let> src names gensyms vals body)
  131. (fold (lambda (name sym res)
  132. (vhash-consq sym (make-var name sym 0 #f) res))
  133. res names gensyms))
  134. (($ <letrec>)
  135. (error "unexpected letrec"))
  136. (($ <fix> src names gensyms vals body)
  137. (fold (lambda (name sym res)
  138. (vhash-consq sym (make-var name sym 0 #f) res))
  139. res names gensyms))
  140. (($ <lexical-set> src name gensym exp)
  141. (set-var-set?! (cdr (vhash-assq gensym res)) #t)
  142. res)
  143. (_ res)))
  144. (lambda (exp res) res)
  145. table exp))
  146. (define (augment-var-table-with-externally-introduced-lexicals exp table)
  147. "Take the previously computed var table TABLE and the term EXP and
  148. return a table augmented with the lexicals bound in EXP which are not
  149. present in TABLE. This is used for the result of `expand-primcalls`,
  150. which may introduce new lexicals if a subexpression needs to be
  151. referenced multiple times."
  152. (define (maybe-add-var name sym table)
  153. ;; Use a refcount of 2 to prevent the copy-single optimization.
  154. (define refcount 2)
  155. (define assigned? #f)
  156. (if (vhash-assq sym table)
  157. table
  158. (vhash-consq sym (make-var name sym refcount assigned?) table)))
  159. (tree-il-fold
  160. (lambda (exp table)
  161. (match exp
  162. (($ <lambda-case> src req opt rest kw init gensyms body alt)
  163. (fold maybe-add-var table
  164. (append req (or opt '()) (if rest (list rest) '())
  165. (match kw
  166. ((aok? (kw name sym) ...) name)
  167. (_ '())))
  168. gensyms))
  169. (($ <let> src names gensyms vals body)
  170. (fold maybe-add-var table names gensyms))
  171. (($ <letrec>)
  172. (error "unexpected letrec"))
  173. (($ <fix> src names gensyms vals body)
  174. (fold maybe-add-var table names gensyms))
  175. (_ table)))
  176. (lambda (exp table) table)
  177. table exp))
  178. ;; Counters are data structures used to limit the effort that peval
  179. ;; spends on particular inlining attempts. Each call site in the source
  180. ;; program is allocated some amount of effort. If peval exceeds the
  181. ;; effort counter while attempting to inline a call site, it aborts the
  182. ;; inlining attempt and residualizes a call instead.
  183. ;;
  184. ;; As there is a fixed number of call sites, that makes `peval' O(N) in
  185. ;; the number of call sites in the source program.
  186. ;;
  187. ;; Counters should limit the size of the residual program as well, but
  188. ;; currently this is not implemented.
  189. ;;
  190. ;; At the top level, before seeing any peval call, there is no counter,
  191. ;; because inlining will terminate as there is no recursion. When peval
  192. ;; sees a call at the top level, it will make a new counter, allocating
  193. ;; it some amount of effort and size.
  194. ;;
  195. ;; This top-level effort counter effectively "prints money". Within a
  196. ;; toplevel counter, no more effort is printed ex nihilo; for a nested
  197. ;; inlining attempt to proceed, effort must be transferred from the
  198. ;; toplevel counter to the nested counter.
  199. ;;
  200. ;; Via `data' and `prev', counters form a linked list, terminating in a
  201. ;; toplevel counter. In practice `data' will be the a pointer to the
  202. ;; source expression of the procedure being inlined.
  203. ;;
  204. ;; In this way peval can detect a recursive inlining attempt, by walking
  205. ;; back on the `prev' links looking for matching `data'. Recursive
  206. ;; counters receive a more limited effort allocation, as we don't want
  207. ;; to spend all of the effort for a toplevel inlining site on loops.
  208. ;; Also, recursive counters don't need a prompt at each inlining site:
  209. ;; either the call chain folds entirely, or it will be residualized at
  210. ;; its original call.
  211. ;;
  212. (define-record-type <counter>
  213. (%make-counter effort size continuation recursive? data prev)
  214. counter?
  215. (effort effort-counter)
  216. (size size-counter)
  217. (continuation counter-continuation)
  218. (recursive? counter-recursive? set-counter-recursive?!)
  219. (data counter-data)
  220. (prev counter-prev))
  221. (define (abort-counter c)
  222. ((counter-continuation c)))
  223. (define (record-effort! c)
  224. (let ((e (effort-counter c)))
  225. (if (zero? (variable-ref e))
  226. (abort-counter c)
  227. (variable-set! e (1- (variable-ref e))))))
  228. (define (record-size! c)
  229. (let ((s (size-counter c)))
  230. (if (zero? (variable-ref s))
  231. (abort-counter c)
  232. (variable-set! s (1- (variable-ref s))))))
  233. (define (find-counter data counter)
  234. (and counter
  235. (if (eq? data (counter-data counter))
  236. counter
  237. (find-counter data (counter-prev counter)))))
  238. (define* (transfer! from to #:optional
  239. (effort (variable-ref (effort-counter from)))
  240. (size (variable-ref (size-counter from))))
  241. (define (transfer-counter! from-v to-v amount)
  242. (let* ((from-balance (variable-ref from-v))
  243. (to-balance (variable-ref to-v))
  244. (amount (min amount from-balance)))
  245. (variable-set! from-v (- from-balance amount))
  246. (variable-set! to-v (+ to-balance amount))))
  247. (transfer-counter! (effort-counter from) (effort-counter to) effort)
  248. (transfer-counter! (size-counter from) (size-counter to) size))
  249. (define (make-top-counter effort-limit size-limit continuation data)
  250. (%make-counter (make-variable effort-limit)
  251. (make-variable size-limit)
  252. continuation
  253. #t
  254. data
  255. #f))
  256. (define (make-nested-counter continuation data current)
  257. (let ((c (%make-counter (make-variable 0)
  258. (make-variable 0)
  259. continuation
  260. #f
  261. data
  262. current)))
  263. (transfer! current c)
  264. c))
  265. (define (make-recursive-counter effort-limit size-limit orig current)
  266. (let ((c (%make-counter (make-variable 0)
  267. (make-variable 0)
  268. (counter-continuation orig)
  269. #t
  270. (counter-data orig)
  271. current)))
  272. (transfer! current c effort-limit size-limit)
  273. c))
  274. ;; Operand structures allow bindings to be processed lazily instead of
  275. ;; eagerly. By doing so, hopefully we can get process them in a way
  276. ;; appropriate to their use contexts. Operands also prevent values from
  277. ;; being visited multiple times, wasting effort.
  278. ;;
  279. ;; TODO: Record value size in operand structure?
  280. ;;
  281. (define-record-type <operand>
  282. (%make-operand var sym visit source visit-count use-count
  283. copyable? residual-value constant-value alias)
  284. operand?
  285. (var operand-var)
  286. (sym operand-sym)
  287. (visit %operand-visit)
  288. (source operand-source)
  289. (visit-count operand-visit-count set-operand-visit-count!)
  290. (use-count operand-use-count set-operand-use-count!)
  291. (copyable? operand-copyable? set-operand-copyable?!)
  292. (residual-value operand-residual-value %set-operand-residual-value!)
  293. (constant-value operand-constant-value set-operand-constant-value!)
  294. (alias operand-alias set-operand-alias!))
  295. (define* (make-operand var sym #:optional source visit alias)
  296. ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
  297. ;; considered copyable until we prove otherwise. If we have a source
  298. ;; expression, truncate it to one value. Copy propagation does not
  299. ;; work on multiply-valued expressions.
  300. (let ((source (and=> source truncate-values)))
  301. (%make-operand var sym visit source 0 0
  302. (and source (not (var-set? var))) #f #f
  303. (and (not (var-set? var)) alias))))
  304. (define* (make-bound-operands vars syms sources visit #:optional aliases)
  305. (if aliases
  306. (map (lambda (name sym source alias)
  307. (make-operand name sym source visit alias))
  308. vars syms sources aliases)
  309. (map (lambda (name sym source)
  310. (make-operand name sym source visit #f))
  311. vars syms sources)))
  312. (define (make-unbound-operands vars syms)
  313. (map make-operand vars syms))
  314. (define (set-operand-residual-value! op val)
  315. (%set-operand-residual-value!
  316. op
  317. (match val
  318. (($ <primcall> src 'values (first))
  319. ;; The continuation of a residualized binding does not need the
  320. ;; introduced `values' node, so undo the effects of truncation.
  321. first)
  322. (else
  323. val))))
  324. (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
  325. ;; Peval is O(N) in call sites of the source program. However,
  326. ;; visiting an operand can introduce new call sites. If we visit an
  327. ;; operand outside a counter -- i.e., outside an inlining attempt --
  328. ;; this can lead to divergence. So, if we are visiting an operand to
  329. ;; try to copy it, and there is no counter, make a new one.
  330. ;;
  331. ;; This will only happen at most as many times as there are lexical
  332. ;; references in the source program.
  333. (and (zero? (operand-visit-count op))
  334. (dynamic-wind
  335. (lambda ()
  336. (set-operand-visit-count! op (1+ (operand-visit-count op))))
  337. (lambda ()
  338. (and (operand-source op)
  339. (if (or counter (and (not effort-limit) (not size-limit)))
  340. ((%operand-visit op) (operand-source op) counter ctx)
  341. (let/ec k
  342. (define (abort)
  343. ;; If we abort when visiting the value in a
  344. ;; fresh context, we won't succeed in any future
  345. ;; attempt, so don't try to copy it again.
  346. (set-operand-copyable?! op #f)
  347. (k #f))
  348. ((%operand-visit op)
  349. (operand-source op)
  350. (make-top-counter effort-limit size-limit abort op)
  351. ctx)))))
  352. (lambda ()
  353. (set-operand-visit-count! op (1- (operand-visit-count op)))))))
  354. ;; A helper for constant folding.
  355. ;;
  356. (define (types-check? primitive-name args)
  357. (case primitive-name
  358. ((values) #t)
  359. ((not pair? null? list? symbol? vector? struct?)
  360. (= (length args) 1))
  361. ((eq? eqv? equal?)
  362. (= (length args) 2))
  363. ;; FIXME: add more cases?
  364. (else #f)))
  365. (define (inlinable-kwargs-bug-fixup exp)
  366. ;; Versions of Guile before 3.0.10 had a bug where they mis-serialized
  367. ;; functions with keyword arguments; work around that. See
  368. ;; https://issues.guix.gnu.org/72936.
  369. (post-order
  370. (match-lambda
  371. (($ <lambda-case> src req opt rest (aok? (kw name #f) ...) inits syms body
  372. alt)
  373. (let ((kw-syms (reverse (list-head (reverse syms) (length kw)))))
  374. (make-lambda-case src req opt rest
  375. (cons aok? (map list kw name kw-syms))
  376. inits syms body alt)))
  377. (exp exp))
  378. exp))
  379. (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
  380. #:key
  381. (operator-size-limit 40)
  382. (operand-size-limit 20)
  383. (value-size-limit 10)
  384. (effort-limit 500)
  385. (recursive-effort-limit 100)
  386. (cross-module-inlining? #f))
  387. "Partially evaluate EXP in compilation environment CENV, with
  388. top-level bindings from ENV and return the resulting expression."
  389. ;; This is a simple partial evaluator. It effectively performs
  390. ;; constant folding, copy propagation, dead code elimination, and
  391. ;; inlining.
  392. ;; TODO:
  393. ;;
  394. ;; Propagate copies across toplevel bindings, if we can prove the
  395. ;; bindings to be immutable.
  396. ;;
  397. ;; Specialize lambda expressions with invariant arguments.
  398. (define local-toplevel-env
  399. ;; The top-level environment of the module being compiled.
  400. (let ()
  401. (define (env-folder x env)
  402. (match x
  403. (($ <toplevel-define> _ _ name)
  404. (vhash-consq name #t env))
  405. (($ <seq> _ head tail)
  406. (env-folder tail (env-folder head env)))
  407. (_ env)))
  408. (env-folder exp vlist-null)))
  409. (define (local-toplevel? name)
  410. (vhash-assq name local-toplevel-env))
  411. ;; gensym -> <var>
  412. ;; renamed-term -> original-term
  413. ;;
  414. (define store (build-var-table exp))
  415. (define (record-new-temporary! name sym refcount)
  416. (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
  417. (define (lookup-var sym)
  418. (let ((v (vhash-assq sym store)))
  419. (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
  420. (define (fresh-gensyms vars)
  421. (map (lambda (var)
  422. (let ((new (gensym (string-append (symbol->string (var-name var))
  423. " "))))
  424. (set! store (vhash-consq new var store))
  425. new))
  426. vars))
  427. (define (fresh-temporaries ls)
  428. (map (lambda (elt)
  429. (let ((new (gensym "tmp ")))
  430. (record-new-temporary! 'tmp new 1)
  431. new))
  432. ls))
  433. (define (assigned-lexical? sym)
  434. (var-set? (lookup-var sym)))
  435. (define (lexical-refcount sym)
  436. (var-refcount (lookup-var sym)))
  437. (define (splice-expression exp)
  438. (define vars (make-hash-table))
  439. (define (rename! old*)
  440. (match old*
  441. (() '())
  442. ((old . old*)
  443. (cons (let ((new (gensym "t")))
  444. (hashq-set! vars old new)
  445. new)
  446. (rename! old*)))))
  447. (define (new-name old) (hashq-ref vars old))
  448. (define renamed
  449. (pre-order
  450. (match-lambda
  451. (($ <lexical-ref> src name gensym)
  452. (make-lexical-ref src name (new-name gensym)))
  453. (($ <lexical-set> src name gensym exp)
  454. (make-lexical-set src name (new-name gensym) exp))
  455. (($ <lambda-case> src req opt rest kw init gensyms body alt)
  456. (let ((gensyms (rename! gensyms)))
  457. (make-lambda-case src req opt rest
  458. (match kw
  459. ((aok? (kw name sym) ...)
  460. (cons aok?
  461. (map (lambda (kw name sym)
  462. (list kw name (new-name sym)))
  463. kw name sym)))
  464. (#f #f))
  465. init gensyms body alt)))
  466. (($ <let> src names gensyms vals body)
  467. (make-let src names (rename! gensyms) vals body))
  468. (($ <letrec>)
  469. (error "unexpected letrec"))
  470. (($ <fix> src names gensyms vals body)
  471. (make-fix src names (rename! gensyms) vals body))
  472. (exp exp))
  473. exp))
  474. (set! store (build-var-table renamed store))
  475. renamed)
  476. (define (with-temporaries src exps refcount can-copy? k)
  477. (let* ((pairs (map (match-lambda
  478. ((and exp (? can-copy?))
  479. (cons #f exp))
  480. (exp
  481. (let ((sym (gensym "tmp ")))
  482. (record-new-temporary! 'tmp sym refcount)
  483. (cons sym exp))))
  484. exps))
  485. (tmps (filter car pairs)))
  486. (match tmps
  487. (() (k exps))
  488. (tmps
  489. (make-let src
  490. (make-list (length tmps) 'tmp)
  491. (map car tmps)
  492. (map cdr tmps)
  493. (k (map (match-lambda
  494. ((#f . val) val)
  495. ((sym . _)
  496. (make-lexical-ref #f 'tmp sym)))
  497. pairs)))))))
  498. (define (make-begin0 src first second)
  499. (make-let-values
  500. src
  501. first
  502. (let ((vals (gensym "vals ")))
  503. (record-new-temporary! 'vals vals 1)
  504. (make-lambda-case
  505. #f
  506. '() #f 'vals #f '() (list vals)
  507. (make-seq
  508. src
  509. second
  510. (make-primcall #f 'apply
  511. (list
  512. (make-primitive-ref #f 'values)
  513. (make-lexical-ref #f 'vals vals))))
  514. #f))))
  515. ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
  516. ;; from it to ORIG.
  517. ;;
  518. (define (record-source-expression! orig new)
  519. (set! store (vhash-consq new (source-expression orig) store))
  520. new)
  521. ;; Find the source expression corresponding to NEW. Used to detect
  522. ;; recursive inlining attempts.
  523. ;;
  524. (define (source-expression new)
  525. (let ((x (vhash-assq new store)))
  526. (if x (cdr x) new)))
  527. (define (record-operand-use op)
  528. (set-operand-use-count! op (1+ (operand-use-count op))))
  529. (define (unrecord-operand-uses op n)
  530. (let ((count (- (operand-use-count op) n)))
  531. (when (zero? count)
  532. (set-operand-residual-value! op #f))
  533. (set-operand-use-count! op count)))
  534. (define* (residualize-lexical op #:optional ctx val)
  535. (log 'residualize op)
  536. (record-operand-use op)
  537. (if (memq ctx '(value values))
  538. (set-operand-residual-value! op val))
  539. (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
  540. (define (fold-constants src name args ctx)
  541. (define (apply-primitive name args)
  542. ;; todo: further optimize commutative primitives
  543. (catch #t
  544. (lambda ()
  545. (define mod (resolve-interface (primitive-module name)))
  546. (call-with-values
  547. (lambda ()
  548. (apply (module-ref mod name) args))
  549. (lambda results
  550. (values #t results))))
  551. (lambda _
  552. (values #f '()))))
  553. (define (make-values src values)
  554. (match values
  555. ((single) single) ; 1 value
  556. ((_ ...) ; 0, or 2 or more values
  557. (make-primcall src 'values values))))
  558. (define (residualize-call)
  559. (make-primcall src name args))
  560. (cond
  561. ((every const? args)
  562. (let-values (((success? values)
  563. (apply-primitive name (map const-exp args))))
  564. (log 'fold success? values name args)
  565. (if success?
  566. (case ctx
  567. ((effect) (make-void src))
  568. ((test)
  569. ;; Values truncation: only take the first
  570. ;; value.
  571. (if (pair? values)
  572. (make-const src (car values))
  573. (make-values src '())))
  574. (else
  575. (make-values src (map (cut make-const src <>) values))))
  576. (residualize-call))))
  577. ((and (eq? ctx 'effect) (types-check? name args))
  578. (make-void #f))
  579. (else
  580. (residualize-call))))
  581. (define (inline-values src exp nmin nmax consumer)
  582. (let loop ((exp exp))
  583. (match exp
  584. ;; Some expression types are always singly-valued.
  585. ((or ($ <const>)
  586. ($ <void>)
  587. ($ <lambda>)
  588. ($ <lexical-ref>)
  589. ($ <toplevel-ref>)
  590. ($ <module-ref>)
  591. ($ <primitive-ref>)
  592. ($ <lexical-set>) ; FIXME: these set! expressions
  593. ($ <toplevel-set>) ; could return zero values in
  594. ($ <toplevel-define>) ; the future
  595. ($ <module-set>) ;
  596. ($ <primcall> src (? singly-valued-primitive?)))
  597. (and (<= nmin 1) (or (not nmax) (>= nmax 1))
  598. (make-call src (make-lambda #f '() consumer) (list exp))))
  599. ;; Statically-known number of values.
  600. (($ <primcall> src 'values vals)
  601. (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
  602. (make-call src (make-lambda #f '() consumer) vals)))
  603. ;; Not going to copy code into both branches.
  604. (($ <conditional>) #f)
  605. ;; Bail on other applications.
  606. (($ <call>) #f)
  607. (($ <primcall>) #f)
  608. ;; Bail on prompt and abort.
  609. (($ <prompt>) #f)
  610. (($ <abort>) #f)
  611. ;; Propagate to tail positions.
  612. (($ <let> src names gensyms vals body)
  613. (let ((body (loop body)))
  614. (and body
  615. (make-let src names gensyms vals body))))
  616. (($ <fix> src names gensyms vals body)
  617. (let ((body (loop body)))
  618. (and body
  619. (make-fix src names gensyms vals body))))
  620. (($ <let-values> src exp
  621. ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
  622. (let ((body (loop body)))
  623. (and body
  624. (make-let-values src exp
  625. (make-lambda-case src2 req opt rest kw
  626. inits gensyms body #f)))))
  627. (($ <seq> src head tail)
  628. (let ((tail (loop tail)))
  629. (and tail (make-seq src head tail)))))))
  630. (define compute-effects
  631. (make-effects-analyzer assigned-lexical?))
  632. (define (constant-expression? x)
  633. ;; Return true if X is constant, for the purposes of copying or
  634. ;; elision---i.e., if it is known to have no effects, does not
  635. ;; allocate storage for a mutable object, and does not access
  636. ;; mutable data (like `car' or toplevel references).
  637. (constant? (compute-effects x)))
  638. (define (prune-bindings ops in-order? body counter ctx build-result)
  639. ;; This helper handles both `let' and `letrec'/`fix'. In the latter
  640. ;; cases we need to make sure that if referenced binding A needs
  641. ;; as-yet-unreferenced binding B, that B is processed for value.
  642. ;; Likewise if C, when processed for effect, needs otherwise
  643. ;; unreferenced D, then D needs to be processed for value too.
  644. ;;
  645. (define (referenced? op)
  646. ;; When we visit lambdas in operator context, we just copy them,
  647. ;; as we will process their body later. However this does have
  648. ;; the problem that any free var referenced by the lambda is not
  649. ;; marked as needing residualization. Here we hack around this
  650. ;; and treat all bindings as referenced if we are in operator
  651. ;; context.
  652. (or (eq? ctx 'operator)
  653. (not (zero? (operand-use-count op)))))
  654. ;; values := (op ...)
  655. ;; effects := (op ...)
  656. (define (residualize values effects)
  657. ;; Note, values and effects are reversed.
  658. (cond
  659. (in-order?
  660. (let ((values (filter operand-residual-value ops)))
  661. (if (null? values)
  662. body
  663. (build-result (map (compose var-name operand-var) values)
  664. (map operand-sym values)
  665. (map operand-residual-value values)
  666. body))))
  667. (else
  668. (let ((body
  669. (if (null? effects)
  670. body
  671. (let ((effect-vals (map operand-residual-value effects)))
  672. (list->seq #f (reverse (cons body effect-vals)))))))
  673. (if (null? values)
  674. body
  675. (let ((values (reverse values)))
  676. (build-result (map (compose var-name operand-var) values)
  677. (map operand-sym values)
  678. (map operand-residual-value values)
  679. body)))))))
  680. ;; old := (bool ...)
  681. ;; values := (op ...)
  682. ;; effects := ((op . value) ...)
  683. (let prune ((old (map referenced? ops)) (values '()) (effects '()))
  684. (let lp ((ops* ops) (values values) (effects effects))
  685. (cond
  686. ((null? ops*)
  687. (let ((new (map referenced? ops)))
  688. (if (not (equal? new old))
  689. (prune new values '())
  690. (residualize values
  691. (map (lambda (op val)
  692. (set-operand-residual-value! op val)
  693. op)
  694. (map car effects) (map cdr effects))))))
  695. (else
  696. (let ((op (car ops*)))
  697. (cond
  698. ((memq op values)
  699. (lp (cdr ops*) values effects))
  700. ((operand-residual-value op)
  701. (lp (cdr ops*) (cons op values) effects))
  702. ((referenced? op)
  703. (set-operand-residual-value! op (visit-operand op counter 'value))
  704. (lp (cdr ops*) (cons op values) effects))
  705. (else
  706. (lp (cdr ops*)
  707. values
  708. (let ((effect (visit-operand op counter 'effect)))
  709. (if (void? effect)
  710. effects
  711. (acons op effect effects))))))))))))
  712. (define (small-expression? x limit)
  713. (let/ec k
  714. (tree-il-fold
  715. (lambda (x res) ; down
  716. (1+ res))
  717. (lambda (x res) ; up
  718. (if (< res limit)
  719. res
  720. (k #f)))
  721. 0 x)
  722. #t))
  723. (define (extend-env sym op env)
  724. (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
  725. (let loop ((exp exp)
  726. (env vlist-null) ; vhash of gensym -> <operand>
  727. (counter #f) ; inlined call stack
  728. (ctx 'values)) ; effect, value, values, test, operator, or call
  729. (define (lookup var)
  730. (cond
  731. ((vhash-assq var env) => cdr)
  732. (else (error "unbound var" var))))
  733. ;; Find a value referenced a specific number of times. This is a hack
  734. ;; that's used for propagating fresh data structures like rest lists and
  735. ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
  736. ;; some special cases like `apply' or prompts if we can account
  737. ;; for all of its uses.
  738. ;;
  739. ;; You don't want to use this in general because it introduces a slight
  740. ;; nonlinearity by running peval again (though with a small effort and size
  741. ;; counter).
  742. ;;
  743. (define (find-definition x n-aliases)
  744. (cond
  745. ((lexical-ref? x)
  746. (cond
  747. ((lookup (lexical-ref-gensym x))
  748. => (lambda (op)
  749. (if (var-set? (operand-var op))
  750. (values #f #f)
  751. (let ((y (or (operand-residual-value op)
  752. (visit-operand op counter 'value 10 10)
  753. (operand-source op))))
  754. (cond
  755. ((and (lexical-ref? y)
  756. (= (lexical-refcount (lexical-ref-gensym x)) 1))
  757. ;; X is a simple alias for Y. Recurse, regardless of
  758. ;; the number of aliases we were expecting.
  759. (find-definition y n-aliases))
  760. ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
  761. ;; We found a definition that is aliased the right
  762. ;; number of times. We still recurse in case it is a
  763. ;; lexical.
  764. (values (find-definition y 1)
  765. op))
  766. (else
  767. ;; We can't account for our aliases.
  768. (values #f #f)))))))
  769. (else
  770. ;; A formal parameter. Can't say anything about that.
  771. (values #f #f))))
  772. ((= n-aliases 1)
  773. ;; Not a lexical: success, but only if we are looking for an
  774. ;; unaliased value.
  775. (values x #f))
  776. (else (values #f #f))))
  777. (define (visit exp ctx)
  778. (loop exp env counter ctx))
  779. (define (for-value exp) (visit exp 'value))
  780. (define (for-values exp) (visit exp 'values))
  781. (define (for-test exp) (visit exp 'test))
  782. (define (for-effect exp) (visit exp 'effect))
  783. (define (for-call exp) (visit exp 'call))
  784. (define (for-tail exp) (visit exp ctx))
  785. (if counter
  786. (record-effort! counter))
  787. (log 'visit ctx (and=> counter effort-counter)
  788. (unparse-tree-il exp))
  789. (match exp
  790. (($ <const>)
  791. (case ctx
  792. ((effect) (make-void #f))
  793. (else exp)))
  794. (($ <void>)
  795. (case ctx
  796. ((test) (make-const #f #t))
  797. (else exp)))
  798. (($ <lexical-ref> _ _ gensym)
  799. (log 'begin-copy gensym)
  800. (let lp ((op (lookup gensym)))
  801. (cond
  802. ((eq? ctx 'effect)
  803. (log 'lexical-for-effect gensym)
  804. (make-void #f))
  805. ((operand-alias op)
  806. ;; This is an unassigned operand that simply aliases some
  807. ;; other operand. Recurse to avoid residualizing the leaf
  808. ;; binding.
  809. => lp)
  810. ((eq? ctx 'call)
  811. ;; Don't propagate copies if we are residualizing a call.
  812. (log 'residualize-lexical-call gensym op)
  813. (residualize-lexical op))
  814. ((var-set? (operand-var op))
  815. ;; Assigned lexicals don't copy-propagate.
  816. (log 'assigned-var gensym op)
  817. (residualize-lexical op))
  818. ((not (operand-copyable? op))
  819. ;; We already know that this operand is not copyable.
  820. (log 'not-copyable gensym op)
  821. (residualize-lexical op))
  822. ((and=> (operand-constant-value op)
  823. (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
  824. ;; A cache hit.
  825. (let ((val (operand-constant-value op)))
  826. (log 'memoized-constant gensym val)
  827. (for-tail val)))
  828. ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
  829. recursive-effort-limit operand-size-limit)
  830. =>
  831. ;; If we end up deciding to residualize this value instead of
  832. ;; copying it, save that residualized value.
  833. (lambda (val)
  834. (cond
  835. ((not (constant-expression? val))
  836. (log 'not-constant gensym op)
  837. ;; At this point, ctx is operator, test, or value. A
  838. ;; value that is non-constant in one context will be
  839. ;; non-constant in the others, so it's safe to record
  840. ;; that here, and avoid future visits.
  841. (set-operand-copyable?! op #f)
  842. (residualize-lexical op ctx val))
  843. ((or (const? val)
  844. (void? val)
  845. (primitive-ref? val))
  846. ;; Always propagate simple values that cannot lead to
  847. ;; code bloat.
  848. (log 'copy-simple gensym val)
  849. ;; It could be this constant is the result of folding.
  850. ;; If that is the case, cache it. This helps loop
  851. ;; unrolling get farther.
  852. (if (or (eq? ctx 'value) (eq? ctx 'values))
  853. (begin
  854. (log 'memoize-constant gensym val)
  855. (set-operand-constant-value! op val)))
  856. val)
  857. ((= 1 (var-refcount (operand-var op)))
  858. ;; Always propagate values referenced only once.
  859. (log 'copy-single gensym val)
  860. val)
  861. ;; FIXME: do demand-driven size accounting rather than
  862. ;; these heuristics.
  863. ((eq? ctx 'operator)
  864. ;; A pure expression in the operator position. Inline
  865. ;; if it's a lambda that's small enough.
  866. (if (and (lambda? val)
  867. (small-expression? val operator-size-limit))
  868. (begin
  869. (log 'copy-operator gensym val)
  870. val)
  871. (begin
  872. (log 'too-big-for-operator gensym val)
  873. (residualize-lexical op ctx val))))
  874. (else
  875. ;; A pure expression, processed for call or for value.
  876. ;; Don't inline lambdas, because they will probably won't
  877. ;; fold because we don't know the operator.
  878. (if (and (small-expression? val value-size-limit)
  879. (not (tree-il-any lambda? val)))
  880. (begin
  881. (log 'copy-value gensym val)
  882. val)
  883. (begin
  884. (log 'too-big-or-has-lambda gensym val)
  885. (residualize-lexical op ctx val)))))))
  886. (else
  887. ;; Visit failed. Either the operand isn't bound, as in
  888. ;; lambda formal parameters, or the copy was aborted.
  889. (log 'unbound-or-aborted gensym op)
  890. (residualize-lexical op)))))
  891. (($ <lexical-set> src name gensym exp)
  892. (let ((op (lookup gensym)))
  893. (if (zero? (var-refcount (operand-var op)))
  894. (let ((exp (for-effect exp)))
  895. (if (void? exp)
  896. exp
  897. (make-seq src exp (make-void #f))))
  898. (begin
  899. (record-operand-use op)
  900. (make-lexical-set src name (operand-sym op) (for-value exp))))))
  901. (($ <let> src
  902. (names ... rest)
  903. (gensyms ... rest-sym)
  904. (vals ... ($ <primcall> _ 'list rest-args))
  905. ($ <primcall> asrc 'apply
  906. (proc args ...
  907. ($ <lexical-ref> _
  908. (? (cut eq? <> rest))
  909. (? (lambda (sym)
  910. (and (eq? sym rest-sym)
  911. (= (lexical-refcount sym) 1))))))))
  912. (let* ((tmps (make-list (length rest-args) 'tmp))
  913. (tmp-syms (fresh-temporaries tmps)))
  914. (for-tail
  915. (make-let src
  916. (append names tmps)
  917. (append gensyms tmp-syms)
  918. (append vals rest-args)
  919. (make-call
  920. asrc
  921. proc
  922. (append args
  923. (map (cut make-lexical-ref #f <> <>)
  924. tmps tmp-syms)))))))
  925. (($ <let> src names gensyms vals body)
  926. (define (lookup-alias exp)
  927. ;; It's very common for macros to introduce something like:
  928. ;;
  929. ;; ((lambda (x y) ...) x-exp y-exp)
  930. ;;
  931. ;; In that case you might end up trying to inline something like:
  932. ;;
  933. ;; (let ((x x-exp) (y y-exp)) ...)
  934. ;;
  935. ;; But if x-exp is itself a lexical-ref that aliases some much
  936. ;; larger expression, perhaps it will fail to inline due to
  937. ;; size. However we don't want to introduce a useless alias
  938. ;; (in this case, x). So if the RHS of a let expression is a
  939. ;; lexical-ref, we record that expression. If we end up having
  940. ;; to residualize X, then instead we residualize X-EXP, as long
  941. ;; as it isn't assigned.
  942. ;;
  943. (match exp
  944. (($ <lexical-ref> _ _ sym)
  945. (let ((op (lookup sym)))
  946. (and (not (var-set? (operand-var op))) op)))
  947. (_ #f)))
  948. (let* ((vars (map lookup-var gensyms))
  949. (new (fresh-gensyms vars))
  950. (ops (make-bound-operands vars new vals
  951. (lambda (exp counter ctx)
  952. (loop exp env counter ctx))
  953. (map lookup-alias vals)))
  954. (env (fold extend-env env gensyms ops))
  955. (body (loop body env counter ctx)))
  956. (match body
  957. (($ <const>)
  958. (for-tail (list->seq src (append vals (list body)))))
  959. (($ <lexical-ref> _ _ (? (lambda (sym) (memq sym new)) sym))
  960. (let ((pairs (map cons new vals)))
  961. ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
  962. (for-tail
  963. (list->seq
  964. src
  965. (append (map cdr (alist-delete sym pairs eq?))
  966. (list (assq-ref pairs sym)))))))
  967. ((and ($ <conditional> src*
  968. ($ <lexical-ref> _ _ sym) ($ <lexical-ref> _ _ sym) alt)
  969. (? (lambda (_)
  970. (case ctx
  971. ((test effect)
  972. (and (equal? (list sym) new)
  973. (= (lexical-refcount sym) 2)))
  974. (else #f)))))
  975. ;; (let ((x EXP)) (if x x ALT)) -> (if EXP #t ALT) in test context
  976. (make-conditional src* (visit-operand (car ops) counter 'test)
  977. (make-const src* #t) alt))
  978. (_
  979. ;; Only include bindings for which lexical references
  980. ;; have been residualized.
  981. (prune-bindings ops #f body counter ctx
  982. (lambda (names gensyms vals body)
  983. (if (null? names) (error "what!" names))
  984. (make-let src names gensyms vals body)))))))
  985. (($ <fix> src names gensyms vals body)
  986. ;; Note the difference from the `let' case: here we use letrec*
  987. ;; so that the `visit' procedure for the new operands closes over
  988. ;; an environment that includes the operands. Also we don't try
  989. ;; to elide aliases, because we can't sensibly reduce something
  990. ;; like (letrec ((a b) (b a)) a).
  991. (letrec* ((visit (lambda (exp counter ctx)
  992. (loop exp env* counter ctx)))
  993. (vars (map lookup-var gensyms))
  994. (new (fresh-gensyms vars))
  995. (ops (make-bound-operands vars new vals visit))
  996. (env* (fold extend-env env gensyms ops))
  997. (body* (visit body counter ctx)))
  998. (if (const? body*)
  999. body*
  1000. (prune-bindings ops #f body* counter ctx
  1001. (lambda (names gensyms vals body)
  1002. (make-fix src names gensyms vals body))))))
  1003. (($ <let-values> lv-src producer consumer)
  1004. ;; Peval the producer, then try to inline the consumer into
  1005. ;; the producer. If that succeeds, peval again. Otherwise
  1006. ;; reconstruct the let-values, pevaling the consumer.
  1007. (let ((producer (for-values producer)))
  1008. (or (match consumer
  1009. ((and ($ <lambda-case> src () #f rest #f () (rest-sym) body #f)
  1010. (? (lambda _ (singly-valued-expression? producer))))
  1011. (let ((tmp (gensym "tmp ")))
  1012. (record-new-temporary! 'tmp tmp 1)
  1013. (for-tail
  1014. (make-let
  1015. src (list 'tmp) (list tmp) (list producer)
  1016. (make-let
  1017. src (list rest) (list rest-sym)
  1018. (list
  1019. (make-primcall #f 'list
  1020. (list (make-lexical-ref #f 'tmp tmp))))
  1021. body)))))
  1022. (($ <lambda-case> src req opt rest #f inits gensyms body #f)
  1023. (let* ((nmin (length req))
  1024. (nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
  1025. (cond
  1026. ((inline-values lv-src producer nmin nmax consumer)
  1027. => for-tail)
  1028. (else #f))))
  1029. (_ #f))
  1030. (make-let-values lv-src producer (for-tail consumer)))))
  1031. (($ <toplevel-ref> src mod (? effect-free-primitive? name))
  1032. exp)
  1033. (($ <toplevel-ref>)
  1034. ;; todo: open private local bindings.
  1035. exp)
  1036. (($ <module-ref> src module (? effect-free-primitive? name) #f)
  1037. (let ((module (false-if-exception
  1038. (resolve-module module #:ensure #f))))
  1039. (if (module? module)
  1040. (let ((var (module-variable module name)))
  1041. (if (eq? var (module-variable the-scm-module name))
  1042. (make-primitive-ref src name)
  1043. exp))
  1044. exp)))
  1045. (($ <module-ref> src module name public?)
  1046. (cond
  1047. ((and cross-module-inlining?
  1048. public?
  1049. (and=> (resolve-module module #:ensure #f)
  1050. (lambda (module)
  1051. (and=> (module-public-interface module)
  1052. (lambda (iface)
  1053. (and=> (and=> (module-inlinable-exports iface)
  1054. (lambda (proc) (proc name)))
  1055. inlinable-kwargs-bug-fixup))))))
  1056. => (lambda (inlined)
  1057. ;; Similar logic to lexical-ref, but we can't enumerate
  1058. ;; uses, and don't know about aliases.
  1059. (log 'begin-xm-copy exp inlined)
  1060. (cond
  1061. ((eq? ctx 'effect)
  1062. (log 'xm-effect)
  1063. (make-void #f))
  1064. ((eq? ctx 'call)
  1065. ;; Don't propagate copies if we are residualizing a call.
  1066. (log 'residualize-xm-call exp)
  1067. exp)
  1068. ((or (const? inlined) (void? inlined) (primitive-ref? inlined))
  1069. ;; Always propagate simple values that cannot lead to
  1070. ;; code bloat.
  1071. (log 'copy-xm-const)
  1072. (for-tail inlined))
  1073. ;; Inline in operator position if it's a lambda that's
  1074. ;; small enough. Normally the inlinable-exports pass
  1075. ;; will only make small lambdas available for inlining,
  1076. ;; but you never know.
  1077. ((and (eq? ctx 'operator) (lambda? inlined)
  1078. (small-expression? inlined operator-size-limit))
  1079. (log 'copy-xm-operator exp inlined)
  1080. (splice-expression inlined))
  1081. (else
  1082. (log 'xm-copy-failed)
  1083. ;; Could copy small lambdas in value context. Something
  1084. ;; to revisit.
  1085. exp))))
  1086. (else exp)))
  1087. (($ <module-set> src mod name public? exp)
  1088. (make-module-set src mod name public? (for-value exp)))
  1089. (($ <toplevel-define> src mod name exp)
  1090. (make-toplevel-define src mod name (for-value exp)))
  1091. (($ <toplevel-set> src mod name exp)
  1092. (make-toplevel-set src mod name (for-value exp)))
  1093. (($ <primitive-ref>)
  1094. (case ctx
  1095. ((effect) (make-void #f))
  1096. ((test) (make-const #f #t))
  1097. (else exp)))
  1098. (($ <conditional> src condition subsequent alternate)
  1099. (define (call-with-failure-thunk exp proc)
  1100. (match exp
  1101. (($ <call> _ _ ()) (proc exp))
  1102. (($ <primcall> _ _ ()) (proc exp))
  1103. (($ <const>) (proc exp))
  1104. (($ <void>) (proc exp))
  1105. (($ <lexical-ref>) (proc exp))
  1106. (_
  1107. (let ((t (gensym "failure-")))
  1108. (record-new-temporary! 'failure t 2)
  1109. (make-let
  1110. src (list 'failure) (list t)
  1111. (list
  1112. (make-lambda
  1113. #f '()
  1114. (make-lambda-case #f '() #f #f #f '() '() exp #f)))
  1115. (proc (make-call #f (make-lexical-ref #f 'failure t)
  1116. '())))))))
  1117. (define (simplify-conditional c)
  1118. (match c
  1119. ;; Swap the arms of (if (not FOO) A B), to simplify.
  1120. (($ <conditional> src ($ <primcall> _ 'not (pred))
  1121. subsequent alternate)
  1122. (simplify-conditional
  1123. (make-conditional src pred alternate subsequent)))
  1124. ;; In the following four cases, we try to expose the test to
  1125. ;; the conditional. This will let the CPS conversion avoid
  1126. ;; reifying boolean literals in some cases.
  1127. (($ <conditional> src ($ <let> src* names vars vals body)
  1128. subsequent alternate)
  1129. (make-let src* names vars vals
  1130. (simplify-conditional
  1131. (make-conditional src body subsequent alternate))))
  1132. (($ <conditional> src ($ <fix> src* names vars vals body)
  1133. subsequent alternate)
  1134. (make-fix src* names vars vals
  1135. (simplify-conditional
  1136. (make-conditional src body subsequent alternate))))
  1137. (($ <conditional> src ($ <seq> src* head tail)
  1138. subsequent alternate)
  1139. (make-seq src* head
  1140. (simplify-conditional
  1141. (make-conditional src tail subsequent alternate))))
  1142. ;; Special cases for common tests in the predicates of chains
  1143. ;; of if expressions.
  1144. (($ <conditional> src
  1145. ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
  1146. inner-subsequent
  1147. alternate)
  1148. (let lp ((alternate alternate))
  1149. (match alternate
  1150. ;; Lift a common repeated test out of a chain of if
  1151. ;; expressions.
  1152. (($ <conditional> _ (? (cut tree-il=? outer-test <>))
  1153. other-subsequent alternate)
  1154. (make-conditional
  1155. src outer-test
  1156. (simplify-conditional
  1157. (make-conditional src* inner-test inner-subsequent
  1158. other-subsequent))
  1159. alternate))
  1160. ;; Likewise, but punching through any surrounding
  1161. ;; failure continuations.
  1162. (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
  1163. (make-let
  1164. let-src (list name) (list sym) (list thunk)
  1165. (lp body)))
  1166. ;; Otherwise, rotate AND tests to expose a simple
  1167. ;; condition in the front. Although this may result in
  1168. ;; lexically binding failure thunks, the thunks will be
  1169. ;; compiled to labels allocation, so there's no actual
  1170. ;; code growth.
  1171. (_
  1172. (call-with-failure-thunk
  1173. alternate
  1174. (lambda (failure)
  1175. (make-conditional
  1176. src outer-test
  1177. (simplify-conditional
  1178. (make-conditional src* inner-test inner-subsequent failure))
  1179. failure)))))))
  1180. (_ c)))
  1181. (match (for-test condition)
  1182. (($ <const> _ val)
  1183. (if val
  1184. (for-tail subsequent)
  1185. (for-tail alternate)))
  1186. (c
  1187. (simplify-conditional
  1188. (make-conditional src c (for-tail subsequent)
  1189. (for-tail alternate))))))
  1190. (($ <primcall> src 'call-with-values
  1191. (producer
  1192. ($ <lambda> _ _
  1193. (and consumer
  1194. ;; No optional or kwargs.
  1195. ($ <lambda-case>
  1196. _ req #f rest #f () gensyms body #f)))))
  1197. (for-tail (make-let-values src (make-call src producer '())
  1198. consumer)))
  1199. (($ <primcall> src 'dynamic-wind (w thunk u))
  1200. (for-tail
  1201. (with-temporaries
  1202. src (list w u) 2 constant-expression?
  1203. (match-lambda
  1204. ((w u)
  1205. (make-seq
  1206. src
  1207. (make-seq
  1208. src
  1209. (make-conditional
  1210. src
  1211. ;; fixme: introduce logic to fold thunk?
  1212. (make-primcall src 'thunk? (list u))
  1213. (make-call src w '())
  1214. (make-primcall src 'raise-type-error
  1215. (list (make-const #f #("dynamic-wind" 3 "thunk"))
  1216. u)))
  1217. (make-primcall src 'wind (list w u)))
  1218. (make-begin0 src
  1219. (make-call src thunk '())
  1220. (make-seq src
  1221. (make-primcall src 'unwind '())
  1222. (make-call src u '())))))))))
  1223. (($ <primcall> src 'with-fluid* (f v thunk))
  1224. (for-tail
  1225. (with-temporaries
  1226. src (list f v thunk) 1 constant-expression?
  1227. (match-lambda
  1228. ((f v thunk)
  1229. (make-seq src
  1230. (make-primcall src 'push-fluid (list f v))
  1231. (make-begin0 src
  1232. (make-call src thunk '())
  1233. (make-primcall src 'pop-fluid '()))))))))
  1234. (($ <primcall> src 'with-dynamic-state (state thunk))
  1235. (for-tail
  1236. (with-temporaries
  1237. src (list state thunk) 1 constant-expression?
  1238. (match-lambda
  1239. ((state thunk)
  1240. (make-seq src
  1241. (make-primcall src 'push-dynamic-state (list state))
  1242. (make-begin0 src
  1243. (make-call src thunk '())
  1244. (make-primcall src 'pop-dynamic-state
  1245. '()))))))))
  1246. (($ <primcall> src 'values exps)
  1247. (match exps
  1248. (()
  1249. (case ctx
  1250. ((effect) (make-void #f))
  1251. ((values) exp)
  1252. ;; Zero values returned to continuation expecting a value:
  1253. ;; ensure that we raise an error.
  1254. (else (make-primcall src 'values (list exp)))))
  1255. ((($ <primcall> _ 'values ())) exp)
  1256. (_
  1257. (let ((vals (map for-value exps)))
  1258. (if (and (case ctx
  1259. ((value test effect) #t)
  1260. (else (null? (cdr vals))))
  1261. (every singly-valued-expression? vals))
  1262. (for-tail (list->seq src (append (cdr vals) (list (car vals)))))
  1263. (make-primcall src 'values vals))))))
  1264. (($ <primcall> src 'apply (proc args ... tail))
  1265. (let lp ((tail* (find-definition tail 1)) (speculative? #t))
  1266. (define (copyable? x)
  1267. ;; Inlining a result from find-definition effectively copies it,
  1268. ;; relying on the let-pruning to remove its original binding. We
  1269. ;; shouldn't copy non-constant expressions.
  1270. (or (not speculative?) (constant-expression? x)))
  1271. (match tail*
  1272. (($ <const> _ (args* ...))
  1273. (let ((args* (map (cut make-const #f <>) args*)))
  1274. (for-tail (make-call src proc (append args args*)))))
  1275. (($ <primcall> _ 'cons
  1276. ((and head (? copyable?)) (and tail (? copyable?))))
  1277. (for-tail (make-primcall src 'apply
  1278. (cons proc
  1279. (append args (list head tail))))))
  1280. (($ <primcall> _ 'list
  1281. (and args* ((? copyable?) ...)))
  1282. (for-tail (make-call src proc (append args args*))))
  1283. (tail*
  1284. (if speculative?
  1285. (lp (for-value tail) #f)
  1286. (let ((args (append (map for-value args) (list tail*))))
  1287. (make-primcall src 'apply
  1288. (cons (for-value proc) args))))))))
  1289. (($ <primcall> src 'append (x z))
  1290. (let ((x (for-value x)))
  1291. (match x
  1292. ((or ($ <const> _ ())
  1293. ($ <primcall> _ 'list ()))
  1294. (for-value z))
  1295. ((or ($ <const> _ (_ . _))
  1296. ($ <primcall> _ 'cons)
  1297. ($ <primcall> _ 'list))
  1298. (for-tail
  1299. (let lp ((x x))
  1300. (match x
  1301. ((or ($ <const> csrc ())
  1302. ($ <primcall> csrc 'list ()))
  1303. ;; Defer visiting z in value context to for-tail.
  1304. z)
  1305. (($ <const> csrc (x . y))
  1306. (let ((x (make-const csrc x))
  1307. (y (make-const csrc y)))
  1308. (make-primcall src 'cons (list x (lp y)))))
  1309. (($ <primcall> csrc 'cons (x y))
  1310. (make-primcall src 'cons (list x (lp y))))
  1311. (($ <primcall> csrc 'list (x . y))
  1312. (let ((y (make-primcall csrc 'list y)))
  1313. (make-primcall src 'cons (list x (lp y)))))
  1314. (x (make-primcall src 'append (list x z)))))))
  1315. (else
  1316. (make-primcall src 'append (list x (for-value z)))))))
  1317. (($ <primcall> src (? constructor-primitive? name) args)
  1318. (cond
  1319. ((and (memq ctx '(effect test))
  1320. (match (cons name args)
  1321. ((or ('cons _ _)
  1322. ('list . _)
  1323. ('vector . _)
  1324. ('make-prompt-tag)
  1325. ('make-prompt-tag ($ <const> _ (? string?))))
  1326. #t)
  1327. (_ #f)))
  1328. (let ((res (if (eq? ctx 'effect)
  1329. (make-void #f)
  1330. (make-const #f #t))))
  1331. (for-tail (list->seq src (append (map for-value args)
  1332. (list res))))))
  1333. (else
  1334. (match (cons name (map for-value args))
  1335. (('cons x ($ <const> _ (? (cut eq? <> '()))))
  1336. (make-primcall src 'list (list x)))
  1337. (('cons x ($ <primcall> _ 'list elts))
  1338. (make-primcall src 'list (cons x elts)))
  1339. (('list)
  1340. (make-const src '()))
  1341. (('vector)
  1342. (make-const src '#()))
  1343. ((name . args)
  1344. (make-primcall src name args))))))
  1345. (($ <primcall> src 'thunk? (proc))
  1346. (case ctx
  1347. ((effect)
  1348. (for-tail (make-seq src proc (make-void src))))
  1349. (else
  1350. (match (for-value proc)
  1351. (($ <lambda> _ _ ($ <lambda-case> _ req))
  1352. (for-tail (make-const src (null? req))))
  1353. (proc
  1354. (match (find-definition proc 2)
  1355. (($ <lambda> _ _ ($ <lambda-case> _ req))
  1356. (for-tail (make-const src (null? req))))
  1357. (_
  1358. (make-primcall src 'thunk? (list proc)))))))))
  1359. (($ <primcall> src name args)
  1360. (match (cons name (map for-value args))
  1361. ;; FIXME: these for-tail recursions could take place outside
  1362. ;; an effort counter.
  1363. (('car ($ <primcall> src 'cons (head tail)))
  1364. (for-tail (make-seq src tail head)))
  1365. (('cdr ($ <primcall> src 'cons (head tail)))
  1366. (for-tail (make-seq src head tail)))
  1367. (('car ($ <primcall> src 'list (head . tail)))
  1368. (for-tail (list->seq src (append tail (list head)))))
  1369. (('cdr ($ <primcall> src 'list (head . tail)))
  1370. (for-tail (make-seq src head (make-primcall #f 'list tail))))
  1371. (('car ($ <const> src (head . tail)))
  1372. (for-tail (make-const src head)))
  1373. (('cdr ($ <const> src (head . tail)))
  1374. (for-tail (make-const src tail)))
  1375. (((or 'memq 'memv) k ($ <const> _ (elts ...)))
  1376. ;; FIXME: factor
  1377. (case ctx
  1378. ((effect)
  1379. (for-tail
  1380. (make-seq src k (make-void #f))))
  1381. ((test)
  1382. (cond
  1383. ((const? k)
  1384. ;; A shortcut. The `else' case would handle it, but
  1385. ;; this way is faster.
  1386. (let ((member (case name ((memq) memq) ((memv) memv))))
  1387. (make-const #f (and (member (const-exp k) elts) #t))))
  1388. ((null? elts)
  1389. (for-tail
  1390. (make-seq src k (make-const #f #f))))
  1391. (else
  1392. (let ((t (gensym "t "))
  1393. (eq (if (eq? name 'memq) 'eq? 'eqv?)))
  1394. (record-new-temporary! 't t (length elts))
  1395. (for-tail
  1396. (make-let
  1397. src (list 't) (list t) (list k)
  1398. (let lp ((elts elts))
  1399. (define test
  1400. (make-primcall #f eq
  1401. (list (make-lexical-ref #f 't t)
  1402. (make-const #f (car elts)))))
  1403. (if (null? (cdr elts))
  1404. test
  1405. (make-conditional src test
  1406. (make-const #f #t)
  1407. (lp (cdr elts)))))))))))
  1408. (else
  1409. (cond
  1410. ((const? k)
  1411. (let ((member (case name ((memq) memq) ((memv) memv))))
  1412. (make-const #f (member (const-exp k) elts))))
  1413. ((null? elts)
  1414. (for-tail (make-seq src k (make-const #f #f))))
  1415. (else
  1416. (make-primcall src name (list k (make-const #f elts))))))))
  1417. (((? equality-primitive?) a (and b ($ <const> _ v)))
  1418. (cond
  1419. ((const? a)
  1420. ;; Constants will be deduplicated later, but eq? folding can
  1421. ;; happen now. Anticipate the deduplication by using equal?
  1422. ;; instead of eq? or eqv?.
  1423. (for-tail (make-const src (equal? (const-exp a) v))))
  1424. ((eq? name 'eq?)
  1425. ;; Already in a reduced state.
  1426. (make-primcall src 'eq? (list a b)))
  1427. ((or (memq v '(#f #t () #nil)) (symbol? v) (char? v)
  1428. ;; Only fold to eq? value is a fixnum on target and
  1429. ;; host, as constant folding may have us compare on host
  1430. ;; as well.
  1431. (and (exact-integer? v)
  1432. (<= (max (target-most-negative-fixnum)
  1433. most-negative-fixnum)
  1434. v
  1435. (min (target-most-positive-fixnum)
  1436. most-positive-fixnum))))
  1437. ;; Reduce to eq?. Note that in Guile, characters are
  1438. ;; comparable with eq?.
  1439. (make-primcall src 'eq? (list a b)))
  1440. ((number? v)
  1441. ;; equal? and eqv? on non-fixnum numbers is the same as
  1442. ;; eqv?, and can't be reduced beyond that.
  1443. (make-primcall src 'eqv? (list a b)))
  1444. ((eq? name 'eqv?)
  1445. ;; eqv? on anything else is the same as eq?.
  1446. (make-primcall src 'eq? (list a b)))
  1447. (else
  1448. ;; FIXME: inline a specialized implementation of equal? for
  1449. ;; V here.
  1450. (make-primcall src name (list a b)))))
  1451. (((? equality-primitive?) (and a ($ <const>)) b)
  1452. (for-tail (make-primcall src name (list b a))))
  1453. (((? equality-primitive?) ($ <lexical-ref> _ _ sym)
  1454. ($ <lexical-ref> _ _ sym))
  1455. (for-tail (make-const src #t)))
  1456. (('logbit? ($ <const> src2
  1457. (? (lambda (bit)
  1458. (and (exact-integer? bit)
  1459. (<= 0 bit (logcount most-positive-fixnum))))
  1460. bit))
  1461. val)
  1462. (for-tail
  1463. (make-primcall src 'logtest
  1464. (list (make-const src2 (ash 1 bit)) val))))
  1465. (('logtest a b)
  1466. (for-tail
  1467. (make-primcall
  1468. src
  1469. 'not
  1470. (list
  1471. (make-primcall src 'eq?
  1472. (list (make-primcall src 'logand (list a b))
  1473. (make-const src 0)))))))
  1474. (((? effect-free-primitive?) . args)
  1475. (fold-constants src name args ctx))
  1476. ((name . args)
  1477. (if (and (eq? ctx 'effect) (effect-free-primcall? name args))
  1478. (if (null? args)
  1479. (make-void src)
  1480. (for-tail (list->seq src args)))
  1481. (make-primcall src name args)))))
  1482. (($ <call> src orig-proc orig-args)
  1483. (define (residualize-call)
  1484. (make-call src (for-call orig-proc) (map for-value orig-args)))
  1485. (define (singly-referenced-lambda? proc)
  1486. (match proc
  1487. (($ <lambda>) #t)
  1488. (($ <lexical-ref> _ _ sym)
  1489. (and (not (assigned-lexical? sym))
  1490. (= (lexical-refcount sym) 1)
  1491. (singly-referenced-lambda?
  1492. (operand-source (lookup sym)))))
  1493. (_ #f)))
  1494. (define (attempt-inlining proc names syms vals body)
  1495. (define inline-key (source-expression proc))
  1496. (define existing-counter (find-counter inline-key counter))
  1497. (define inlined-exp (make-let src names syms vals body))
  1498. (cond
  1499. ((and=> existing-counter counter-recursive?)
  1500. ;; A recursive call. Process again in tail context.
  1501. ;; Mark intervening counters as recursive, so we can
  1502. ;; handle a toplevel counter that recurses mutually with
  1503. ;; some other procedure. Otherwise, the next time we see
  1504. ;; the other procedure, the effort limit would be clamped
  1505. ;; to 100.
  1506. (let lp ((counter counter))
  1507. (unless (eq? counter existing-counter)
  1508. (set-counter-recursive?! counter #t)
  1509. (lp (counter-prev counter))))
  1510. (log 'inline-recurse inline-key)
  1511. (loop inlined-exp env counter ctx))
  1512. ((singly-referenced-lambda? orig-proc)
  1513. ;; A lambda in the operator position of the source
  1514. ;; expression. Process again in tail context.
  1515. (log 'inline-beta inline-key)
  1516. (loop inlined-exp env counter ctx))
  1517. (else
  1518. ;; An integration at the top-level, the first
  1519. ;; recursion of a recursive procedure, or a nested
  1520. ;; integration of a procedure that hasn't been seen
  1521. ;; yet.
  1522. (log 'inline-begin exp)
  1523. (let/ec k
  1524. (define (abort)
  1525. (log 'inline-abort exp)
  1526. (k (residualize-call)))
  1527. (define new-counter
  1528. (cond
  1529. ;; These first two cases will transfer effort from
  1530. ;; the current counter into the new counter.
  1531. (existing-counter
  1532. (make-recursive-counter recursive-effort-limit
  1533. operand-size-limit
  1534. existing-counter counter))
  1535. (counter
  1536. (make-nested-counter abort inline-key counter))
  1537. ;; This case opens a new account, effectively
  1538. ;; printing money. It should only do so once for
  1539. ;; each call site in the source program.
  1540. (else
  1541. (make-top-counter effort-limit operand-size-limit
  1542. abort inline-key))))
  1543. (define result
  1544. (loop inlined-exp env new-counter ctx))
  1545. (when counter
  1546. ;; The nested inlining attempt succeeded. Deposit the
  1547. ;; unspent effort and size back into the current
  1548. ;; counter.
  1549. (transfer! new-counter counter))
  1550. (log 'inline-end result exp)
  1551. result))))
  1552. (let revisit-proc ((proc (visit orig-proc 'operator)))
  1553. (match proc
  1554. (($ <primitive-ref> _ name)
  1555. (let ((exp (expand-primcall (make-primcall src name orig-args))))
  1556. (set! store
  1557. (augment-var-table-with-externally-introduced-lexicals
  1558. exp store))
  1559. (for-tail exp)))
  1560. (($ <lambda> _ _ clause)
  1561. ;; A lambda. Attempt to find the matching clause, if
  1562. ;; possible.
  1563. (define (inline-clause req opt rest kw inits gensyms body
  1564. arity-mismatch)
  1565. (define (bind name sym val binds)
  1566. (cons (vector name sym val) binds))
  1567. (define (has-binding? binds sym)
  1568. (match binds
  1569. (() #f)
  1570. ((#(n s v) . binds)
  1571. (or (eq? s sym) (has-binding? binds sym)))))
  1572. ;; The basic idea is that we are going to transform an
  1573. ;; expression like ((lambda (param ...) body) arg ...)
  1574. ;; into (let ((param arg) ...) body). However, we have to
  1575. ;; consider order of effects and scope: the args are
  1576. ;; logically parallel, whereas initializer expressions for
  1577. ;; params that don't have arguments are evaluated in
  1578. ;; order, after the arguments. Therefore we have a set of
  1579. ;; parallel bindings, abbreviated pbinds, which proceed
  1580. ;; from the call site, and a set of serial bindings, the
  1581. ;; sbinds, which result from callee initializers. We
  1582. ;; collect these in reverse order as we parse arguments.
  1583. ;; The result is an outer let for the parallel bindings
  1584. ;; containing a let* of the serial bindings and then the
  1585. ;; body.
  1586. (define (process-req req syms args pbinds sbinds)
  1587. (match req
  1588. (() (process-opt (or opt '()) syms inits args pbinds sbinds))
  1589. ((name . req)
  1590. (match syms
  1591. ((sym . syms)
  1592. (match args
  1593. (() (arity-mismatch))
  1594. ((arg . args)
  1595. (process-req req syms args
  1596. (bind name sym arg pbinds)
  1597. sbinds))))))))
  1598. (define (keyword-arg? exp)
  1599. (match exp
  1600. (($ <const> _ (? keyword?)) #t)
  1601. (_ #f)))
  1602. (define (not-keyword-arg? exp)
  1603. (match exp
  1604. ((or ($ <const> _ (not (? keyword?)))
  1605. ($ <void>)
  1606. ($ <primitive-ref>)
  1607. ($ <lambda>))
  1608. #t)
  1609. (_ #f)))
  1610. (define (process-opt opt syms inits args pbinds sbinds)
  1611. (match opt
  1612. (() (process-rest syms inits args pbinds sbinds))
  1613. ((name . opt)
  1614. (match inits
  1615. ((init . inits)
  1616. (match syms
  1617. ((sym . syms)
  1618. (cond
  1619. (kw
  1620. (match args
  1621. ((or () ((? keyword-arg?) . _))
  1622. ;; Optargs and kwargs; stop optarg dispatch at
  1623. ;; first keyword.
  1624. (process-opt opt syms inits args pbinds
  1625. (bind name sym init sbinds)))
  1626. (((? not-keyword-arg? arg) . args)
  1627. ;; Arg is definitely not a keyword; it is an
  1628. ;; optarg.
  1629. (process-opt opt syms inits args
  1630. (bind name sym arg pbinds)
  1631. sbinds))
  1632. (_
  1633. ;; We can't tell whether the arg is a keyword
  1634. ;; or not! Annoying semantics, this.
  1635. (residualize-call))))
  1636. (else
  1637. ;; No kwargs.
  1638. (match args
  1639. (()
  1640. (process-opt opt syms inits args pbinds
  1641. (bind name sym init sbinds)))
  1642. ((arg . args)
  1643. (process-opt opt syms inits args
  1644. (bind name sym arg pbinds)
  1645. sbinds))))))))))))
  1646. (define (process-rest syms inits args pbinds sbinds)
  1647. (match rest
  1648. (#f
  1649. (match kw
  1650. ((#f . kw)
  1651. (process-kw kw syms inits args pbinds sbinds))
  1652. (#f
  1653. (unless (and (null? syms) (null? inits))
  1654. (error "internal error"))
  1655. (match args
  1656. (() (finish pbinds sbinds body))
  1657. (_ (arity-mismatch))))))
  1658. (rest
  1659. (match syms
  1660. ((sym . syms)
  1661. (let ((rest-val (make-primcall src 'list args)))
  1662. (unless (and (null? syms) (null? inits))
  1663. (error "internal error"))
  1664. (finish pbinds (bind rest sym rest-val sbinds)
  1665. body)))))))
  1666. (define (process-kw kw syms inits args pbinds sbinds)
  1667. ;; Require that the ordered list of the keywords'
  1668. ;; syms is the same as the remaining gensyms to bind.
  1669. ;; Psyntax emits tree-il with this property, and it
  1670. ;; is required by (and checked by) other parts of the
  1671. ;; compiler, e.g. tree-il-to-cps lowering.
  1672. (unless (equal? syms (match kw (((k name sym) ...) sym)))
  1673. (error "internal error: unexpected kwarg syms" kw syms))
  1674. (define (process-kw-args positional? args pbinds)
  1675. (match args
  1676. (()
  1677. (process-kw-inits kw inits pbinds sbinds))
  1678. ((($ <const> _ (? keyword? keyword)) arg . args)
  1679. (match (assq keyword kw)
  1680. ((keyword name sym)
  1681. ;; Because of side effects, we don't
  1682. ;; optimize passing the same keyword arg
  1683. ;; multiple times.
  1684. (if (has-binding? pbinds sym)
  1685. (residualize-call)
  1686. (process-kw-args #f args
  1687. (bind name sym arg pbinds))))
  1688. (#f (residualize-call))))
  1689. (((? not-keyword-arg?) . args)
  1690. (if positional?
  1691. (arity-mismatch)
  1692. (residualize-call)))
  1693. (_ (residualize-call))))
  1694. (define (process-kw-inits kw inits pbinds sbinds)
  1695. (match kw
  1696. (()
  1697. (unless (null? inits) (error "internal error"))
  1698. (finish pbinds sbinds body))
  1699. (((keyword name sym) . kw)
  1700. (match inits
  1701. ((init . inits)
  1702. (process-kw-inits kw inits pbinds
  1703. (if (has-binding? pbinds sym)
  1704. sbinds
  1705. (bind name sym init sbinds))))))))
  1706. (process-kw-args #t args pbinds))
  1707. (define (finish pbinds sbinds body)
  1708. (match sbinds
  1709. (()
  1710. (match (reverse pbinds)
  1711. ((#(name sym val) ...)
  1712. (attempt-inlining proc name sym val body))))
  1713. ((#(name sym val) . sbinds)
  1714. (finish pbinds sbinds
  1715. (make-let src (list name) (list sym) (list val)
  1716. body)))))
  1717. ;; Limitations:
  1718. ;;
  1719. ;; - #:key or #:rest, but not both.
  1720. ;; - #:allow-other-keys unsupported.
  1721. (cond
  1722. ((and kw (or rest (match kw ((aok? . _) aok?))))
  1723. (residualize-call))
  1724. (else
  1725. (process-req req gensyms orig-args '() '()))))
  1726. (let lp ((clause clause))
  1727. (match clause
  1728. ;; No clause matches.
  1729. (#f (residualize-call))
  1730. (($ <lambda-case> src req opt rest kw inits gensyms body alt)
  1731. (inline-clause req opt rest kw inits gensyms body
  1732. (lambda () (lp alt)))))))
  1733. (($ <let> _ _ _ vals _)
  1734. ;; Attempt to inline `let' in the operator position.
  1735. ;;
  1736. ;; We have to re-visit the proc in value mode, since the
  1737. ;; `let' bindings might have been introduced or renamed,
  1738. ;; whereas the lambda (if any) in operator position has not
  1739. ;; been renamed.
  1740. (if (or (and-map constant-expression? vals)
  1741. (and-map constant-expression? orig-args))
  1742. ;; The arguments and the let-bound values commute.
  1743. (match (for-value orig-proc)
  1744. (($ <let> lsrc names syms vals body)
  1745. (log 'inline-let orig-proc)
  1746. (for-tail
  1747. (make-let lsrc names syms vals
  1748. (make-call src body orig-args))))
  1749. ;; It's possible for a `let' to go away after the
  1750. ;; visit due to the fact that visiting a procedure in
  1751. ;; value context will prune unused bindings, whereas
  1752. ;; visiting in operator mode can't because it doesn't
  1753. ;; traverse through lambdas. In that case re-visit
  1754. ;; the procedure.
  1755. (proc (revisit-proc proc)))
  1756. (residualize-call)))
  1757. (_ (residualize-call)))))
  1758. (($ <lambda> src meta body)
  1759. (case ctx
  1760. ((effect) (make-void #f))
  1761. ((test) (make-const #f #t))
  1762. ((operator) exp)
  1763. (else (record-source-expression!
  1764. exp
  1765. (make-lambda src meta (and body (for-values body)))))))
  1766. (($ <lambda-case> src req opt rest kw inits gensyms body alt)
  1767. (define (lift-applied-lambda body gensyms)
  1768. (and (not opt) rest (not kw)
  1769. (match body
  1770. (($ <primcall> _ 'apply
  1771. (($ <lambda> _ _ (and lcase ($ <lambda-case> _ req1)))
  1772. ($ <lexical-ref> _ _ sym)
  1773. ...))
  1774. (and (equal? sym gensyms)
  1775. (not (lambda-case-alternate lcase))
  1776. (<= (length req) (length req1))
  1777. (every (lambda (s)
  1778. (= (lexical-refcount s) 1))
  1779. sym)
  1780. lcase))
  1781. (_ #f))))
  1782. (let* ((vars (map lookup-var gensyms))
  1783. (new (fresh-gensyms vars))
  1784. (env (fold extend-env env gensyms
  1785. (make-unbound-operands vars new)))
  1786. (new-sym (lambda (old)
  1787. (operand-sym (cdr (vhash-assq old env)))))
  1788. (body (loop body env counter ctx)))
  1789. (or
  1790. ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
  1791. (lift-applied-lambda body new)
  1792. (make-lambda-case src req opt rest
  1793. (match kw
  1794. ((aok? (kw name old) ...)
  1795. (cons aok? (map list kw name (map new-sym old))))
  1796. (_ #f))
  1797. (map (cut loop <> env counter 'value) inits)
  1798. new
  1799. body
  1800. (and alt (for-tail alt))))))
  1801. (($ <seq> src head tail)
  1802. (let ((head (for-effect head))
  1803. (tail (for-tail tail)))
  1804. (if (void? head)
  1805. tail
  1806. (make-seq src
  1807. (if (and (seq? head)
  1808. (void? (seq-tail head)))
  1809. (seq-head head)
  1810. head)
  1811. tail))))
  1812. (($ <prompt> src escape-only? tag body handler)
  1813. (define (make-prompt-tag? x)
  1814. (match x
  1815. (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
  1816. #t)
  1817. (_ #f)))
  1818. (let ((tag (for-value tag))
  1819. (body (if escape-only? (for-tail body) (for-value body))))
  1820. (cond
  1821. ((find-definition tag 1)
  1822. (lambda (val op)
  1823. (make-prompt-tag? val))
  1824. => (lambda (val op)
  1825. ;; There is no way that an <abort> could know the tag
  1826. ;; for this <prompt>, so we can elide the <prompt>
  1827. ;; entirely.
  1828. (when op (unrecord-operand-uses op 1))
  1829. (for-tail (if escape-only? body (make-call src body '())))))
  1830. (else
  1831. (let ((handler (for-value handler)))
  1832. (define (escape-only-handler? handler)
  1833. (match handler
  1834. (($ <lambda> _ _
  1835. ($ <lambda-case> _ (_ . _) _ _ _ _ (k . _) body #f))
  1836. (not (tree-il-any
  1837. (match-lambda
  1838. (($ <lexical-ref> _ _ (? (cut eq? <> k))) #t)
  1839. (_ #f))
  1840. body)))
  1841. (else #f)))
  1842. (if (and (not escape-only?) (escape-only-handler? handler))
  1843. ;; Prompt transitioning to escape-only; transition body
  1844. ;; to be an expression.
  1845. (for-tail
  1846. (make-prompt src #t tag (make-call #f body '()) handler))
  1847. (make-prompt src escape-only? tag body handler)))))))
  1848. (($ <abort> src tag args tail)
  1849. (make-abort src (for-value tag) (map for-value args)
  1850. (for-value tail))))))