LangImpl05.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. :orphan:
  2. ==================================================
  3. Kaleidoscope: Extending the Language: Control Flow
  4. ==================================================
  5. .. contents::
  6. :local:
  7. Chapter 5 Introduction
  8. ======================
  9. Welcome to Chapter 5 of the "`Implementing a language with
  10. LLVM <index.html>`_" tutorial. Parts 1-4 described the implementation of
  11. the simple Kaleidoscope language and included support for generating
  12. LLVM IR, followed by optimizations and a JIT compiler. Unfortunately, as
  13. presented, Kaleidoscope is mostly useless: it has no control flow other
  14. than call and return. This means that you can't have conditional
  15. branches in the code, significantly limiting its power. In this episode
  16. of "build that compiler", we'll extend Kaleidoscope to have an
  17. if/then/else expression plus a simple 'for' loop.
  18. If/Then/Else
  19. ============
  20. Extending Kaleidoscope to support if/then/else is quite straightforward.
  21. It basically requires adding support for this "new" concept to the
  22. lexer, parser, AST, and LLVM code emitter. This example is nice, because
  23. it shows how easy it is to "grow" a language over time, incrementally
  24. extending it as new ideas are discovered.
  25. Before we get going on "how" we add this extension, let's talk about
  26. "what" we want. The basic idea is that we want to be able to write this
  27. sort of thing:
  28. ::
  29. def fib(x)
  30. if x < 3 then
  31. 1
  32. else
  33. fib(x-1)+fib(x-2);
  34. In Kaleidoscope, every construct is an expression: there are no
  35. statements. As such, the if/then/else expression needs to return a value
  36. like any other. Since we're using a mostly functional form, we'll have
  37. it evaluate its conditional, then return the 'then' or 'else' value
  38. based on how the condition was resolved. This is very similar to the C
  39. "?:" expression.
  40. The semantics of the if/then/else expression is that it evaluates the
  41. condition to a boolean equality value: 0.0 is considered to be false and
  42. everything else is considered to be true. If the condition is true, the
  43. first subexpression is evaluated and returned, if the condition is
  44. false, the second subexpression is evaluated and returned. Since
  45. Kaleidoscope allows side-effects, this behavior is important to nail
  46. down.
  47. Now that we know what we "want", let's break this down into its
  48. constituent pieces.
  49. Lexer Extensions for If/Then/Else
  50. ---------------------------------
  51. The lexer extensions are straightforward. First we add new enum values
  52. for the relevant tokens:
  53. .. code-block:: c++
  54. // control
  55. tok_if = -6,
  56. tok_then = -7,
  57. tok_else = -8,
  58. Once we have that, we recognize the new keywords in the lexer. This is
  59. pretty simple stuff:
  60. .. code-block:: c++
  61. ...
  62. if (IdentifierStr == "def")
  63. return tok_def;
  64. if (IdentifierStr == "extern")
  65. return tok_extern;
  66. if (IdentifierStr == "if")
  67. return tok_if;
  68. if (IdentifierStr == "then")
  69. return tok_then;
  70. if (IdentifierStr == "else")
  71. return tok_else;
  72. return tok_identifier;
  73. AST Extensions for If/Then/Else
  74. -------------------------------
  75. To represent the new expression we add a new AST node for it:
  76. .. code-block:: c++
  77. /// IfExprAST - Expression class for if/then/else.
  78. class IfExprAST : public ExprAST {
  79. std::unique_ptr<ExprAST> Cond, Then, Else;
  80. public:
  81. IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
  82. std::unique_ptr<ExprAST> Else)
  83. : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
  84. Value *codegen() override;
  85. };
  86. The AST node just has pointers to the various subexpressions.
  87. Parser Extensions for If/Then/Else
  88. ----------------------------------
  89. Now that we have the relevant tokens coming from the lexer and we have
  90. the AST node to build, our parsing logic is relatively straightforward.
  91. First we define a new parsing function:
  92. .. code-block:: c++
  93. /// ifexpr ::= 'if' expression 'then' expression 'else' expression
  94. static std::unique_ptr<ExprAST> ParseIfExpr() {
  95. getNextToken(); // eat the if.
  96. // condition.
  97. auto Cond = ParseExpression();
  98. if (!Cond)
  99. return nullptr;
  100. if (CurTok != tok_then)
  101. return LogError("expected then");
  102. getNextToken(); // eat the then
  103. auto Then = ParseExpression();
  104. if (!Then)
  105. return nullptr;
  106. if (CurTok != tok_else)
  107. return LogError("expected else");
  108. getNextToken();
  109. auto Else = ParseExpression();
  110. if (!Else)
  111. return nullptr;
  112. return std::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
  113. std::move(Else));
  114. }
  115. Next we hook it up as a primary expression:
  116. .. code-block:: c++
  117. static std::unique_ptr<ExprAST> ParsePrimary() {
  118. switch (CurTok) {
  119. default:
  120. return LogError("unknown token when expecting an expression");
  121. case tok_identifier:
  122. return ParseIdentifierExpr();
  123. case tok_number:
  124. return ParseNumberExpr();
  125. case '(':
  126. return ParseParenExpr();
  127. case tok_if:
  128. return ParseIfExpr();
  129. }
  130. }
  131. LLVM IR for If/Then/Else
  132. ------------------------
  133. Now that we have it parsing and building the AST, the final piece is
  134. adding LLVM code generation support. This is the most interesting part
  135. of the if/then/else example, because this is where it starts to
  136. introduce new concepts. All of the code above has been thoroughly
  137. described in previous chapters.
  138. To motivate the code we want to produce, let's take a look at a simple
  139. example. Consider:
  140. ::
  141. extern foo();
  142. extern bar();
  143. def baz(x) if x then foo() else bar();
  144. If you disable optimizations, the code you'll (soon) get from
  145. Kaleidoscope looks like this:
  146. .. code-block:: llvm
  147. declare double @foo()
  148. declare double @bar()
  149. define double @baz(double %x) {
  150. entry:
  151. %ifcond = fcmp one double %x, 0.000000e+00
  152. br i1 %ifcond, label %then, label %else
  153. then: ; preds = %entry
  154. %calltmp = call double @foo()
  155. br label %ifcont
  156. else: ; preds = %entry
  157. %calltmp1 = call double @bar()
  158. br label %ifcont
  159. ifcont: ; preds = %else, %then
  160. %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
  161. ret double %iftmp
  162. }
  163. To visualize the control flow graph, you can use a nifty feature of the
  164. LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
  165. IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
  166. window will pop up <../ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ and you'll
  167. see this graph:
  168. .. figure:: LangImpl05-cfg.png
  169. :align: center
  170. :alt: Example CFG
  171. Example CFG
  172. Another way to get this is to call "``F->viewCFG()``" or
  173. "``F->viewCFGOnly()``" (where F is a "``Function*``") either by
  174. inserting actual calls into the code and recompiling or by calling these
  175. in the debugger. LLVM has many nice features for visualizing various
  176. graphs.
  177. Getting back to the generated code, it is fairly simple: the entry block
  178. evaluates the conditional expression ("x" in our case here) and compares
  179. the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
  180. and Not Equal"). Based on the result of this expression, the code jumps
  181. to either the "then" or "else" blocks, which contain the expressions for
  182. the true/false cases.
  183. Once the then/else blocks are finished executing, they both branch back
  184. to the 'ifcont' block to execute the code that happens after the
  185. if/then/else. In this case the only thing left to do is to return to the
  186. caller of the function. The question then becomes: how does the code
  187. know which expression to return?
  188. The answer to this question involves an important SSA operation: the
  189. `Phi
  190. operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
  191. If you're not familiar with SSA, `the wikipedia
  192. article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
  193. is a good introduction and there are various other introductions to it
  194. available on your favorite search engine. The short version is that
  195. "execution" of the Phi operation requires "remembering" which block
  196. control came from. The Phi operation takes on the value corresponding to
  197. the input control block. In this case, if control comes in from the
  198. "then" block, it gets the value of "calltmp". If control comes from the
  199. "else" block, it gets the value of "calltmp1".
  200. At this point, you are probably starting to think "Oh no! This means my
  201. simple and elegant front-end will have to start generating SSA form in
  202. order to use LLVM!". Fortunately, this is not the case, and we strongly
  203. advise *not* implementing an SSA construction algorithm in your
  204. front-end unless there is an amazingly good reason to do so. In
  205. practice, there are two sorts of values that float around in code
  206. written for your average imperative programming language that might need
  207. Phi nodes:
  208. #. Code that involves user variables: ``x = 1; x = x + 1;``
  209. #. Values that are implicit in the structure of your AST, such as the
  210. Phi node in this case.
  211. In `Chapter 7 <LangImpl07.html>`_ of this tutorial ("mutable variables"),
  212. we'll talk about #1 in depth. For now, just believe me that you don't
  213. need SSA construction to handle this case. For #2, you have the choice
  214. of using the techniques that we will describe for #1, or you can insert
  215. Phi nodes directly, if convenient. In this case, it is really
  216. easy to generate the Phi node, so we choose to do it directly.
  217. Okay, enough of the motivation and overview, let's generate code!
  218. Code Generation for If/Then/Else
  219. --------------------------------
  220. In order to generate code for this, we implement the ``codegen`` method
  221. for ``IfExprAST``:
  222. .. code-block:: c++
  223. Value *IfExprAST::codegen() {
  224. Value *CondV = Cond->codegen();
  225. if (!CondV)
  226. return nullptr;
  227. // Convert condition to a bool by comparing non-equal to 0.0.
  228. CondV = Builder.CreateFCmpONE(
  229. CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
  230. This code is straightforward and similar to what we saw before. We emit
  231. the expression for the condition, then compare that value to zero to get
  232. a truth value as a 1-bit (bool) value.
  233. .. code-block:: c++
  234. Function *TheFunction = Builder.GetInsertBlock()->getParent();
  235. // Create blocks for the then and else cases. Insert the 'then' block at the
  236. // end of the function.
  237. BasicBlock *ThenBB =
  238. BasicBlock::Create(TheContext, "then", TheFunction);
  239. BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
  240. BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
  241. Builder.CreateCondBr(CondV, ThenBB, ElseBB);
  242. This code creates the basic blocks that are related to the if/then/else
  243. statement, and correspond directly to the blocks in the example above.
  244. The first line gets the current Function object that is being built. It
  245. gets this by asking the builder for the current BasicBlock, and asking
  246. that block for its "parent" (the function it is currently embedded
  247. into).
  248. Once it has that, it creates three blocks. Note that it passes
  249. "TheFunction" into the constructor for the "then" block. This causes the
  250. constructor to automatically insert the new block into the end of the
  251. specified function. The other two blocks are created, but aren't yet
  252. inserted into the function.
  253. Once the blocks are created, we can emit the conditional branch that
  254. chooses between them. Note that creating new blocks does not implicitly
  255. affect the IRBuilder, so it is still inserting into the block that the
  256. condition went into. Also note that it is creating a branch to the
  257. "then" block and the "else" block, even though the "else" block isn't
  258. inserted into the function yet. This is all ok: it is the standard way
  259. that LLVM supports forward references.
  260. .. code-block:: c++
  261. // Emit then value.
  262. Builder.SetInsertPoint(ThenBB);
  263. Value *ThenV = Then->codegen();
  264. if (!ThenV)
  265. return nullptr;
  266. Builder.CreateBr(MergeBB);
  267. // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
  268. ThenBB = Builder.GetInsertBlock();
  269. After the conditional branch is inserted, we move the builder to start
  270. inserting into the "then" block. Strictly speaking, this call moves the
  271. insertion point to be at the end of the specified block. However, since
  272. the "then" block is empty, it also starts out by inserting at the
  273. beginning of the block. :)
  274. Once the insertion point is set, we recursively codegen the "then"
  275. expression from the AST. To finish off the "then" block, we create an
  276. unconditional branch to the merge block. One interesting (and very
  277. important) aspect of the LLVM IR is that it `requires all basic blocks
  278. to be "terminated" <../LangRef.html#functionstructure>`_ with a `control
  279. flow instruction <../LangRef.html#terminators>`_ such as return or
  280. branch. This means that all control flow, *including fall throughs* must
  281. be made explicit in the LLVM IR. If you violate this rule, the verifier
  282. will emit an error.
  283. The final line here is quite subtle, but is very important. The basic
  284. issue is that when we create the Phi node in the merge block, we need to
  285. set up the block/value pairs that indicate how the Phi will work.
  286. Importantly, the Phi node expects to have an entry for each predecessor
  287. of the block in the CFG. Why then, are we getting the current block when
  288. we just set it to ThenBB 5 lines above? The problem is that the "Then"
  289. expression may actually itself change the block that the Builder is
  290. emitting into if, for example, it contains a nested "if/then/else"
  291. expression. Because calling ``codegen()`` recursively could arbitrarily change
  292. the notion of the current block, we are required to get an up-to-date
  293. value for code that will set up the Phi node.
  294. .. code-block:: c++
  295. // Emit else block.
  296. TheFunction->getBasicBlockList().push_back(ElseBB);
  297. Builder.SetInsertPoint(ElseBB);
  298. Value *ElseV = Else->codegen();
  299. if (!ElseV)
  300. return nullptr;
  301. Builder.CreateBr(MergeBB);
  302. // codegen of 'Else' can change the current block, update ElseBB for the PHI.
  303. ElseBB = Builder.GetInsertBlock();
  304. Code generation for the 'else' block is basically identical to codegen
  305. for the 'then' block. The only significant difference is the first line,
  306. which adds the 'else' block to the function. Recall previously that the
  307. 'else' block was created, but not added to the function. Now that the
  308. 'then' and 'else' blocks are emitted, we can finish up with the merge
  309. code:
  310. .. code-block:: c++
  311. // Emit merge block.
  312. TheFunction->getBasicBlockList().push_back(MergeBB);
  313. Builder.SetInsertPoint(MergeBB);
  314. PHINode *PN =
  315. Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
  316. PN->addIncoming(ThenV, ThenBB);
  317. PN->addIncoming(ElseV, ElseBB);
  318. return PN;
  319. }
  320. The first two lines here are now familiar: the first adds the "merge"
  321. block to the Function object (it was previously floating, like the else
  322. block above). The second changes the insertion point so that newly
  323. created code will go into the "merge" block. Once that is done, we need
  324. to create the PHI node and set up the block/value pairs for the PHI.
  325. Finally, the CodeGen function returns the phi node as the value computed
  326. by the if/then/else expression. In our example above, this returned
  327. value will feed into the code for the top-level function, which will
  328. create the return instruction.
  329. Overall, we now have the ability to execute conditional code in
  330. Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
  331. language that can calculate a wide variety of numeric functions. Next up
  332. we'll add another useful expression that is familiar from non-functional
  333. languages...
  334. 'for' Loop Expression
  335. =====================
  336. Now that we know how to add basic control flow constructs to the
  337. language, we have the tools to add more powerful things. Let's add
  338. something more aggressive, a 'for' expression:
  339. ::
  340. extern putchard(char);
  341. def printstar(n)
  342. for i = 1, i < n, 1.0 in
  343. putchard(42); # ascii 42 = '*'
  344. # print 100 '*' characters
  345. printstar(100);
  346. This expression defines a new variable ("i" in this case) which iterates
  347. from a starting value, while the condition ("i < n" in this case) is
  348. true, incrementing by an optional step value ("1.0" in this case). If
  349. the step value is omitted, it defaults to 1.0. While the loop is true,
  350. it executes its body expression. Because we don't have anything better
  351. to return, we'll just define the loop as always returning 0.0. In the
  352. future when we have mutable variables, it will get more useful.
  353. As before, let's talk about the changes that we need to Kaleidoscope to
  354. support this.
  355. Lexer Extensions for the 'for' Loop
  356. -----------------------------------
  357. The lexer extensions are the same sort of thing as for if/then/else:
  358. .. code-block:: c++
  359. ... in enum Token ...
  360. // control
  361. tok_if = -6, tok_then = -7, tok_else = -8,
  362. tok_for = -9, tok_in = -10
  363. ... in gettok ...
  364. if (IdentifierStr == "def")
  365. return tok_def;
  366. if (IdentifierStr == "extern")
  367. return tok_extern;
  368. if (IdentifierStr == "if")
  369. return tok_if;
  370. if (IdentifierStr == "then")
  371. return tok_then;
  372. if (IdentifierStr == "else")
  373. return tok_else;
  374. if (IdentifierStr == "for")
  375. return tok_for;
  376. if (IdentifierStr == "in")
  377. return tok_in;
  378. return tok_identifier;
  379. AST Extensions for the 'for' Loop
  380. ---------------------------------
  381. The AST node is just as simple. It basically boils down to capturing the
  382. variable name and the constituent expressions in the node.
  383. .. code-block:: c++
  384. /// ForExprAST - Expression class for for/in.
  385. class ForExprAST : public ExprAST {
  386. std::string VarName;
  387. std::unique_ptr<ExprAST> Start, End, Step, Body;
  388. public:
  389. ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
  390. std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
  391. std::unique_ptr<ExprAST> Body)
  392. : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
  393. Step(std::move(Step)), Body(std::move(Body)) {}
  394. Value *codegen() override;
  395. };
  396. Parser Extensions for the 'for' Loop
  397. ------------------------------------
  398. The parser code is also fairly standard. The only interesting thing here
  399. is handling of the optional step value. The parser code handles it by
  400. checking to see if the second comma is present. If not, it sets the step
  401. value to null in the AST node:
  402. .. code-block:: c++
  403. /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
  404. static std::unique_ptr<ExprAST> ParseForExpr() {
  405. getNextToken(); // eat the for.
  406. if (CurTok != tok_identifier)
  407. return LogError("expected identifier after for");
  408. std::string IdName = IdentifierStr;
  409. getNextToken(); // eat identifier.
  410. if (CurTok != '=')
  411. return LogError("expected '=' after for");
  412. getNextToken(); // eat '='.
  413. auto Start = ParseExpression();
  414. if (!Start)
  415. return nullptr;
  416. if (CurTok != ',')
  417. return LogError("expected ',' after for start value");
  418. getNextToken();
  419. auto End = ParseExpression();
  420. if (!End)
  421. return nullptr;
  422. // The step value is optional.
  423. std::unique_ptr<ExprAST> Step;
  424. if (CurTok == ',') {
  425. getNextToken();
  426. Step = ParseExpression();
  427. if (!Step)
  428. return nullptr;
  429. }
  430. if (CurTok != tok_in)
  431. return LogError("expected 'in' after for");
  432. getNextToken(); // eat 'in'.
  433. auto Body = ParseExpression();
  434. if (!Body)
  435. return nullptr;
  436. return std::make_unique<ForExprAST>(IdName, std::move(Start),
  437. std::move(End), std::move(Step),
  438. std::move(Body));
  439. }
  440. And again we hook it up as a primary expression:
  441. .. code-block:: c++
  442. static std::unique_ptr<ExprAST> ParsePrimary() {
  443. switch (CurTok) {
  444. default:
  445. return LogError("unknown token when expecting an expression");
  446. case tok_identifier:
  447. return ParseIdentifierExpr();
  448. case tok_number:
  449. return ParseNumberExpr();
  450. case '(':
  451. return ParseParenExpr();
  452. case tok_if:
  453. return ParseIfExpr();
  454. case tok_for:
  455. return ParseForExpr();
  456. }
  457. }
  458. LLVM IR for the 'for' Loop
  459. --------------------------
  460. Now we get to the good part: the LLVM IR we want to generate for this
  461. thing. With the simple example above, we get this LLVM IR (note that
  462. this dump is generated with optimizations disabled for clarity):
  463. .. code-block:: llvm
  464. declare double @putchard(double)
  465. define double @printstar(double %n) {
  466. entry:
  467. ; initial value = 1.0 (inlined into phi)
  468. br label %loop
  469. loop: ; preds = %loop, %entry
  470. %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
  471. ; body
  472. %calltmp = call double @putchard(double 4.200000e+01)
  473. ; increment
  474. %nextvar = fadd double %i, 1.000000e+00
  475. ; termination test
  476. %cmptmp = fcmp ult double %i, %n
  477. %booltmp = uitofp i1 %cmptmp to double
  478. %loopcond = fcmp one double %booltmp, 0.000000e+00
  479. br i1 %loopcond, label %loop, label %afterloop
  480. afterloop: ; preds = %loop
  481. ; loop always returns 0.0
  482. ret double 0.000000e+00
  483. }
  484. This loop contains all the same constructs we saw before: a phi node,
  485. several expressions, and some basic blocks. Let's see how this fits
  486. together.
  487. Code Generation for the 'for' Loop
  488. ----------------------------------
  489. The first part of codegen is very simple: we just output the start
  490. expression for the loop value:
  491. .. code-block:: c++
  492. Value *ForExprAST::codegen() {
  493. // Emit the start code first, without 'variable' in scope.
  494. Value *StartVal = Start->codegen();
  495. if (!StartVal)
  496. return nullptr;
  497. With this out of the way, the next step is to set up the LLVM basic
  498. block for the start of the loop body. In the case above, the whole loop
  499. body is one block, but remember that the body code itself could consist
  500. of multiple blocks (e.g. if it contains an if/then/else or a for/in
  501. expression).
  502. .. code-block:: c++
  503. // Make the new basic block for the loop header, inserting after current
  504. // block.
  505. Function *TheFunction = Builder.GetInsertBlock()->getParent();
  506. BasicBlock *PreheaderBB = Builder.GetInsertBlock();
  507. BasicBlock *LoopBB =
  508. BasicBlock::Create(TheContext, "loop", TheFunction);
  509. // Insert an explicit fall through from the current block to the LoopBB.
  510. Builder.CreateBr(LoopBB);
  511. This code is similar to what we saw for if/then/else. Because we will
  512. need it to create the Phi node, we remember the block that falls through
  513. into the loop. Once we have that, we create the actual block that starts
  514. the loop and create an unconditional branch for the fall-through between
  515. the two blocks.
  516. .. code-block:: c++
  517. // Start insertion in LoopBB.
  518. Builder.SetInsertPoint(LoopBB);
  519. // Start the PHI node with an entry for Start.
  520. PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(TheContext),
  521. 2, VarName.c_str());
  522. Variable->addIncoming(StartVal, PreheaderBB);
  523. Now that the "preheader" for the loop is set up, we switch to emitting
  524. code for the loop body. To begin with, we move the insertion point and
  525. create the PHI node for the loop induction variable. Since we already
  526. know the incoming value for the starting value, we add it to the Phi
  527. node. Note that the Phi will eventually get a second value for the
  528. backedge, but we can't set it up yet (because it doesn't exist!).
  529. .. code-block:: c++
  530. // Within the loop, the variable is defined equal to the PHI node. If it
  531. // shadows an existing variable, we have to restore it, so save it now.
  532. Value *OldVal = NamedValues[VarName];
  533. NamedValues[VarName] = Variable;
  534. // Emit the body of the loop. This, like any other expr, can change the
  535. // current BB. Note that we ignore the value computed by the body, but don't
  536. // allow an error.
  537. if (!Body->codegen())
  538. return nullptr;
  539. Now the code starts to get more interesting. Our 'for' loop introduces a
  540. new variable to the symbol table. This means that our symbol table can
  541. now contain either function arguments or loop variables. To handle this,
  542. before we codegen the body of the loop, we add the loop variable as the
  543. current value for its name. Note that it is possible that there is a
  544. variable of the same name in the outer scope. It would be easy to make
  545. this an error (emit an error and return null if there is already an
  546. entry for VarName) but we choose to allow shadowing of variables. In
  547. order to handle this correctly, we remember the Value that we are
  548. potentially shadowing in ``OldVal`` (which will be null if there is no
  549. shadowed variable).
  550. Once the loop variable is set into the symbol table, the code
  551. recursively codegen's the body. This allows the body to use the loop
  552. variable: any references to it will naturally find it in the symbol
  553. table.
  554. .. code-block:: c++
  555. // Emit the step value.
  556. Value *StepVal = nullptr;
  557. if (Step) {
  558. StepVal = Step->codegen();
  559. if (!StepVal)
  560. return nullptr;
  561. } else {
  562. // If not specified, use 1.0.
  563. StepVal = ConstantFP::get(TheContext, APFloat(1.0));
  564. }
  565. Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
  566. Now that the body is emitted, we compute the next value of the iteration
  567. variable by adding the step value, or 1.0 if it isn't present.
  568. '``NextVar``' will be the value of the loop variable on the next
  569. iteration of the loop.
  570. .. code-block:: c++
  571. // Compute the end condition.
  572. Value *EndCond = End->codegen();
  573. if (!EndCond)
  574. return nullptr;
  575. // Convert condition to a bool by comparing non-equal to 0.0.
  576. EndCond = Builder.CreateFCmpONE(
  577. EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
  578. Finally, we evaluate the exit value of the loop, to determine whether
  579. the loop should exit. This mirrors the condition evaluation for the
  580. if/then/else statement.
  581. .. code-block:: c++
  582. // Create the "after loop" block and insert it.
  583. BasicBlock *LoopEndBB = Builder.GetInsertBlock();
  584. BasicBlock *AfterBB =
  585. BasicBlock::Create(TheContext, "afterloop", TheFunction);
  586. // Insert the conditional branch into the end of LoopEndBB.
  587. Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
  588. // Any new code will be inserted in AfterBB.
  589. Builder.SetInsertPoint(AfterBB);
  590. With the code for the body of the loop complete, we just need to finish
  591. up the control flow for it. This code remembers the end block (for the
  592. phi node), then creates the block for the loop exit ("afterloop"). Based
  593. on the value of the exit condition, it creates a conditional branch that
  594. chooses between executing the loop again and exiting the loop. Any
  595. future code is emitted in the "afterloop" block, so it sets the
  596. insertion position to it.
  597. .. code-block:: c++
  598. // Add a new entry to the PHI node for the backedge.
  599. Variable->addIncoming(NextVar, LoopEndBB);
  600. // Restore the unshadowed variable.
  601. if (OldVal)
  602. NamedValues[VarName] = OldVal;
  603. else
  604. NamedValues.erase(VarName);
  605. // for expr always returns 0.0.
  606. return Constant::getNullValue(Type::getDoubleTy(TheContext));
  607. }
  608. The final code handles various cleanups: now that we have the "NextVar"
  609. value, we can add the incoming value to the loop PHI node. After that,
  610. we remove the loop variable from the symbol table, so that it isn't in
  611. scope after the for loop. Finally, code generation of the for loop
  612. always returns 0.0, so that is what we return from
  613. ``ForExprAST::codegen()``.
  614. With this, we conclude the "adding control flow to Kaleidoscope" chapter
  615. of the tutorial. In this chapter we added two control flow constructs,
  616. and used them to motivate a couple of aspects of the LLVM IR that are
  617. important for front-end implementors to know. In the next chapter of our
  618. saga, we will get a bit crazier and add `user-defined
  619. operators <LangImpl06.html>`_ to our poor innocent language.
  620. Full Code Listing
  621. =================
  622. Here is the complete code listing for our running example, enhanced with
  623. the if/then/else and for expressions. To build this example, use:
  624. .. code-block:: bash
  625. # Compile
  626. clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
  627. # Run
  628. ./toy
  629. Here is the code:
  630. .. literalinclude:: ../../../examples/Kaleidoscope/Chapter5/toy.cpp
  631. :language: c++
  632. `Next: Extending the language: user-defined operators <LangImpl06.html>`_