clang  10.0.0svn
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 <memory>
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 namespace {
32  class CodeGeneratorImpl : public CodeGenerator {
33  DiagnosticsEngine &Diags;
34  ASTContext *Ctx;
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.
38 
39  unsigned HandlingTopLevelDecls;
40 
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;
46  bool EmitDeferred;
47  HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
48  bool EmitDeferred = true)
49  : Self(Self), EmitDeferred(EmitDeferred) {
50  ++Self.HandlingTopLevelDecls;
51  }
52  ~HandlingTopLevelDeclRAII() {
53  unsigned Level = --Self.HandlingTopLevelDecls;
54  if (Level == 0 && EmitDeferred)
55  Self.EmitDeferredDecls();
56  }
57  };
58 
59  CoverageSourceInfo *CoverageInfo;
60 
61  protected:
62  std::unique_ptr<llvm::Module> M;
63  std::unique_ptr<CodeGen::CodeGenModule> Builder;
64 
65  private:
66  SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
67 
68  public:
69  CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
70  const HeaderSearchOptions &HSO,
71  const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
72  llvm::LLVMContext &C,
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);
78  }
79 
80  ~CodeGeneratorImpl() override {
81  // There should normally not be any leftover inline method definitions.
82  assert(DeferredInlineMemberFuncDefs.empty() ||
83  Diags.hasErrorOccurred());
84  }
85 
86  CodeGenModule &CGM() {
87  return *Builder;
88  }
89 
90  llvm::Module *GetModule() {
91  return M.get();
92  }
93 
94  CGDebugInfo *getCGDebugInfo() {
95  return Builder->getModuleDebugInfo();
96  }
97 
98  llvm::Module *ReleaseModule() {
99  return M.release();
100  }
101 
102  const Decl *GetDeclForMangledName(StringRef MangledName) {
103  GlobalDecl Result;
104  if (!Builder->lookupRepresentativeDecl(MangledName, Result))
105  return nullptr;
106  const Decl *D = Result.getCanonicalDecl().getDecl();
107  if (auto FD = dyn_cast<FunctionDecl>(D)) {
108  if (FD->hasBody(FD))
109  return FD;
110  } else if (auto TD = dyn_cast<TagDecl>(D)) {
111  if (auto Def = TD->getDefinition())
112  return Def;
113  }
114  return D;
115  }
116 
117  llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
118  return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
119  }
120 
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));
125  Initialize(*Ctx);
126  return M.get();
127  }
128 
129  void Initialize(ASTContext &Context) override {
130  Ctx = &Context;
131 
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));
140 
141  for (auto &&Lib : CodeGenOpts.DependentLibraries)
142  Builder->AddDependentLib(Lib);
143  for (auto &&Opt : CodeGenOpts.LinkerOptions)
144  Builder->AppendLinkerOptions(Opt);
145  }
146 
147  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
148  if (Diags.hasErrorOccurred())
149  return;
150 
151  Builder->HandleCXXStaticMemberVarInstantiation(VD);
152  }
153 
154  bool HandleTopLevelDecl(DeclGroupRef DG) override {
155  if (Diags.hasErrorOccurred())
156  return true;
157 
158  HandlingTopLevelDeclRAII HandlingDecl(*this);
159 
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);
163 
164  return true;
165  }
166 
167  void EmitDeferredDecls() {
168  if (DeferredInlineMemberFuncDefs.empty())
169  return;
170 
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();
178  }
179 
180  void HandleInlineFunctionDefinition(FunctionDecl *D) override {
181  if (Diags.hasErrorOccurred())
182  return;
183 
184  assert(D->doesThisDeclarationHaveABody());
185 
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,
189  // e.g.
190  // typedef struct {
191  // void bar();
192  // void foo() { bar(); }
193  // } A;
194  DeferredInlineMemberFuncDefs.push_back(D);
195 
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
198  // instantiable.
200  Builder->AddDeferredUnusedCoverageMapping(D);
201  }
202 
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())
209  return;
210 
211  // Don't allow re-entrant calls to CodeGen triggered by PCH
212  // deserialization to emit deferred decls.
213  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
214 
215  Builder->UpdateCompletedType(D);
216 
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)) {
223  Ctx->DeclMustBeEmitted(VD)) {
224  Builder->EmitGlobal(VD);
225  }
226  }
227  }
228  }
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);
235  } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
236  if (Ctx->DeclMustBeEmitted(DMD))
237  Builder->EmitGlobal(DMD);
238  }
239  }
240  }
241  }
242 
243  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
244  if (Diags.hasErrorOccurred())
245  return;
246 
247  // Don't allow re-entrant calls to CodeGen triggered by PCH
248  // deserialization to emit deferred decls.
249  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
250 
251  if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
252  if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
253  DI->completeRequiredType(RD);
254  }
255 
256  void HandleTranslationUnit(ASTContext &Ctx) override {
257  // Release the Builder when there is no error.
258  if (!Diags.hasErrorOccurred() && Builder)
259  Builder->Release();
260 
261  // If there are errors before or when releasing the Builder, reset
262  // the module to stop here before invoking the backend.
263  if (Diags.hasErrorOccurred()) {
264  if (Builder)
265  Builder->clear();
266  M.reset();
267  return;
268  }
269  }
270 
271  void AssignInheritanceModel(CXXRecordDecl *RD) override {
272  if (Diags.hasErrorOccurred())
273  return;
274 
275  Builder->RefreshTypeCacheForClass(RD);
276  }
277 
278  void CompleteTentativeDefinition(VarDecl *D) override {
279  if (Diags.hasErrorOccurred())
280  return;
281 
282  Builder->EmitTentativeDefinition(D);
283  }
284 
285  void HandleVTable(CXXRecordDecl *RD) override {
286  if (Diags.hasErrorOccurred())
287  return;
288 
289  Builder->EmitVTable(RD);
290  }
291  };
292 }
293 
294 void CodeGenerator::anchor() { }
295 
297  return static_cast<CodeGeneratorImpl*>(this)->CGM();
298 }
299 
300 llvm::Module *CodeGenerator::GetModule() {
301  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
302 }
303 
305  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
306 }
307 
309  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
310 }
311 
313  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
314 }
315 
317  bool isForDefinition) {
318  return static_cast<CodeGeneratorImpl*>(this)
319  ->GetAddrOfGlobal(global, isForDefinition);
320 }
321 
322 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
323  llvm::LLVMContext &C) {
324  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
325 }
326 
328  DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
329  const HeaderSearchOptions &HeaderSearchOpts,
330  const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
331  llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
332  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
333  PreprocessorOpts, CGO, C, CoverageInfo);
334 }
Defines the clang::ASTContext interface.
llvm::Constant * GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition)
Return the LLVM address of the given global entity.
Represents a function declaration or definition.
Definition: Decl.h:1748
bool hasErrorOccurred() const
Definition: Diagnostic.h:749
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:991
iterator end()
Definition: DeclGroup.h:105
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:68
Stores additional source code information like skipped ranges which is required by the coverage mappi...
llvm::Module * StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C)
Create a new llvm::Module after calling HandleTranslationUnit.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr or CxxCtorInitializer) selects the name&#39;s to...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
llvm::Module * ReleaseModule()
Release ownership of the module to the caller.
Represents a variable declaration or definition.
Definition: Decl.h:812
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2021
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
Represents a struct/union/class.
Definition: Decl.h:3626
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1060
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Describes a module or submodule.
Definition: Module.h:64
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
iterator begin()
Definition: DeclGroup.h:99
Defines the Diagnostic-related interfaces.
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:43
std::vector< std::string > DependentLibraries
A list of dependent libraries.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1082
llvm::Module * GetModule()
Return the module that this code generator is building into.
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
CodeGen::CodeGenModule & CGM()
Return an opaque reference to the CodeGenModule object, which can be used in various secondary APIs...
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1363
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...
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3097
const Decl * getDecl() const
Definition: GlobalDecl.h:77
const llvm::DataLayout & getDataLayout() const
Definition: TargetInfo.h:995
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Defines the clang::TargetInfo interface.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:153
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2003
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
CodeGen::CGDebugInfo * getCGDebugInfo()
Return debug info code generator.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:710