1:orphan: 2 3====================================== 4Kaleidoscope: Adding Debug Information 5====================================== 6 7.. contents:: 8 :local: 9 10Chapter 9 Introduction 11====================== 12 13Welcome to Chapter 9 of the "`Implementing a language with 14LLVM <index.html>`_" tutorial. In chapters 1 through 8, we've built a 15decent little programming language with functions and variables. 16What happens if something goes wrong though, how do you debug your 17program? 18 19Source level debugging uses formatted data that helps a debugger 20translate from binary and the state of the machine back to the 21source that the programmer wrote. In LLVM we generally use a format 22called `DWARF <http://dwarfstd.org>`_. DWARF is a compact encoding 23that represents types, source locations, and variable locations. 24 25The short summary of this chapter is that we'll go through the 26various things you have to add to a programming language to 27support debug info, and how you translate that into DWARF. 28 29Caveat: For now we can't debug via the JIT, so we'll need to compile 30our program down to something small and standalone. As part of this 31we'll make a few modifications to the running of the language and 32how programs are compiled. This means that we'll have a source file 33with a simple program written in Kaleidoscope rather than the 34interactive JIT. It does involve a limitation that we can only 35have one "top level" command at a time to reduce the number of 36changes necessary. 37 38Here's the sample program we'll be compiling: 39 40.. code-block:: python 41 42 def fib(x) 43 if x < 3 then 44 1 45 else 46 fib(x-1)+fib(x-2); 47 48 fib(10) 49 50 51Why is this a hard problem? 52=========================== 53 54Debug information is a hard problem for a few different reasons - mostly 55centered around optimized code. First, optimization makes keeping source 56locations more difficult. In LLVM IR we keep the original source location 57for each IR level instruction on the instruction. Optimization passes 58should keep the source locations for newly created instructions, but merged 59instructions only get to keep a single location - this can cause jumping 60around when stepping through optimized programs. Secondly, optimization 61can move variables in ways that are either optimized out, shared in memory 62with other variables, or difficult to track. For the purposes of this 63tutorial we're going to avoid optimization (as you'll see with one of the 64next sets of patches). 65 66Ahead-of-Time Compilation Mode 67============================== 68 69To highlight only the aspects of adding debug information to a source 70language without needing to worry about the complexities of JIT debugging 71we're going to make a few changes to Kaleidoscope to support compiling 72the IR emitted by the front end into a simple standalone program that 73you can execute, debug, and see results. 74 75First we make our anonymous function that contains our top level 76statement be our "main": 77 78.. code-block:: udiff 79 80 - auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>()); 81 + auto Proto = std::make_unique<PrototypeAST>("main", std::vector<std::string>()); 82 83just with the simple change of giving it a name. 84 85Then we're going to remove the command line code wherever it exists: 86 87.. code-block:: udiff 88 89 @@ -1129,7 +1129,6 @@ static void HandleTopLevelExpression() { 90 /// top ::= definition | external | expression | ';' 91 static void MainLoop() { 92 while (1) { 93 - fprintf(stderr, "ready> "); 94 switch (CurTok) { 95 case tok_eof: 96 return; 97 @@ -1184,7 +1183,6 @@ int main() { 98 BinopPrecedence['*'] = 40; // highest. 99 100 // Prime the first token. 101 - fprintf(stderr, "ready> "); 102 getNextToken(); 103 104Lastly we're going to disable all of the optimization passes and the JIT so 105that the only thing that happens after we're done parsing and generating 106code is that the LLVM IR goes to standard error: 107 108.. code-block:: udiff 109 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); 119 - 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. 124 - (void)FP; 125 + if (!F->codegen()) { 126 + fprintf(stderr, "Error generating code for top level expr"); 127 } 128 } else { 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()); 134 +#if 0 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()); 142 - 143 + #endif 144 OurFPM.doInitialization(); 145 146 // Set the global so the code gen can use this. 147 148This relatively small set of changes get us to the point that we can compile 149our piece of Kaleidoscope language down to an executable program via this 150command line: 151 152.. code-block:: bash 153 154 Kaleidoscope-Ch9 < fib.ks | & clang -x ir - 155 156which gives an a.out/a.exe in the current working directory. 157 158Compile Unit 159============ 160 161The top level container for a section of code in DWARF is a compile unit. 162This 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 164construct one for our fib.ks file. 165 166DWARF Emission Setup 167==================== 168 169Similar to the ``IRBuilder`` class we have a 170`DIBuilder <http://llvm.org/doxygen/classllvm_1_1DIBuilder.html>`_ class 171that helps in constructing debug metadata for an LLVM IR file. It 172corresponds 1:1 similarly to ``IRBuilder`` and LLVM IR, but with nicer names. 173Using it does require that you be more familiar with DWARF terminology than 174you needed to be with ``IRBuilder`` and ``Instruction`` names, but if you 175read through the general documentation on the 176`Metadata Format <http://llvm.org/docs/SourceLevelDebugging.html>`_ it 177should be a little more clear. We'll be using this class to construct all 178of our IR level descriptions. Construction for it takes a module so we 179need to construct it shortly after we construct our module. We've left it 180as a global static variable to make it a bit easier to use. 181 182Next we're going to create a small container to cache some of our frequent 183data. The first will be our compile unit, but we'll also write a bit of 184code for our one type since we won't have to worry about multiple typed 185expressions: 186 187.. code-block:: c++ 188 189 static DIBuilder *DBuilder; 190 191 struct DebugInfo { 192 DICompileUnit *TheCU; 193 DIType *DblTy; 194 195 DIType *getDoubleTy(); 196 } KSDbgInfo; 197 198 DIType *DebugInfo::getDoubleTy() { 199 if (DblTy) 200 return DblTy; 201 202 DblTy = DBuilder->createBasicType("double", 64, dwarf::DW_ATE_float); 203 return DblTy; 204 } 205 206And then later on in ``main`` when we're constructing our module: 207 208.. code-block:: c++ 209 210 DBuilder = new DIBuilder(*TheModule); 211 212 KSDbgInfo.TheCU = DBuilder->createCompileUnit( 213 dwarf::DW_LANG_C, DBuilder->createFile("fib.ks", "."), 214 "Kaleidoscope Compiler", 0, "", 0); 215 216There are a couple of things to note here. First, while we're producing a 217compile unit for a language called Kaleidoscope we used the language 218constant for C. This is because a debugger wouldn't necessarily understand 219the calling conventions or default ABI for a language it doesn't recognize 220and we follow the C ABI in our LLVM code generation so it's the closest 221thing to accurate. This ensures we can actually call functions from the 222debugger and have them execute. Secondly, you'll see the "fib.ks" in the 223call to ``createCompileUnit``. This is a default hard coded value since 224we're using shell redirection to put our source into the Kaleidoscope 225compiler. In a usual front end you'd have an input file name and it would 226go there. 227 228One last thing as part of emitting debug information via DIBuilder is that 229we need to "finalize" the debug information. The reasons are part of the 230underlying API for DIBuilder, but make sure you do this near the end of 231main: 232 233.. code-block:: c++ 234 235 DBuilder->finalize(); 236 237before you dump out the module. 238 239Functions 240========= 241 242Now that we have our ``Compile Unit`` and our source locations, we can add 243function definitions to the debug info. So in ``PrototypeAST::codegen()`` we 244add a few lines of code to describe a context for our subprogram, in this 245case the "File", and the actual definition of the function itself. 246 247So the context: 248 249.. code-block:: c++ 250 251 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(), 252 KSDbgInfo.TheCU.getDirectory()); 253 254giving us an DIFile and asking the ``Compile Unit`` we created above for the 255directory and filename where we are currently. Then, for now, we use some 256source locations of 0 (since our AST doesn't currently have source location 257information) and construct our function definition: 258 259.. code-block:: c++ 260 261 DIScope *FContext = Unit; 262 unsigned LineNo = 0; 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); 270 271and we now have an DISubprogram that contains a reference to all of our 272metadata for the function. 273 274Source Locations 275================ 276 277The most important thing for debug information is accurate source location - 278this makes it possible to map your source code back. We have a problem though, 279Kaleidoscope really doesn't have any source location information in the lexer 280or parser so we'll need to add it. 281 282.. code-block:: c++ 283 284 struct SourceLocation { 285 int Line; 286 int Col; 287 }; 288 static SourceLocation CurLoc; 289 static SourceLocation LexLoc = {1, 0}; 290 291 static int advance() { 292 int LastChar = getchar(); 293 294 if (LastChar == '\n' || LastChar == '\r') { 295 LexLoc.Line++; 296 LexLoc.Col = 0; 297 } else 298 LexLoc.Col++; 299 return LastChar; 300 } 301 302In this set of code we've added some functionality on how to keep track of the 303line and column of the "source file". As we lex every token we set our current 304current "lexical location" to the assorted line and column for the beginning 305of 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 307and then we have added to all of our AST classes a source location: 308 309.. code-block:: c++ 310 311 class ExprAST { 312 SourceLocation Loc; 313 314 public: 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'; 322 } 323 324that we pass down through when we create a new expression: 325 326.. code-block:: c++ 327 328 LHS = std::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS), 329 std::move(RHS)); 330 331giving us locations for each of our expressions and variables. 332 333To make sure that every instruction gets proper source location information, 334we have to tell ``Builder`` whenever we're at a new source location. 335We use a small helper function for this: 336 337.. code-block:: c++ 338 339 void DebugInfo::emitLocation(ExprAST *AST) { 340 DIScope *Scope; 341 if (LexicalBlocks.empty()) 342 Scope = TheCU; 343 else 344 Scope = LexicalBlocks.back(); 345 Builder.SetCurrentDebugLocation( 346 DebugLoc::get(AST->getLine(), AST->getCol(), Scope)); 347 } 348 349This both tells the main ``IRBuilder`` where we are, but also what scope 350we're in. The scope can either be on compile-unit level or be the nearest 351enclosing lexical block like the current function. 352To represent this we create a stack of scopes: 353 354.. code-block:: c++ 355 356 std::vector<DIScope *> LexicalBlocks; 357 358and push the scope (function) to the top of the stack when we start 359generating the code for each function: 360 361.. code-block:: c++ 362 363 KSDbgInfo.LexicalBlocks.push_back(SP); 364 365Also, we may not forget to pop the scope back off of the scope stack at the 366end of the code generation for the function: 367 368.. code-block:: c++ 369 370 // Pop off the lexical block for the function since we added it 371 // unconditionally. 372 KSDbgInfo.LexicalBlocks.pop_back(); 373 374Then we make sure to emit the location every time we start to generate code 375for a new AST object: 376 377.. code-block:: c++ 378 379 KSDbgInfo.emitLocation(this); 380 381Variables 382========= 383 384Now that we have functions, we need to be able to print out the variables 385we have in scope. Let's get our function arguments set up so we can get 386decent backtraces and see how our functions are being called. It isn't 387a lot of code, and we generally handle it when we're creating the 388argument allocas in ``FunctionAST::codegen``. 389 390.. code-block:: c++ 391 392 // Record the function arguments in the NamedValues map. 393 NamedValues.clear(); 394 unsigned ArgIdx = 0; 395 for (auto &Arg : TheFunction->args()) { 396 // Create an alloca for this variable. 397 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName()); 398 399 // Create a debug descriptor for the variable. 400 DILocalVariable *D = DBuilder->createParameterVariable( 401 SP, Arg.getName(), ++ArgIdx, Unit, LineNo, KSDbgInfo.getDoubleTy(), 402 true); 403 404 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(), 405 DebugLoc::get(LineNo, 0, SP), 406 Builder.GetInsertBlock()); 407 408 // Store the initial value into the alloca. 409 Builder.CreateStore(&Arg, Alloca); 410 411 // Add arguments to variable symbol table. 412 NamedValues[Arg.getName()] = Alloca; 413 } 414 415 416Here we're first creating the variable, giving it the scope (``SP``), 417the name, source location, type, and since it's an argument, the argument 418index. Next, we create an ``lvm.dbg.declare`` call to indicate at the IR 419level that we've got a variable in an alloca (and it gives a starting 420location for the variable), and setting a source location for the 421beginning of the scope on the declare. 422 423One interesting thing to note at this point is that various debuggers have 424assumptions based on how code and debug information was generated for them 425in the past. In this case we need to do a little bit of a hack to avoid 426generating line information for the function prologue so that the debugger 427knows to skip over those instructions when setting a breakpoint. So in 428``FunctionAST::CodeGen`` we add some more lines: 429 430.. code-block:: c++ 431 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); 436 437and then emit a new location when we actually start generating code for the 438body of the function: 439 440.. code-block:: c++ 441 442 KSDbgInfo.emitLocation(Body.get()); 443 444With this we have enough debug information to set breakpoints in functions, 445print out argument variables, and call functions. Not too bad for just a 446few simple lines of code! 447 448Full Code Listing 449================= 450 451Here is the complete code listing for our running example, enhanced with 452debug information. To build this example, use: 453 454.. code-block:: bash 455 456 # Compile 457 clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy 458 # Run 459 ./toy 460 461Here is the code: 462 463.. literalinclude:: ../../../examples/Kaleidoscope/Chapter9/toy.cpp 464 :language: c++ 465 466`Next: Conclusion and other useful LLVM tidbits <LangImpl10.html>`_ 467 468