/3rd_party/llvm/docs/tutorial/OCamlLangImpl3.html

https://code.google.com/p/softart/ · HTML · 1093 lines · 904 code · 176 blank · 13 comment · 0 complexity · bd189a4152f53887e8590535eabe61ac MD5 · raw file

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  2. "http://www.w3.org/TR/html4/strict.dtd">
  3. <html>
  4. <head>
  5. <title>Kaleidoscope: Implementing code generation to LLVM IR</title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <meta name="author" content="Chris Lattner">
  8. <meta name="author" content="Erick Tryzelaar">
  9. <link rel="stylesheet" href="../_static/llvm.css" type="text/css">
  10. </head>
  11. <body>
  12. <h1>Kaleidoscope: Code generation to LLVM IR</h1>
  13. <ul>
  14. <li><a href="index.html">Up to Tutorial Index</a></li>
  15. <li>Chapter 3
  16. <ol>
  17. <li><a href="#intro">Chapter 3 Introduction</a></li>
  18. <li><a href="#basics">Code Generation Setup</a></li>
  19. <li><a href="#exprs">Expression Code Generation</a></li>
  20. <li><a href="#funcs">Function Code Generation</a></li>
  21. <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
  22. <li><a href="#code">Full Code Listing</a></li>
  23. </ol>
  24. </li>
  25. <li><a href="OCamlLangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
  26. Support</li>
  27. </ul>
  28. <div class="doc_author">
  29. <p>
  30. Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>
  31. and <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a>
  32. </p>
  33. </div>
  34. <!-- *********************************************************************** -->
  35. <h2><a name="intro">Chapter 3 Introduction</a></h2>
  36. <!-- *********************************************************************** -->
  37. <div>
  38. <p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
  39. with LLVM</a>" tutorial. This chapter shows you how to transform the <a
  40. href="OCamlLangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into
  41. LLVM IR. This will teach you a little bit about how LLVM does things, as well
  42. as demonstrate how easy it is to use. It's much more work to build a lexer and
  43. parser than it is to generate LLVM IR code. :)
  44. </p>
  45. <p><b>Please note</b>: the code in this chapter and later require LLVM 2.3 or
  46. LLVM SVN to work. LLVM 2.2 and before will not work with it.</p>
  47. </div>
  48. <!-- *********************************************************************** -->
  49. <h2><a name="basics">Code Generation Setup</a></h2>
  50. <!-- *********************************************************************** -->
  51. <div>
  52. <p>
  53. In order to generate LLVM IR, we want some simple setup to get started. First
  54. we define virtual code generation (codegen) methods in each AST class:</p>
  55. <div class="doc_code">
  56. <pre>
  57. let rec codegen_expr = function
  58. | Ast.Number n -&gt; ...
  59. | Ast.Variable name -&gt; ...
  60. </pre>
  61. </div>
  62. <p>The <tt>Codegen.codegen_expr</tt> function says to emit IR for that AST node
  63. along with all the things it depends on, and they all return an LLVM Value
  64. object. "Value" is the class used to represent a "<a
  65. href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
  66. Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
  67. of SSA values is that their value is computed as the related instruction
  68. executes, and it does not get a new value until (and if) the instruction
  69. re-executes. In other words, there is no way to "change" an SSA value. For
  70. more information, please read up on <a
  71. href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
  72. Assignment</a> - the concepts are really quite natural once you grok them.</p>
  73. <p>The
  74. second thing we want is an "Error" exception like we used for the parser, which
  75. will be used to report errors found during code generation (for example, use of
  76. an undeclared parameter):</p>
  77. <div class="doc_code">
  78. <pre>
  79. exception Error of string
  80. let context = global_context ()
  81. let the_module = create_module context "my cool jit"
  82. let builder = builder context
  83. let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
  84. let double_type = double_type context
  85. </pre>
  86. </div>
  87. <p>The static variables will be used during code generation.
  88. <tt>Codgen.the_module</tt> is the LLVM construct that contains all of the
  89. functions and global variables in a chunk of code. In many ways, it is the
  90. top-level structure that the LLVM IR uses to contain code.</p>
  91. <p>The <tt>Codegen.builder</tt> object is a helper object that makes it easy to
  92. generate LLVM instructions. Instances of the <a
  93. href="http://llvm.org/doxygen/IRBuilder_8h-source.html"><tt>IRBuilder</tt></a>
  94. class keep track of the current place to insert instructions and has methods to
  95. create new instructions.</p>
  96. <p>The <tt>Codegen.named_values</tt> map keeps track of which values are defined
  97. in the current scope and what their LLVM representation is. (In other words, it
  98. is a symbol table for the code). In this form of Kaleidoscope, the only things
  99. that can be referenced are function parameters. As such, function parameters
  100. will be in this map when generating code for their function body.</p>
  101. <p>
  102. With these basics in place, we can start talking about how to generate code for
  103. each expression. Note that this assumes that the <tt>Codgen.builder</tt> has
  104. been set up to generate code <em>into</em> something. For now, we'll assume
  105. that this has already been done, and we'll just use it to emit code.</p>
  106. </div>
  107. <!-- *********************************************************************** -->
  108. <h2><a name="exprs">Expression Code Generation</a></h2>
  109. <!-- *********************************************************************** -->
  110. <div>
  111. <p>Generating LLVM code for expression nodes is very straightforward: less
  112. than 30 lines of commented code for all four of our expression nodes. First
  113. we'll do numeric literals:</p>
  114. <div class="doc_code">
  115. <pre>
  116. | Ast.Number n -&gt; const_float double_type n
  117. </pre>
  118. </div>
  119. <p>In the LLVM IR, numeric constants are represented with the
  120. <tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
  121. internally (<tt>APFloat</tt> has the capability of holding floating point
  122. constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
  123. creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
  124. that constants are all uniqued together and shared. For this reason, the API
  125. uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::Create(..)".</p>
  126. <div class="doc_code">
  127. <pre>
  128. | Ast.Variable name -&gt;
  129. (try Hashtbl.find named_values name with
  130. | Not_found -&gt; raise (Error "unknown variable name"))
  131. </pre>
  132. </div>
  133. <p>References to variables are also quite simple using LLVM. In the simple
  134. version of Kaleidoscope, we assume that the variable has already been emitted
  135. somewhere and its value is available. In practice, the only values that can be
  136. in the <tt>Codegen.named_values</tt> map are function arguments. This code
  137. simply checks to see that the specified name is in the map (if not, an unknown
  138. variable is being referenced) and returns the value for it. In future chapters,
  139. we'll add support for <a href="LangImpl5.html#for">loop induction variables</a>
  140. in the symbol table, and for <a href="LangImpl7.html#localvars">local
  141. variables</a>.</p>
  142. <div class="doc_code">
  143. <pre>
  144. | Ast.Binary (op, lhs, rhs) -&gt;
  145. let lhs_val = codegen_expr lhs in
  146. let rhs_val = codegen_expr rhs in
  147. begin
  148. match op with
  149. | '+' -&gt; build_fadd lhs_val rhs_val "addtmp" builder
  150. | '-' -&gt; build_fsub lhs_val rhs_val "subtmp" builder
  151. | '*' -&gt; build_fmul lhs_val rhs_val "multmp" builder
  152. | '&lt;' -&gt;
  153. (* Convert bool 0/1 to double 0.0 or 1.0 *)
  154. let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
  155. build_uitofp i double_type "booltmp" builder
  156. | _ -&gt; raise (Error "invalid binary operator")
  157. end
  158. </pre>
  159. </div>
  160. <p>Binary operators start to get more interesting. The basic idea here is that
  161. we recursively emit code for the left-hand side of the expression, then the
  162. right-hand side, then we compute the result of the binary expression. In this
  163. code, we do a simple switch on the opcode to create the right LLVM instruction.
  164. </p>
  165. <p>In the example above, the LLVM builder class is starting to show its value.
  166. IRBuilder knows where to insert the newly created instruction, all you have to
  167. do is specify what instruction to create (e.g. with <tt>Llvm.create_add</tt>),
  168. which operands to use (<tt>lhs</tt> and <tt>rhs</tt> here) and optionally
  169. provide a name for the generated instruction.</p>
  170. <p>One nice thing about LLVM is that the name is just a hint. For instance, if
  171. the code above emits multiple "addtmp" variables, LLVM will automatically
  172. provide each one with an increasing, unique numeric suffix. Local value names
  173. for instructions are purely optional, but it makes it much easier to read the
  174. IR dumps.</p>
  175. <p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
  176. strict rules: for example, the Left and Right operators of
  177. an <a href="../LangRef.html#i_add">add instruction</a> must have the same
  178. type, and the result type of the add must match the operand types. Because
  179. all values in Kaleidoscope are doubles, this makes for very simple code for add,
  180. sub and mul.</p>
  181. <p>On the other hand, LLVM specifies that the <a
  182. href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
  183. (a one bit integer). The problem with this is that Kaleidoscope wants the value to be a 0.0 or 1.0 value. In order to get these semantics, we combine the fcmp instruction with
  184. a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
  185. converts its input integer into a floating point value by treating the input
  186. as an unsigned value. In contrast, if we used the <a
  187. href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '&lt;'
  188. operator would return 0.0 and -1.0, depending on the input value.</p>
  189. <div class="doc_code">
  190. <pre>
  191. | Ast.Call (callee, args) -&gt;
  192. (* Look up the name in the module table. *)
  193. let callee =
  194. match lookup_function callee the_module with
  195. | Some callee -&gt; callee
  196. | None -&gt; raise (Error "unknown function referenced")
  197. in
  198. let params = params callee in
  199. (* If argument mismatch error. *)
  200. if Array.length params == Array.length args then () else
  201. raise (Error "incorrect # arguments passed");
  202. let args = Array.map codegen_expr args in
  203. build_call callee args "calltmp" builder
  204. </pre>
  205. </div>
  206. <p>Code generation for function calls is quite straightforward with LLVM. The
  207. code above initially does a function name lookup in the LLVM Module's symbol
  208. table. Recall that the LLVM Module is the container that holds all of the
  209. functions we are JIT'ing. By giving each function the same name as what the
  210. user specifies, we can use the LLVM symbol table to resolve function names for
  211. us.</p>
  212. <p>Once we have the function to call, we recursively codegen each argument that
  213. is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
  214. instruction</a>. Note that LLVM uses the native C calling conventions by
  215. default, allowing these calls to also call into standard library functions like
  216. "sin" and "cos", with no additional effort.</p>
  217. <p>This wraps up our handling of the four basic expressions that we have so far
  218. in Kaleidoscope. Feel free to go in and add some more. For example, by
  219. browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
  220. several other interesting instructions that are really easy to plug into our
  221. basic framework.</p>
  222. </div>
  223. <!-- *********************************************************************** -->
  224. <h2><a name="funcs">Function Code Generation</a></h2>
  225. <!-- *********************************************************************** -->
  226. <div>
  227. <p>Code generation for prototypes and functions must handle a number of
  228. details, which make their code less beautiful than expression code
  229. generation, but allows us to illustrate some important points. First, lets
  230. talk about code generation for prototypes: they are used both for function
  231. bodies and external function declarations. The code starts with:</p>
  232. <div class="doc_code">
  233. <pre>
  234. let codegen_proto = function
  235. | Ast.Prototype (name, args) -&gt;
  236. (* Make the function type: double(double,double) etc. *)
  237. let doubles = Array.make (Array.length args) double_type in
  238. let ft = function_type double_type doubles in
  239. let f =
  240. match lookup_function name the_module with
  241. </pre>
  242. </div>
  243. <p>This code packs a lot of power into a few lines. Note first that this
  244. function returns a "Function*" instead of a "Value*" (although at the moment
  245. they both are modeled by <tt>llvalue</tt> in ocaml). Because a "prototype"
  246. really talks about the external interface for a function (not the value computed
  247. by an expression), it makes sense for it to return the LLVM Function it
  248. corresponds to when codegen'd.</p>
  249. <p>The call to <tt>Llvm.function_type</tt> creates the <tt>Llvm.llvalue</tt>
  250. that should be used for a given Prototype. Since all function arguments in
  251. Kaleidoscope are of type double, the first line creates a vector of "N" LLVM
  252. double types. It then uses the <tt>Llvm.function_type</tt> method to create a
  253. function type that takes "N" doubles as arguments, returns one double as a
  254. result, and that is not vararg (that uses the function
  255. <tt>Llvm.var_arg_function_type</tt>). Note that Types in LLVM are uniqued just
  256. like <tt>Constant</tt>s are, so you don't "new" a type, you "get" it.</p>
  257. <p>The final line above checks if the function has already been defined in
  258. <tt>Codegen.the_module</tt>. If not, we will create it.</p>
  259. <div class="doc_code">
  260. <pre>
  261. | None -&gt; declare_function name ft the_module
  262. </pre>
  263. </div>
  264. <p>This indicates the type and name to use, as well as which module to insert
  265. into. By default we assume a function has
  266. <tt>Llvm.Linkage.ExternalLinkage</tt>. "<a href="LangRef.html#linkage">external
  267. linkage</a>" means that the function may be defined outside the current module
  268. and/or that it is callable by functions outside the module. The "<tt>name</tt>"
  269. passed in is the name the user specified: this name is registered in
  270. "<tt>Codegen.the_module</tt>"s symbol table, which is used by the function call
  271. code above.</p>
  272. <p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
  273. first, we want to allow 'extern'ing a function more than once, as long as the
  274. prototypes for the externs match (since all arguments have the same type, we
  275. just have to check that the number of arguments match). Second, we want to
  276. allow 'extern'ing a function and then defining a body for it. This is useful
  277. when defining mutually recursive functions.</p>
  278. <div class="doc_code">
  279. <pre>
  280. (* If 'f' conflicted, there was already something named 'name'. If it
  281. * has a body, don't allow redefinition or reextern. *)
  282. | Some f -&gt;
  283. (* If 'f' already has a body, reject this. *)
  284. if Array.length (basic_blocks f) == 0 then () else
  285. raise (Error "redefinition of function");
  286. (* If 'f' took a different number of arguments, reject. *)
  287. if Array.length (params f) == Array.length args then () else
  288. raise (Error "redefinition of function with different # args");
  289. f
  290. in
  291. </pre>
  292. </div>
  293. <p>In order to verify the logic above, we first check to see if the pre-existing
  294. function is "empty". In this case, empty means that it has no basic blocks in
  295. it, which means it has no body. If it has no body, it is a forward
  296. declaration. Since we don't allow anything after a full definition of the
  297. function, the code rejects this case. If the previous reference to a function
  298. was an 'extern', we simply verify that the number of arguments for that
  299. definition and this one match up. If not, we emit an error.</p>
  300. <div class="doc_code">
  301. <pre>
  302. (* Set names for all arguments. *)
  303. Array.iteri (fun i a -&gt;
  304. let n = args.(i) in
  305. set_value_name n a;
  306. Hashtbl.add named_values n a;
  307. ) (params f);
  308. f
  309. </pre>
  310. </div>
  311. <p>The last bit of code for prototypes loops over all of the arguments in the
  312. function, setting the name of the LLVM Argument objects to match, and registering
  313. the arguments in the <tt>Codegen.named_values</tt> map for future use by the
  314. <tt>Ast.Variable</tt> variant. Once this is set up, it returns the Function
  315. object to the caller. Note that we don't check for conflicting
  316. argument names here (e.g. "extern foo(a b a)"). Doing so would be very
  317. straight-forward with the mechanics we have already used above.</p>
  318. <div class="doc_code">
  319. <pre>
  320. let codegen_func = function
  321. | Ast.Function (proto, body) -&gt;
  322. Hashtbl.clear named_values;
  323. let the_function = codegen_proto proto in
  324. </pre>
  325. </div>
  326. <p>Code generation for function definitions starts out simply enough: we just
  327. codegen the prototype (Proto) and verify that it is ok. We then clear out the
  328. <tt>Codegen.named_values</tt> map to make sure that there isn't anything in it
  329. from the last function we compiled. Code generation of the prototype ensures
  330. that there is an LLVM Function object that is ready to go for us.</p>
  331. <div class="doc_code">
  332. <pre>
  333. (* Create a new basic block to start insertion into. *)
  334. let bb = append_block context "entry" the_function in
  335. position_at_end bb builder;
  336. try
  337. let ret_val = codegen_expr body in
  338. </pre>
  339. </div>
  340. <p>Now we get to the point where the <tt>Codegen.builder</tt> is set up. The
  341. first line creates a new
  342. <a href="http://en.wikipedia.org/wiki/Basic_block">basic block</a> (named
  343. "entry"), which is inserted into <tt>the_function</tt>. The second line then
  344. tells the builder that new instructions should be inserted into the end of the
  345. new basic block. Basic blocks in LLVM are an important part of functions that
  346. define the <a
  347. href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
  348. Since we don't have any control flow, our functions will only contain one
  349. block at this point. We'll fix this in <a href="OCamlLangImpl5.html">Chapter
  350. 5</a> :).</p>
  351. <div class="doc_code">
  352. <pre>
  353. let ret_val = codegen_expr body in
  354. (* Finish off the function. *)
  355. let _ = build_ret ret_val builder in
  356. (* Validate the generated code, checking for consistency. *)
  357. Llvm_analysis.assert_valid_function the_function;
  358. the_function
  359. </pre>
  360. </div>
  361. <p>Once the insertion point is set up, we call the <tt>Codegen.codegen_func</tt>
  362. method for the root expression of the function. If no error happens, this emits
  363. code to compute the expression into the entry block and returns the value that
  364. was computed. Assuming no error, we then create an LLVM <a
  365. href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
  366. Once the function is built, we call
  367. <tt>Llvm_analysis.assert_valid_function</tt>, which is provided by LLVM. This
  368. function does a variety of consistency checks on the generated code, to
  369. determine if our compiler is doing everything right. Using this is important:
  370. it can catch a lot of bugs. Once the function is finished and validated, we
  371. return it.</p>
  372. <div class="doc_code">
  373. <pre>
  374. with e -&gt;
  375. delete_function the_function;
  376. raise e
  377. </pre>
  378. </div>
  379. <p>The only piece left here is handling of the error case. For simplicity, we
  380. handle this by merely deleting the function we produced with the
  381. <tt>Llvm.delete_function</tt> method. This allows the user to redefine a
  382. function that they incorrectly typed in before: if we didn't delete it, it
  383. would live in the symbol table, with a body, preventing future redefinition.</p>
  384. <p>This code does have a bug, though. Since the <tt>Codegen.codegen_proto</tt>
  385. can return a previously defined forward declaration, our code can actually delete
  386. a forward declaration. There are a number of ways to fix this bug, see what you
  387. can come up with! Here is a testcase:</p>
  388. <div class="doc_code">
  389. <pre>
  390. extern foo(a b); # ok, defines foo.
  391. def foo(a b) c; # error, 'c' is invalid.
  392. def bar() foo(1, 2); # error, unknown function "foo"
  393. </pre>
  394. </div>
  395. </div>
  396. <!-- *********************************************************************** -->
  397. <h2><a name="driver">Driver Changes and Closing Thoughts</a></h2>
  398. <!-- *********************************************************************** -->
  399. <div>
  400. <p>
  401. For now, code generation to LLVM doesn't really get us much, except that we can
  402. look at the pretty IR calls. The sample code inserts calls to Codegen into the
  403. "<tt>Toplevel.main_loop</tt>", and then dumps out the LLVM IR. This gives a
  404. nice way to look at the LLVM IR for simple functions. For example:
  405. </p>
  406. <div class="doc_code">
  407. <pre>
  408. ready&gt; <b>4+5</b>;
  409. Read top-level expression:
  410. define double @""() {
  411. entry:
  412. %addtmp = fadd double 4.000000e+00, 5.000000e+00
  413. ret double %addtmp
  414. }
  415. </pre>
  416. </div>
  417. <p>Note how the parser turns the top-level expression into anonymous functions
  418. for us. This will be handy when we add <a href="OCamlLangImpl4.html#jit">JIT
  419. support</a> in the next chapter. Also note that the code is very literally
  420. transcribed, no optimizations are being performed. We will
  421. <a href="OCamlLangImpl4.html#trivialconstfold">add optimizations</a> explicitly
  422. in the next chapter.</p>
  423. <div class="doc_code">
  424. <pre>
  425. ready&gt; <b>def foo(a b) a*a + 2*a*b + b*b;</b>
  426. Read function definition:
  427. define double @foo(double %a, double %b) {
  428. entry:
  429. %multmp = fmul double %a, %a
  430. %multmp1 = fmul double 2.000000e+00, %a
  431. %multmp2 = fmul double %multmp1, %b
  432. %addtmp = fadd double %multmp, %multmp2
  433. %multmp3 = fmul double %b, %b
  434. %addtmp4 = fadd double %addtmp, %multmp3
  435. ret double %addtmp4
  436. }
  437. </pre>
  438. </div>
  439. <p>This shows some simple arithmetic. Notice the striking similarity to the
  440. LLVM builder calls that we use to create the instructions.</p>
  441. <div class="doc_code">
  442. <pre>
  443. ready&gt; <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
  444. Read function definition:
  445. define double @bar(double %a) {
  446. entry:
  447. %calltmp = call double @foo(double %a, double 4.000000e+00)
  448. %calltmp1 = call double @bar(double 3.133700e+04)
  449. %addtmp = fadd double %calltmp, %calltmp1
  450. ret double %addtmp
  451. }
  452. </pre>
  453. </div>
  454. <p>This shows some function calls. Note that this function will take a long
  455. time to execute if you call it. In the future we'll add conditional control
  456. flow to actually make recursion useful :).</p>
  457. <div class="doc_code">
  458. <pre>
  459. ready&gt; <b>extern cos(x);</b>
  460. Read extern:
  461. declare double @cos(double)
  462. ready&gt; <b>cos(1.234);</b>
  463. Read top-level expression:
  464. define double @""() {
  465. entry:
  466. %calltmp = call double @cos(double 1.234000e+00)
  467. ret double %calltmp
  468. }
  469. </pre>
  470. </div>
  471. <p>This shows an extern for the libm "cos" function, and a call to it.</p>
  472. <div class="doc_code">
  473. <pre>
  474. ready&gt; <b>^D</b>
  475. ; ModuleID = 'my cool jit'
  476. define double @""() {
  477. entry:
  478. %addtmp = fadd double 4.000000e+00, 5.000000e+00
  479. ret double %addtmp
  480. }
  481. define double @foo(double %a, double %b) {
  482. entry:
  483. %multmp = fmul double %a, %a
  484. %multmp1 = fmul double 2.000000e+00, %a
  485. %multmp2 = fmul double %multmp1, %b
  486. %addtmp = fadd double %multmp, %multmp2
  487. %multmp3 = fmul double %b, %b
  488. %addtmp4 = fadd double %addtmp, %multmp3
  489. ret double %addtmp4
  490. }
  491. define double @bar(double %a) {
  492. entry:
  493. %calltmp = call double @foo(double %a, double 4.000000e+00)
  494. %calltmp1 = call double @bar(double 3.133700e+04)
  495. %addtmp = fadd double %calltmp, %calltmp1
  496. ret double %addtmp
  497. }
  498. declare double @cos(double)
  499. define double @""() {
  500. entry:
  501. %calltmp = call double @cos(double 1.234000e+00)
  502. ret double %calltmp
  503. }
  504. </pre>
  505. </div>
  506. <p>When you quit the current demo, it dumps out the IR for the entire module
  507. generated. Here you can see the big picture with all the functions referencing
  508. each other.</p>
  509. <p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next, we'll
  510. describe how to <a href="OCamlLangImpl4.html">add JIT codegen and optimizer
  511. support</a> to this so we can actually start running code!</p>
  512. </div>
  513. <!-- *********************************************************************** -->
  514. <h2><a name="code">Full Code Listing</a></h2>
  515. <!-- *********************************************************************** -->
  516. <div>
  517. <p>
  518. Here is the complete code listing for our running example, enhanced with the
  519. LLVM code generator. Because this uses the LLVM libraries, we need to link
  520. them in. To do this, we use the <a
  521. href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
  522. our makefile/command line about which options to use:</p>
  523. <div class="doc_code">
  524. <pre>
  525. # Compile
  526. ocamlbuild toy.byte
  527. # Run
  528. ./toy.byte
  529. </pre>
  530. </div>
  531. <p>Here is the code:</p>
  532. <dl>
  533. <dt>_tags:</dt>
  534. <dd class="doc_code">
  535. <pre>
  536. &lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
  537. &lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
  538. </pre>
  539. </dd>
  540. <dt>myocamlbuild.ml:</dt>
  541. <dd class="doc_code">
  542. <pre>
  543. open Ocamlbuild_plugin;;
  544. ocaml_lib ~extern:true "llvm";;
  545. ocaml_lib ~extern:true "llvm_analysis";;
  546. flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
  547. </pre>
  548. </dd>
  549. <dt>token.ml:</dt>
  550. <dd class="doc_code">
  551. <pre>
  552. (*===----------------------------------------------------------------------===
  553. * Lexer Tokens
  554. *===----------------------------------------------------------------------===*)
  555. (* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
  556. * these others for known things. *)
  557. type token =
  558. (* commands *)
  559. | Def | Extern
  560. (* primary *)
  561. | Ident of string | Number of float
  562. (* unknown *)
  563. | Kwd of char
  564. </pre>
  565. </dd>
  566. <dt>lexer.ml:</dt>
  567. <dd class="doc_code">
  568. <pre>
  569. (*===----------------------------------------------------------------------===
  570. * Lexer
  571. *===----------------------------------------------------------------------===*)
  572. let rec lex = parser
  573. (* Skip any whitespace. *)
  574. | [&lt; ' (' ' | '\n' | '\r' | '\t'); stream &gt;] -&gt; lex stream
  575. (* identifier: [a-zA-Z][a-zA-Z0-9] *)
  576. | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' as c); stream &gt;] -&gt;
  577. let buffer = Buffer.create 1 in
  578. Buffer.add_char buffer c;
  579. lex_ident buffer stream
  580. (* number: [0-9.]+ *)
  581. | [&lt; ' ('0' .. '9' as c); stream &gt;] -&gt;
  582. let buffer = Buffer.create 1 in
  583. Buffer.add_char buffer c;
  584. lex_number buffer stream
  585. (* Comment until end of line. *)
  586. | [&lt; ' ('#'); stream &gt;] -&gt;
  587. lex_comment stream
  588. (* Otherwise, just return the character as its ascii value. *)
  589. | [&lt; 'c; stream &gt;] -&gt;
  590. [&lt; 'Token.Kwd c; lex stream &gt;]
  591. (* end of stream. *)
  592. | [&lt; &gt;] -&gt; [&lt; &gt;]
  593. and lex_number buffer = parser
  594. | [&lt; ' ('0' .. '9' | '.' as c); stream &gt;] -&gt;
  595. Buffer.add_char buffer c;
  596. lex_number buffer stream
  597. | [&lt; stream=lex &gt;] -&gt;
  598. [&lt; 'Token.Number (float_of_string (Buffer.contents buffer)); stream &gt;]
  599. and lex_ident buffer = parser
  600. | [&lt; ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream &gt;] -&gt;
  601. Buffer.add_char buffer c;
  602. lex_ident buffer stream
  603. | [&lt; stream=lex &gt;] -&gt;
  604. match Buffer.contents buffer with
  605. | "def" -&gt; [&lt; 'Token.Def; stream &gt;]
  606. | "extern" -&gt; [&lt; 'Token.Extern; stream &gt;]
  607. | id -&gt; [&lt; 'Token.Ident id; stream &gt;]
  608. and lex_comment = parser
  609. | [&lt; ' ('\n'); stream=lex &gt;] -&gt; stream
  610. | [&lt; 'c; e=lex_comment &gt;] -&gt; e
  611. | [&lt; &gt;] -&gt; [&lt; &gt;]
  612. </pre>
  613. </dd>
  614. <dt>ast.ml:</dt>
  615. <dd class="doc_code">
  616. <pre>
  617. (*===----------------------------------------------------------------------===
  618. * Abstract Syntax Tree (aka Parse Tree)
  619. *===----------------------------------------------------------------------===*)
  620. (* expr - Base type for all expression nodes. *)
  621. type expr =
  622. (* variant for numeric literals like "1.0". *)
  623. | Number of float
  624. (* variant for referencing a variable, like "a". *)
  625. | Variable of string
  626. (* variant for a binary operator. *)
  627. | Binary of char * expr * expr
  628. (* variant for function calls. *)
  629. | Call of string * expr array
  630. (* proto - This type represents the "prototype" for a function, which captures
  631. * its name, and its argument names (thus implicitly the number of arguments the
  632. * function takes). *)
  633. type proto = Prototype of string * string array
  634. (* func - This type represents a function definition itself. *)
  635. type func = Function of proto * expr
  636. </pre>
  637. </dd>
  638. <dt>parser.ml:</dt>
  639. <dd class="doc_code">
  640. <pre>
  641. (*===---------------------------------------------------------------------===
  642. * Parser
  643. *===---------------------------------------------------------------------===*)
  644. (* binop_precedence - This holds the precedence for each binary operator that is
  645. * defined *)
  646. let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
  647. (* precedence - Get the precedence of the pending binary operator token. *)
  648. let precedence c = try Hashtbl.find binop_precedence c with Not_found -&gt; -1
  649. (* primary
  650. * ::= identifier
  651. * ::= numberexpr
  652. * ::= parenexpr *)
  653. let rec parse_primary = parser
  654. (* numberexpr ::= number *)
  655. | [&lt; 'Token.Number n &gt;] -&gt; Ast.Number n
  656. (* parenexpr ::= '(' expression ')' *)
  657. | [&lt; 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" &gt;] -&gt; e
  658. (* identifierexpr
  659. * ::= identifier
  660. * ::= identifier '(' argumentexpr ')' *)
  661. | [&lt; 'Token.Ident id; stream &gt;] -&gt;
  662. let rec parse_args accumulator = parser
  663. | [&lt; e=parse_expr; stream &gt;] -&gt;
  664. begin parser
  665. | [&lt; 'Token.Kwd ','; e=parse_args (e :: accumulator) &gt;] -&gt; e
  666. | [&lt; &gt;] -&gt; e :: accumulator
  667. end stream
  668. | [&lt; &gt;] -&gt; accumulator
  669. in
  670. let rec parse_ident id = parser
  671. (* Call. *)
  672. | [&lt; 'Token.Kwd '(';
  673. args=parse_args [];
  674. 'Token.Kwd ')' ?? "expected ')'"&gt;] -&gt;
  675. Ast.Call (id, Array.of_list (List.rev args))
  676. (* Simple variable ref. *)
  677. | [&lt; &gt;] -&gt; Ast.Variable id
  678. in
  679. parse_ident id stream
  680. | [&lt; &gt;] -&gt; raise (Stream.Error "unknown token when expecting an expression.")
  681. (* binoprhs
  682. * ::= ('+' primary)* *)
  683. and parse_bin_rhs expr_prec lhs stream =
  684. match Stream.peek stream with
  685. (* If this is a binop, find its precedence. *)
  686. | Some (Token.Kwd c) when Hashtbl.mem binop_precedence c -&gt;
  687. let token_prec = precedence c in
  688. (* If this is a binop that binds at least as tightly as the current binop,
  689. * consume it, otherwise we are done. *)
  690. if token_prec &lt; expr_prec then lhs else begin
  691. (* Eat the binop. *)
  692. Stream.junk stream;
  693. (* Parse the primary expression after the binary operator. *)
  694. let rhs = parse_primary stream in
  695. (* Okay, we know this is a binop. *)
  696. let rhs =
  697. match Stream.peek stream with
  698. | Some (Token.Kwd c2) -&gt;
  699. (* If BinOp binds less tightly with rhs than the operator after
  700. * rhs, let the pending operator take rhs as its lhs. *)
  701. let next_prec = precedence c2 in
  702. if token_prec &lt; next_prec
  703. then parse_bin_rhs (token_prec + 1) rhs stream
  704. else rhs
  705. | _ -&gt; rhs
  706. in
  707. (* Merge lhs/rhs. *)
  708. let lhs = Ast.Binary (c, lhs, rhs) in
  709. parse_bin_rhs expr_prec lhs stream
  710. end
  711. | _ -&gt; lhs
  712. (* expression
  713. * ::= primary binoprhs *)
  714. and parse_expr = parser
  715. | [&lt; lhs=parse_primary; stream &gt;] -&gt; parse_bin_rhs 0 lhs stream
  716. (* prototype
  717. * ::= id '(' id* ')' *)
  718. let parse_prototype =
  719. let rec parse_args accumulator = parser
  720. | [&lt; 'Token.Ident id; e=parse_args (id::accumulator) &gt;] -&gt; e
  721. | [&lt; &gt;] -&gt; accumulator
  722. in
  723. parser
  724. | [&lt; 'Token.Ident id;
  725. 'Token.Kwd '(' ?? "expected '(' in prototype";
  726. args=parse_args [];
  727. 'Token.Kwd ')' ?? "expected ')' in prototype" &gt;] -&gt;
  728. (* success. *)
  729. Ast.Prototype (id, Array.of_list (List.rev args))
  730. | [&lt; &gt;] -&gt;
  731. raise (Stream.Error "expected function name in prototype")
  732. (* definition ::= 'def' prototype expression *)
  733. let parse_definition = parser
  734. | [&lt; 'Token.Def; p=parse_prototype; e=parse_expr &gt;] -&gt;
  735. Ast.Function (p, e)
  736. (* toplevelexpr ::= expression *)
  737. let parse_toplevel = parser
  738. | [&lt; e=parse_expr &gt;] -&gt;
  739. (* Make an anonymous proto. *)
  740. Ast.Function (Ast.Prototype ("", [||]), e)
  741. (* external ::= 'extern' prototype *)
  742. let parse_extern = parser
  743. | [&lt; 'Token.Extern; e=parse_prototype &gt;] -&gt; e
  744. </pre>
  745. </dd>
  746. <dt>codegen.ml:</dt>
  747. <dd class="doc_code">
  748. <pre>
  749. (*===----------------------------------------------------------------------===
  750. * Code Generation
  751. *===----------------------------------------------------------------------===*)
  752. open Llvm
  753. exception Error of string
  754. let context = global_context ()
  755. let the_module = create_module context "my cool jit"
  756. let builder = builder context
  757. let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
  758. let double_type = double_type context
  759. let rec codegen_expr = function
  760. | Ast.Number n -&gt; const_float double_type n
  761. | Ast.Variable name -&gt;
  762. (try Hashtbl.find named_values name with
  763. | Not_found -&gt; raise (Error "unknown variable name"))
  764. | Ast.Binary (op, lhs, rhs) -&gt;
  765. let lhs_val = codegen_expr lhs in
  766. let rhs_val = codegen_expr rhs in
  767. begin
  768. match op with
  769. | '+' -&gt; build_add lhs_val rhs_val "addtmp" builder
  770. | '-' -&gt; build_sub lhs_val rhs_val "subtmp" builder
  771. | '*' -&gt; build_mul lhs_val rhs_val "multmp" builder
  772. | '&lt;' -&gt;
  773. (* Convert bool 0/1 to double 0.0 or 1.0 *)
  774. let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
  775. build_uitofp i double_type "booltmp" builder
  776. | _ -&gt; raise (Error "invalid binary operator")
  777. end
  778. | Ast.Call (callee, args) -&gt;
  779. (* Look up the name in the module table. *)
  780. let callee =
  781. match lookup_function callee the_module with
  782. | Some callee -&gt; callee
  783. | None -&gt; raise (Error "unknown function referenced")
  784. in
  785. let params = params callee in
  786. (* If argument mismatch error. *)
  787. if Array.length params == Array.length args then () else
  788. raise (Error "incorrect # arguments passed");
  789. let args = Array.map codegen_expr args in
  790. build_call callee args "calltmp" builder
  791. let codegen_proto = function
  792. | Ast.Prototype (name, args) -&gt;
  793. (* Make the function type: double(double,double) etc. *)
  794. let doubles = Array.make (Array.length args) double_type in
  795. let ft = function_type double_type doubles in
  796. let f =
  797. match lookup_function name the_module with
  798. | None -&gt; declare_function name ft the_module
  799. (* If 'f' conflicted, there was already something named 'name'. If it
  800. * has a body, don't allow redefinition or reextern. *)
  801. | Some f -&gt;
  802. (* If 'f' already has a body, reject this. *)
  803. if block_begin f &lt;&gt; At_end f then
  804. raise (Error "redefinition of function");
  805. (* If 'f' took a different number of arguments, reject. *)
  806. if element_type (type_of f) &lt;&gt; ft then
  807. raise (Error "redefinition of function with different # args");
  808. f
  809. in
  810. (* Set names for all arguments. *)
  811. Array.iteri (fun i a -&gt;
  812. let n = args.(i) in
  813. set_value_name n a;
  814. Hashtbl.add named_values n a;
  815. ) (params f);
  816. f
  817. let codegen_func = function
  818. | Ast.Function (proto, body) -&gt;
  819. Hashtbl.clear named_values;
  820. let the_function = codegen_proto proto in
  821. (* Create a new basic block to start insertion into. *)
  822. let bb = append_block context "entry" the_function in
  823. position_at_end bb builder;
  824. try
  825. let ret_val = codegen_expr body in
  826. (* Finish off the function. *)
  827. let _ = build_ret ret_val builder in
  828. (* Validate the generated code, checking for consistency. *)
  829. Llvm_analysis.assert_valid_function the_function;
  830. the_function
  831. with e -&gt;
  832. delete_function the_function;
  833. raise e
  834. </pre>
  835. </dd>
  836. <dt>toplevel.ml:</dt>
  837. <dd class="doc_code">
  838. <pre>
  839. (*===----------------------------------------------------------------------===
  840. * Top-Level parsing and JIT Driver
  841. *===----------------------------------------------------------------------===*)
  842. open Llvm
  843. (* top ::= definition | external | expression | ';' *)
  844. let rec main_loop stream =
  845. match Stream.peek stream with
  846. | None -&gt; ()
  847. (* ignore top-level semicolons. *)
  848. | Some (Token.Kwd ';') -&gt;
  849. Stream.junk stream;
  850. main_loop stream
  851. | Some token -&gt;
  852. begin
  853. try match token with
  854. | Token.Def -&gt;
  855. let e = Parser.parse_definition stream in
  856. print_endline "parsed a function definition.";
  857. dump_value (Codegen.codegen_func e);
  858. | Token.Extern -&gt;
  859. let e = Parser.parse_extern stream in
  860. print_endline "parsed an extern.";
  861. dump_value (Codegen.codegen_proto e);
  862. | _ -&gt;
  863. (* Evaluate a top-level expression into an anonymous function. *)
  864. let e = Parser.parse_toplevel stream in
  865. print_endline "parsed a top-level expr";
  866. dump_value (Codegen.codegen_func e);
  867. with Stream.Error s | Codegen.Error s -&gt;
  868. (* Skip token for error recovery. *)
  869. Stream.junk stream;
  870. print_endline s;
  871. end;
  872. print_string "ready&gt; "; flush stdout;
  873. main_loop stream
  874. </pre>
  875. </dd>
  876. <dt>toy.ml:</dt>
  877. <dd class="doc_code">
  878. <pre>
  879. (*===----------------------------------------------------------------------===
  880. * Main driver code.
  881. *===----------------------------------------------------------------------===*)
  882. open Llvm
  883. let main () =
  884. (* Install standard binary operators.
  885. * 1 is the lowest precedence. *)
  886. Hashtbl.add Parser.binop_precedence '&lt;' 10;
  887. Hashtbl.add Parser.binop_precedence '+' 20;
  888. Hashtbl.add Parser.binop_precedence '-' 20;
  889. Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
  890. (* Prime the first token. *)
  891. print_string "ready&gt; "; flush stdout;
  892. let stream = Lexer.lex (Stream.of_channel stdin) in
  893. (* Run the main "interpreter loop" now. *)
  894. Toplevel.main_loop stream;
  895. (* Print out all the generated code. *)
  896. dump_module Codegen.the_module
  897. ;;
  898. main ()
  899. </pre>
  900. </dd>
  901. </dl>
  902. <a href="OCamlLangImpl4.html">Next: Adding JIT and Optimizer Support</a>
  903. </div>
  904. <!-- *********************************************************************** -->
  905. <hr>
  906. <address>
  907. <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
  908. src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
  909. <a href="http://validator.w3.org/check/referer"><img
  910. src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
  911. <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
  912. <a href="mailto:idadesub@users.sourceforge.net">Erick Tryzelaar</a><br>
  913. <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
  914. Last modified: $Date: 2012-05-03 06:46:36 +0800 (周四, 03 五月 2012) $
  915. </address>
  916. </body>
  917. </html>