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;
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.
38 unsigned HandlingTopLevelDecls;
39 struct HandlingTopLevelDeclRAII {
40 CodeGeneratorImpl &Self;
41 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
42 ++Self.HandlingTopLevelDecls;
44 ~HandlingTopLevelDeclRAII() {
45 if (--Self.HandlingTopLevelDecls == 0)
46 Self.EmitDeferredDecls();
50 CoverageSourceInfo *CoverageInfo;
53 std::unique_ptr<llvm::Module> M;
54 std::unique_ptr<CodeGen::CodeGenModule> Builder;
57 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
60 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
61 const HeaderSearchOptions &HSO,
62 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
64 CoverageSourceInfo *CoverageInfo = nullptr)
65 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
66 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
67 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
68 C.setDiscardValueNames(CGO.DiscardValueNames);
71 ~CodeGeneratorImpl() override {
72 // There should normally not be any leftover inline method definitions.
73 assert(DeferredInlineMethodDefinitions.empty() ||
74 Diags.hasErrorOccurred());
77 llvm::Module* GetModule() override {
81 const Decl *GetDeclForMangledName(StringRef MangledName) override {
83 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
85 const Decl *D = Result.getCanonicalDecl().getDecl();
86 if (auto FD = dyn_cast<FunctionDecl>(D)) {
89 } else if (auto TD = dyn_cast<TagDecl>(D)) {
90 if (auto Def = TD->getDefinition())
96 llvm::Module *ReleaseModule() override { return M.release(); }
98 void Initialize(ASTContext &Context) override {
101 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
102 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
103 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
104 PreprocessorOpts, CodeGenOpts,
105 *M, Diags, CoverageInfo));
107 for (auto &&Lib : CodeGenOpts.DependentLibraries)
108 Builder->AddDependentLib(Lib);
109 for (auto &&Opt : CodeGenOpts.LinkerOptions)
110 Builder->AppendLinkerOptions(Opt);
113 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
114 if (Diags.hasErrorOccurred())
117 Builder->HandleCXXStaticMemberVarInstantiation(VD);
120 bool HandleTopLevelDecl(DeclGroupRef DG) override {
121 if (Diags.hasErrorOccurred())
124 HandlingTopLevelDeclRAII HandlingDecl(*this);
126 // Make sure to emit all elements of a Decl.
127 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
128 Builder->EmitTopLevelDecl(*I);
133 void EmitDeferredDecls() {
134 if (DeferredInlineMethodDefinitions.empty())
137 // Emit any deferred inline method definitions. Note that more deferred
138 // methods may be added during this loop, since ASTConsumer callbacks
139 // can be invoked if AST inspection results in declarations being added.
140 HandlingTopLevelDeclRAII HandlingDecl(*this);
141 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
142 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
143 DeferredInlineMethodDefinitions.clear();
146 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
147 if (Diags.hasErrorOccurred())
150 assert(D->doesThisDeclarationHaveABody());
152 // Handle friend functions.
153 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
154 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
155 && !D->getLexicalDeclContext()->isDependentContext())
156 Builder->EmitTopLevelDecl(D);
160 // Otherwise, must be a method.
161 auto MD = cast<CXXMethodDecl>(D);
163 // We may want to emit this definition. However, that decision might be
164 // based on computing the linkage, and we have to defer that in case we
165 // are inside of something that will change the method's final linkage,
169 // void foo() { bar(); }
171 DeferredInlineMethodDefinitions.push_back(MD);
173 // Provide some coverage mapping even for methods that aren't emitted.
174 // Don't do this for templated classes though, as they may not be
176 if (!MD->getParent()->getDescribedClassTemplate())
177 Builder->AddDeferredUnusedCoverageMapping(MD);
180 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
181 /// to (e.g. struct, union, enum, class) is completed. This allows the
182 /// client hack on the type, which can occur at any point in the file
183 /// (because these can be defined in declspecs).
184 void HandleTagDeclDefinition(TagDecl *D) override {
185 if (Diags.hasErrorOccurred())
188 Builder->UpdateCompletedType(D);
190 // For MSVC compatibility, treat declarations of static data members with
191 // inline initializers as definitions.
192 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
193 for (Decl *Member : D->decls()) {
194 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
195 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
196 Ctx->DeclMustBeEmitted(VD)) {
197 Builder->EmitGlobal(VD);
202 // For OpenMP emit declare reduction functions, if required.
203 if (Ctx->getLangOpts().OpenMP) {
204 for (Decl *Member : D->decls()) {
205 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
206 if (Ctx->DeclMustBeEmitted(DRD))
207 Builder->EmitGlobal(DRD);
213 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
214 if (Diags.hasErrorOccurred())
217 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
218 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
219 DI->completeRequiredType(RD);
222 void HandleTranslationUnit(ASTContext &Ctx) override {
223 // Release the Builder when there is no error.
224 if (!Diags.hasErrorOccurred() && Builder)
227 // If there are errors before or when releasing the Builder, reset
228 // the module to stop here before invoking the backend.
229 if (Diags.hasErrorOccurred()) {
237 void AssignInheritanceModel(CXXRecordDecl *RD) override {
238 if (Diags.hasErrorOccurred())
241 Builder->RefreshTypeCacheForClass(RD);
244 void CompleteTentativeDefinition(VarDecl *D) override {
245 if (Diags.hasErrorOccurred())
248 Builder->EmitTentativeDefinition(D);
251 void HandleVTable(CXXRecordDecl *RD) override {
252 if (Diags.hasErrorOccurred())
255 Builder->EmitVTable(RD);
260 void CodeGenerator::anchor() { }
262 CodeGenerator *clang::CreateLLVMCodeGen(
263 DiagnosticsEngine &Diags, const std::string &ModuleName,
264 const HeaderSearchOptions &HeaderSearchOpts,
265 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
266 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
267 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
268 PreprocessorOpts, CGO, C, CoverageInfo);