compiler.texi 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Compiling to the Virtual Machine
  7. @section Compiling to the Virtual Machine
  8. Compilers! The word itself inspires excitement and awe, even among
  9. experienced practitioners. But a compiler is just a program: an
  10. eminently hackable thing. This section aims to to describe Guile's
  11. compiler in such a way that interested Scheme hackers can feel
  12. comfortable reading and extending it.
  13. @xref{Read/Load/Eval/Compile}, if you're lost and you just wanted to
  14. know how to compile your @code{.scm} file.
  15. @menu
  16. * Compiler Tower::
  17. * The Scheme Compiler::
  18. * Tree-IL::
  19. * Continuation-Passing Style::
  20. * Bytecode::
  21. * Writing New High-Level Languages::
  22. * Extending the Compiler::
  23. @end menu
  24. @node Compiler Tower
  25. @subsection Compiler Tower
  26. Guile's compiler is quite simple -- its @emph{compilers}, to put it more
  27. accurately. Guile defines a tower of languages, starting at Scheme and
  28. progressively simplifying down to languages that resemble the VM
  29. instruction set (@pxref{Instruction Set}).
  30. Each language knows how to compile to the next, so each step is simple
  31. and understandable. Furthermore, this set of languages is not hardcoded
  32. into Guile, so it is possible for the user to add new high-level
  33. languages, new passes, or even different compilation targets.
  34. Languages are registered in the module, @code{(system base language)}:
  35. @example
  36. (use-modules (system base language))
  37. @end example
  38. They are registered with the @code{define-language} form.
  39. @deffn {Scheme Syntax} define-language @
  40. [#:name] [#:title] [#:reader] [#:printer] @
  41. [#:parser=#f] [#:compilers='()] @
  42. [#:decompilers='()] [#:evaluator=#f] @
  43. [#:joiner=#f] [#:for-humans?=#t] @
  44. [#:make-default-environment=make-fresh-user-module]
  45. Define a language.
  46. This syntax defines a @code{<language>} object, bound to @var{name} in
  47. the current environment. In addition, the language will be added to the
  48. global language set. For example, this is the language definition for
  49. Scheme:
  50. @example
  51. (define-language scheme
  52. #:title "Scheme"
  53. #:reader (lambda (port env) ...)
  54. #:compilers `((tree-il . ,compile-tree-il))
  55. #:decompilers `((tree-il . ,decompile-tree-il))
  56. #:evaluator (lambda (x module) (primitive-eval x))
  57. #:printer write
  58. #:make-default-environment (lambda () ...))
  59. @end example
  60. @end deffn
  61. The interesting thing about having languages defined this way is that
  62. they present a uniform interface to the read-eval-print loop. This
  63. allows the user to change the current language of the REPL:
  64. @example
  65. scheme@@(guile-user)> ,language tree-il
  66. Happy hacking with Tree Intermediate Language! To switch back, type `,L scheme'.
  67. tree-il@@(guile-user)> ,L scheme
  68. Happy hacking with Scheme! To switch back, type `,L tree-il'.
  69. scheme@@(guile-user)>
  70. @end example
  71. Languages can be looked up by name, as they were above.
  72. @deffn {Scheme Procedure} lookup-language name
  73. Looks up a language named @var{name}, autoloading it if necessary.
  74. Languages are autoloaded by looking for a variable named @var{name} in
  75. a module named @code{(language @var{name} spec)}.
  76. The language object will be returned, or @code{#f} if there does not
  77. exist a language with that name.
  78. @end deffn
  79. Defining languages this way allows us to programmatically determine
  80. the necessary steps for compiling code from one language to another.
  81. @deffn {Scheme Procedure} lookup-compilation-order from to
  82. Recursively traverses the set of languages to which @var{from} can
  83. compile, depth-first, and return the first path that can transform
  84. @var{from} to @var{to}. Returns @code{#f} if no path is found.
  85. This function memoizes its results in a cache that is invalidated by
  86. subsequent calls to @code{define-language}, so it should be quite
  87. fast.
  88. @end deffn
  89. There is a notion of a ``current language'', which is maintained in the
  90. @code{current-language} parameter, defined in the core @code{(guile)}
  91. module. This language is normally Scheme, and may be rebound by the
  92. user. The run-time compilation interfaces
  93. (@pxref{Read/Load/Eval/Compile}) also allow you to choose other source
  94. and target languages.
  95. The normal tower of languages when compiling Scheme goes like this:
  96. @itemize
  97. @item Scheme
  98. @item Tree Intermediate Language (Tree-IL)
  99. @item Continuation-Passing Style (CPS)
  100. @item Bytecode
  101. @end itemize
  102. As discussed before (@pxref{Object File Format}), bytecode is in ELF
  103. format, ready to be serialized to disk. But when compiling Scheme at
  104. run time, you want a Scheme value: for example, a compiled procedure.
  105. For this reason, so as not to break the abstraction, Guile defines a
  106. fake language at the bottom of the tower:
  107. @itemize
  108. @item Value
  109. @end itemize
  110. Compiling to @code{value} loads the bytecode into a procedure, turning
  111. cold bytes into warm code.
  112. Perhaps this strangeness can be explained by example:
  113. @code{compile-file} defaults to compiling to bytecode, because it
  114. produces object code that has to live in the barren world outside the
  115. Guile runtime; but @code{compile} defaults to compiling to @code{value},
  116. as its product re-enters the Guile world.
  117. @c FIXME: This doesn't work anymore :( Should we add some kind of
  118. @c special GC pass, or disclaim this kind of code, or what?
  119. Indeed, the process of compilation can circulate through these
  120. different worlds indefinitely, as shown by the following quine:
  121. @example
  122. ((lambda (x) ((compile x) x)) '(lambda (x) ((compile x) x)))
  123. @end example
  124. @node The Scheme Compiler
  125. @subsection The Scheme Compiler
  126. The job of the Scheme compiler is to expand all macros and all of Scheme
  127. to its most primitive expressions. The definition of ``primitive
  128. expression'' is given by the inventory of constructs provided by
  129. Tree-IL, the target language of the Scheme compiler: procedure calls,
  130. conditionals, lexical references, and so on. This is described more
  131. fully in the next section.
  132. The tricky and amusing thing about the Scheme-to-Tree-IL compiler is
  133. that it is completely implemented by the macro expander. Since the
  134. macro expander has to run over all of the source code already in order
  135. to expand macros, it might as well do the analysis at the same time,
  136. producing Tree-IL expressions directly.
  137. Because this compiler is actually the macro expander, it is extensible.
  138. Any macro which the user writes becomes part of the compiler.
  139. The Scheme-to-Tree-IL expander may be invoked using the generic
  140. @code{compile} procedure:
  141. @lisp
  142. (compile '(+ 1 2) #:from 'scheme #:to 'tree-il)
  143. @result{}
  144. #<tree-il (call (toplevel +) (const 1) (const 2))>
  145. @end lisp
  146. @code{(compile @var{foo} #:from 'scheme #:to 'tree-il)} is entirely
  147. equivalent to calling the macro expander as @code{(macroexpand @var{foo}
  148. 'c '(compile load eval))}. @xref{Macro Expansion}.
  149. @code{compile-tree-il}, the procedure dispatched by @code{compile} to
  150. @code{'tree-il}, is a small wrapper around @code{macroexpand}, to make
  151. it conform to the general form of compiler procedures in Guile's
  152. language tower.
  153. Compiler procedures take three arguments: an expression, an
  154. environment, and a keyword list of options. They return three values:
  155. the compiled expression, the corresponding environment for the target
  156. language, and a ``continuation environment''. The compiled expression
  157. and environment will serve as input to the next language's compiler.
  158. The ``continuation environment'' can be used to compile another
  159. expression from the same source language within the same module.
  160. For example, you might compile the expression, @code{(define-module
  161. (foo))}. This will result in a Tree-IL expression and environment. But
  162. if you compiled a second expression, you would want to take into
  163. account the compile-time effect of compiling the previous expression,
  164. which puts the user in the @code{(foo)} module. That is purpose of the
  165. ``continuation environment''; you would pass it as the environment
  166. when compiling the subsequent expression.
  167. For Scheme, an environment is a module. By default, the @code{compile}
  168. and @code{compile-file} procedures compile in a fresh module, such
  169. that bindings and macros introduced by the expression being compiled
  170. are isolated:
  171. @example
  172. (eq? (current-module) (compile '(current-module)))
  173. @result{} #f
  174. (compile '(define hello 'world))
  175. (defined? 'hello)
  176. @result{} #f
  177. (define / *)
  178. (eq? (compile '/) /)
  179. @result{} #f
  180. @end example
  181. Similarly, changes to the @code{current-reader} fluid (@pxref{Loading,
  182. @code{current-reader}}) are isolated:
  183. @example
  184. (compile '(fluid-set! current-reader (lambda args 'fail)))
  185. (fluid-ref current-reader)
  186. @result{} #f
  187. @end example
  188. Nevertheless, having the compiler and @dfn{compilee} share the same name
  189. space can be achieved by explicitly passing @code{(current-module)} as
  190. the compilation environment:
  191. @example
  192. (define hello 'world)
  193. (compile 'hello #:env (current-module))
  194. @result{} world
  195. @end example
  196. @node Tree-IL
  197. @subsection Tree-IL
  198. Tree Intermediate Language (Tree-IL) is a structured intermediate
  199. language that is close in expressive power to Scheme. It is an
  200. expanded, pre-analyzed Scheme.
  201. Tree-IL is ``structured'' in the sense that its representation is
  202. based on records, not S-expressions. This gives a rigidity to the
  203. language that ensures that compiling to a lower-level language only
  204. requires a limited set of transformations. For example, the Tree-IL
  205. type @code{<const>} is a record type with two fields, @code{src} and
  206. @code{exp}. Instances of this type are created via @code{make-const}.
  207. Fields of this type are accessed via the @code{const-src} and
  208. @code{const-exp} procedures. There is also a predicate, @code{const?}.
  209. @xref{Records}, for more information on records.
  210. @c alpha renaming
  211. All Tree-IL types have a @code{src} slot, which holds source location
  212. information for the expression. This information, if present, will be
  213. residualized into the compiled object code, allowing backtraces to
  214. show source information. The format of @code{src} is the same as that
  215. returned by Guile's @code{source-properties} function. @xref{Source
  216. Properties}, for more information.
  217. Although Tree-IL objects are represented internally using records,
  218. there is also an equivalent S-expression external representation for
  219. each kind of Tree-IL. For example, the S-expression representation
  220. of @code{#<const src: #f exp: 3>} expression would be:
  221. @example
  222. (const 3)
  223. @end example
  224. Users may program with this format directly at the REPL:
  225. @example
  226. scheme@@(guile-user)> ,language tree-il
  227. Happy hacking with Tree Intermediate Language! To switch back, type `,L scheme'.
  228. tree-il@@(guile-user)> (call (primitive +) (const 32) (const 10))
  229. @result{} 42
  230. @end example
  231. The @code{src} fields are left out of the external representation.
  232. One may create Tree-IL objects from their external representations via
  233. calling @code{parse-tree-il}, the reader for Tree-IL. If any source
  234. information is attached to the input S-expression, it will be
  235. propagated to the resulting Tree-IL expressions. This is probably the
  236. easiest way to compile to Tree-IL: just make the appropriate external
  237. representations in S-expression format, and let @code{parse-tree-il}
  238. take care of the rest.
  239. @deftp {Scheme Variable} <void> src
  240. @deftpx {External Representation} (void)
  241. An empty expression. In practice, equivalent to Scheme's @code{(if #f
  242. #f)}.
  243. @end deftp
  244. @deftp {Scheme Variable} <const> src exp
  245. @deftpx {External Representation} (const @var{exp})
  246. A constant.
  247. @end deftp
  248. @deftp {Scheme Variable} <primitive-ref> src name
  249. @deftpx {External Representation} (primitive @var{name})
  250. A reference to a ``primitive''. A primitive is a procedure that, when
  251. compiled, may be open-coded. For example, @code{cons} is usually
  252. recognized as a primitive, so that it compiles down to a single
  253. instruction.
  254. Compilation of Tree-IL usually begins with a pass that resolves some
  255. @code{<module-ref>} and @code{<toplevel-ref>} expressions to
  256. @code{<primitive-ref>} expressions. The actual compilation pass has
  257. special cases for calls to certain primitives, like @code{apply} or
  258. @code{cons}.
  259. @end deftp
  260. @deftp {Scheme Variable} <lexical-ref> src name gensym
  261. @deftpx {External Representation} (lexical @var{name} @var{gensym})
  262. A reference to a lexically-bound variable. The @var{name} is the
  263. original name of the variable in the source program. @var{gensym} is a
  264. unique identifier for this variable.
  265. @end deftp
  266. @deftp {Scheme Variable} <lexical-set> src name gensym exp
  267. @deftpx {External Representation} (set! (lexical @var{name} @var{gensym}) @var{exp})
  268. Sets a lexically-bound variable.
  269. @end deftp
  270. @deftp {Scheme Variable} <module-ref> src mod name public?
  271. @deftpx {External Representation} (@@ @var{mod} @var{name})
  272. @deftpx {External Representation} (@@@@ @var{mod} @var{name})
  273. A reference to a variable in a specific module. @var{mod} should be
  274. the name of the module, e.g.@: @code{(guile-user)}.
  275. If @var{public?} is true, the variable named @var{name} will be looked
  276. up in @var{mod}'s public interface, and serialized with @code{@@};
  277. otherwise it will be looked up among the module's private bindings,
  278. and is serialized with @code{@@@@}.
  279. @end deftp
  280. @deftp {Scheme Variable} <module-set> src mod name public? exp
  281. @deftpx {External Representation} (set! (@@ @var{mod} @var{name}) @var{exp})
  282. @deftpx {External Representation} (set! (@@@@ @var{mod} @var{name}) @var{exp})
  283. Sets a variable in a specific module.
  284. @end deftp
  285. @deftp {Scheme Variable} <toplevel-ref> src name
  286. @deftpx {External Representation} (toplevel @var{name})
  287. References a variable from the current procedure's module.
  288. @end deftp
  289. @deftp {Scheme Variable} <toplevel-set> src name exp
  290. @deftpx {External Representation} (set! (toplevel @var{name}) @var{exp})
  291. Sets a variable in the current procedure's module.
  292. @end deftp
  293. @deftp {Scheme Variable} <toplevel-define> src name exp
  294. @deftpx {External Representation} (define (toplevel @var{name}) @var{exp})
  295. Defines a new top-level variable in the current procedure's module.
  296. @end deftp
  297. @deftp {Scheme Variable} <conditional> src test then else
  298. @deftpx {External Representation} (if @var{test} @var{then} @var{else})
  299. A conditional. Note that @var{else} is not optional.
  300. @end deftp
  301. @deftp {Scheme Variable} <call> src proc args
  302. @deftpx {External Representation} (call @var{proc} . @var{args})
  303. A procedure call.
  304. @end deftp
  305. @deftp {Scheme Variable} <primcall> src name args
  306. @deftpx {External Representation} (primcall @var{name} . @var{args})
  307. A call to a primitive. Equivalent to @code{(call (primitive @var{name})
  308. . @var{args})}. This construct is often more convenient to generate and
  309. analyze than @code{<call>}.
  310. As part of the compilation process, instances of @code{(call (primitive
  311. @var{name}) . @var{args})} are transformed into primcalls.
  312. @end deftp
  313. @deftp {Scheme Variable} <seq> src head tail
  314. @deftpx {External Representation} (seq @var{head} @var{tail})
  315. A sequence. The semantics is that @var{head} is evaluated first, and
  316. any resulting values are ignored. Then @var{tail} is evaluated, in tail
  317. position.
  318. @end deftp
  319. @deftp {Scheme Variable} <lambda> src meta body
  320. @deftpx {External Representation} (lambda @var{meta} @var{body})
  321. A closure. @var{meta} is an association list of properties for the
  322. procedure. @var{body} is a single Tree-IL expression of type
  323. @code{<lambda-case>}. As the @code{<lambda-case>} clause can chain to
  324. an alternate clause, this makes Tree-IL's @code{<lambda>} have the
  325. expressiveness of Scheme's @code{case-lambda}.
  326. @end deftp
  327. @deftp {Scheme Variable} <lambda-case> req opt rest kw inits gensyms body alternate
  328. @deftpx {External Representation} @
  329. (lambda-case ((@var{req} @var{opt} @var{rest} @var{kw} @var{inits} @var{gensyms})@
  330. @var{body})@
  331. [@var{alternate}])
  332. One clause of a @code{case-lambda}. A @code{lambda} expression in
  333. Scheme is treated as a @code{case-lambda} with one clause.
  334. @var{req} is a list of the procedure's required arguments, as symbols.
  335. @var{opt} is a list of the optional arguments, or @code{#f} if there
  336. are no optional arguments. @var{rest} is the name of the rest
  337. argument, or @code{#f}.
  338. @var{kw} is a list of the form, @code{(@var{allow-other-keys?}
  339. (@var{keyword} @var{name} @var{var}) ...)}, where @var{keyword} is the
  340. keyword corresponding to the argument named @var{name}, and whose
  341. corresponding gensym is @var{var}. @var{inits} are tree-il expressions
  342. corresponding to all of the optional and keyword arguments, evaluated to
  343. bind variables whose value is not supplied by the procedure caller.
  344. Each @var{init} expression is evaluated in the lexical context of
  345. previously bound variables, from left to right.
  346. @var{gensyms} is a list of gensyms corresponding to all arguments:
  347. first all of the required arguments, then the optional arguments if
  348. any, then the rest argument if any, then all of the keyword arguments.
  349. @var{body} is the body of the clause. If the procedure is called with
  350. an appropriate number of arguments, @var{body} is evaluated in tail
  351. position. Otherwise, if there is an @var{alternate}, it should be a
  352. @code{<lambda-case>} expression, representing the next clause to try.
  353. If there is no @var{alternate}, a wrong-number-of-arguments error is
  354. signaled.
  355. @end deftp
  356. @deftp {Scheme Variable} <let> src names gensyms vals exp
  357. @deftpx {External Representation} (let @var{names} @var{gensyms} @var{vals} @var{exp})
  358. Lexical binding, like Scheme's @code{let}. @var{names} are the original
  359. binding names, @var{gensyms} are gensyms corresponding to the
  360. @var{names}, and @var{vals} are Tree-IL expressions for the values.
  361. @var{exp} is a single Tree-IL expression.
  362. @end deftp
  363. @deftp {Scheme Variable} <letrec> in-order? src names gensyms vals exp
  364. @deftpx {External Representation} (letrec @var{names} @var{gensyms} @var{vals} @var{exp})
  365. @deftpx {External Representation} (letrec* @var{names} @var{gensyms} @var{vals} @var{exp})
  366. A version of @code{<let>} that creates recursive bindings, like
  367. Scheme's @code{letrec}, or @code{letrec*} if @var{in-order?} is true.
  368. @end deftp
  369. @deftp {Scheme Variable} <prompt> escape-only? tag body handler
  370. @deftpx {External Representation} (prompt @var{escape-only?} @var{tag} @var{body} @var{handler})
  371. A dynamic prompt. Instates a prompt named @var{tag}, an expression,
  372. during the dynamic extent of the execution of @var{body}, also an
  373. expression. If an abort occurs to this prompt, control will be passed
  374. to @var{handler}, also an expression, which should be a procedure. The
  375. first argument to the handler procedure will be the captured
  376. continuation, followed by all of the values passed to the abort. If
  377. @var{escape-only?} is true, the handler should be a @code{<lambda>} with
  378. a single @code{<lambda-case>} body expression with no optional or
  379. keyword arguments, and no alternate, and whose first argument is
  380. unreferenced. @xref{Prompts}, for more information.
  381. @end deftp
  382. @deftp {Scheme Variable} <abort> tag args tail
  383. @deftpx {External Representation} (abort @var{tag} @var{args} @var{tail})
  384. An abort to the nearest prompt with the name @var{tag}, an expression.
  385. @var{args} should be a list of expressions to pass to the prompt's
  386. handler, and @var{tail} should be an expression that will evaluate to
  387. a list of additional arguments. An abort will save the partial
  388. continuation, which may later be reinstated, resulting in the
  389. @code{<abort>} expression evaluating to some number of values.
  390. @end deftp
  391. There are two Tree-IL constructs that are not normally produced by
  392. higher-level compilers, but instead are generated during the
  393. source-to-source optimization and analysis passes that the Tree-IL
  394. compiler does. Users should not generate these expressions directly,
  395. unless they feel very clever, as the default analysis pass will generate
  396. them as necessary.
  397. @deftp {Scheme Variable} <let-values> src names gensyms exp body
  398. @deftpx {External Representation} (let-values @var{names} @var{gensyms} @var{exp} @var{body})
  399. Like Scheme's @code{receive} -- binds the values returned by
  400. evaluating @code{exp} to the @code{lambda}-like bindings described by
  401. @var{gensyms}. That is to say, @var{gensyms} may be an improper list.
  402. @code{<let-values>} is an optimization of a @code{<call>} to the
  403. primitive, @code{call-with-values}.
  404. @end deftp
  405. @deftp {Scheme Variable} <fix> src names gensyms vals body
  406. @deftpx {External Representation} (fix @var{names} @var{gensyms} @var{vals} @var{body})
  407. Like @code{<letrec>}, but only for @var{vals} that are unset
  408. @code{lambda} expressions.
  409. @code{fix} is an optimization of @code{letrec} (and @code{let}).
  410. @end deftp
  411. Tree-IL is a convenient compilation target from source languages. It
  412. can be convenient as a medium for optimization, though CPS is usually
  413. better. The strength of Tree-IL is that it does not fix order of
  414. evaluation, so it makes some code motion a bit easier.
  415. Optimization passes performed on Tree-IL currently include:
  416. @itemize
  417. @item Open-coding (turning toplevel-refs into primitive-refs,
  418. and calls to primitives to primcalls)
  419. @item Partial evaluation (comprising inlining, copy propagation, and
  420. constant folding)
  421. @end itemize
  422. @node Continuation-Passing Style
  423. @subsection Continuation-Passing Style
  424. @cindex CPS
  425. Continuation-passing style (CPS) is Guile's principal intermediate
  426. language, bridging the gap between languages for people and languages
  427. for machines. CPS gives a name to every part of a program: every
  428. control point, and every intermediate value. This makes it an excellent
  429. medium for reasoning about programs, which is the principal job of a
  430. compiler.
  431. @menu
  432. * An Introduction to CPS::
  433. * CPS in Guile::
  434. * Building CPS::
  435. * CPS Soup::
  436. * Compiling CPS::
  437. @end menu
  438. @node An Introduction to CPS
  439. @subsubsection An Introduction to CPS
  440. Consider the following Scheme expression:
  441. @lisp
  442. (begin
  443. (display "The sum of 32 and 10 is: ")
  444. (display 42)
  445. (newline))
  446. @end lisp
  447. Let us identify all of the sub-expressions in this expression,
  448. annotating them with unique labels:
  449. @lisp
  450. (begin
  451. (display "The sum of 32 and 10 is: ")
  452. |k1 k2
  453. k0
  454. (display 42)
  455. |k4 k5
  456. k3
  457. (newline))
  458. |k7
  459. k6
  460. @end lisp
  461. Each of these labels identifies a point in a program. One label may be
  462. the continuation of another label. For example, the continuation of
  463. @code{k7} is @code{k6}. This is because after evaluating the value of
  464. @code{newline}, performed by the expression labelled @code{k7}, we
  465. continue to apply it in @code{k6}.
  466. Which expression has @code{k0} as its continuation? It is either the
  467. expression labelled @code{k1} or the expression labelled @code{k2}.
  468. Scheme does not have a fixed order of evaluation of arguments, though it
  469. does guarantee that they are evaluated in some order. Unlike general
  470. Scheme, continuation-passing style makes evaluation order explicit. In
  471. Guile, this choice is made by the higher-level language compilers.
  472. Let us assume a left-to-right evaluation order. In that case the
  473. continuation of @code{k1} is @code{k2}, and the continuation of
  474. @code{k2} is @code{k0}.
  475. With this example established, we are ready to give an example of CPS in
  476. Scheme:
  477. @smalllisp
  478. (lambda (ktail)
  479. (let ((k1 (lambda ()
  480. (let ((k2 (lambda (proc)
  481. (let ((k0 (lambda (arg0)
  482. (proc k4 arg0))))
  483. (k0 "The sum of 32 and 10 is: ")))))
  484. (k2 display))))
  485. (k4 (lambda _
  486. (let ((k5 (lambda (proc)
  487. (let ((k3 (lambda (arg0)
  488. (proc k7 arg0))))
  489. (k3 42)))))
  490. (k5 display))))
  491. (k7 (lambda _
  492. (let ((k6 (lambda (proc)
  493. (proc ktail))))
  494. (k6 newline)))))
  495. (k1))
  496. @end smalllisp
  497. Holy code explosion, Batman! What's with all the lambdas? Indeed, CPS
  498. is by nature much more verbose than ``direct-style'' intermediate
  499. languages like Tree-IL. At the same time, CPS is simpler than full
  500. Scheme, because it makes things more explicit.
  501. In the original program, the expression labelled @code{k0} is in effect
  502. context. Any values it returns are ignored. In Scheme, this fact is
  503. implicit. In CPS, we can see it explicitly by noting that its
  504. continuation, @code{k4}, takes any number of values and ignores them.
  505. Compare this to @code{k2}, which takes a single value; in this way we
  506. can say that @code{k1} is in a ``value'' context. Likewise @code{k6} is
  507. in tail context with respect to the expression as a whole, because its
  508. continuation is the tail continuation, @code{ktail}. CPS makes these
  509. details manifest, and gives them names.
  510. @node CPS in Guile
  511. @subsubsection CPS in Guile
  512. @cindex continuation, CPS
  513. Guile's CPS language is composed of @dfn{continuations}. A continuation
  514. is a labelled program point. If you are used to traditional compilers,
  515. think of a continuation as a trivial basic block. A program is a
  516. ``soup'' of continuations, represented as a map from labels to
  517. continuations.
  518. @cindex term, CPS
  519. @cindex expression, CPS
  520. Like basic blocks, each continuation belongs to only one function. Some
  521. continuations are special, like the continuation corresponding to a
  522. function's entry point, or the continuation that represents the tail of
  523. a function. Others contain a @dfn{term}. A term contains an
  524. @dfn{expression}, which evaluates to zero or more values. The term also
  525. records the continuation to which it will pass its values. Some terms,
  526. like conditional branches, may continue to one of a number of
  527. continuations.
  528. Continuation labels are small integers. This makes it easy to sort them
  529. and to group them into sets. Whenever a term refers to a continuation,
  530. it does so by name, simply recording the label of the continuation.
  531. Continuation labels are unique among the set of labels in a program.
  532. Variables are also named by small integers. Variable names are unique
  533. among the set of variables in a program.
  534. For example, a simple continuation that receives two values and adds
  535. them together can be matched like this, using the @code{match} form from
  536. @code{(ice-9 match)}:
  537. @smallexample
  538. (match cont
  539. (($ $kargs (x-name y-name) (x-var y-var)
  540. ($ $continue k src ($ $primcall '+ (x-var y-var))))
  541. (format #t "Add ~a and ~a and pass the result to label ~a"
  542. x-var y-var k)))
  543. @end smallexample
  544. Here we see the most common kind of continuation, @code{$kargs}, which
  545. binds some number of values to variables and then evaluates a term.
  546. @deftp {CPS Continuation} $kargs names vars term
  547. Bind the incoming values to the variables @var{vars}, with original
  548. names @var{names}, and then evaluate @var{term}.
  549. @end deftp
  550. The @var{names} of a @code{$kargs} are just for debugging, and will end
  551. up residualized in the object file for use by the debugger.
  552. The @var{term} in a @code{$kargs} is always a @code{$continue}, which
  553. evaluates an expression and continues to a continuation.
  554. @deftp {CPS Term} $continue k src exp
  555. Evaluate the expression @var{exp} and pass the resulting values (if any)
  556. to the continuation labelled @var{k}. The source information associated
  557. with the expression may be found in @var{src}, which is either an alist
  558. as in @code{source-properties} or is @code{#f} if there is no associated
  559. source.
  560. @end deftp
  561. There are a number of expression kinds. Above you see an example of
  562. @code{$primcall}.
  563. @deftp {CPS Expression} $primcall name args
  564. Perform the primitive operation identified by @code{name}, a well-known
  565. symbol, passing it the arguments @var{args}, and pass all resulting
  566. values to the continuation. The set of available primitives includes
  567. all primitives known to Tree-IL and then some more; see the source code
  568. for details.
  569. @end deftp
  570. @cindex dominate, CPS
  571. The variables that are used by @code{$primcall}, or indeed by any
  572. expression, must be defined before the expression is evaluated. An
  573. equivalent way of saying this is that predecessor @code{$kargs}
  574. continuation(s) that bind the variables(s) used by the expression must
  575. @dfn{dominate} the continuation that uses the expression: definitions
  576. dominate uses. This condition is trivially satisfied in our example
  577. above, but in general to determine the set of variables that are in
  578. ``scope'' for a given term, you need to do a flow analysis to see what
  579. continuations dominate a term. The variables that are in scope are
  580. those variables defined by the continuations that dominate a term.
  581. Here is an inventory of the kinds of expressions in Guile's CPS
  582. language, besides @code{$primcall} which has already been described.
  583. Recall that all expressions are wrapped in a @code{$continue} term which
  584. specifies their continuation.
  585. @deftp {CPS Expression} $const val
  586. Continue with the constant value @var{val}.
  587. @end deftp
  588. @deftp {CPS Expression} $prim name
  589. Continue with the procedure that implements the primitive operation
  590. named by @var{name}.
  591. @end deftp
  592. @deftp {CPS Expression} $call proc args
  593. Call @var{proc} with the arguments @var{args}, and pass all values to
  594. the continuation. @var{proc} and the elements of the @var{args} list
  595. should all be variable names. The continuation identified by the term's
  596. @var{k} should be a @code{$kreceive} or a @code{$ktail} instance.
  597. @end deftp
  598. @deftp {CPS Expression} $values args
  599. Pass the values named by the list @var{args} to the continuation.
  600. @end deftp
  601. @deftp {CPS Expression} $branch kt exp
  602. Evaluate the branching expression @var{exp}, and continue to @var{kt}
  603. with zero values if the test evaluates to true. Otherwise continue to
  604. the continuation named in the outer @code{$continue} term.
  605. Only certain expressions are valid in a @var{$branch}. Compiling a
  606. @code{$branch} avoids allocating space for the test variable, so the
  607. expression should be evaluatable without temporary values. In practice
  608. this condition is true for @code{$primcall}s to @code{null?}, @code{=},
  609. and similar primitives that have corresponding @code{br-if-@var{foo}} VM
  610. operations; see the source code for full details. When in doubt, bind
  611. the test expression to a variable, and branch on a @code{$values}
  612. expression that references that variable. The optimizer should inline
  613. the reference if possible.
  614. @end deftp
  615. @deftp {CPS Expression} $prompt escape? tag handler
  616. Push a prompt on the stack identified by the variable name @var{tag},
  617. which may be escape-only if @var{escape?} is true, and continue with
  618. zero values. If the body aborts to this prompt, control will proceed at
  619. the continuation labelled @var{handler}, which should be a
  620. @code{$kreceive} continuation. Prompts are later popped by
  621. @code{pop-prompt} primcalls.
  622. @end deftp
  623. @cindex higher-order CPS
  624. @cindex CPS, higher-order
  625. @cindex first-order CPS
  626. @cindex CPS, first-order
  627. There are two sub-languages of CPS, @dfn{higher-order CPS} and
  628. @dfn{first-order CPS}. The difference is that in higher-order CPS,
  629. there are @code{$fun} and @code{$rec} expressions that bind functions or
  630. mutually-recursive functions in the implicit scope of their use sites.
  631. Guile transforms higher-order CPS into first-order CPS by @dfn{closure
  632. conversion}, which chooses representations for all closures and which
  633. arranges to access free variables through the implicit closure parameter
  634. that is passed to every function call.
  635. @deftp {CPS Expression} $fun body
  636. Continue with a procedure. @var{body} names the entry point of the
  637. function, which should be a @code{$kfun}. This expression kind is only
  638. valid in higher-order CPS, which is the CPS language before closure
  639. conversion.
  640. @end deftp
  641. @deftp {CPS Expression} $rec names vars funs
  642. Continue with a set of mutually recursive procedures denoted by
  643. @var{names}, @var{vars}, and @var{funs}. @var{names} is a list of
  644. symbols, @var{vars} is a list of variable names (unique integers), and
  645. @var{funs} is a list of @code{$fun} values. Note that the @code{$kargs}
  646. continuation should also define @var{names}/@var{vars} bindings.
  647. @end deftp
  648. The contification pass will attempt to transform the functions declared
  649. in a @code{$rec} into local continuations. Any remaining @code{$fun}
  650. instances are later removed by the closure conversion pass. By default,
  651. a closure is represented as an object built by a @code{$closure}
  652. expression.
  653. @deftp {CPS Expression} $closure label nfree
  654. Build a closure that joins the code at the continuation named
  655. @var{label} with space for @var{nfree} free variables. The variables
  656. will be initialized later via @code{free-set!} primcalls. This
  657. expression kind is part of first-order CPS.
  658. @end deftp
  659. If the closure can be proven to never escape its scope then other
  660. lighter-weight representations can be chosen. Additionally, if all call
  661. sites are known, closure conversion will hard-wire the calls by lowering
  662. @code{$call} to @code{$callk}.
  663. @deftp {CPS Expression} $callk label proc args
  664. Like @code{$call}, but for the case where the call target is known to be
  665. in the same compilation unit. @var{label} should denote some
  666. @code{$kfun} continuation in the program. In this case the @var{proc}
  667. is simply an additional argument, since it is not used to determine the
  668. call target at run-time.
  669. @end deftp
  670. At this point we have described terms, expressions, and the most common
  671. kind of continuation, @code{$kargs}. @code{$kargs} is used when the
  672. predecessors of the continuation can be instructed to pass the values
  673. where the continuation wants them. For example, if a @code{$kargs}
  674. continuation @var{k} binds a variable @var{v}, and the compiler decides
  675. to allocate @var{v} to slot 6, all predecessors of @var{k} should put
  676. the value for @var{v} in slot 6 before jumping to @var{k}. One
  677. situation in which this isn't possible is receiving values from function
  678. calls. Guile has a calling convention for functions which currently
  679. places return values on the stack. A continuation of a call must check
  680. that the number of values returned from a function matches the expected
  681. number of values, and then must shuffle or collect those values to named
  682. variables. @code{$kreceive} denotes this kind of continuation.
  683. @deftp {CPS Continuation} $kreceive arity k
  684. Receive values on the stack. Parse them according to @var{arity}, and
  685. then proceed with the parsed values to the @code{$kargs} continuation
  686. labelled @var{k}. As a limitation specific to @code{$kreceive},
  687. @var{arity} may only contain required and rest arguments.
  688. @end deftp
  689. @code{$arity} is a helper data structure used by @code{$kreceive} and
  690. also by @code{$kclause}, described below.
  691. @deftp {CPS Data} $arity req opt rest kw allow-other-keys?
  692. A data type declaring an arity. @var{req} and @var{opt} are lists of
  693. source names of required and optional arguments, respectively.
  694. @var{rest} is either the source name of the rest variable, or @code{#f}
  695. if this arity does not accept additional values. @var{kw} is a list of
  696. the form @code{((@var{keyword} @var{name} @var{var}) ...)}, describing
  697. the keyword arguments. @var{allow-other-keys?} is true if other keyword
  698. arguments are allowed and false otherwise.
  699. Note that all of these names with the exception of the @var{var}s in the
  700. @var{kw} list are source names, not unique variable names.
  701. @end deftp
  702. Additionally, there are three specific kinds of continuations that are
  703. only used in function entries.
  704. @deftp {CPS Continuation} $kfun src meta self tail clauses
  705. Declare a function entry. @var{src} is the source information for the
  706. procedure declaration, and @var{meta} is the metadata alist as described
  707. above in Tree-IL's @code{<lambda>}. @var{self} is a variable bound to
  708. the procedure being called, and which may be used for self-references.
  709. @var{tail} is the label of the @code{$ktail} for this function,
  710. corresponding to the function's tail continuation. @var{clause} is the
  711. label of the first @code{$kclause} for the first @code{case-lambda}
  712. clause in the function, or otherwise @code{#f}.
  713. @end deftp
  714. @deftp {CPS Continuation} $ktail
  715. A tail continuation.
  716. @end deftp
  717. @deftp {CPS Continuation} $kclause arity cont alternate
  718. A clause of a function with a given arity. Applications of a function
  719. with a compatible set of actual arguments will continue to the
  720. continuation labelled @var{cont}, a @code{$kargs} instance representing
  721. the clause body. If the arguments are incompatible, control proceeds to
  722. @var{alternate}, which is a @code{$kclause} for the next clause, or
  723. @code{#f} if there is no next clause.
  724. @end deftp
  725. @node Building CPS
  726. @subsubsection Building CPS
  727. Unlike Tree-IL, the CPS language is built to be constructed and
  728. deconstructed with abstract macros instead of via procedural
  729. constructors or accessors, or instead of S-expression matching.
  730. Deconstruction and matching is handled adequately by the @code{match}
  731. form from @code{(ice-9 match)}. @xref{Pattern Matching}. Construction
  732. is handled by a set of mutually builder macros:
  733. @code{build-term}, @code{build-cont}, and @code{build-exp}.
  734. In the following interface definitions, consider @code{term} and
  735. @code{exp} to be built by @code{build-term} or @code{build-exp},
  736. respectively. Consider any other name to be evaluated as a Scheme
  737. expression. Many of these forms recognize @code{unquote} in some
  738. contexts, to splice in a previously-built value; see the specifications
  739. below for full details.
  740. @deffn {Scheme Syntax} build-term ,val
  741. @deffnx {Scheme Syntax} build-term ($continue k src exp)
  742. @deffnx {Scheme Syntax} build-exp ,val
  743. @deffnx {Scheme Syntax} build-exp ($const val)
  744. @deffnx {Scheme Syntax} build-exp ($prim name)
  745. @deffnx {Scheme Syntax} build-exp ($branch kt exp)
  746. @deffnx {Scheme Syntax} build-exp ($fun kentry)
  747. @deffnx {Scheme Syntax} build-exp ($rec names syms funs)
  748. @deffnx {Scheme Syntax} build-exp ($closure k nfree)
  749. @deffnx {Scheme Syntax} build-exp ($call proc (arg ...))
  750. @deffnx {Scheme Syntax} build-exp ($call proc args)
  751. @deffnx {Scheme Syntax} build-exp ($callk k proc (arg ...))
  752. @deffnx {Scheme Syntax} build-exp ($callk k proc args)
  753. @deffnx {Scheme Syntax} build-exp ($primcall name (arg ...))
  754. @deffnx {Scheme Syntax} build-exp ($primcall name args)
  755. @deffnx {Scheme Syntax} build-exp ($values (arg ...))
  756. @deffnx {Scheme Syntax} build-exp ($values args)
  757. @deffnx {Scheme Syntax} build-exp ($prompt escape? tag handler)
  758. @deffnx {Scheme Syntax} build-cont ,val
  759. @deffnx {Scheme Syntax} build-cont ($kargs (name ...) (sym ...) term)
  760. @deffnx {Scheme Syntax} build-cont ($kargs names syms term)
  761. @deffnx {Scheme Syntax} build-cont ($kreceive req rest kargs)
  762. @deffnx {Scheme Syntax} build-cont ($kfun src meta self ktail kclause)
  763. @deffnx {Scheme Syntax} build-cont ($kclause ,arity kbody kalt)
  764. @deffnx {Scheme Syntax} build-cont ($kclause (req opt rest kw aok?) kbody)
  765. Construct a CPS term, expression, or continuation.
  766. @end deffn
  767. There are a few more miscellaneous interfaces as well.
  768. @deffn {Scheme Procedure} make-arity req opt rest kw allow-other-keywords?
  769. A procedural constructor for @code{$arity} objects.
  770. @end deffn
  771. @deffn {Scheme Syntax} rewrite-term val (pat term) ...
  772. @deffnx {Scheme Syntax} rewrite-exp val (pat exp) ...
  773. @deffnx {Scheme Syntax} rewrite-cont val (pat cont) ...
  774. Match @var{val} against the series of patterns @var{pat...}, using
  775. @code{match}. The body of the matching clause should be a template in
  776. the syntax of @code{build-term}, @code{build-exp}, or @code{build-cont},
  777. respectively.
  778. @end deffn
  779. @node CPS Soup
  780. @subsubsection CPS Soup
  781. We describe programs in Guile's CPS language as being a kind of ``soup''
  782. because all continuations in the program are mixed into the same
  783. ``pot'', so to speak, without explicit markers as to what function or
  784. scope a continuation is in. A program in CPS is a map from continuation
  785. labels to continuation values. As discussed in the introduction, a
  786. continuation label is an integer. No label may be negative.
  787. As a matter of convention, label 0 should map to the @code{$kfun}
  788. continuation of the entry to the program, which should be a function of
  789. no arguments. The body of a function consists of the labelled
  790. continuations that are reachable from the function entry. A program can
  791. refer to other functions, either via @code{$fun} and @code{$rec} in
  792. higher-order CPS, or via @code{$closure} and @code{$callk} in
  793. first-order CPS. The program logically contains all continuations of
  794. all functions reachable from the entry function. A compiler pass may
  795. leave unreachable continuations in a program; subsequent compiler passes
  796. should ensure that their transformations and analyses only take
  797. reachable continuations into account. It's OK though if transformation
  798. runs over all continuations if including the unreachable continuations
  799. has no effect on the transformations on the live continuations.
  800. @cindex intmap
  801. The ``soup'' itself is implemented as an @dfn{intmap}, a functional
  802. array-mapped trie specialized for integer keys. Intmaps associate
  803. integers with values of any kind. Currently intmaps are a private data
  804. structure only used by the CPS phase of the compiler. To work with
  805. intmaps, load the @code{(language cps intmap)} module:
  806. @example
  807. (use-modules (language cps intmap))
  808. @end example
  809. Intmaps are functional data structures, so there is no constructor as
  810. such: one can simply start with the empty intmap and add entries to it.
  811. @example
  812. (intmap? empty-intmap) @result{} #t
  813. (define x (intmap-add empty-intmap 42 "hi"))
  814. (intmap? x) @result{} #t
  815. (intmap-ref x 42) @result{} "hi"
  816. (intmap-ref x 43) @result{} @i{error: 43 not present}
  817. (intmap-ref x 43 (lambda (k) "yo!")) @result{} "yo"
  818. (intmap-add x 42 "hej") @result{} @i{error: 42 already present}
  819. @end example
  820. @code{intmap-ref} and @code{intmap-add} are the core of the intmap
  821. interface. There is also @code{intmap-replace}, which replaces the
  822. value associated with a given key, requiring that the key was present
  823. already, and @code{intmap-remove}, which removes a key from an intmap.
  824. Intmaps have a tree-like structure that is well-suited to set operations
  825. such as union and intersection, so there is are also the binary
  826. @code{intmap-union} and @code{intmap-intersect} procedures. If the
  827. result is equivalent to either argument, that argument is returned
  828. as-is; in that way, one can detect whether the set operation produced a
  829. new result simply by checking with @code{eq?}. This makes intmaps
  830. useful when computing fixed points.
  831. If a key is present in both intmaps and the associated values are not
  832. the same in the sense of @code{eq?}, the resulting value is determined
  833. by a ``meet'' procedure, which is the optional last argument to
  834. @code{intmap-union}, @code{intmap-intersect}, and also to
  835. @code{intmap-add}, @code{intmap-replace}, and similar functions. The
  836. meet procedure will be called with the two values and should return the
  837. intersected or unioned value in some domain-specific way. If no meet
  838. procedure is given, the default meet procedure will raise an error.
  839. To traverse over the set of values in an intmap, there are the
  840. @code{intmap-next} and @code{intmap-prev} procedures. For example, if
  841. intmap @var{x} has one entry mapping 42 to some value, we would have:
  842. @example
  843. (intmap-next x) @result{} 42
  844. (intmap-next x 0) @result{} 42
  845. (intmap-next x 42) @result{} 42
  846. (intmap-next x 43) @result{} #f
  847. (intmap-prev x) @result{} 42
  848. (intmap-prev x 42) @result{} 42
  849. (intmap-prev x 41) @result{} #f
  850. @end example
  851. There is also the @code{intmap-fold} procedure, which folds over keys
  852. and values in the intmap from lowest to highest value, and
  853. @code{intmap-fold-right} which does so in the opposite direction. These
  854. procedures may take up to 3 seed values. The number of values that the
  855. fold procedure returns is the number of seed values.
  856. @example
  857. (define q (intmap-add (intmap-add empty-intmap 1 2) 3 4))
  858. (intmap-fold acons q '()) @result{} ((3 . 4) (1 . 2))
  859. (intmap-fold-right acons q '()) @result{} ((1 . 2) (3 . 4))
  860. @end example
  861. When an entry in an intmap is updated (removed, added, or changed), a
  862. new intmap is created that shares structure with the original intmap.
  863. This operation ensures that the result of existing computations is not
  864. affected by future computations: no mutation is ever visible to user
  865. code. This is a great property in a compiler data structure, as it lets
  866. us hold a copy of a program before a transformation and use it while we
  867. build a post-transformation program. Updating an intmap is O(log
  868. @var{n}) in the size of the intmap.
  869. However, the O(log @var{n}) allocation costs are sometimes too much,
  870. especially in cases when we know that we can just update the intmap in
  871. place. As an example, say we have an intmap mapping the integers 1 to
  872. 100 to the integers 42 to 141. Let's say that we want to transform this
  873. map by adding 1 to each value. There is already an efficient
  874. @code{intmap-map} procedure in the @code{(language cps utils}) module,
  875. but if we didn't know about that we might do:
  876. @example
  877. (define (intmap-increment map)
  878. (let lp ((k 0) (map map))
  879. (let ((k (intmap-next map k)))
  880. (if k
  881. (let ((v (intmap-ref map k)))
  882. (lp (1+ k) (intmap-replace map k (1+ v))))
  883. map))))
  884. @end example
  885. @cindex intmap, transient
  886. @cindex transient intmaps
  887. Observe that the intermediate values created by @code{intmap-replace}
  888. are completely invisible to the program -- only the last result of
  889. @code{intmap-replace} value is needed. The rest might as well share
  890. state with the last one, and we could update in place. Guile allows
  891. this kind of interface via @dfn{transient intmaps}, inspired by
  892. Clojure's transient interface (@uref{http://clojure.org/transients}).
  893. The in-place @code{intmap-add!} and @code{intmap-replace!} procedures
  894. return transient intmaps. If one of these in-place procedures is called
  895. on a normal persistent intmap, a new transient intmap is created. This
  896. is an O(1) operation. In all other respects the interface is like their
  897. persistent counterparts, @code{intmap-add} and @code{intmap-replace}.
  898. If an in-place procedure is called on a transient intmap, the intmap is
  899. mutated in-place and the same value is returned.
  900. If a persistent operation like @code{intmap-add} is called on a
  901. transient intmap, the transient's mutable substructure is then marked as
  902. persistent, and @code{intmap-add} then runs on a new persistent intmap
  903. sharing structure but not state with the original transient. Mutating a
  904. transient will cause enough copying to ensure that it can make its
  905. change, but if part of its substructure is already ``owned'' by it, no
  906. more copying is needed.
  907. We can use transients to make @code{intmap-increment} more efficient.
  908. The two changed elements have been marked @strong{like this}.
  909. @example
  910. (define (intmap-increment map)
  911. (let lp ((k 0) (map map))
  912. (let ((k (intmap-next map k)))
  913. (if k
  914. (let ((v (intmap-ref map k)))
  915. (lp (1+ k) (@strong{intmap-replace!} map k (1+ v))))
  916. (@strong{persistent-intmap} map)))))
  917. @end example
  918. Be sure to tag the result as persistent using the
  919. @code{persistent-intmap} procedure to prevent the mutability from
  920. leaking to other parts of the program. For added paranoia, you could
  921. call @code{persistent-intmap} on the incoming map, to ensure that if it
  922. were already transient, that the mutations in the body of
  923. @code{intmap-increment} wouldn't affect the incoming value.
  924. In summary, programs in CPS are intmaps whose values are continuations.
  925. See the source code of @code{(language cps utils)} for a number of
  926. useful facilities for working with CPS values.
  927. @node Compiling CPS
  928. @subsubsection Compiling CPS
  929. Compiling CPS in Guile has three phases: conversion, optimization, and
  930. code generation.
  931. CPS conversion is the process of taking a higher-level language and
  932. compiling it to CPS. Source languages can do this directly, or they can
  933. convert to Tree-IL (which is probably easier) and let Tree-IL convert to
  934. CPS later. Going through Tree-IL has the advantage of running Tree-IL
  935. optimization passes, like partial evaluation. Also, the compiler from
  936. Tree-IL to CPS handles assignment conversion, in which assigned local
  937. variables (in Tree-IL, locals that are @code{<lexical-set>}) are
  938. converted to being boxed values on the heap. @xref{Variables and the
  939. VM}.
  940. After CPS conversion, Guile runs some optimization passes over the CPS.
  941. Most optimization in Guile is done on the CPS language. The one major
  942. exception is partial evaluation, which for historic reasons is done on
  943. Tree-IL.
  944. The major optimization performed on CPS is contification, in which
  945. functions that are always called with the same continuation are
  946. incorporated directly into a function's body. This opens up space for
  947. more optimizations, and turns procedure calls into @code{goto}. It can
  948. also make loops out of recursive function nests. Guile also does dead
  949. code elimination, common subexpression elimination, loop peeling and
  950. invariant code motion, and range and type inference.
  951. The rest of the optimization passes are really cleanups and
  952. canonicalizations. CPS spans the gap between high-level languages and
  953. low-level bytecodes, which allows much of the compilation process to be
  954. expressed as source-to-source transformations. Such is the case for
  955. closure conversion, in which references to variables that are free in a
  956. function are converted to closure references, and in which functions are
  957. converted to closures. There are a few more passes to ensure that the
  958. only primcalls left in the term are those that have a corresponding
  959. instruction in the virtual machine, and that their continuations expect
  960. the right number of values.
  961. Finally, the backend of the CPS compiler emits bytecode for each
  962. function, one by one. To do so, it determines the set of live variables
  963. at all points in the function. Using this liveness information, it
  964. allocates stack slots to each variable, such that a variable can live in
  965. one slot for the duration of its lifetime, without shuffling. (Of
  966. course, variables with disjoint lifetimes can share a slot.) Finally
  967. the backend emits code, typically just one VM instruction, for each
  968. continuation in the function.
  969. @node Bytecode
  970. @subsection Bytecode
  971. As mentioned before, Guile compiles all code to bytecode, and that
  972. bytecode is contained in ELF images. @xref{Object File Format}, for
  973. more on Guile's use of ELF.
  974. To produce a bytecode image, Guile provides an assembler and a linker.
  975. The assembler, defined in the @code{(system vm assembler)} module, has a
  976. relatively straightforward imperative interface. It provides a
  977. @code{make-assembler} function to instantiate an assembler and a set of
  978. @code{emit-@var{inst}} procedures to emit instructions of each kind.
  979. The @code{emit-@var{inst}} procedures are actually generated at
  980. compile-time from a machine-readable description of the VM. With a few
  981. exceptions for certain operand types, each operand of an emit procedure
  982. corresponds to an operand of the corresponding instruction.
  983. Consider @code{vector-length}, from @pxref{Miscellaneous Instructions}.
  984. It is documented as:
  985. @deftypefn Instruction {} vector-length u12:@var{dst} u12:@var{src}
  986. @end deftypefn
  987. Therefore the emit procedure has the form:
  988. @deffn {Scheme Procedure} emit-vector-length asm dst src
  989. @end deffn
  990. All emit procedure take the assembler as their first argument, and
  991. return no useful values.
  992. The argument types depend on the operand types. @xref{Instruction Set}.
  993. Most are integers within a restricted range, though labels are generally
  994. expressed as opaque symbols.
  995. There are a few macro-instructions as well.
  996. @deffn {Scheme Procedure} emit-label asm label
  997. Define a label at the current program point.
  998. @end deffn
  999. @deffn {Scheme Procedure} emit-source asm source
  1000. Associate @var{source} with the current program point.
  1001. @end deffn
  1002. @deffn {Scheme Procedure} emit-cache-current-module! asm module scope
  1003. @deffnx {Scheme Procedure} emit-cached-toplevel-box asm dst scope sym bound?
  1004. @deffnx {Scheme Procedure} emit-cached-module-box asm dst module-name sym public? bound?
  1005. Macro-instructions to implement caching of top-level variables. The
  1006. first takes the current module, in the slot @var{module}, and associates
  1007. it with a cache location identified by @var{scope}. The second takes a
  1008. @var{scope}, and resolves the variable. @xref{Top-Level Environment
  1009. Instructions}. The last does not need a cached module, rather taking
  1010. the module name directly.
  1011. @end deffn
  1012. @deffn {Scheme Procedure} emit-load-constant asm dst constant
  1013. Load the Scheme datum @var{constant} into @var{dst}.
  1014. @end deffn
  1015. @deffn {Scheme Procedure} emit-begin-program asm label properties
  1016. @deffnx {Scheme Procedure} emit-end-program asm
  1017. Delimit the bounds of a procedure, with the given @var{label} and the
  1018. metadata @var{properties}.
  1019. @end deffn
  1020. @deffn {Scheme Procedure} emit-load-static-procedure asm dst label
  1021. Load a procedure with the given @var{label} into local @var{dst}. This
  1022. macro-instruction should only be used with procedures without free
  1023. variables -- procedures that are not closures.
  1024. @end deffn
  1025. @deffn {Scheme Procedure} emit-begin-standard-arity asm req nlocals alternate
  1026. @deffnx {Scheme Procedure} emit-begin-opt-arity asm req opt rest nlocals alternate
  1027. @deffnx {Scheme Procedure} emit-begin-kw-arity asm req opt rest kw-indices allow-other-keys? nlocals alternate
  1028. @deffnx {Scheme Procedure} emit-end-arity asm
  1029. Delimit a clause of a procedure.
  1030. @end deffn
  1031. @deffn {Scheme Procedure} emit-br-if-symbol asm slot invert? label
  1032. @deffnx {Scheme Procedure} emit-br-if-variable asm slot invert? label
  1033. @deffnx {Scheme Procedure} emit-br-if-vector asm slot invert? label
  1034. @deffnx {Scheme Procedure} emit-br-if-string asm slot invert? label
  1035. @deffnx {Scheme Procedure} emit-br-if-bytevector asm slot invert? label
  1036. @deffnx {Scheme Procedure} emit-br-if-bitvector asm slot invert? label
  1037. TC7-specific test-and-branch instructions. The TC7 is a 7-bit code that
  1038. is part of a heap object's type. @xref{The SCM Type in Guile}. Also,
  1039. @xref{Branch Instructions}.
  1040. @end deffn
  1041. The linker is a complicated beast. Hackers interested in how it works
  1042. would do well do read Ian Lance Taylor's series of articles on linkers.
  1043. Searching the internet should find them easily. From the user's
  1044. perspective, there is only one knob to control: whether the resulting
  1045. image will be written out to a file or not. If the user passes
  1046. @code{#:to-file? #t} as part of the compiler options (@pxref{The Scheme
  1047. Compiler}), the linker will align the resulting segments on page
  1048. boundaries, and otherwise not.
  1049. @deffn {Scheme Procedure} link-assembly asm #:page-aligned?=#t
  1050. Link an ELF image, and return the bytevector. If @var{page-aligned?} is
  1051. true, Guile will align the segments with different permissions on
  1052. page-sized boundaries, in order to maximize code sharing between
  1053. different processes. Otherwise, padding is minimized, to minimize
  1054. address space consumption.
  1055. @end deffn
  1056. To write an image to disk, just use @code{put-bytevector} from
  1057. @code{(ice-9 binary-ports)}.
  1058. Compiling object code to the fake language, @code{value}, is performed
  1059. via loading objcode into a program, then executing that thunk with
  1060. respect to the compilation environment. Normally the environment
  1061. propagates through the compiler transparently, but users may specify the
  1062. compilation environment manually as well, as a module. Procedures to
  1063. load images can be found in the @code{(system vm loader)} module:
  1064. @lisp
  1065. (use-modules (system vm loader))
  1066. @end lisp
  1067. @deffn {Scheme Variable} load-thunk-from-file file
  1068. @deffnx {C Function} scm_load_thunk_from_file (file)
  1069. Load object code from a file named @var{file}. The file will be mapped
  1070. into memory via @code{mmap}, so this is a very fast operation.
  1071. @end deffn
  1072. @deffn {Scheme Variable} load-thunk-from-memory bv
  1073. @deffnx {C Function} scm_load_thunk_from_memory (bv)
  1074. Load object code from a bytevector. The data will be copied out of the
  1075. bytevector in order to ensure proper alignment of embedded Scheme
  1076. values.
  1077. @end deffn
  1078. Additionally there are procedures to find the ELF image for a given
  1079. pointer, or to list all mapped ELF images:
  1080. @deffn {Scheme Variable} find-mapped-elf-image ptr
  1081. Given the integer value @var{ptr}, find and return the ELF image that
  1082. contains that pointer, as a bytevector. If no image is found, return
  1083. @code{#f}. This routine is mostly used by debuggers and other
  1084. introspective tools.
  1085. @end deffn
  1086. @deffn {Scheme Variable} all-mapped-elf-images
  1087. Return all mapped ELF images, as a list of bytevectors.
  1088. @end deffn
  1089. @node Writing New High-Level Languages
  1090. @subsection Writing New High-Level Languages
  1091. In order to integrate a new language @var{lang} into Guile's compiler
  1092. system, one has to create the module @code{(language @var{lang} spec)}
  1093. containing the language definition and referencing the parser,
  1094. compiler and other routines processing it. The module hierarchy in
  1095. @code{(language brainfuck)} defines a very basic Brainfuck
  1096. implementation meant to serve as easy-to-understand example on how to
  1097. do this. See for instance @url{http://en.wikipedia.org/wiki/Brainfuck}
  1098. for more information about the Brainfuck language itself.
  1099. @node Extending the Compiler
  1100. @subsection Extending the Compiler
  1101. At this point we take a detour from the impersonal tone of the rest of
  1102. the manual. Admit it: if you've read this far into the compiler
  1103. internals manual, you are a junkie. Perhaps a course at your university
  1104. left you unsated, or perhaps you've always harbored a desire to hack the
  1105. holy of computer science holies: a compiler. Well you're in good
  1106. company, and in a good position. Guile's compiler needs your help.
  1107. There are many possible avenues for improving Guile's compiler.
  1108. Probably the most important improvement, speed-wise, will be some form
  1109. of native compilation, both just-in-time and ahead-of-time. This could
  1110. be done in many ways. Probably the easiest strategy would be to extend
  1111. the compiled procedure structure to include a pointer to a native code
  1112. vector, and compile from bytecode to native code at run-time after a
  1113. procedure is called a certain number of times.
  1114. The name of the game is a profiling-based harvest of the low-hanging
  1115. fruit, running programs of interest under a system-level profiler and
  1116. determining which improvements would give the most bang for the buck.
  1117. It's really getting to the point though that native compilation is the
  1118. next step.
  1119. The compiler also needs help at the top end, enhancing the Scheme that
  1120. it knows to also understand R6RS, and adding new high-level compilers.
  1121. We have JavaScript and Emacs Lisp mostly complete, but they could use
  1122. some love; Lua would be nice as well, but whatever language it is
  1123. that strikes your fancy would be welcome too.
  1124. Compilers are for hacking, not for admiring or for complaining about.
  1125. Get to it!