blob: 1f2d20f40c76f97d8ac1492d9d0e9bb5e5bbb3dc [file] [log] [blame]
Sean Silvad7fb3962012-12-05 00:26:32 +00001========================================
2Kaleidoscope: Code generation to LLVM IR
3========================================
4
5.. contents::
6 :local:
7
Sean Silvad7fb3962012-12-05 00:26:32 +00008Chapter 3 Introduction
9======================
10
11Welcome to Chapter 3 of the "`Implementing a language with
12LLVM <index.html>`_" tutorial. This chapter shows you how to transform
Kirill Bobyreve4364832017-07-10 09:07:23 +000013the `Abstract Syntax Tree <LangImpl02.html>`_, built in Chapter 2, into
Sean Silvad7fb3962012-12-05 00:26:32 +000014LLVM IR. This will teach you a little bit about how LLVM does things, as
15well as demonstrate how easy it is to use. It's much more work to build
16a lexer and parser than it is to generate LLVM IR code. :)
17
Lang Hames2d789c32015-08-26 03:07:41 +000018**Please note**: the code in this chapter and later require LLVM 3.7 or
19later. LLVM 3.6 and before will not work with it. Also note that you
Sean Silvad7fb3962012-12-05 00:26:32 +000020need to use a version of this tutorial that matches your LLVM release:
21If you are using an official LLVM release, use the version of the
22documentation included with your release or on the `llvm.org releases
23page <http://llvm.org/releases/>`_.
24
25Code Generation Setup
26=====================
27
28In order to generate LLVM IR, we want some simple setup to get started.
29First we define virtual code generation (codegen) methods in each AST
30class:
31
32.. code-block:: c++
33
34 /// ExprAST - Base class for all expression nodes.
35 class ExprAST {
36 public:
37 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +000038 virtual Value *codegen() = 0;
Sean Silvad7fb3962012-12-05 00:26:32 +000039 };
40
41 /// NumberExprAST - Expression class for numeric literals like "1.0".
42 class NumberExprAST : public ExprAST {
43 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +000044
Sean Silvad7fb3962012-12-05 00:26:32 +000045 public:
Lang Hames09bf4c12015-08-18 18:11:06 +000046 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +000047 virtual Value *codegen();
Sean Silvad7fb3962012-12-05 00:26:32 +000048 };
49 ...
50
Lang Hames2d789c32015-08-26 03:07:41 +000051The codegen() method says to emit IR for that AST node along with all
Sean Silvad7fb3962012-12-05 00:26:32 +000052the things it depends on, and they all return an LLVM Value object.
53"Value" is the class used to represent a "`Static Single Assignment
54(SSA) <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
55register" or "SSA value" in LLVM. The most distinct aspect of SSA values
56is that their value is computed as the related instruction executes, and
57it does not get a new value until (and if) the instruction re-executes.
58In other words, there is no way to "change" an SSA value. For more
59information, please read up on `Static Single
60Assignment <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
61- the concepts are really quite natural once you grok them.
62
63Note that instead of adding virtual methods to the ExprAST class
64hierarchy, it could also make sense to use a `visitor
65pattern <http://en.wikipedia.org/wiki/Visitor_pattern>`_ or some other
66way to model this. Again, this tutorial won't dwell on good software
67engineering practices: for our purposes, adding a virtual method is
68simplest.
69
Lang Hames5d045a92016-03-25 17:41:26 +000070The second thing we want is an "LogError" method like we used for the
Sean Silvad7fb3962012-12-05 00:26:32 +000071parser, which will be used to report errors found during code generation
72(for example, use of an undeclared parameter):
73
74.. code-block:: c++
75
Lang Hames9dc125b2016-06-07 05:40:08 +000076 static LLVMContext TheContext;
77 static IRBuilder<> Builder(TheContext);
78 static std::unique_ptr<Module> TheModule;
79 static std::map<std::string, Value *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +000080
Lang Hames5d045a92016-03-25 17:41:26 +000081 Value *LogErrorV(const char *Str) {
82 LogError(Str);
Lang Hames59b0da82015-08-19 18:15:58 +000083 return nullptr;
84 }
Sean Silvad7fb3962012-12-05 00:26:32 +000085
Lang Hames9dc125b2016-06-07 05:40:08 +000086The static variables will be used during code generation. ``TheContext``
87is an opaque object that owns a lot of core LLVM data structures, such as
88the type and constant value tables. We don't need to understand it in
89detail, we just need a single instance to pass into APIs that require it.
Sean Silvad7fb3962012-12-05 00:26:32 +000090
91The ``Builder`` object is a helper object that makes it easy to generate
92LLVM instructions. Instances of the
Sean Silva78da1a52015-03-17 21:02:37 +000093`IRBuilder <http://llvm.org/doxygen/IRBuilder_8h-source.html>`_
Sean Silvad7fb3962012-12-05 00:26:32 +000094class template keep track of the current place to insert instructions
95and has methods to create new instructions.
96
Lang Hames9dc125b2016-06-07 05:40:08 +000097``TheModule`` is an LLVM construct that contains functions and global
98variables. In many ways, it is the top-level structure that the LLVM IR
99uses to contain code. It will own the memory for all of the IR that we
100generate, which is why the codegen() method returns a raw Value\*,
101rather than a unique_ptr<Value>.
102
Sean Silvad7fb3962012-12-05 00:26:32 +0000103The ``NamedValues`` map keeps track of which values are defined in the
104current scope and what their LLVM representation is. (In other words, it
105is a symbol table for the code). In this form of Kaleidoscope, the only
106things that can be referenced are function parameters. As such, function
107parameters will be in this map when generating code for their function
108body.
109
110With these basics in place, we can start talking about how to generate
111code for each expression. Note that this assumes that the ``Builder``
112has been set up to generate code *into* something. For now, we'll assume
113that this has already been done, and we'll just use it to emit code.
114
115Expression Code Generation
116==========================
117
118Generating LLVM code for expression nodes is very straightforward: less
119than 45 lines of commented code for all four of our expression nodes.
120First we'll do numeric literals:
121
122.. code-block:: c++
123
Lang Hames2d789c32015-08-26 03:07:41 +0000124 Value *NumberExprAST::codegen() {
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000125 return ConstantFP::get(TheContext, APFloat(Val));
Sean Silvad7fb3962012-12-05 00:26:32 +0000126 }
127
128In the LLVM IR, numeric constants are represented with the
129``ConstantFP`` class, which holds the numeric value in an ``APFloat``
130internally (``APFloat`` has the capability of holding floating point
131constants of Arbitrary Precision). This code basically just creates
132and returns a ``ConstantFP``. Note that in the LLVM IR that constants
133are all uniqued together and shared. For this reason, the API uses the
134"foo::get(...)" idiom instead of "new foo(..)" or "foo::Create(..)".
135
136.. code-block:: c++
137
Lang Hames2d789c32015-08-26 03:07:41 +0000138 Value *VariableExprAST::codegen() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000139 // Look this variable up in the function.
140 Value *V = NamedValues[Name];
Lang Hames596aec92015-08-19 18:32:58 +0000141 if (!V)
Lang Hames5d045a92016-03-25 17:41:26 +0000142 LogErrorV("Unknown variable name");
Lang Hames596aec92015-08-19 18:32:58 +0000143 return V;
Sean Silvad7fb3962012-12-05 00:26:32 +0000144 }
145
146References to variables are also quite simple using LLVM. In the simple
147version of Kaleidoscope, we assume that the variable has already been
148emitted somewhere and its value is available. In practice, the only
149values that can be in the ``NamedValues`` map are function arguments.
150This code simply checks to see that the specified name is in the map (if
151not, an unknown variable is being referenced) and returns the value for
152it. In future chapters, we'll add support for `loop induction
Alex Denisov596e9792015-12-15 20:50:29 +0000153variables <LangImpl5.html#for-loop-expression>`_ in the symbol table, and for `local
154variables <LangImpl7.html#user-defined-local-variables>`_.
Sean Silvad7fb3962012-12-05 00:26:32 +0000155
156.. code-block:: c++
157
Lang Hames2d789c32015-08-26 03:07:41 +0000158 Value *BinaryExprAST::codegen() {
159 Value *L = LHS->codegen();
160 Value *R = RHS->codegen();
Lang Hames59b0da82015-08-19 18:15:58 +0000161 if (!L || !R)
162 return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000163
164 switch (Op) {
Lang Hames59b0da82015-08-19 18:15:58 +0000165 case '+':
166 return Builder.CreateFAdd(L, R, "addtmp");
167 case '-':
168 return Builder.CreateFSub(L, R, "subtmp");
169 case '*':
170 return Builder.CreateFMul(L, R, "multmp");
Sean Silvad7fb3962012-12-05 00:26:32 +0000171 case '<':
172 L = Builder.CreateFCmpULT(L, R, "cmptmp");
173 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000174 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext),
Sean Silvad7fb3962012-12-05 00:26:32 +0000175 "booltmp");
Lang Hames59b0da82015-08-19 18:15:58 +0000176 default:
Lang Hames5d045a92016-03-25 17:41:26 +0000177 return LogErrorV("invalid binary operator");
Sean Silvad7fb3962012-12-05 00:26:32 +0000178 }
179 }
180
181Binary operators start to get more interesting. The basic idea here is
182that we recursively emit code for the left-hand side of the expression,
183then the right-hand side, then we compute the result of the binary
184expression. In this code, we do a simple switch on the opcode to create
185the right LLVM instruction.
186
187In the example above, the LLVM builder class is starting to show its
188value. IRBuilder knows where to insert the newly created instruction,
189all you have to do is specify what instruction to create (e.g. with
190``CreateFAdd``), which operands to use (``L`` and ``R`` here) and
191optionally provide a name for the generated instruction.
192
193One nice thing about LLVM is that the name is just a hint. For instance,
194if the code above emits multiple "addtmp" variables, LLVM will
195automatically provide each one with an increasing, unique numeric
196suffix. Local value names for instructions are purely optional, but it
197makes it much easier to read the IR dumps.
198
Alex Denisov596e9792015-12-15 20:50:29 +0000199`LLVM instructions <../LangRef.html#instruction-reference>`_ are constrained by strict
Sean Silvad7fb3962012-12-05 00:26:32 +0000200rules: for example, the Left and Right operators of an `add
Alex Denisov596e9792015-12-15 20:50:29 +0000201instruction <../LangRef.html#add-instruction>`_ must have the same type, and the
Sean Silvad7fb3962012-12-05 00:26:32 +0000202result type of the add must match the operand types. Because all values
203in Kaleidoscope are doubles, this makes for very simple code for add,
204sub and mul.
205
206On the other hand, LLVM specifies that the `fcmp
Alex Denisov596e9792015-12-15 20:50:29 +0000207instruction <../LangRef.html#fcmp-instruction>`_ always returns an 'i1' value (a
Sean Silvad7fb3962012-12-05 00:26:32 +0000208one bit integer). The problem with this is that Kaleidoscope wants the
209value to be a 0.0 or 1.0 value. In order to get these semantics, we
210combine the fcmp instruction with a `uitofp
Alex Denisov596e9792015-12-15 20:50:29 +0000211instruction <../LangRef.html#uitofp-to-instruction>`_. This instruction converts its
Sean Silvad7fb3962012-12-05 00:26:32 +0000212input integer into a floating point value by treating the input as an
213unsigned value. In contrast, if we used the `sitofp
Alex Denisov596e9792015-12-15 20:50:29 +0000214instruction <../LangRef.html#sitofp-to-instruction>`_, the Kaleidoscope '<' operator
Sean Silvad7fb3962012-12-05 00:26:32 +0000215would return 0.0 and -1.0, depending on the input value.
216
217.. code-block:: c++
218
Lang Hames2d789c32015-08-26 03:07:41 +0000219 Value *CallExprAST::codegen() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000220 // Look up the name in the global module table.
221 Function *CalleeF = TheModule->getFunction(Callee);
Lang Hames59b0da82015-08-19 18:15:58 +0000222 if (!CalleeF)
Lang Hames5d045a92016-03-25 17:41:26 +0000223 return LogErrorV("Unknown function referenced");
Sean Silvad7fb3962012-12-05 00:26:32 +0000224
225 // If argument mismatch error.
226 if (CalleeF->arg_size() != Args.size())
Lang Hames5d045a92016-03-25 17:41:26 +0000227 return LogErrorV("Incorrect # arguments passed");
Sean Silvad7fb3962012-12-05 00:26:32 +0000228
Lang Hames59b0da82015-08-19 18:15:58 +0000229 std::vector<Value *> ArgsV;
Sean Silvad7fb3962012-12-05 00:26:32 +0000230 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000231 ArgsV.push_back(Args[i]->codegen());
Lang Hames59b0da82015-08-19 18:15:58 +0000232 if (!ArgsV.back())
233 return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000234 }
235
236 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
237 }
238
Lang Hames2d789c32015-08-26 03:07:41 +0000239Code generation for function calls is quite straightforward with LLVM. The code
240above initially does a function name lookup in the LLVM Module's symbol table.
241Recall that the LLVM Module is the container that holds the functions we are
242JIT'ing. By giving each function the same name as what the user specifies, we
243can use the LLVM symbol table to resolve function names for us.
Sean Silvad7fb3962012-12-05 00:26:32 +0000244
245Once we have the function to call, we recursively codegen each argument
246that is to be passed in, and create an LLVM `call
Alex Denisov596e9792015-12-15 20:50:29 +0000247instruction <../LangRef.html#call-instruction>`_. Note that LLVM uses the native C
Sean Silvad7fb3962012-12-05 00:26:32 +0000248calling conventions by default, allowing these calls to also call into
249standard library functions like "sin" and "cos", with no additional
250effort.
251
252This wraps up our handling of the four basic expressions that we have so
253far in Kaleidoscope. Feel free to go in and add some more. For example,
254by browsing the `LLVM language reference <../LangRef.html>`_ you'll find
255several other interesting instructions that are really easy to plug into
256our basic framework.
257
258Function Code Generation
259========================
260
261Code generation for prototypes and functions must handle a number of
262details, which make their code less beautiful than expression code
263generation, but allows us to illustrate some important points. First,
Sjoerd Meijer4f8f1e52018-03-29 12:31:06 +0000264let's talk about code generation for prototypes: they are used both for
Sean Silvad7fb3962012-12-05 00:26:32 +0000265function bodies and external function declarations. The code starts
266with:
267
268.. code-block:: c++
269
Lang Hames2d789c32015-08-26 03:07:41 +0000270 Function *PrototypeAST::codegen() {
Sean Silvad7fb3962012-12-05 00:26:32 +0000271 // Make the function type: double(double,double) etc.
272 std::vector<Type*> Doubles(Args.size(),
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000273 Type::getDoubleTy(TheContext));
Lang Hames59b0da82015-08-19 18:15:58 +0000274 FunctionType *FT =
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000275 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Sean Silvad7fb3962012-12-05 00:26:32 +0000276
Lang Hames59b0da82015-08-19 18:15:58 +0000277 Function *F =
278 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
Sean Silvad7fb3962012-12-05 00:26:32 +0000279
280This code packs a lot of power into a few lines. Note first that this
281function returns a "Function\*" instead of a "Value\*". Because a
282"prototype" really talks about the external interface for a function
283(not the value computed by an expression), it makes sense for it to
284return the LLVM Function it corresponds to when codegen'd.
285
286The call to ``FunctionType::get`` creates the ``FunctionType`` that
287should be used for a given Prototype. Since all function arguments in
288Kaleidoscope are of type double, the first line creates a vector of "N"
289LLVM double types. It then uses the ``Functiontype::get`` method to
290create a function type that takes "N" doubles as arguments, returns one
291double as a result, and that is not vararg (the false parameter
292indicates this). Note that Types in LLVM are uniqued just like Constants
293are, so you don't "new" a type, you "get" it.
294
Lang Hames2d789c32015-08-26 03:07:41 +0000295The final line above actually creates the IR Function corresponding to
296the Prototype. This indicates the type, linkage and name to use, as
Sean Silvad7fb3962012-12-05 00:26:32 +0000297well as which module to insert into. "`external
298linkage <../LangRef.html#linkage>`_" means that the function may be
299defined outside the current module and/or that it is callable by
300functions outside the module. The Name passed in is the name the user
301specified: since "``TheModule``" is specified, this name is registered
Lang Hames2d789c32015-08-26 03:07:41 +0000302in "``TheModule``"s symbol table.
Sean Silvad7fb3962012-12-05 00:26:32 +0000303
304.. code-block:: c++
305
Lang Hames2d789c32015-08-26 03:07:41 +0000306 // Set names for all arguments.
307 unsigned Idx = 0;
308 for (auto &Arg : F->args())
309 Arg.setName(Args[Idx++]);
Sean Silvad7fb3962012-12-05 00:26:32 +0000310
Lang Hames2d789c32015-08-26 03:07:41 +0000311 return F;
Sean Silvad7fb3962012-12-05 00:26:32 +0000312
Lang Hames2d789c32015-08-26 03:07:41 +0000313Finally, we set the name of each of the function's arguments according to the
314names given in the Prototype. This step isn't strictly necessary, but keeping
315the names consistent makes the IR more readable, and allows subsequent code to
316refer directly to the arguments for their names, rather than having to look up
317them up in the Prototype AST.
Sean Silvad7fb3962012-12-05 00:26:32 +0000318
Lang Hames2d789c32015-08-26 03:07:41 +0000319At this point we have a function prototype with no body. This is how LLVM IR
320represents function declarations. For extern statements in Kaleidoscope, this
321is as far as we need to go. For function definitions however, we need to
322codegen and attach a function body.
Sean Silvad7fb3962012-12-05 00:26:32 +0000323
324.. code-block:: c++
325
Lang Hames2d789c32015-08-26 03:07:41 +0000326 Function *FunctionAST::codegen() {
327 // First, check for an existing function from a previous 'extern' declaration.
328 Function *TheFunction = TheModule->getFunction(Proto->getName());
Sean Silvad7fb3962012-12-05 00:26:32 +0000329
Lang Hames2d789c32015-08-26 03:07:41 +0000330 if (!TheFunction)
331 TheFunction = Proto->codegen();
Sean Silvad7fb3962012-12-05 00:26:32 +0000332
Lang Hames2d789c32015-08-26 03:07:41 +0000333 if (!TheFunction)
334 return nullptr;
335
336 if (!TheFunction->empty())
Lang Hames5d045a92016-03-25 17:41:26 +0000337 return (Function*)LogErrorV("Function cannot be redefined.");
Lang Hames2d789c32015-08-26 03:07:41 +0000338
339
340For function definitions, we start by searching TheModule's symbol table for an
341existing version of this function, in case one has already been created using an
342'extern' statement. If Module::getFunction returns null then no previous version
343exists, so we'll codegen one from the Prototype. In either case, we want to
344assert that the function is empty (i.e. has no body yet) before we start.
Sean Silvad7fb3962012-12-05 00:26:32 +0000345
346.. code-block:: c++
347
Lang Hames2d789c32015-08-26 03:07:41 +0000348 // Create a new basic block to start insertion into.
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000349 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Lang Hames2d789c32015-08-26 03:07:41 +0000350 Builder.SetInsertPoint(BB);
Sean Silvad7fb3962012-12-05 00:26:32 +0000351
Lang Hames2d789c32015-08-26 03:07:41 +0000352 // Record the function arguments in the NamedValues map.
353 NamedValues.clear();
354 for (auto &Arg : TheFunction->args())
355 NamedValues[Arg.getName()] = &Arg;
Sean Silvad7fb3962012-12-05 00:26:32 +0000356
357Now we get to the point where the ``Builder`` is set up. The first line
358creates a new `basic block <http://en.wikipedia.org/wiki/Basic_block>`_
359(named "entry"), which is inserted into ``TheFunction``. The second line
360then tells the builder that new instructions should be inserted into the
361end of the new basic block. Basic blocks in LLVM are an important part
362of functions that define the `Control Flow
363Graph <http://en.wikipedia.org/wiki/Control_flow_graph>`_. Since we
364don't have any control flow, our functions will only contain one block
Kirill Bobyreve4364832017-07-10 09:07:23 +0000365at this point. We'll fix this in `Chapter 5 <LangImpl05.html>`_ :).
Sean Silvad7fb3962012-12-05 00:26:32 +0000366
Lang Hames2d789c32015-08-26 03:07:41 +0000367Next we add the function arguments to the NamedValues map (after first clearing
368it out) so that they're accessible to ``VariableExprAST`` nodes.
369
Sean Silvad7fb3962012-12-05 00:26:32 +0000370.. code-block:: c++
371
Lang Hames2d789c32015-08-26 03:07:41 +0000372 if (Value *RetVal = Body->codegen()) {
Sean Silvad7fb3962012-12-05 00:26:32 +0000373 // Finish off the function.
374 Builder.CreateRet(RetVal);
375
376 // Validate the generated code, checking for consistency.
377 verifyFunction(*TheFunction);
378
379 return TheFunction;
380 }
381
Lang Hames2d789c32015-08-26 03:07:41 +0000382Once the insertion point has been set up and the NamedValues map populated,
383we call the ``codegen()`` method for the root expression of the function. If no
384error happens, this emits code to compute the expression into the entry block
385and returns the value that was computed. Assuming no error, we then create an
Alex Denisov596e9792015-12-15 20:50:29 +0000386LLVM `ret instruction <../LangRef.html#ret-instruction>`_, which completes the function.
Sean Silvad7fb3962012-12-05 00:26:32 +0000387Once the function is built, we call ``verifyFunction``, which is
388provided by LLVM. This function does a variety of consistency checks on
389the generated code, to determine if our compiler is doing everything
390right. Using this is important: it can catch a lot of bugs. Once the
391function is finished and validated, we return it.
392
393.. code-block:: c++
394
395 // Error reading body, remove function.
396 TheFunction->eraseFromParent();
Lang Hames59b0da82015-08-19 18:15:58 +0000397 return nullptr;
Sean Silvad7fb3962012-12-05 00:26:32 +0000398 }
399
400The only piece left here is handling of the error case. For simplicity,
401we handle this by merely deleting the function we produced with the
402``eraseFromParent`` method. This allows the user to redefine a function
403that they incorrectly typed in before: if we didn't delete it, it would
404live in the symbol table, with a body, preventing future redefinition.
405
Lang Hames2d789c32015-08-26 03:07:41 +0000406This code does have a bug, though: If the ``FunctionAST::codegen()`` method
407finds an existing IR Function, it does not validate its signature against the
408definition's own prototype. This means that an earlier 'extern' declaration will
409take precedence over the function definition's signature, which can cause
410codegen to fail, for instance if the function arguments are named differently.
411There are a number of ways to fix this bug, see what you can come up with! Here
412is a testcase:
Sean Silvad7fb3962012-12-05 00:26:32 +0000413
414::
415
Lang Hames2d789c32015-08-26 03:07:41 +0000416 extern foo(a); # ok, defines foo.
417 def foo(b) b; # Error: Unknown variable name. (decl using 'a' takes precedence).
Sean Silvad7fb3962012-12-05 00:26:32 +0000418
419Driver Changes and Closing Thoughts
420===================================
421
422For now, code generation to LLVM doesn't really get us much, except that
423we can look at the pretty IR calls. The sample code inserts calls to
Lang Hames2d789c32015-08-26 03:07:41 +0000424codegen into the "``HandleDefinition``", "``HandleExtern``" etc
Sean Silvad7fb3962012-12-05 00:26:32 +0000425functions, and then dumps out the LLVM IR. This gives a nice way to look
426at the LLVM IR for simple functions. For example:
427
428::
429
430 ready> 4+5;
431 Read top-level expression:
432 define double @0() {
433 entry:
434 ret double 9.000000e+00
435 }
436
437Note how the parser turns the top-level expression into anonymous
438functions for us. This will be handy when we add `JIT
Alex Denisov596e9792015-12-15 20:50:29 +0000439support <LangImpl4.html#adding-a-jit-compiler>`_ in the next chapter. Also note that the
Sean Silvad7fb3962012-12-05 00:26:32 +0000440code is very literally transcribed, no optimizations are being performed
441except simple constant folding done by IRBuilder. We will `add
Alex Denisov596e9792015-12-15 20:50:29 +0000442optimizations <LangImpl4.html#trivial-constant-folding>`_ explicitly in the next
Sean Silvad7fb3962012-12-05 00:26:32 +0000443chapter.
444
445::
446
447 ready> def foo(a b) a*a + 2*a*b + b*b;
448 Read function definition:
449 define double @foo(double %a, double %b) {
450 entry:
451 %multmp = fmul double %a, %a
452 %multmp1 = fmul double 2.000000e+00, %a
453 %multmp2 = fmul double %multmp1, %b
454 %addtmp = fadd double %multmp, %multmp2
455 %multmp3 = fmul double %b, %b
456 %addtmp4 = fadd double %addtmp, %multmp3
457 ret double %addtmp4
458 }
459
460This shows some simple arithmetic. Notice the striking similarity to the
461LLVM builder calls that we use to create the instructions.
462
463::
464
465 ready> def bar(a) foo(a, 4.0) + bar(31337);
466 Read function definition:
467 define double @bar(double %a) {
468 entry:
469 %calltmp = call double @foo(double %a, double 4.000000e+00)
470 %calltmp1 = call double @bar(double 3.133700e+04)
471 %addtmp = fadd double %calltmp, %calltmp1
472 ret double %addtmp
473 }
474
475This shows some function calls. Note that this function will take a long
476time to execute if you call it. In the future we'll add conditional
477control flow to actually make recursion useful :).
478
479::
480
481 ready> extern cos(x);
482 Read extern:
483 declare double @cos(double)
484
485 ready> cos(1.234);
486 Read top-level expression:
487 define double @1() {
488 entry:
489 %calltmp = call double @cos(double 1.234000e+00)
490 ret double %calltmp
491 }
492
493This shows an extern for the libm "cos" function, and a call to it.
494
495.. TODO:: Abandon Pygments' horrible `llvm` lexer. It just totally gives up
496 on highlighting this due to the first line.
497
498::
499
500 ready> ^D
501 ; ModuleID = 'my cool jit'
502
503 define double @0() {
504 entry:
505 %addtmp = fadd double 4.000000e+00, 5.000000e+00
506 ret double %addtmp
507 }
508
509 define double @foo(double %a, double %b) {
510 entry:
511 %multmp = fmul double %a, %a
512 %multmp1 = fmul double 2.000000e+00, %a
513 %multmp2 = fmul double %multmp1, %b
514 %addtmp = fadd double %multmp, %multmp2
515 %multmp3 = fmul double %b, %b
516 %addtmp4 = fadd double %addtmp, %multmp3
517 ret double %addtmp4
518 }
519
520 define double @bar(double %a) {
521 entry:
522 %calltmp = call double @foo(double %a, double 4.000000e+00)
523 %calltmp1 = call double @bar(double 3.133700e+04)
524 %addtmp = fadd double %calltmp, %calltmp1
525 ret double %addtmp
526 }
527
528 declare double @cos(double)
529
530 define double @1() {
531 entry:
532 %calltmp = call double @cos(double 1.234000e+00)
533 ret double %calltmp
534 }
535
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000536When you quit the current demo (by sending an EOF via CTRL+D on Linux
537or CTRL+Z and ENTER on Windows), it dumps out the IR for the entire
Sean Silvad7fb3962012-12-05 00:26:32 +0000538module generated. Here you can see the big picture with all the
539functions referencing each other.
540
541This wraps up the third chapter of the Kaleidoscope tutorial. Up next,
542we'll describe how to `add JIT codegen and optimizer
Kirill Bobyreve4364832017-07-10 09:07:23 +0000543support <LangImpl04.html>`_ to this so we can actually start running
Sean Silvad7fb3962012-12-05 00:26:32 +0000544code!
545
546Full Code Listing
547=================
548
549Here is the complete code listing for our running example, enhanced with
550the LLVM code generator. Because this uses the LLVM libraries, we need
551to link them in. To do this, we use the
552`llvm-config <http://llvm.org/cmds/llvm-config.html>`_ tool to inform
553our makefile/command line about which options to use:
554
555.. code-block:: bash
556
557 # Compile
Lang Hamesaa0f6732014-11-06 00:31:04 +0000558 clang++ -g -O3 toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core` -o toy
Sean Silvad7fb3962012-12-05 00:26:32 +0000559 # Run
560 ./toy
561
562Here is the code:
563
Logan Chien855b17d2013-06-08 09:03:03 +0000564.. literalinclude:: ../../examples/Kaleidoscope/Chapter3/toy.cpp
565 :language: c++
Sean Silvad7fb3962012-12-05 00:26:32 +0000566
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000567`Next: Adding JIT and Optimizer Support <LangImpl04.html>`_
Sean Silvad7fb3962012-12-05 00:26:32 +0000568