xref: /llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp (revision b214cbc7852fa1719c5d0bd3ccb9615481e03c55)
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     ASTContext *Ctx;
34     const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
35     const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
36     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
37 
38     unsigned HandlingTopLevelDecls;
39     struct HandlingTopLevelDeclRAII {
40       CodeGeneratorImpl &Self;
41       HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
42         ++Self.HandlingTopLevelDecls;
43       }
44       ~HandlingTopLevelDeclRAII() {
45         if (--Self.HandlingTopLevelDecls == 0)
46           Self.EmitDeferredDecls();
47       }
48     };
49 
50     CoverageSourceInfo *CoverageInfo;
51 
52   protected:
53     std::unique_ptr<llvm::Module> M;
54     std::unique_ptr<CodeGen::CodeGenModule> Builder;
55 
56   private:
57     SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
58 
59   public:
60     CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
61                       const HeaderSearchOptions &HSO,
62                       const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
63                       llvm::LLVMContext &C,
64                       CoverageSourceInfo *CoverageInfo = nullptr)
65         : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
66           PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
67           CoverageInfo(CoverageInfo),
68           M(new llvm::Module(ModuleName, C)) {}
69 
70     ~CodeGeneratorImpl() override {
71       // There should normally not be any leftover inline method definitions.
72       assert(DeferredInlineMethodDefinitions.empty() ||
73              Diags.hasErrorOccurred());
74     }
75 
76     llvm::Module* GetModule() override {
77       return M.get();
78     }
79 
80     const Decl *GetDeclForMangledName(StringRef MangledName) override {
81       GlobalDecl Result;
82       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
83         return nullptr;
84       const Decl *D = Result.getCanonicalDecl().getDecl();
85       if (auto FD = dyn_cast<FunctionDecl>(D)) {
86         if (FD->hasBody(FD))
87           return FD;
88       } else if (auto TD = dyn_cast<TagDecl>(D)) {
89         if (auto Def = TD->getDefinition())
90           return Def;
91       }
92       return D;
93     }
94 
95     llvm::Module *ReleaseModule() override { return M.release(); }
96 
97     void Initialize(ASTContext &Context) override {
98       Ctx = &Context;
99 
100       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
101       M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
102       Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
103                                                PreprocessorOpts, CodeGenOpts,
104                                                *M, Diags, CoverageInfo));
105 
106       for (auto &&Lib : CodeGenOpts.DependentLibraries)
107         Builder->AddDependentLib(Lib);
108       for (auto &&Opt : CodeGenOpts.LinkerOptions)
109         Builder->AppendLinkerOptions(Opt);
110     }
111 
112     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
113       if (Diags.hasErrorOccurred())
114         return;
115 
116       Builder->HandleCXXStaticMemberVarInstantiation(VD);
117     }
118 
119     bool HandleTopLevelDecl(DeclGroupRef DG) override {
120       if (Diags.hasErrorOccurred())
121         return true;
122 
123       HandlingTopLevelDeclRAII HandlingDecl(*this);
124 
125       // Make sure to emit all elements of a Decl.
126       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
127         Builder->EmitTopLevelDecl(*I);
128 
129       return true;
130     }
131 
132     void EmitDeferredDecls() {
133       if (DeferredInlineMethodDefinitions.empty())
134         return;
135 
136       // Emit any deferred inline method definitions. Note that more deferred
137       // methods may be added during this loop, since ASTConsumer callbacks
138       // can be invoked if AST inspection results in declarations being added.
139       HandlingTopLevelDeclRAII HandlingDecl(*this);
140       for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
141         Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
142       DeferredInlineMethodDefinitions.clear();
143     }
144 
145     void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
146       if (Diags.hasErrorOccurred())
147         return;
148 
149       assert(D->doesThisDeclarationHaveABody());
150 
151       // We may want to emit this definition. However, that decision might be
152       // based on computing the linkage, and we have to defer that in case we
153       // are inside of something that will change the method's final linkage,
154       // e.g.
155       //   typedef struct {
156       //     void bar();
157       //     void foo() { bar(); }
158       //   } A;
159       DeferredInlineMethodDefinitions.push_back(D);
160 
161       // Provide some coverage mapping even for methods that aren't emitted.
162       // Don't do this for templated classes though, as they may not be
163       // instantiable.
164       if (!D->getParent()->getDescribedClassTemplate())
165         Builder->AddDeferredUnusedCoverageMapping(D);
166     }
167 
168     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
169     /// to (e.g. struct, union, enum, class) is completed. This allows the
170     /// client hack on the type, which can occur at any point in the file
171     /// (because these can be defined in declspecs).
172     void HandleTagDeclDefinition(TagDecl *D) override {
173       if (Diags.hasErrorOccurred())
174         return;
175 
176       Builder->UpdateCompletedType(D);
177 
178       // For MSVC compatibility, treat declarations of static data members with
179       // inline initializers as definitions.
180       if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
181         for (Decl *Member : D->decls()) {
182           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
183             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
184                 Ctx->DeclMustBeEmitted(VD)) {
185               Builder->EmitGlobal(VD);
186             }
187           }
188         }
189       }
190       // For OpenMP emit declare reduction functions, if required.
191       if (Ctx->getLangOpts().OpenMP) {
192         for (Decl *Member : D->decls()) {
193           if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
194             if (Ctx->DeclMustBeEmitted(DRD))
195               Builder->EmitGlobal(DRD);
196           }
197         }
198       }
199     }
200 
201     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
202       if (Diags.hasErrorOccurred())
203         return;
204 
205       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
206         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
207           DI->completeRequiredType(RD);
208     }
209 
210     void HandleTranslationUnit(ASTContext &Ctx) override {
211       // Release the Builder when there is no error.
212       if (!Diags.hasErrorOccurred() && Builder)
213         Builder->Release();
214 
215       // If there are errors before or when releasing the Builder, reset
216       // the module to stop here before invoking the backend.
217       if (Diags.hasErrorOccurred()) {
218         if (Builder)
219           Builder->clear();
220         M.reset();
221         return;
222       }
223     }
224 
225     void AssignInheritanceModel(CXXRecordDecl *RD) override {
226       if (Diags.hasErrorOccurred())
227         return;
228 
229       Builder->RefreshTypeCacheForClass(RD);
230     }
231 
232     void CompleteTentativeDefinition(VarDecl *D) override {
233       if (Diags.hasErrorOccurred())
234         return;
235 
236       Builder->EmitTentativeDefinition(D);
237     }
238 
239     void HandleVTable(CXXRecordDecl *RD) override {
240       if (Diags.hasErrorOccurred())
241         return;
242 
243       Builder->EmitVTable(RD);
244     }
245   };
246 }
247 
248 void CodeGenerator::anchor() { }
249 
250 CodeGenerator *clang::CreateLLVMCodeGen(
251     DiagnosticsEngine &Diags, const std::string &ModuleName,
252     const HeaderSearchOptions &HeaderSearchOpts,
253     const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
254     llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
255   return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
256                                PreprocessorOpts, CGO, C, CoverageInfo);
257 }
258