xref: /llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp (revision cf08ff50dd35e1a75d3237b2e297683922a9518d)
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   protected:
37     std::unique_ptr<llvm::Module> M;
38     std::unique_ptr<CodeGen::CodeGenModule> Builder;
39 
40   public:
41     CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
42                       const CodeGenOptions &CGO, llvm::LLVMContext& C)
43       : Diags(diags), CodeGenOpts(CGO),
44         M(new llvm::Module(ModuleName, C)) {}
45 
46     virtual ~CodeGeneratorImpl() {}
47 
48     llvm::Module* GetModule() override {
49       return M.get();
50     }
51 
52     const Decl *GetDeclForMangledName(StringRef MangledName) override {
53       GlobalDecl Result;
54       if (!Builder->lookupRepresentativeDecl(MangledName, Result))
55         return nullptr;
56       const Decl *D = Result.getCanonicalDecl().getDecl();
57       if (auto FD = dyn_cast<FunctionDecl>(D)) {
58         if (FD->hasBody(FD))
59           return FD;
60       } else if (auto TD = dyn_cast<TagDecl>(D)) {
61         if (auto Def = TD->getDefinition())
62           return Def;
63       }
64       return D;
65     }
66 
67     llvm::Module *ReleaseModule() override { return M.release(); }
68 
69     void Initialize(ASTContext &Context) override {
70       Ctx = &Context;
71 
72       M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
73       M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
74       TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
75       Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
76                                                Diags));
77 
78       for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
79         HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
80     }
81 
82     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
83       if (Diags.hasErrorOccurred())
84         return;
85 
86       Builder->HandleCXXStaticMemberVarInstantiation(VD);
87     }
88 
89     bool HandleTopLevelDecl(DeclGroupRef DG) override {
90       if (Diags.hasErrorOccurred())
91         return true;
92 
93       // Make sure to emit all elements of a Decl.
94       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
95         Builder->EmitTopLevelDecl(*I);
96 
97       // Emit any deferred inline method definitions. Note that more deferred
98       // methods may be added during this loop.
99       while (!DeferredInlineMethodDefinitions.empty()) {
100         CXXMethodDecl *MD = DeferredInlineMethodDefinitions.back();
101         DeferredInlineMethodDefinitions.pop_back();
102         Builder->EmitTopLevelDecl(MD);
103       }
104 
105       return true;
106     }
107 
108     void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
109       if (Diags.hasErrorOccurred())
110         return;
111 
112       assert(D->doesThisDeclarationHaveABody());
113 
114       // We may want to emit this definition. However, that decision might be
115       // based on computing the linkage, and we have to defer that in case we
116       // are inside of something that will change the method's final linkage,
117       // e.g.
118       //   typedef struct {
119       //     void bar();
120       //     void foo() { bar(); }
121       //   } A;
122       DeferredInlineMethodDefinitions.push_back(D);
123     }
124 
125     /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
126     /// to (e.g. struct, union, enum, class) is completed. This allows the
127     /// client hack on the type, which can occur at any point in the file
128     /// (because these can be defined in declspecs).
129     void HandleTagDeclDefinition(TagDecl *D) override {
130       if (Diags.hasErrorOccurred())
131         return;
132 
133       Builder->UpdateCompletedType(D);
134 
135       // For MSVC compatibility, treat declarations of static data members with
136       // inline initializers as definitions.
137       if (Ctx->getLangOpts().MSVCCompat) {
138         for (Decl *Member : D->decls()) {
139           if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
140             if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
141                 Ctx->DeclMustBeEmitted(VD)) {
142               Builder->EmitGlobal(VD);
143             }
144           }
145         }
146       }
147     }
148 
149     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
150       if (Diags.hasErrorOccurred())
151         return;
152 
153       if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
154         if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
155           DI->completeRequiredType(RD);
156     }
157 
158     void HandleTranslationUnit(ASTContext &Ctx) override {
159       if (Diags.hasErrorOccurred()) {
160         if (Builder)
161           Builder->clear();
162         M.reset();
163         return;
164       }
165 
166       if (Builder)
167         Builder->Release();
168     }
169 
170     void CompleteTentativeDefinition(VarDecl *D) override {
171       if (Diags.hasErrorOccurred())
172         return;
173 
174       Builder->EmitTentativeDefinition(D);
175     }
176 
177     void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
178       if (Diags.hasErrorOccurred())
179         return;
180 
181       Builder->EmitVTable(RD, DefinitionRequired);
182     }
183 
184     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
185       Builder->AppendLinkerOptions(Opts);
186     }
187 
188     void HandleDetectMismatch(llvm::StringRef Name,
189                               llvm::StringRef Value) override {
190       Builder->AddDetectMismatch(Name, Value);
191     }
192 
193     void HandleDependentLibrary(llvm::StringRef Lib) override {
194       Builder->AddDependentLib(Lib);
195     }
196 
197   private:
198     std::vector<CXXMethodDecl *> DeferredInlineMethodDefinitions;
199   };
200 }
201 
202 void CodeGenerator::anchor() { }
203 
204 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
205                                         const std::string& ModuleName,
206                                         const CodeGenOptions &CGO,
207                                         const TargetOptions &/*TO*/,
208                                         llvm::LLVMContext& C) {
209   return new CodeGeneratorImpl(Diags, ModuleName, CGO, C);
210 }
211