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 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 namespace {
33   class CodeGeneratorImpl : public CodeGenerator {
34     DiagnosticsEngine &Diags;
35     ASTContext *Ctx;
36     const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37     const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
38     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
39 
40     unsigned HandlingTopLevelDecls;
41 
42     /// Use this when emitting decls to block re-entrant decl emission. It will
43     /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
44     /// emission must be deferred longer, like at the end of a tag definition.
45     struct HandlingTopLevelDeclRAII {
46       CodeGeneratorImpl &Self;
47       bool EmitDeferred;
HandlingTopLevelDeclRAII__anon765d2f370111::CodeGeneratorImpl::HandlingTopLevelDeclRAII48       HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49                                bool EmitDeferred = true)
50           : Self(Self), EmitDeferred(EmitDeferred) {
51         ++Self.HandlingTopLevelDecls;
52       }
~HandlingTopLevelDeclRAII__anon765d2f370111::CodeGeneratorImpl::HandlingTopLevelDeclRAII53       ~HandlingTopLevelDeclRAII() {
54         unsigned Level = --Self.HandlingTopLevelDecls;
55         if (Level == 0 && EmitDeferred)
56           Self.EmitDeferredDecls();
57       }
58     };
59 
60     CoverageSourceInfo *CoverageInfo;
61 
62   protected:
63     std::unique_ptr<llvm::Module> M;
64     std::unique_ptr<CodeGen::CodeGenModule> Builder;
65 
66   private:
67     SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
68 
69   public:
CodeGeneratorImpl(DiagnosticsEngine & diags,llvm::StringRef ModuleName,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo=nullptr)70     CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
71                       const HeaderSearchOptions &HSO,
72                       const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73                       llvm::LLVMContext &C,
74                       CoverageSourceInfo *CoverageInfo = nullptr)
75         : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76           PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
77           CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78       C.setDiscardValueNames(CGO.DiscardValueNames);
79     }
80 
~CodeGeneratorImpl()81     ~CodeGeneratorImpl() override {
82       // There should normally not be any leftover inline method definitions.
83       assert(DeferredInlineMethodDefinitions.empty() ||
84              Diags.hasErrorOccurred());
85     }
86 
CGM()87     CodeGenModule &CGM() {
88       return *Builder;
89     }
90 
GetModule()91     llvm::Module *GetModule() {
92       return M.get();
93     }
94 
getCGDebugInfo()95     CGDebugInfo *getCGDebugInfo() {
96       return Builder->getModuleDebugInfo();
97     }
98 
ReleaseModule()99     llvm::Module *ReleaseModule() {
100       return M.release();
101     }
102 
GetDeclForMangledName(StringRef MangledName)103     const Decl *GetDeclForMangledName(StringRef MangledName) {
104       GlobalDecl Result;
105       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
106         return nullptr;
107       const Decl *D = Result.getCanonicalDecl().getDecl();
108       if (auto FD = dyn_cast<FunctionDecl>(D)) {
109         if (FD->hasBody(FD))
110           return FD;
111       } else if (auto TD = dyn_cast<TagDecl>(D)) {
112         if (auto Def = TD->getDefinition())
113           return Def;
114       }
115       return D;
116     }
117 
GetAddrOfGlobal(GlobalDecl global,bool isForDefinition)118     llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
119       return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
120     }
121 
StartModule(llvm::StringRef ModuleName,llvm::LLVMContext & C)122     llvm::Module *StartModule(llvm::StringRef ModuleName,
123                               llvm::LLVMContext &C) {
124       assert(!M && "Replacing existing Module?");
125       M.reset(new llvm::Module(ModuleName, C));
126       Initialize(*Ctx);
127       return M.get();
128     }
129 
Initialize(ASTContext & Context)130     void Initialize(ASTContext &Context) override {
131       Ctx = &Context;
132 
133       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
134       M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
135       Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
136                                                PreprocessorOpts, CodeGenOpts,
137                                                *M, Diags, CoverageInfo));
138 
139       for (auto &&Lib : CodeGenOpts.DependentLibraries)
140         Builder->AddDependentLib(Lib);
141       for (auto &&Opt : CodeGenOpts.LinkerOptions)
142         Builder->AppendLinkerOptions(Opt);
143     }
144 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)145     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
146       if (Diags.hasErrorOccurred())
147         return;
148 
149       Builder->HandleCXXStaticMemberVarInstantiation(VD);
150     }
151 
HandleTopLevelDecl(DeclGroupRef DG)152     bool HandleTopLevelDecl(DeclGroupRef DG) override {
153       if (Diags.hasErrorOccurred())
154         return true;
155 
156       HandlingTopLevelDeclRAII HandlingDecl(*this);
157 
158       // Make sure to emit all elements of a Decl.
159       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
160         Builder->EmitTopLevelDecl(*I);
161 
162       return true;
163     }
164 
EmitDeferredDecls()165     void EmitDeferredDecls() {
166       if (DeferredInlineMethodDefinitions.empty())
167         return;
168 
169       // Emit any deferred inline method definitions. Note that more deferred
170       // methods may be added during this loop, since ASTConsumer callbacks
171       // can be invoked if AST inspection results in declarations being added.
172       HandlingTopLevelDeclRAII HandlingDecl(*this);
173       for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
174         Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
175       DeferredInlineMethodDefinitions.clear();
176     }
177 
HandleInlineFunctionDefinition(FunctionDecl * D)178     void HandleInlineFunctionDefinition(FunctionDecl *D) override {
179       if (Diags.hasErrorOccurred())
180         return;
181 
182       assert(D->doesThisDeclarationHaveABody());
183 
184       // Handle friend functions.
185       if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
186         if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
187             && !D->getLexicalDeclContext()->isDependentContext())
188           Builder->EmitTopLevelDecl(D);
189         return;
190       }
191 
192       // Otherwise, must be a method.
193       auto MD = cast<CXXMethodDecl>(D);
194 
195       // We may want to emit this definition. However, that decision might be
196       // based on computing the linkage, and we have to defer that in case we
197       // are inside of something that will change the method's final linkage,
198       // e.g.
199       //   typedef struct {
200       //     void bar();
201       //     void foo() { bar(); }
202       //   } A;
203       DeferredInlineMethodDefinitions.push_back(MD);
204 
205       // Provide some coverage mapping even for methods that aren't emitted.
206       // Don't do this for templated classes though, as they may not be
207       // instantiable.
208       if (!MD->getParent()->isDependentContext())
209         Builder->AddDeferredUnusedCoverageMapping(MD);
210     }
211 
212     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
213     /// to (e.g. struct, union, enum, class) is completed. This allows the
214     /// client hack on the type, which can occur at any point in the file
215     /// (because these can be defined in declspecs).
HandleTagDeclDefinition(TagDecl * D)216     void HandleTagDeclDefinition(TagDecl *D) override {
217       if (Diags.hasErrorOccurred())
218         return;
219 
220       // Don't allow re-entrant calls to CodeGen triggered by PCH
221       // deserialization to emit deferred decls.
222       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
223 
224       Builder->UpdateCompletedType(D);
225 
226       // For MSVC compatibility, treat declarations of static data members with
227       // inline initializers as definitions.
228       if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
229         for (Decl *Member : D->decls()) {
230           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
231             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
232                 Ctx->DeclMustBeEmitted(VD)) {
233               Builder->EmitGlobal(VD);
234             }
235           }
236         }
237       }
238       // For OpenMP emit declare reduction functions, if required.
239       if (Ctx->getLangOpts().OpenMP) {
240         for (Decl *Member : D->decls()) {
241           if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
242             if (Ctx->DeclMustBeEmitted(DRD))
243               Builder->EmitGlobal(DRD);
244           }
245         }
246       }
247     }
248 
HandleTagDeclRequiredDefinition(const TagDecl * D)249     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
250       if (Diags.hasErrorOccurred())
251         return;
252 
253       // Don't allow re-entrant calls to CodeGen triggered by PCH
254       // deserialization to emit deferred decls.
255       HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
256 
257       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
258         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
259           DI->completeRequiredType(RD);
260     }
261 
HandleTranslationUnit(ASTContext & Ctx)262     void HandleTranslationUnit(ASTContext &Ctx) override {
263       // Release the Builder when there is no error.
264       if (!Diags.hasErrorOccurred() && Builder)
265         Builder->Release();
266 
267       // If there are errors before or when releasing the Builder, reset
268       // the module to stop here before invoking the backend.
269       if (Diags.hasErrorOccurred()) {
270         if (Builder)
271           Builder->clear();
272         M.reset();
273         return;
274       }
275     }
276 
AssignInheritanceModel(CXXRecordDecl * RD)277     void AssignInheritanceModel(CXXRecordDecl *RD) override {
278       if (Diags.hasErrorOccurred())
279         return;
280 
281       Builder->RefreshTypeCacheForClass(RD);
282     }
283 
CompleteTentativeDefinition(VarDecl * D)284     void CompleteTentativeDefinition(VarDecl *D) override {
285       if (Diags.hasErrorOccurred())
286         return;
287 
288       Builder->EmitTentativeDefinition(D);
289     }
290 
HandleVTable(CXXRecordDecl * RD)291     void HandleVTable(CXXRecordDecl *RD) override {
292       if (Diags.hasErrorOccurred())
293         return;
294 
295       Builder->EmitVTable(RD);
296     }
297   };
298 }
299 
anchor()300 void CodeGenerator::anchor() { }
301 
CGM()302 CodeGenModule &CodeGenerator::CGM() {
303   return static_cast<CodeGeneratorImpl*>(this)->CGM();
304 }
305 
GetModule()306 llvm::Module *CodeGenerator::GetModule() {
307   return static_cast<CodeGeneratorImpl*>(this)->GetModule();
308 }
309 
ReleaseModule()310 llvm::Module *CodeGenerator::ReleaseModule() {
311   return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
312 }
313 
getCGDebugInfo()314 CGDebugInfo *CodeGenerator::getCGDebugInfo() {
315   return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
316 }
317 
GetDeclForMangledName(llvm::StringRef name)318 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
319   return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
320 }
321 
GetAddrOfGlobal(GlobalDecl global,bool isForDefinition)322 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
323                                                bool isForDefinition) {
324   return static_cast<CodeGeneratorImpl*>(this)
325            ->GetAddrOfGlobal(global, isForDefinition);
326 }
327 
StartModule(llvm::StringRef ModuleName,llvm::LLVMContext & C)328 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
329                                          llvm::LLVMContext &C) {
330   return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
331 }
332 
CreateLLVMCodeGen(DiagnosticsEngine & Diags,llvm::StringRef ModuleName,const HeaderSearchOptions & HeaderSearchOpts,const PreprocessorOptions & PreprocessorOpts,const CodeGenOptions & CGO,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo)333 CodeGenerator *clang::CreateLLVMCodeGen(
334     DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
335     const HeaderSearchOptions &HeaderSearchOpts,
336     const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
337     llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
338   return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
339                                PreprocessorOpts, CGO, C, CoverageInfo);
340 }
341