clang  16.0.0git
ModuleBuilder.cpp
Go to the documentation of this file.
1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This builds an AST and converts it to LLVM Code.
10 //
11 //===----------------------------------------------------------------------===//
12 
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"
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"
26 #include "llvm/Support/VirtualFileSystem.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  IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS; // Only used for debug info.
37  const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
38  const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
39  const CodeGenOptions CodeGenOpts; // Intentionally copied in.
40 
41  unsigned HandlingTopLevelDecls;
42 
43  /// Use this when emitting decls to block re-entrant decl emission. It will
44  /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
45  /// emission must be deferred longer, like at the end of a tag definition.
46  struct HandlingTopLevelDeclRAII {
47  CodeGeneratorImpl &Self;
48  bool EmitDeferred;
49  HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
50  bool EmitDeferred = true)
51  : Self(Self), EmitDeferred(EmitDeferred) {
52  ++Self.HandlingTopLevelDecls;
53  }
54  ~HandlingTopLevelDeclRAII() {
55  unsigned Level = --Self.HandlingTopLevelDecls;
56  if (Level == 0 && EmitDeferred)
57  Self.EmitDeferredDecls();
58  }
59  };
60 
61  CoverageSourceInfo *CoverageInfo;
62 
63  protected:
64  std::unique_ptr<llvm::Module> M;
65  std::unique_ptr<CodeGen::CodeGenModule> Builder;
66 
67  private:
68  SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
69 
70  static llvm::StringRef ExpandModuleName(llvm::StringRef ModuleName,
71  const CodeGenOptions &CGO) {
72  if (ModuleName == "-" && !CGO.MainFileName.empty())
73  return CGO.MainFileName;
74  return ModuleName;
75  }
76 
77  public:
78  CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
80  const HeaderSearchOptions &HSO,
81  const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
82  llvm::LLVMContext &C,
83  CoverageSourceInfo *CoverageInfo = nullptr)
84  : Diags(diags), Ctx(nullptr), FS(std::move(FS)), HeaderSearchOpts(HSO),
85  PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
86  CoverageInfo(CoverageInfo),
87  M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
88  C.setDiscardValueNames(CGO.DiscardValueNames);
89  }
90 
91  ~CodeGeneratorImpl() override {
92  // There should normally not be any leftover inline method definitions.
93  assert(DeferredInlineMemberFuncDefs.empty() ||
94  Diags.hasErrorOccurred());
95  }
96 
97  CodeGenModule &CGM() {
98  return *Builder;
99  }
100 
101  llvm::Module *GetModule() {
102  return M.get();
103  }
104 
105  CGDebugInfo *getCGDebugInfo() {
106  return Builder->getModuleDebugInfo();
107  }
108 
109  llvm::Module *ReleaseModule() {
110  return M.release();
111  }
112 
113  const Decl *GetDeclForMangledName(StringRef MangledName) {
114  GlobalDecl Result;
115  if (!Builder->lookupRepresentativeDecl(MangledName, Result))
116  return nullptr;
117  const Decl *D = Result.getCanonicalDecl().getDecl();
118  if (auto FD = dyn_cast<FunctionDecl>(D)) {
119  if (FD->hasBody(FD))
120  return FD;
121  } else if (auto TD = dyn_cast<TagDecl>(D)) {
122  if (auto Def = TD->getDefinition())
123  return Def;
124  }
125  return D;
126  }
127 
128  llvm::StringRef GetMangledName(GlobalDecl GD) {
129  return Builder->getMangledName(GD);
130  }
131 
132  llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
133  return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
134  }
135 
136  llvm::Module *StartModule(llvm::StringRef ModuleName,
137  llvm::LLVMContext &C) {
138  assert(!M && "Replacing existing Module?");
139  M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
140 
141  std::unique_ptr<CodeGenModule> OldBuilder = std::move(Builder);
142 
143  Initialize(*Ctx);
144 
145  if (OldBuilder)
146  OldBuilder->moveLazyEmissionStates(Builder.get());
147 
148  return M.get();
149  }
150 
151  void Initialize(ASTContext &Context) override {
152  Ctx = &Context;
153 
154  M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
155  M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
156  const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
157  if (!SDKVersion.empty())
158  M->setSDKVersion(SDKVersion);
159  if (const auto *TVT = Ctx->getTargetInfo().getDarwinTargetVariantTriple())
160  M->setDarwinTargetVariantTriple(TVT->getTriple());
161  if (auto TVSDKVersion =
163  M->setDarwinTargetVariantSDKVersion(*TVSDKVersion);
164  Builder.reset(new CodeGen::CodeGenModule(Context, FS, HeaderSearchOpts,
165  PreprocessorOpts, CodeGenOpts,
166  *M, Diags, CoverageInfo));
167 
168  for (auto &&Lib : CodeGenOpts.DependentLibraries)
169  Builder->AddDependentLib(Lib);
170  for (auto &&Opt : CodeGenOpts.LinkerOptions)
171  Builder->AppendLinkerOptions(Opt);
172  }
173 
174  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
175  if (Diags.hasErrorOccurred())
176  return;
177 
178  Builder->HandleCXXStaticMemberVarInstantiation(VD);
179  }
180 
181  bool HandleTopLevelDecl(DeclGroupRef DG) override {
182  if (Diags.hasErrorOccurred())
183  return true;
184 
185  HandlingTopLevelDeclRAII HandlingDecl(*this);
186 
187  // Make sure to emit all elements of a Decl.
188  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
189  Builder->EmitTopLevelDecl(*I);
190 
191  return true;
192  }
193 
194  void EmitDeferredDecls() {
195  if (DeferredInlineMemberFuncDefs.empty())
196  return;
197 
198  // Emit any deferred inline method definitions. Note that more deferred
199  // methods may be added during this loop, since ASTConsumer callbacks
200  // can be invoked if AST inspection results in declarations being added.
201  HandlingTopLevelDeclRAII HandlingDecl(*this);
202  for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
203  Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
204  DeferredInlineMemberFuncDefs.clear();
205  }
206 
207  void HandleInlineFunctionDefinition(FunctionDecl *D) override {
208  if (Diags.hasErrorOccurred())
209  return;
210 
211  assert(D->doesThisDeclarationHaveABody());
212 
213  // We may want to emit this definition. However, that decision might be
214  // based on computing the linkage, and we have to defer that in case we
215  // are inside of something that will change the method's final linkage,
216  // e.g.
217  // typedef struct {
218  // void bar();
219  // void foo() { bar(); }
220  // } A;
221  DeferredInlineMemberFuncDefs.push_back(D);
222 
223  // Provide some coverage mapping even for methods that aren't emitted.
224  // Don't do this for templated classes though, as they may not be
225  // instantiable.
227  Builder->AddDeferredUnusedCoverageMapping(D);
228  }
229 
230  /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
231  /// to (e.g. struct, union, enum, class) is completed. This allows the
232  /// client hack on the type, which can occur at any point in the file
233  /// (because these can be defined in declspecs).
234  void HandleTagDeclDefinition(TagDecl *D) override {
235  if (Diags.hasErrorOccurred())
236  return;
237 
238  // Don't allow re-entrant calls to CodeGen triggered by PCH
239  // deserialization to emit deferred decls.
240  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
241 
242  Builder->UpdateCompletedType(D);
243 
244  // For MSVC compatibility, treat declarations of static data members with
245  // inline initializers as definitions.
246  if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
247  for (Decl *Member : D->decls()) {
248  if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
250  Ctx->DeclMustBeEmitted(VD)) {
251  Builder->EmitGlobal(VD);
252  }
253  }
254  }
255  }
256  // For OpenMP emit declare reduction functions, if required.
257  if (Ctx->getLangOpts().OpenMP) {
258  for (Decl *Member : D->decls()) {
259  if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
260  if (Ctx->DeclMustBeEmitted(DRD))
261  Builder->EmitGlobal(DRD);
262  } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
263  if (Ctx->DeclMustBeEmitted(DMD))
264  Builder->EmitGlobal(DMD);
265  }
266  }
267  }
268  }
269 
270  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
271  if (Diags.hasErrorOccurred())
272  return;
273 
274  // Don't allow re-entrant calls to CodeGen triggered by PCH
275  // deserialization to emit deferred decls.
276  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
277 
278  if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
279  if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
280  DI->completeRequiredType(RD);
281  }
282 
283  void HandleTranslationUnit(ASTContext &Ctx) override {
284  // Release the Builder when there is no error.
285  if (!Diags.hasErrorOccurred() && Builder)
286  Builder->Release();
287 
288  // If there are errors before or when releasing the Builder, reset
289  // the module to stop here before invoking the backend.
290  if (Diags.hasErrorOccurred()) {
291  if (Builder)
292  Builder->clear();
293  M.reset();
294  return;
295  }
296  }
297 
298  void AssignInheritanceModel(CXXRecordDecl *RD) override {
299  if (Diags.hasErrorOccurred())
300  return;
301 
302  Builder->RefreshTypeCacheForClass(RD);
303  }
304 
305  void CompleteTentativeDefinition(VarDecl *D) override {
306  if (Diags.hasErrorOccurred())
307  return;
308 
309  Builder->EmitTentativeDefinition(D);
310  }
311 
312  void CompleteExternalDeclaration(VarDecl *D) override {
313  Builder->EmitExternalDeclaration(D);
314  }
315 
316  void HandleVTable(CXXRecordDecl *RD) override {
317  if (Diags.hasErrorOccurred())
318  return;
319 
320  Builder->EmitVTable(RD);
321  }
322  };
323 }
324 
325 void CodeGenerator::anchor() { }
326 
328  return static_cast<CodeGeneratorImpl*>(this)->CGM();
329 }
330 
331 llvm::Module *CodeGenerator::GetModule() {
332  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
333 }
334 
336  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
337 }
338 
340  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
341 }
342 
344  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
345 }
346 
348  return static_cast<CodeGeneratorImpl *>(this)->GetMangledName(GD);
349 }
350 
352  bool isForDefinition) {
353  return static_cast<CodeGeneratorImpl*>(this)
354  ->GetAddrOfGlobal(global, isForDefinition);
355 }
356 
357 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
358  llvm::LLVMContext &C) {
359  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
360 }
361 
363 clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
365  const HeaderSearchOptions &HeaderSearchOpts,
366  const PreprocessorOptions &PreprocessorOpts,
367  const CodeGenOptions &CGO, llvm::LLVMContext &C,
368  CoverageSourceInfo *CoverageInfo) {
369  return new CodeGeneratorImpl(Diags, ModuleName, std::move(FS),
370  HeaderSearchOpts, PreprocessorOpts, CGO, C,
371  CoverageInfo);
372 }
clang::TargetInfo::getDataLayoutString
const char * getDataLayoutString() const
Definition: TargetInfo.h:1202
clang::CodeGenerator::CGM
CodeGen::CodeGenModule & CGM()
Return an opaque reference to the CodeGenModule object, which can be used in various secondary APIs.
Definition: ModuleBuilder.cpp:327
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2217
clang::CodeGenerator
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:48
llvm
YAML serialization mapping.
Definition: Dominators.h:30
clang::CodeGenerator::GetAddrOfGlobal
llvm::Constant * GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition)
Return the LLVM address of the given global entity.
Definition: ModuleBuilder.cpp:351
clang::DeclContext::decls
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2178
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
clang::CodeGenerator::getCGDebugInfo
CodeGen::CGDebugInfo * getCGDebugInfo()
Return debug info code generator.
Definition: ModuleBuilder.cpp:339
clang::CodeGen::ForDefinition_t
ForDefinition_t
Definition: CodeGenModule.h:96
llvm::SmallVector
Definition: LLVM.h:38
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
TargetInfo.h
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:56
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::CreateLLVMCodeGen
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
Definition: ModuleBuilder.cpp:363
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1268
clang::TargetInfo::getSDKVersion
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1652
ModuleBuilder.h
clang::DeclGroupRef::begin
iterator begin()
Definition: DeclGroup.h:99
clang::DeclGroupRef::end
iterator end()
Definition: DeclGroup.h:105
clang::CodeGenerator::GetDeclForMangledName
const Decl * GetDeclForMangledName(llvm::StringRef MangledName)
Given a mangled name, return a declaration which mangles that way which has been added to this code g...
Definition: ModuleBuilder.cpp:343
clang::CoverageSourceInfo
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Definition: CoverageMappingGen.h:62
CGDebugInfo.h
DeclObjC.h
clang::GlobalDecl
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
clang::CodeGenerator::GetMangledName
llvm::StringRef GetMangledName(GlobalDecl GD)
Given a global declaration, return a mangled name for this declaration which has been added to this c...
Definition: ModuleBuilder.cpp:347
CodeGenOptions.h
clang::Decl::getLexicalDeclContext
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:883
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::DiagnosticsEngine::hasErrorOccurred
bool hasErrorOccurred() const
Definition: Diagnostic.h:838
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:209
clang::CodeGenerator::StartModule
llvm::Module * StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C)
Create a new llvm::Module after calling HandleTranslationUnit.
Definition: ModuleBuilder.cpp:357
Diagnostic.h
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
clang::CodeGen::CGDebugInfo
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:55
Expr.h
ASTContext.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:906
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3423
CodeGenModule.h
clang::CodeGenOptions::DependentLibraries
std::vector< std::string > DependentLibraries
A list of dependent libraries.
Definition: CodeGenOptions.h:247
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::TargetInfo::getDarwinTargetVariantTriple
const llvm::Triple * getDarwinTargetVariantTriple() const
Returns the darwin target variant triple, the variant of the deployment target for which the code is ...
Definition: TargetInfo.h:1673
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1195
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CodeGenerator::GetModule
llvm::Module * GetModule()
Return the module that this code generator is building into.
Definition: ModuleBuilder.cpp:331
clang::CodeGen::CodeGenModule
This class organizes the cross-function state that is used while generating LLVM code.
Definition: CodeGenModule.h:279
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::TargetInfo::getDarwinTargetVariantSDKVersion
const Optional< VersionTuple > getDarwinTargetVariantSDKVersion() const
Returns the version of the darwin target variant SDK which was used during the compilation if one was...
Definition: TargetInfo.h:1679
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:773
std
Definition: Format.h:4477
clang
Definition: CalledOnceCheck.h:17
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1173
clang::CodeGenerator::ReleaseModule
llvm::Module * ReleaseModule()
Release ownership of the module to the caller.
Definition: ModuleBuilder.cpp:335
clang::ASTContext::isMSStaticDataMemberInlineDefinition
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Definition: ASTContext.cpp:7626
clang::CodeGenOptions::LinkerOptions
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
Definition: CodeGenOptions.h:250
clang::transformer::name
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Definition: RangeSelector.cpp:200
clang::ASTContext::DeclMustBeEmitted
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
Definition: ASTContext.cpp:11692
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1904
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3983
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:791
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem >
clang::CodeGenOptions::MainFileName
std::string MainFileName
The user provided name for the "main file", if non-empty.
Definition: CodeGenOptions.h:227
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68