-=======================================================
-Kaleidoscope: Extending the Language: Debug Information
-=======================================================
+======================================
+Kaleidoscope: Adding Debug Information
+======================================
.. contents::
:local:
.. code-block:: udiff
-- PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
-+ PrototypeAST *Proto = new PrototypeAST("main", std::vector<std::string>());
+ - auto Proto = llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
+ + auto Proto = llvm::make_unique<PrototypeAST>("main", std::vector<std::string>());
just with the simple change of giving it a name.
.. code-block:: udiff
-@@ -1129,7 +1129,6 @@ static void HandleTopLevelExpression() {
- /// top ::= definition | external | expression | ';'
- static void MainLoop() {
- while (1) {
-- fprintf(stderr, "ready> ");
- switch (CurTok) {
- case tok_eof:
- return;
-@@ -1184,7 +1183,6 @@ int main() {
- BinopPrecedence['*'] = 40; // highest.
+ @@ -1129,7 +1129,6 @@ static void HandleTopLevelExpression() {
+ /// top ::= definition | external | expression | ';'
+ static void MainLoop() {
+ while (1) {
+ - fprintf(stderr, "ready> ");
+ switch (CurTok) {
+ case tok_eof:
+ return;
+ @@ -1184,7 +1183,6 @@ int main() {
+ BinopPrecedence['*'] = 40; // highest.
- // Prime the first token.
-- fprintf(stderr, "ready> ");
- getNextToken();
+ // Prime the first token.
+ - fprintf(stderr, "ready> ");
+ getNextToken();
Lastly we're going to disable all of the optimization passes and the JIT so
that the only thing that happens after we're done parsing and generating
.. code-block:: udiff
-@@ -1108,17 +1108,8 @@ static void HandleExtern() {
- static void HandleTopLevelExpression() {
- // Evaluate a top-level expression into an anonymous function.
- if (FunctionAST *F = ParseTopLevelExpr()) {
-- if (Function *LF = F->Codegen()) {
-- // We're just doing this to make sure it executes.
-- TheExecutionEngine->finalizeObject();
-- // JIT the function, returning a function pointer.
-- void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
--
-- // Cast it to the right type (takes no arguments, returns a double) so we
-- // can call it as a native function.
-- double (*FP)() = (double (*)())(intptr_t)FPtr;
-- // Ignore the return value for this.
-- (void)FP;
-+ if (!F->Codegen()) {
-+ fprintf(stderr, "Error generating code for top level expr");
- }
- } else {
- // Skip token for error recovery.
-@@ -1439,11 +1459,11 @@ int main() {
- // target lays out data structures.
- TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
- OurFPM.add(new DataLayoutPass());
-+#if 0
- OurFPM.add(createBasicAliasAnalysisPass());
- // Promote allocas to registers.
- OurFPM.add(createPromoteMemoryToRegisterPass());
-@@ -1218,7 +1210,7 @@ int main() {
- OurFPM.add(createGVNPass());
- // Simplify the control flow graph (deleting unreachable blocks, etc).
- OurFPM.add(createCFGSimplificationPass());
--
-+ #endif
- OurFPM.doInitialization();
+ @@ -1108,17 +1108,8 @@ static void HandleExtern() {
+ static void HandleTopLevelExpression() {
+ // Evaluate a top-level expression into an anonymous function.
+ if (auto FnAST = ParseTopLevelExpr()) {
+ - if (auto *FnIR = FnAST->codegen()) {
+ - // We're just doing this to make sure it executes.
+ - TheExecutionEngine->finalizeObject();
+ - // JIT the function, returning a function pointer.
+ - void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
+ -
+ - // Cast it to the right type (takes no arguments, returns a double) so we
+ - // can call it as a native function.
+ - double (*FP)() = (double (*)())(intptr_t)FPtr;
+ - // Ignore the return value for this.
+ - (void)FP;
+ + if (!F->codegen()) {
+ + fprintf(stderr, "Error generating code for top level expr");
+ }
+ } else {
+ // Skip token for error recovery.
+ @@ -1439,11 +1459,11 @@ int main() {
+ // target lays out data structures.
+ TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
+ OurFPM.add(new DataLayoutPass());
+ +#if 0
+ OurFPM.add(createBasicAliasAnalysisPass());
+ // Promote allocas to registers.
+ OurFPM.add(createPromoteMemoryToRegisterPass());
+ @@ -1218,7 +1210,7 @@ int main() {
+ OurFPM.add(createGVNPass());
+ // Simplify the control flow graph (deleting unreachable blocks, etc).
+ OurFPM.add(createCFGSimplificationPass());
+ -
+ + #endif
+ OurFPM.doInitialization();
- // Set the global so the code gen can use this.
+ // Set the global so the code gen can use this.
This relatively small set of changes get us to the point that we can compile
our piece of Kaleidoscope language down to an executable program via this
.. code-block:: bash
-Kaleidoscope-Ch8 < fib.ks | & clang -x ir -
+ Kaleidoscope-Ch8 < fib.ks | & clang -x ir -
which gives an a.out/a.exe in the current working directory.
====================
Similar to the ``IRBuilder`` class we have a
-```DIBuilder`` <http://llvm.org/doxygen/classllvm_1_1DIBuilder.html>`_ class
+`DIBuilder <http://llvm.org/doxygen/classllvm_1_1DIBuilder.html>`_ class
that helps in constructing debug metadata for an llvm IR file. It
corresponds 1:1 similarly to ``IRBuilder`` and llvm IR, but with nicer names.
Using it does require that you be more familiar with DWARF terminology than
you needed to be with ``IRBuilder`` and ``Instruction`` names, but if you
read through the general documentation on the
-```Metadata Format`` <http://llvm.org/docs/SourceLevelDebugging.html>`_ it
+`Metadata Format <http://llvm.org/docs/SourceLevelDebugging.html>`_ it
should be a little more clear. We'll be using this class to construct all
of our IR level descriptions. Construction for it takes a module so we
need to construct it shortly after we construct our module. We've left it
static DIBuilder *DBuilder;
struct DebugInfo {
- DICompileUnit TheCU;
- DIType DblTy;
+ DICompileUnit *TheCU;
+ DIType *DblTy;
- DIType getDoubleTy();
+ DIType *getDoubleTy();
} KSDbgInfo;
- DIType DebugInfo::getDoubleTy() {
+ DIType *DebugInfo::getDoubleTy() {
if (DblTy.isValid())
return DblTy;
=========
Now that we have our ``Compile Unit`` and our source locations, we can add
-function definitions to the debug info. So in ``PrototypeAST::Codegen`` we
+function definitions to the debug info. So in ``PrototypeAST::codegen()`` we
add a few lines of code to describe a context for our subprogram, in this
case the "File", and the actual definition of the function itself.
.. code-block:: c++
- DIFile Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
- KSDbgInfo.TheCU.getDirectory());
+ DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
+ KSDbgInfo.TheCU.getDirectory());
-giving us a DIFile and asking the ``Compile Unit`` we created above for the
+giving us an DIFile and asking the ``Compile Unit`` we created above for the
directory and filename where we are currently. Then, for now, we use some
source locations of 0 (since our AST doesn't currently have source location
information) and construct our function definition:
.. code-block:: c++
- DIDescriptor FContext(Unit);
+ DIScope *FContext = Unit;
unsigned LineNo = 0;
unsigned ScopeLine = 0;
- DISubprogram SP = DBuilder->createFunction(
+ DISubprogram *SP = DBuilder->createFunction(
FContext, Name, StringRef(), Unit, LineNo,
CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
- true /* definition */, ScopeLine, DIDescriptor::FlagPrototyped, false, F);
+ true /* definition */, ScopeLine, DINode::FlagPrototyped, false);
+ F->setSubprogram(SP);
-and we now have a DISubprogram that contains a reference to all of our metadata
-for the function.
+and we now have an DISubprogram that contains a reference to all of our
+metadata for the function.
Source Locations
================
SourceLocation Loc;
public:
+ ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
+ virtual ~ExprAST() {}
+ virtual Value* codegen() = 0;
int getLine() const { return Loc.Line; }
int getCol() const { return Loc.Col; }
- ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
- virtual std::ostream &dump(std::ostream &out, int ind) {
+ virtual raw_ostream &dump(raw_ostream &out, int ind) {
return out << ':' << getLine() << ':' << getCol() << '\n';
}
.. code-block:: c++
- LHS = new BinaryExprAST(BinLoc, BinOp, LHS, RHS);
+ LHS = llvm::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
+ std::move(RHS));
giving us locations for each of our expressions and variables.
void DebugInfo::emitLocation(ExprAST *AST) {
DIScope *Scope;
if (LexicalBlocks.empty())
- Scope = &TheCU;
+ Scope = TheCU;
else
Scope = LexicalBlocks.back();
Builder.SetCurrentDebugLocation(
- DebugLoc::get(AST->getLine(), AST->getCol(), DIScope(*Scope)));
+ DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
}
that both tells the main ``IRBuilder`` where we are, but also what scope
.. code-block:: c++
std::vector<DIScope *> LexicalBlocks;
- std::map<const PrototypeAST *, DIScope> FnScopeMap;
+ std::map<const PrototypeAST *, DIScope *> FnScopeMap;
-and keep a map of each function to the scope that it represents (a DISubprogram
-is also a DIScope).
+and keep a map of each function to the scope that it represents (an
+DISubprogram is also an DIScope).
Then we make sure to:
when we start generating the code for each function.
+also, don't forget to pop the scope back off of your scope stack at the
+end of the code generation for the function:
+
+.. code-block:: c++
+
+ // Pop off the lexical block for the function since we added it
+ // unconditionally.
+ KSDbgInfo.LexicalBlocks.pop_back();
+
+Variables
+=========
+
+Now that we have functions, we need to be able to print out the variables
+we have in scope. Let's get our function arguments set up so we can get
+decent backtraces and see how our functions are being called. It isn't
+a lot of code, and we generally handle it when we're creating the
+argument allocas in ``PrototypeAST::CreateArgumentAllocas``.
+
+.. code-block:: c++
+
+ DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
+ DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU.getFilename(),
+ KSDbgInfo.TheCU.getDirectory());
+ DILocalVariable D = DBuilder->createParameterVariable(
+ Scope, Args[Idx], Idx + 1, Unit, Line, KSDbgInfo.getDoubleTy(), true);
+
+ DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
+ DebugLoc::get(Line, 0, Scope),
+ Builder.GetInsertBlock());
+
+Here we're doing a few things. First, we're grabbing our current scope
+for the variable so we can say what range of code our variable is valid
+through. Second, we're creating the variable, giving it the scope,
+the name, source location, type, and since it's an argument, the argument
+index. Third, we create an ``lvm.dbg.declare`` call to indicate at the IR
+level that we've got a variable in an alloca (and it gives a starting
+location for the variable), and setting a source location for the
+beginning of the scope on the declare.
+
One interesting thing to note at this point is that various debuggers have
assumptions based on how code and debug information was generated for them
in the past. In this case we need to do a little bit of a hack to avoid
KSDbgInfo.emitLocation(Body);
-also, don't forget to pop the scope back off of your scope stack at the
-end of the code generation for the function:
-
-.. code-block:: c++
-
- // Pop off the lexical block for the function since we added it
- // unconditionally.
- KSDbgInfo.LexicalBlocks.pop_back();
-
+With this we have enough debug information to set breakpoints in functions,
+print out argument variables, and call functions. Not too bad for just a
+few simple lines of code!
Full Code Listing
=================
.. code-block:: bash
# Compile
- clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core jit native` -O3 -o toy
+ clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
# Run
./toy