1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This builds an AST and converts it to LLVM Code.
11 //===----------------------------------------------------------------------===//
13 #include "clang/CodeGen/ModuleBuilder.h"
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/Basic/CodeGenOptions.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
28 using namespace clang;
29 using namespace CodeGen;
32 class CodeGeneratorImpl : public CodeGenerator {
33 DiagnosticsEngine &Diags;
35 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
36 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
37 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
39 unsigned HandlingTopLevelDecls;
41 /// Use this when emitting decls to block re-entrant decl emission. It will
42 /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
43 /// emission must be deferred longer, like at the end of a tag definition.
44 struct HandlingTopLevelDeclRAII {
45 CodeGeneratorImpl &Self;
47 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
48 bool EmitDeferred = true)
49 : Self(Self), EmitDeferred(EmitDeferred) {
50 ++Self.HandlingTopLevelDecls;
52 ~HandlingTopLevelDeclRAII() {
53 unsigned Level = --Self.HandlingTopLevelDecls;
54 if (Level == 0 && EmitDeferred)
55 Self.EmitDeferredDecls();
59 CoverageSourceInfo *CoverageInfo;
62 std::unique_ptr<llvm::Module> M;
63 std::unique_ptr<CodeGen::CodeGenModule> Builder;
66 SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
69 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
70 const HeaderSearchOptions &HSO,
71 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73 CoverageSourceInfo *CoverageInfo = nullptr)
74 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
75 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
76 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
77 C.setDiscardValueNames(CGO.DiscardValueNames);
80 ~CodeGeneratorImpl() override {
81 // There should normally not be any leftover inline method definitions.
82 assert(DeferredInlineMemberFuncDefs.empty() ||
83 Diags.hasErrorOccurred());
86 CodeGenModule &CGM() {
90 llvm::Module *GetModule() {
94 CGDebugInfo *getCGDebugInfo() {
95 return Builder->getModuleDebugInfo();
98 llvm::Module *ReleaseModule() {
102 const Decl *GetDeclForMangledName(StringRef MangledName) {
104 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
106 const Decl *D = Result.getCanonicalDecl().getDecl();
107 if (auto FD = dyn_cast<FunctionDecl>(D)) {
110 } else if (auto TD = dyn_cast<TagDecl>(D)) {
111 if (auto Def = TD->getDefinition())
117 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
118 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
121 llvm::Module *StartModule(llvm::StringRef ModuleName,
122 llvm::LLVMContext &C) {
123 assert(!M && "Replacing existing Module?");
124 M.reset(new llvm::Module(ModuleName, C));
129 void Initialize(ASTContext &Context) override {
132 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
133 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
134 const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
135 if (!SDKVersion.empty())
136 M->setSDKVersion(SDKVersion);
137 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
138 PreprocessorOpts, CodeGenOpts,
139 *M, Diags, CoverageInfo));
141 for (auto &&Lib : CodeGenOpts.DependentLibraries)
142 Builder->AddDependentLib(Lib);
143 for (auto &&Opt : CodeGenOpts.LinkerOptions)
144 Builder->AppendLinkerOptions(Opt);
147 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
148 if (Diags.hasErrorOccurred())
151 Builder->HandleCXXStaticMemberVarInstantiation(VD);
154 bool HandleTopLevelDecl(DeclGroupRef DG) override {
155 if (Diags.hasErrorOccurred())
158 HandlingTopLevelDeclRAII HandlingDecl(*this);
160 // Make sure to emit all elements of a Decl.
161 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
162 Builder->EmitTopLevelDecl(*I);
167 void EmitDeferredDecls() {
168 if (DeferredInlineMemberFuncDefs.empty())
171 // Emit any deferred inline method definitions. Note that more deferred
172 // methods may be added during this loop, since ASTConsumer callbacks
173 // can be invoked if AST inspection results in declarations being added.
174 HandlingTopLevelDeclRAII HandlingDecl(*this);
175 for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
176 Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
177 DeferredInlineMemberFuncDefs.clear();
180 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
181 if (Diags.hasErrorOccurred())
184 assert(D->doesThisDeclarationHaveABody());
186 // We may want to emit this definition. However, that decision might be
187 // based on computing the linkage, and we have to defer that in case we
188 // are inside of something that will change the method's final linkage,
192 // void foo() { bar(); }
194 DeferredInlineMemberFuncDefs.push_back(D);
196 // Provide some coverage mapping even for methods that aren't emitted.
197 // Don't do this for templated classes though, as they may not be
199 if (!D->getLexicalDeclContext()->isDependentContext())
200 Builder->AddDeferredUnusedCoverageMapping(D);
203 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
204 /// to (e.g. struct, union, enum, class) is completed. This allows the
205 /// client hack on the type, which can occur at any point in the file
206 /// (because these can be defined in declspecs).
207 void HandleTagDeclDefinition(TagDecl *D) override {
208 if (Diags.hasErrorOccurred())
211 // Don't allow re-entrant calls to CodeGen triggered by PCH
212 // deserialization to emit deferred decls.
213 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
215 Builder->UpdateCompletedType(D);
217 // For MSVC compatibility, treat declarations of static data members with
218 // inline initializers as definitions.
219 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
220 for (Decl *Member : D->decls()) {
221 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
222 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
223 Ctx->DeclMustBeEmitted(VD)) {
224 Builder->EmitGlobal(VD);
229 // For OpenMP emit declare reduction functions, if required.
230 if (Ctx->getLangOpts().OpenMP) {
231 for (Decl *Member : D->decls()) {
232 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
233 if (Ctx->DeclMustBeEmitted(DRD))
234 Builder->EmitGlobal(DRD);
240 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
241 if (Diags.hasErrorOccurred())
244 // Don't allow re-entrant calls to CodeGen triggered by PCH
245 // deserialization to emit deferred decls.
246 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
248 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
249 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
250 DI->completeRequiredType(RD);
253 void HandleTranslationUnit(ASTContext &Ctx) override {
254 // Release the Builder when there is no error.
255 if (!Diags.hasErrorOccurred() && Builder)
258 // If there are errors before or when releasing the Builder, reset
259 // the module to stop here before invoking the backend.
260 if (Diags.hasErrorOccurred()) {
268 void AssignInheritanceModel(CXXRecordDecl *RD) override {
269 if (Diags.hasErrorOccurred())
272 Builder->RefreshTypeCacheForClass(RD);
275 void CompleteTentativeDefinition(VarDecl *D) override {
276 if (Diags.hasErrorOccurred())
279 Builder->EmitTentativeDefinition(D);
282 void HandleVTable(CXXRecordDecl *RD) override {
283 if (Diags.hasErrorOccurred())
286 Builder->EmitVTable(RD);
291 void CodeGenerator::anchor() { }
293 CodeGenModule &CodeGenerator::CGM() {
294 return static_cast<CodeGeneratorImpl*>(this)->CGM();
297 llvm::Module *CodeGenerator::GetModule() {
298 return static_cast<CodeGeneratorImpl*>(this)->GetModule();
301 llvm::Module *CodeGenerator::ReleaseModule() {
302 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
305 CGDebugInfo *CodeGenerator::getCGDebugInfo() {
306 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
309 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
310 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
313 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
314 bool isForDefinition) {
315 return static_cast<CodeGeneratorImpl*>(this)
316 ->GetAddrOfGlobal(global, isForDefinition);
319 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
320 llvm::LLVMContext &C) {
321 return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
324 CodeGenerator *clang::CreateLLVMCodeGen(
325 DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
326 const HeaderSearchOptions &HeaderSearchOpts,
327 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
328 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
329 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
330 PreprocessorOpts, CGO, C, CoverageInfo);