1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This builds an AST and converts it to LLVM Code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/CodeGen/ModuleBuilder.h"
15 #include "CodeGenModule.h"
16 #include "clang/CodeGen/CodeGenOptions.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/ADT/OwningPtr.h"
26 using namespace clang;
29 class CodeGeneratorImpl : public CodeGenerator {
31 llvm::OwningPtr<const llvm::TargetData> TD;
32 const llvm::TargetMachine &TM;
34 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
36 llvm::OwningPtr<llvm::Module> M;
37 llvm::OwningPtr<CodeGen::CodeGenModule> Builder;
39 CodeGeneratorImpl(Diagnostic &diags, const std::string& ModuleName,
40 const CodeGenOptions &CGO,
41 const llvm::TargetMachine &TM,
43 : Diags(diags), TM(TM), CodeGenOpts(CGO),
44 M(new llvm::Module(ModuleName, C)) {}
46 virtual ~CodeGeneratorImpl() {}
48 virtual llvm::Module* GetModule() {
52 virtual llvm::Module* ReleaseModule() {
56 virtual void Initialize(ASTContext &Context) {
59 M->setTargetTriple(Ctx->Target.getTriple().getTriple());
60 M->setDataLayout(Ctx->Target.getTargetDescription());
61 TD.reset(new llvm::TargetData(Ctx->Target.getTargetDescription()));
62 Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts,
66 virtual void HandleTopLevelDecl(DeclGroupRef DG) {
67 // Make sure to emit all elements of a Decl.
68 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
69 Builder->EmitTopLevelDecl(*I);
72 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
73 /// to (e.g. struct, union, enum, class) is completed. This allows the
74 /// client hack on the type, which can occur at any point in the file
75 /// (because these can be defined in declspecs).
76 virtual void HandleTagDeclDefinition(TagDecl *D) {
77 Builder->UpdateCompletedType(D);
80 virtual void HandleTranslationUnit(ASTContext &Ctx) {
81 if (Diags.hasErrorOccurred()) {
90 virtual void CompleteTentativeDefinition(VarDecl *D) {
91 if (Diags.hasErrorOccurred())
94 Builder->EmitTentativeDefinition(D);
99 CodeGenerator *clang::CreateLLVMCodeGen(Diagnostic &Diags,
100 const std::string& ModuleName,
101 const CodeGenOptions &CGO,
102 const llvm::TargetMachine &Machine,
103 llvm::LLVMContext& C) {
104 return new CodeGeneratorImpl(Diags, ModuleName, CGO, Machine, C);