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 "CGDebugInfo.h"
16 #include "CodeGenModule.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 "clang/Frontend/CodeGenOptions.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
28 using namespace clang;
31 class CodeGeneratorImpl : public CodeGenerator {
32 DiagnosticsEngine &Diags;
33 std::unique_ptr<const llvm::DataLayout> TD;
35 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
37 unsigned HandlingTopLevelDecls;
38 struct HandlingTopLevelDeclRAII {
39 CodeGeneratorImpl &Self;
40 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
41 ++Self.HandlingTopLevelDecls;
43 ~HandlingTopLevelDeclRAII() {
44 if (--Self.HandlingTopLevelDecls == 0)
45 Self.EmitDeferredDecls();
49 CoverageSourceInfo *CoverageInfo;
52 std::unique_ptr<llvm::Module> M;
53 std::unique_ptr<CodeGen::CodeGenModule> Builder;
56 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
59 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
60 const CodeGenOptions &CGO, llvm::LLVMContext& C,
61 CoverageSourceInfo *CoverageInfo = nullptr)
62 : Diags(diags), Ctx(nullptr), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
63 CoverageInfo(CoverageInfo),
64 M(new llvm::Module(ModuleName, C)) {}
66 virtual ~CodeGeneratorImpl() {
67 // There should normally not be any leftover inline method definitions.
68 assert(DeferredInlineMethodDefinitions.empty() ||
69 Diags.hasErrorOccurred());
72 llvm::Module* GetModule() override {
76 const Decl *GetDeclForMangledName(StringRef MangledName) override {
78 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
80 const Decl *D = Result.getCanonicalDecl().getDecl();
81 if (auto FD = dyn_cast<FunctionDecl>(D)) {
84 } else if (auto TD = dyn_cast<TagDecl>(D)) {
85 if (auto Def = TD->getDefinition())
91 llvm::Module *ReleaseModule() override { return M.release(); }
93 void Initialize(ASTContext &Context) override {
96 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
97 M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
98 TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
99 Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
100 Diags, CoverageInfo));
102 for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
103 HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
106 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
107 if (Diags.hasErrorOccurred())
110 Builder->HandleCXXStaticMemberVarInstantiation(VD);
113 bool HandleTopLevelDecl(DeclGroupRef DG) override {
114 if (Diags.hasErrorOccurred())
117 HandlingTopLevelDeclRAII HandlingDecl(*this);
119 // Make sure to emit all elements of a Decl.
120 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
121 Builder->EmitTopLevelDecl(*I);
126 void EmitDeferredDecls() {
127 if (DeferredInlineMethodDefinitions.empty())
130 // Emit any deferred inline method definitions. Note that more deferred
131 // methods may be added during this loop, since ASTConsumer callbacks
132 // can be invoked if AST inspection results in declarations being added.
133 HandlingTopLevelDeclRAII HandlingDecl(*this);
134 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
135 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
136 DeferredInlineMethodDefinitions.clear();
139 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
140 if (Diags.hasErrorOccurred())
143 assert(D->doesThisDeclarationHaveABody());
145 // We may want to emit this definition. However, that decision might be
146 // based on computing the linkage, and we have to defer that in case we
147 // are inside of something that will change the method's final linkage,
151 // void foo() { bar(); }
153 DeferredInlineMethodDefinitions.push_back(D);
155 // Provide some coverage mapping even for methods that aren't emitted.
156 // Don't do this for templated classes though, as they may not be
158 if (!D->getParent()->getDescribedClassTemplate())
159 Builder->AddDeferredUnusedCoverageMapping(D);
162 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
163 /// to (e.g. struct, union, enum, class) is completed. This allows the
164 /// client hack on the type, which can occur at any point in the file
165 /// (because these can be defined in declspecs).
166 void HandleTagDeclDefinition(TagDecl *D) override {
167 if (Diags.hasErrorOccurred())
170 Builder->UpdateCompletedType(D);
172 // For MSVC compatibility, treat declarations of static data members with
173 // inline initializers as definitions.
174 if (Ctx->getLangOpts().MSVCCompat) {
175 for (Decl *Member : D->decls()) {
176 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
177 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
178 Ctx->DeclMustBeEmitted(VD)) {
179 Builder->EmitGlobal(VD);
186 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
187 if (Diags.hasErrorOccurred())
190 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
191 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
192 DI->completeRequiredType(RD);
195 void HandleTranslationUnit(ASTContext &Ctx) override {
196 if (Diags.hasErrorOccurred()) {
207 void CompleteTentativeDefinition(VarDecl *D) override {
208 if (Diags.hasErrorOccurred())
211 Builder->EmitTentativeDefinition(D);
214 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
215 if (Diags.hasErrorOccurred())
218 Builder->EmitVTable(RD, DefinitionRequired);
221 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
222 Builder->AppendLinkerOptions(Opts);
225 void HandleDetectMismatch(llvm::StringRef Name,
226 llvm::StringRef Value) override {
227 Builder->AddDetectMismatch(Name, Value);
230 void HandleDependentLibrary(llvm::StringRef Lib) override {
231 Builder->AddDependentLib(Lib);
236 void CodeGenerator::anchor() { }
238 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
239 const std::string& ModuleName,
240 const CodeGenOptions &CGO,
241 const TargetOptions &/*TO*/,
242 llvm::LLVMContext& C,
243 CoverageSourceInfo *CoverageInfo) {
244 return new CodeGeneratorImpl(Diags, ModuleName, CGO, C, CoverageInfo);