Improve debuggability of LLVM library
When the LLVM AST we have generated is incorrect, this usually results in either (i) a segmentation fault when writing the bitcode/readable IR to a file or (ii) a bitcode file that cannot be parsed, and therefore cannot be disassembled to a readable ll file. In such cases it could be useful to get some feedback. This is purely meant to make developing the code generator easier: the goal is to get more information why the newly generated IR is incorrect, not to assist the end user in any way.
I stumbled across two bits of functionality that can be helpful:
-
LLVMVerifyModule/LLVMVerifyFunction - Converting functions to dot graphs
1 can be used like this (though in this case, LLVMPrintModuleToFile has no issues):
#include <llvm-c/Core.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/BitWriter.h>
#include <stdio.h>
int main(int argc, char const *argv[]) {
LLVMBuilderRef builder = LLVMCreateBuilder();
LLVMModuleRef mod = LLVMModuleCreateWithName("my_module");
LLVMTypeRef ret_type = LLVMFunctionType(LLVMInt32Type(), NULL, 0, 0);
LLVMValueRef f = LLVMAddFunction(mod, "f", ret_type);
LLVMBasicBlockRef entry = LLVMAppendBasicBlock(f, "entry");
LLVMPositionBuilderAtEnd(builder, entry);
LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 0, 1));
LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 0, 1));
char *error = NULL;
LLVMVerifyModule(mod, LLVMPrintMessageAction, &error);
LLVMDisposeMessage(error);
if (LLVMWriteBitcodeToFile(mod, "x.bc") != 0)
fprintf(stderr, "error writing bitcode to file\n");
if (LLVMPrintModuleToFile(mod, "x.ll", NULL) != 0)
fprintf(stderr, "error writing module to file\n");
LLVMDisposeBuilder(builder);
}
2 is available in opt with opt-20 -passes='print<memoryssa>' -dot-cfg-mssa=x.dot x.bc >/dev/null, or opt-20 -passes=dot-cfg x.bc >/dev/null and the various alternatives listed there. These must be available from the C API too, but I haven't looked into it.
Just something to be aware of that it's possible and consider implementing the next time something like this happens.