[cfe-dev] Once I have an AST, how do I compile it?
Martin C.Martin
martin at martincmartin.com
Mon Apr 5 13:06:14 PDT 2010
I've managed to create a test program, included below for the curious,
which creates a super simple AST corresponding to "void foo() { }".
What do I call to generate code from it? Any pointers on what
classes/files to look at?
Best,
Martin
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/Parse/Scope.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetSelect.h"
using namespace clang;
using namespace std;
int main(int argc, char **argv) {
CompilerInstance MyCI;
MyCI.setLLVMContext(new llvm::LLVMContext);
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
TextDiagnosticBuffer DiagsBuffer;
Diagnostic Diags(&DiagsBuffer);
CompilerInvocation::CreateFromArgs(MyCI.getInvocation(), NULL, NULL,
Diags);
// Create the actual diagnostics engine.
MyCI.createDiagnostics(0, NULL);
if (!MyCI.hasDiagnostics())
return 1;
MyCI.createSourceManager();
MyCI.createFileManager();
// Create the target instance.
MyCI.setTarget(TargetInfo::CreateTargetInfo(MyCI.getDiagnostics(),
MyCI.getTargetOpts()));
MyCI.createPreprocessor();
MyCI.getPreprocessor();
MyCI.createASTContext();
// ************ Initialization finished. Now time for the fun.
ASTContext &context = MyCI.getASTContext();
DeclContext *DC = context.getTranslationUnitDecl();
IdentifierInfo &info =
MyCI.getPreprocessor().getIdentifierTable().get("foo");
DeclarationName myname(&info);
FunctionDecl *fd = FunctionDecl::Create(context, DC,
SourceLocation(), myname,
context.DoubleTy, NULL, FunctionDecl::None,
/* isInline = */ false, /* hasPrototype = */ false);
}
More information about the cfe-dev
mailing list