1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This builds an AST and converts it to LLVM Code.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
27 #include <memory>
28 using namespace clang;
29 
30 namespace {
31   class CodeGeneratorImpl : public CodeGenerator {
32     DiagnosticsEngine &Diags;
33     std::unique_ptr<const llvm::DataLayout> TD;
34     ASTContext *Ctx;
35     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
36 
37     unsigned HandlingTopLevelDecls;
38     struct HandlingTopLevelDeclRAII {
39       CodeGeneratorImpl &Self;
HandlingTopLevelDeclRAII__anon8d4184ed0111::CodeGeneratorImpl::HandlingTopLevelDeclRAII40       HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
41         ++Self.HandlingTopLevelDecls;
42       }
~HandlingTopLevelDeclRAII__anon8d4184ed0111::CodeGeneratorImpl::HandlingTopLevelDeclRAII43       ~HandlingTopLevelDeclRAII() {
44         if (--Self.HandlingTopLevelDecls == 0)
45           Self.EmitDeferredDecls();
46       }
47     };
48 
49     CoverageSourceInfo *CoverageInfo;
50 
51   protected:
52     std::unique_ptr<llvm::Module> M;
53     std::unique_ptr<CodeGen::CodeGenModule> Builder;
54 
55   private:
56     SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
57 
58   public:
CodeGeneratorImpl(DiagnosticsEngine & diags,const std::string & ModuleName,const CodeGenOptions & CGO,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo=nullptr)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)) {}
65 
~CodeGeneratorImpl()66     ~CodeGeneratorImpl() override {
67       // There should normally not be any leftover inline method definitions.
68       assert(DeferredInlineMethodDefinitions.empty() ||
69              Diags.hasErrorOccurred());
70     }
71 
GetModule()72     llvm::Module* GetModule() override {
73       return M.get();
74     }
75 
GetDeclForMangledName(StringRef MangledName)76     const Decl *GetDeclForMangledName(StringRef MangledName) override {
77       GlobalDecl Result;
78       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
79         return nullptr;
80       const Decl *D = Result.getCanonicalDecl().getDecl();
81       if (auto FD = dyn_cast<FunctionDecl>(D)) {
82         if (FD->hasBody(FD))
83           return FD;
84       } else if (auto TD = dyn_cast<TagDecl>(D)) {
85         if (auto Def = TD->getDefinition())
86           return Def;
87       }
88       return D;
89     }
90 
ReleaseModule()91     llvm::Module *ReleaseModule() override { return M.release(); }
92 
Initialize(ASTContext & Context)93     void Initialize(ASTContext &Context) override {
94       Ctx = &Context;
95 
96       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
97       M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
98       TD.reset(
99           new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
100       Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
101                                                Diags, CoverageInfo));
102 
103       for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
104         HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
105     }
106 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)107     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
108       if (Diags.hasErrorOccurred())
109         return;
110 
111       Builder->HandleCXXStaticMemberVarInstantiation(VD);
112     }
113 
HandleTopLevelDecl(DeclGroupRef DG)114     bool HandleTopLevelDecl(DeclGroupRef DG) override {
115       if (Diags.hasErrorOccurred())
116         return true;
117 
118       HandlingTopLevelDeclRAII HandlingDecl(*this);
119 
120       // Make sure to emit all elements of a Decl.
121       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
122         Builder->EmitTopLevelDecl(*I);
123 
124       return true;
125     }
126 
EmitDeferredDecls()127     void EmitDeferredDecls() {
128       if (DeferredInlineMethodDefinitions.empty())
129         return;
130 
131       // Emit any deferred inline method definitions. Note that more deferred
132       // methods may be added during this loop, since ASTConsumer callbacks
133       // can be invoked if AST inspection results in declarations being added.
134       HandlingTopLevelDeclRAII HandlingDecl(*this);
135       for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
136         Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
137       DeferredInlineMethodDefinitions.clear();
138     }
139 
HandleInlineMethodDefinition(CXXMethodDecl * D)140     void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
141       if (Diags.hasErrorOccurred())
142         return;
143 
144       assert(D->doesThisDeclarationHaveABody());
145 
146       // We may want to emit this definition. However, that decision might be
147       // based on computing the linkage, and we have to defer that in case we
148       // are inside of something that will change the method's final linkage,
149       // e.g.
150       //   typedef struct {
151       //     void bar();
152       //     void foo() { bar(); }
153       //   } A;
154       DeferredInlineMethodDefinitions.push_back(D);
155 
156       // Provide some coverage mapping even for methods that aren't emitted.
157       // Don't do this for templated classes though, as they may not be
158       // instantiable.
159       if (!D->getParent()->getDescribedClassTemplate())
160         Builder->AddDeferredUnusedCoverageMapping(D);
161     }
162 
163     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
164     /// to (e.g. struct, union, enum, class) is completed. This allows the
165     /// client hack on the type, which can occur at any point in the file
166     /// (because these can be defined in declspecs).
HandleTagDeclDefinition(TagDecl * D)167     void HandleTagDeclDefinition(TagDecl *D) override {
168       if (Diags.hasErrorOccurred())
169         return;
170 
171       Builder->UpdateCompletedType(D);
172 
173       // For MSVC compatibility, treat declarations of static data members with
174       // inline initializers as definitions.
175       if (Ctx->getLangOpts().MSVCCompat) {
176         for (Decl *Member : D->decls()) {
177           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
178             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
179                 Ctx->DeclMustBeEmitted(VD)) {
180               Builder->EmitGlobal(VD);
181             }
182           }
183         }
184       }
185     }
186 
HandleTagDeclRequiredDefinition(const TagDecl * D)187     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
188       if (Diags.hasErrorOccurred())
189         return;
190 
191       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
192         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
193           DI->completeRequiredType(RD);
194     }
195 
HandleTranslationUnit(ASTContext & Ctx)196     void HandleTranslationUnit(ASTContext &Ctx) override {
197       if (Diags.hasErrorOccurred()) {
198         if (Builder)
199           Builder->clear();
200         M.reset();
201         return;
202       }
203 
204       if (Builder)
205         Builder->Release();
206     }
207 
CompleteTentativeDefinition(VarDecl * D)208     void CompleteTentativeDefinition(VarDecl *D) override {
209       if (Diags.hasErrorOccurred())
210         return;
211 
212       Builder->EmitTentativeDefinition(D);
213     }
214 
HandleVTable(CXXRecordDecl * RD)215     void HandleVTable(CXXRecordDecl *RD) override {
216       if (Diags.hasErrorOccurred())
217         return;
218 
219       Builder->EmitVTable(RD);
220     }
221 
HandleLinkerOptionPragma(llvm::StringRef Opts)222     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
223       Builder->AppendLinkerOptions(Opts);
224     }
225 
HandleDetectMismatch(llvm::StringRef Name,llvm::StringRef Value)226     void HandleDetectMismatch(llvm::StringRef Name,
227                               llvm::StringRef Value) override {
228       Builder->AddDetectMismatch(Name, Value);
229     }
230 
HandleDependentLibrary(llvm::StringRef Lib)231     void HandleDependentLibrary(llvm::StringRef Lib) override {
232       Builder->AddDependentLib(Lib);
233     }
234   };
235 }
236 
anchor()237 void CodeGenerator::anchor() { }
238 
CreateLLVMCodeGen(DiagnosticsEngine & Diags,const std::string & ModuleName,const CodeGenOptions & CGO,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo)239 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
240                                         const std::string& ModuleName,
241                                         const CodeGenOptions &CGO,
242                                         llvm::LLVMContext& C,
243                                         CoverageSourceInfo *CoverageInfo) {
244   return new CodeGeneratorImpl(Diags, ModuleName, CGO, C, CoverageInfo);
245 }
246