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/Frontend/CompileOptions.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/Support/Compiler.h"
26 #include "llvm/ADT/OwningPtr.h"
27 using namespace clang
;
31 class VISIBILITY_HIDDEN CodeGeneratorImpl
: public CodeGenerator
{
33 llvm::OwningPtr
<const llvm::TargetData
> TD
;
35 const CompileOptions CompileOpts
; // Intentionally copied in.
37 llvm::OwningPtr
<llvm::Module
> M
;
38 llvm::OwningPtr
<CodeGen::CodeGenModule
> Builder
;
40 CodeGeneratorImpl(Diagnostic
&diags
, const std::string
& ModuleName
,
41 const CompileOptions
&CO
, llvm::LLVMContext
& C
)
42 : Diags(diags
), CompileOpts(CO
), M(new llvm::Module(ModuleName
, C
)) {}
44 virtual ~CodeGeneratorImpl() {}
46 virtual llvm::Module
* GetModule() {
50 virtual llvm::Module
* ReleaseModule() {
54 virtual void Initialize(ASTContext
&Context
) {
57 M
->setTargetTriple(Ctx
->Target
.getTargetTriple());
58 M
->setDataLayout(Ctx
->Target
.getTargetDescription());
59 TD
.reset(new llvm::TargetData(Ctx
->Target
.getTargetDescription()));
60 Builder
.reset(new CodeGen::CodeGenModule(Context
, CompileOpts
,
64 virtual void HandleTopLevelDecl(DeclGroupRef DG
) {
65 // Make sure to emit all elements of a Decl.
66 for (DeclGroupRef::iterator I
= DG
.begin(), E
= DG
.end(); I
!= E
; ++I
)
67 Builder
->EmitTopLevelDecl(*I
);
70 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
71 /// to (e.g. struct, union, enum, class) is completed. This allows the
72 /// client hack on the type, which can occur at any point in the file
73 /// (because these can be defined in declspecs).
74 virtual void HandleTagDeclDefinition(TagDecl
*D
) {
75 Builder
->UpdateCompletedType(D
);
78 virtual void HandleTranslationUnit(ASTContext
&Ctx
) {
79 if (Diags
.hasErrorOccurred()) {
88 virtual void CompleteTentativeDefinition(VarDecl
*D
) {
89 if (Diags
.hasErrorOccurred())
92 Builder
->EmitTentativeDefinition(D
);
97 CodeGenerator
*clang::CreateLLVMCodeGen(Diagnostic
&Diags
,
98 const std::string
& ModuleName
,
99 const CompileOptions
&CO
,
100 llvm::LLVMContext
& C
) {
101 return new CodeGeneratorImpl(Diags
, ModuleName
, CO
, C
);