+<p>Code generation for function calls is quite straightforward with LLVM. The
+code above initially does a function name lookup in the LLVM Module's symbol
+table. Recall that the LLVM Module is the container that holds all of the
+functions we are JIT'ing. By giving each function the same name as what the
+user specifies, we can use the LLVM symbol table to resolve function names for
+us.</p>
+
+<p>Once we have the function to call, we recursively codegen each argument that
+is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
+instruction</a>. Note that LLVM uses the native C calling conventions by
+default, allowing these calls to also call into standard library functions like
+"sin" and "cos", with no additional effort.</p>
+
+<p>This wraps up our handling of the four basic expressions that we have so far
+in Kaleidoscope. Feel free to go in and add some more. For example, by
+browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
+several other interesting instructions that are really easy to plug into our
+basic framework.</p>
+
+</div>
+
+<!-- *********************************************************************** -->
+<div class="doc_section"><a name="funcs">Function Code Generation</a></div>
+<!-- *********************************************************************** -->
+
+<div class="doc_text">
+
+<p>Code generation for prototypes and functions must handle a number of
+details, which make their code less beautiful than expression code
+generation, but allows us to illustrate some important points. First, lets
+talk about code generation for prototypes: they are used both for function
+bodies and external function declarations. The code starts with:</p>
+
+<div class="doc_code">
+<pre>
+Function *PrototypeAST::Codegen() {
+ // Make the function type: double(double,double) etc.
+ std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
+ FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
+
+ Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
+</pre>
+</div>
+
+<p>This code packs a lot of power into a few lines. Note first that this
+function returns a "Function*" instead of a "Value*". Because a "prototype"
+really talks about the external interface for a function (not the value computed
+by an expression), it makes sense for it to return the LLVM Function it
+corresponds to when codegen'd.</p>
+
+<p>The call to <tt>FunctionType::get</tt> creates
+the <tt>FunctionType</tt> that should be used for a given Prototype. Since all
+function arguments in Kaleidoscope are of type double, the first line creates
+a vector of "N" LLVM double types. It then uses the <tt>FunctionType::get</tt>
+method to create a function type that takes "N" doubles as arguments, returns
+one double as a result, and that is not vararg (the false parameter indicates
+this). Note that Types in LLVM are uniqued just like Constants are, so you
+don't "new" a type, you "get" it.</p>
+
+<p>The final line above actually creates the function that the prototype will
+correspond to. This indicates the type, linkage and name to use, as well as which
+module to insert into. "<a href="../LangRef.html#linkage">external linkage</a>"
+means that the function may be defined outside the current module and/or that it
+is callable by functions outside the module. The Name passed in is the name the
+user specified: since "<tt>TheModule</tt>" is specified, this name is registered
+in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
+above.</p>
+
+<div class="doc_code">
+<pre>
+ // If F conflicted, there was already something named 'Name'. If it has a
+ // body, don't allow redefinition or reextern.
+ if (F->getName() != Name) {
+ // Delete the one we just made and get the existing one.
+ F->eraseFromParent();
+ F = TheModule->getFunction(Name);
+</pre>
+</div>
+
+<p>The Module symbol table works just like the Function symbol table when it
+comes to name conflicts: if a new function is created with a name was previously
+added to the symbol table, it will get implicitly renamed when added to the
+Module. The code above exploits this fact to determine if there was a previous
+definition of this function.</p>
+
+<p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
+first, we want to allow 'extern'ing a function more than once, as long as the
+prototypes for the externs match (since all arguments have the same type, we
+just have to check that the number of arguments match). Second, we want to
+allow 'extern'ing a function and then definining a body for it. This is useful
+when defining mutually recursive functions.</p>
+
+<p>In order to implement this, the code above first checks to see if there is
+a collision on the name of the function. If so, it deletes the function we just
+created (by calling <tt>eraseFromParent</tt>) and then calling
+<tt>getFunction</tt> to get the existing function with the specified name. Note
+that many APIs in LLVM have "erase" forms and "remove" forms. The "remove" form
+unlinks the object from its parent (e.g. a Function from a Module) and returns
+it. The "erase" form unlinks the object and then deletes it.</p>
+
+<div class="doc_code">
+<pre>
+ // If F already has a body, reject this.
+ if (!F->empty()) {
+ ErrorF("redefinition of function");
+ return 0;
+ }
+
+ // If F took a different number of args, reject.
+ if (F->arg_size() != Args.size()) {
+ ErrorF("redefinition of function with different # args");
+ return 0;
+ }
+ }
+</pre>
+</div>
+
+<p>In order to verify the logic above, we first check to see if the pre-existing
+function is "empty". In this case, empty means that it has no basic blocks in
+it, which means it has no body. If it has no body, it is a forward
+declaration. Since we don't allow anything after a full definition of the
+function, the code rejects this case. If the previous reference to a function
+was an 'extern', we simply verify that the number of arguments for that
+definition and this one match up. If not, we emit an error.</p>
+
+<div class="doc_code">
+<pre>
+ // Set names for all arguments.
+ unsigned Idx = 0;
+ for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
+ ++AI, ++Idx) {
+ AI->setName(Args[Idx]);
+
+ // Add arguments to variable symbol table.
+ NamedValues[Args[Idx]] = AI;
+ }
+ return F;
+}
+</pre>
+</div>
+
+<p>The last bit of code for prototypes loops over all of the arguments in the
+function, setting the name of the LLVM Argument objects to match, and registering
+the arguments in the <tt>NamedValues</tt> map for future use by the
+<tt>VariableExprAST</tt> AST node. Once this is set up, it returns the Function
+object to the caller. Note that we don't check for conflicting
+argument names here (e.g. "extern foo(a b a)"). Doing so would be very
+straight-forward with the mechanics we have already used above.</p>
+
+<div class="doc_code">
+<pre>
+Function *FunctionAST::Codegen() {
+ NamedValues.clear();
+
+ Function *TheFunction = Proto->Codegen();
+ if (TheFunction == 0)
+ return 0;
+</pre>
+</div>
+
+<p>Code generation for function definitions starts out simply enough: we just
+codegen the prototype (Proto) and verify that it is ok. We then clear out the
+<tt>NamedValues</tt> map to make sure that there isn't anything in it from the
+last function we compiled. Code generation of the prototype ensures that there
+is an LLVM Function object that is ready to go for us.</p>
+
+<div class="doc_code">
+<pre>
+ // Create a new basic block to start insertion into.
+ BasicBlock *BB = BasicBlock::Create("entry", TheFunction);
+ Builder.SetInsertPoint(BB);
+
+ if (Value *RetVal = Body->Codegen()) {
+</pre>
+</div>
+
+<p>Now we get to the point where the <tt>Builder</tt> is set up. The first
+line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
+block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>. The
+second line then tells the builder that new instructions should be inserted into
+the end of the new basic block. Basic blocks in LLVM are an important part
+of functions that define the <a
+href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
+Since we don't have any control flow, our functions will only contain one
+block at this point. We'll fix this in <a href="LangImpl5.html">Chapter 5</a> :).</p>
+
+<div class="doc_code">
+<pre>
+ if (Value *RetVal = Body->Codegen()) {
+ // Finish off the function.
+ Builder.CreateRet(RetVal);
+
+ // Validate the generated code, checking for consistency.
+ verifyFunction(*TheFunction);
+ return TheFunction;
+ }
+</pre>
+</div>
+
+<p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
+the root expression of the function. If no error happens, this emits code to
+compute the expression into the entry block and returns the value that was
+computed. Assuming no error, we then create an LLVM <a
+href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
+Once the function is built, we call <tt>verifyFunction</tt>, which
+is provided by LLVM. This function does a variety of consistency checks on the
+generated code, to determine if our compiler is doing everything right. Using
+this is important: it can catch a lot of bugs. Once the function is finished
+and validated, we return it.</p>
+
+<div class="doc_code">
+<pre>
+ // Error reading body, remove function.
+ TheFunction->eraseFromParent();
+ return 0;
+}
+</pre>
+</div>
+
+<p>The only piece left here is handling of the error case. For simplicity, we
+handle this by merely deleting the function we produced with the
+<tt>eraseFromParent</tt> method. This allows the user to redefine a function
+that they incorrectly typed in before: if we didn't delete it, it would live in
+the symbol table, with a body, preventing future redefinition.</p>
+
+<p>This code does have a bug, though. Since the <tt>PrototypeAST::Codegen</tt>
+can return a previously defined forward declaration, our code can actually delete
+a forward declaration. There are a number of ways to fix this bug, see what you
+can come up with! Here is a testcase:</p>
+
+<div class="doc_code">
+<pre>
+extern foo(a b); # ok, defines foo.
+def foo(a b) c; # error, 'c' is invalid.
+def bar() foo(1, 2); # error, unknown function "foo"
+</pre>
+</div>