3 ======================================
4 Kaleidoscope: Adding Debug Information
5 ======================================
10 Chapter 9 Introduction
11 ======================
13 Welcome to Chapter 9 of the "`Implementing a language with
14 LLVM <index.html>`_" tutorial. In chapters 1 through 8, we've built a
15 decent little programming language with functions and variables.
16 What happens if something goes wrong though, how do you debug your
19 Source level debugging uses formatted data that helps a debugger
20 translate from binary and the state of the machine back to the
21 source that the programmer wrote. In LLVM we generally use a format
22 called `DWARF <http://dwarfstd.org>`_. DWARF is a compact encoding
23 that represents types, source locations, and variable locations.
25 The short summary of this chapter is that we'll go through the
26 various things you have to add to a programming language to
27 support debug info, and how you translate that into DWARF.
29 Caveat: For now we can't debug via the JIT, so we'll need to compile
30 our program down to something small and standalone. As part of this
31 we'll make a few modifications to the running of the language and
32 how programs are compiled. This means that we'll have a source file
33 with a simple program written in Kaleidoscope rather than the
34 interactive JIT. It does involve a limitation that we can only
35 have one "top level" command at a time to reduce the number of
38 Here's the sample program we'll be compiling:
40 .. code-block:: python
51 Why is this a hard problem?
52 ===========================
54 Debug information is a hard problem for a few different reasons - mostly
55 centered around optimized code. First, optimization makes keeping source
56 locations more difficult. In LLVM IR we keep the original source location
57 for each IR level instruction on the instruction. Optimization passes
58 should keep the source locations for newly created instructions, but merged
59 instructions only get to keep a single location - this can cause jumping
60 around when stepping through optimized programs. Secondly, optimization
61 can move variables in ways that are either optimized out, shared in memory
62 with other variables, or difficult to track. For the purposes of this
63 tutorial we're going to avoid optimization (as you'll see with one of the
64 next sets of patches).
66 Ahead-of-Time Compilation Mode
67 ==============================
69 To highlight only the aspects of adding debug information to a source
70 language without needing to worry about the complexities of JIT debugging
71 we're going to make a few changes to Kaleidoscope to support compiling
72 the IR emitted by the front end into a simple standalone program that
73 you can execute, debug, and see results.
75 First we make our anonymous function that contains our top level
76 statement be our "main":
80 - auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>());
81 + auto Proto = std::make_unique<PrototypeAST>("main", std::vector<std::string>());
83 just with the simple change of giving it a name.
85 Then we're going to remove the command line code wherever it exists:
89 @@ -1129,7 +1129,6 @@ static void HandleTopLevelExpression() {
90 /// top ::= definition | external | expression | ';'
91 static void MainLoop() {
93 - fprintf(stderr, "ready> ");
97 @@ -1184,7 +1183,6 @@ int main() {
98 BinopPrecedence['*'] = 40; // highest.
100 // Prime the first token.
101 - fprintf(stderr, "ready> ");
104 Lastly we're going to disable all of the optimization passes and the JIT so
105 that the only thing that happens after we're done parsing and generating
106 code is that the LLVM IR goes to standard error:
108 .. code-block:: udiff
110 @@ -1108,17 +1108,8 @@ static void HandleExtern() {
111 static void HandleTopLevelExpression() {
112 // Evaluate a top-level expression into an anonymous function.
113 if (auto FnAST = ParseTopLevelExpr()) {
114 - if (auto *FnIR = FnAST->codegen()) {
115 - // We're just doing this to make sure it executes.
116 - TheExecutionEngine->finalizeObject();
117 - // JIT the function, returning a function pointer.
118 - void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
120 - // Cast it to the right type (takes no arguments, returns a double) so we
121 - // can call it as a native function.
122 - double (*FP)() = (double (*)())(intptr_t)FPtr;
123 - // Ignore the return value for this.
125 + if (!F->codegen()) {
126 + fprintf(stderr, "Error generating code for top level expr");
129 // Skip token for error recovery.
130 @@ -1439,11 +1459,11 @@ int main() {
131 // target lays out data structures.
132 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
133 OurFPM.add(new DataLayoutPass());
135 OurFPM.add(createBasicAliasAnalysisPass());
136 // Promote allocas to registers.
137 OurFPM.add(createPromoteMemoryToRegisterPass());
138 @@ -1218,7 +1210,7 @@ int main() {
139 OurFPM.add(createGVNPass());
140 // Simplify the control flow graph (deleting unreachable blocks, etc).
141 OurFPM.add(createCFGSimplificationPass());
144 OurFPM.doInitialization();
146 // Set the global so the code gen can use this.
148 This relatively small set of changes get us to the point that we can compile
149 our piece of Kaleidoscope language down to an executable program via this
154 Kaleidoscope-Ch9 < fib.ks | & clang -x ir -
156 which gives an a.out/a.exe in the current working directory.
161 The top level container for a section of code in DWARF is a compile unit.
162 This contains the type and function data for an individual translation unit
163 (read: one file of source code). So the first thing we need to do is
164 construct one for our fib.ks file.
169 Similar to the ``IRBuilder`` class we have a
170 `DIBuilder <http://llvm.org/doxygen/classllvm_1_1DIBuilder.html>`_ class
171 that helps in constructing debug metadata for an LLVM IR file. It
172 corresponds 1:1 similarly to ``IRBuilder`` and LLVM IR, but with nicer names.
173 Using it does require that you be more familiar with DWARF terminology than
174 you needed to be with ``IRBuilder`` and ``Instruction`` names, but if you
175 read through the general documentation on the
176 `Metadata Format <http://llvm.org/docs/SourceLevelDebugging.html>`_ it
177 should be a little more clear. We'll be using this class to construct all
178 of our IR level descriptions. Construction for it takes a module so we
179 need to construct it shortly after we construct our module. We've left it
180 as a global static variable to make it a bit easier to use.
182 Next we're going to create a small container to cache some of our frequent
183 data. The first will be our compile unit, but we'll also write a bit of
184 code for our one type since we won't have to worry about multiple typed
189 static DIBuilder *DBuilder;
192 DICompileUnit *TheCU;
195 DIType *getDoubleTy();
198 DIType *DebugInfo::getDoubleTy() {
202 DblTy = DBuilder->createBasicType("double", 64, dwarf::DW_ATE_float);
206 And then later on in ``main`` when we're constructing our module:
210 DBuilder = new DIBuilder(*TheModule);
212 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
213 dwarf::DW_LANG_C, DBuilder->createFile("fib.ks", "."),
214 "Kaleidoscope Compiler", 0, "", 0);
216 There are a couple of things to note here. First, while we're producing a
217 compile unit for a language called Kaleidoscope we used the language
218 constant for C. This is because a debugger wouldn't necessarily understand
219 the calling conventions or default ABI for a language it doesn't recognize
220 and we follow the C ABI in our LLVM code generation so it's the closest
221 thing to accurate. This ensures we can actually call functions from the
222 debugger and have them execute. Secondly, you'll see the "fib.ks" in the
223 call to ``createCompileUnit``. This is a default hard coded value since
224 we're using shell redirection to put our source into the Kaleidoscope
225 compiler. In a usual front end you'd have an input file name and it would
228 One last thing as part of emitting debug information via DIBuilder is that
229 we need to "finalize" the debug information. The reasons are part of the
230 underlying API for DIBuilder, but make sure you do this near the end of
235 DBuilder->finalize();
237 before you dump out the module.
242 Now that we have our ``Compile Unit`` and our source locations, we can add
243 function definitions to the debug info. So in ``PrototypeAST::codegen()`` we
244 add a few lines of code to describe a context for our subprogram, in this
245 case the "File", and the actual definition of the function itself.
251 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
252 KSDbgInfo.TheCU.getDirectory());
254 giving us an DIFile and asking the ``Compile Unit`` we created above for the
255 directory and filename where we are currently. Then, for now, we use some
256 source locations of 0 (since our AST doesn't currently have source location
257 information) and construct our function definition:
261 DIScope *FContext = Unit;
263 unsigned ScopeLine = 0;
264 DISubprogram *SP = DBuilder->createFunction(
265 FContext, P.getName(), StringRef(), Unit, LineNo,
266 CreateFunctionType(TheFunction->arg_size(), Unit),
267 false /* internal linkage */, true /* definition */, ScopeLine,
268 DINode::FlagPrototyped, false);
269 TheFunction->setSubprogram(SP);
271 and we now have an DISubprogram that contains a reference to all of our
272 metadata for the function.
277 The most important thing for debug information is accurate source location -
278 this makes it possible to map your source code back. We have a problem though,
279 Kaleidoscope really doesn't have any source location information in the lexer
280 or parser so we'll need to add it.
284 struct SourceLocation {
288 static SourceLocation CurLoc;
289 static SourceLocation LexLoc = {1, 0};
291 static int advance() {
292 int LastChar = getchar();
294 if (LastChar == '\n' || LastChar == '\r') {
302 In this set of code we've added some functionality on how to keep track of the
303 line and column of the "source file". As we lex every token we set our current
304 current "lexical location" to the assorted line and column for the beginning
305 of the token. We do this by overriding all of the previous calls to
306 ``getchar()`` with our new ``advance()`` that keeps track of the information
307 and then we have added to all of our AST classes a source location:
315 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
316 virtual ~ExprAST() {}
317 virtual Value* codegen() = 0;
318 int getLine() const { return Loc.Line; }
319 int getCol() const { return Loc.Col; }
320 virtual raw_ostream &dump(raw_ostream &out, int ind) {
321 return out << ':' << getLine() << ':' << getCol() << '\n';
324 that we pass down through when we create a new expression:
328 LHS = std::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
331 giving us locations for each of our expressions and variables.
333 To make sure that every instruction gets proper source location information,
334 we have to tell ``Builder`` whenever we're at a new source location.
335 We use a small helper function for this:
339 void DebugInfo::emitLocation(ExprAST *AST) {
341 if (LexicalBlocks.empty())
344 Scope = LexicalBlocks.back();
345 Builder.SetCurrentDebugLocation(
346 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
349 This both tells the main ``IRBuilder`` where we are, but also what scope
350 we're in. The scope can either be on compile-unit level or be the nearest
351 enclosing lexical block like the current function.
352 To represent this we create a stack of scopes:
356 std::vector<DIScope *> LexicalBlocks;
358 and push the scope (function) to the top of the stack when we start
359 generating the code for each function:
363 KSDbgInfo.LexicalBlocks.push_back(SP);
365 Also, we may not forget to pop the scope back off of the scope stack at the
366 end of the code generation for the function:
370 // Pop off the lexical block for the function since we added it
372 KSDbgInfo.LexicalBlocks.pop_back();
374 Then we make sure to emit the location every time we start to generate code
375 for a new AST object:
379 KSDbgInfo.emitLocation(this);
384 Now that we have functions, we need to be able to print out the variables
385 we have in scope. Let's get our function arguments set up so we can get
386 decent backtraces and see how our functions are being called. It isn't
387 a lot of code, and we generally handle it when we're creating the
388 argument allocas in ``FunctionAST::codegen``.
392 // Record the function arguments in the NamedValues map.
395 for (auto &Arg : TheFunction->args()) {
396 // Create an alloca for this variable.
397 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
399 // Create a debug descriptor for the variable.
400 DILocalVariable *D = DBuilder->createParameterVariable(
401 SP, Arg.getName(), ++ArgIdx, Unit, LineNo, KSDbgInfo.getDoubleTy(),
404 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
405 DebugLoc::get(LineNo, 0, SP),
406 Builder.GetInsertBlock());
408 // Store the initial value into the alloca.
409 Builder.CreateStore(&Arg, Alloca);
411 // Add arguments to variable symbol table.
412 NamedValues[Arg.getName()] = Alloca;
416 Here we're first creating the variable, giving it the scope (``SP``),
417 the name, source location, type, and since it's an argument, the argument
418 index. Next, we create an ``lvm.dbg.declare`` call to indicate at the IR
419 level that we've got a variable in an alloca (and it gives a starting
420 location for the variable), and setting a source location for the
421 beginning of the scope on the declare.
423 One interesting thing to note at this point is that various debuggers have
424 assumptions based on how code and debug information was generated for them
425 in the past. In this case we need to do a little bit of a hack to avoid
426 generating line information for the function prologue so that the debugger
427 knows to skip over those instructions when setting a breakpoint. So in
428 ``FunctionAST::CodeGen`` we add some more lines:
432 // Unset the location for the prologue emission (leading instructions with no
433 // location in a function are considered part of the prologue and the debugger
434 // will run past them when breaking on a function)
435 KSDbgInfo.emitLocation(nullptr);
437 and then emit a new location when we actually start generating code for the
438 body of the function:
442 KSDbgInfo.emitLocation(Body.get());
444 With this we have enough debug information to set breakpoints in functions,
445 print out argument variables, and call functions. Not too bad for just a
446 few simple lines of code!
451 Here is the complete code listing for our running example, enhanced with
452 debug information. To build this example, use:
457 clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
463 .. literalinclude:: ../../../examples/Kaleidoscope/Chapter9/toy.cpp
466 `Next: Conclusion and other useful LLVM tidbits <LangImpl10.html>`_