clang  8.0.0svn
ModuleBuilder.cpp
Go to the documentation of this file.
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 
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"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/TargetInfo.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 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 namespace {
33  class CodeGeneratorImpl : public CodeGenerator {
34  DiagnosticsEngine &Diags;
35  ASTContext *Ctx;
36  const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37  const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
38  const CodeGenOptions CodeGenOpts; // Intentionally copied in.
39 
40  unsigned HandlingTopLevelDecls;
41 
42  /// Use this when emitting decls to block re-entrant decl emission. It will
43  /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
44  /// emission must be deferred longer, like at the end of a tag definition.
45  struct HandlingTopLevelDeclRAII {
46  CodeGeneratorImpl &Self;
47  bool EmitDeferred;
48  HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49  bool EmitDeferred = true)
50  : Self(Self), EmitDeferred(EmitDeferred) {
51  ++Self.HandlingTopLevelDecls;
52  }
53  ~HandlingTopLevelDeclRAII() {
54  unsigned Level = --Self.HandlingTopLevelDecls;
55  if (Level == 0 && EmitDeferred)
56  Self.EmitDeferredDecls();
57  }
58  };
59 
60  CoverageSourceInfo *CoverageInfo;
61 
62  protected:
63  std::unique_ptr<llvm::Module> M;
64  std::unique_ptr<CodeGen::CodeGenModule> Builder;
65 
66  private:
67  SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
68 
69  public:
70  CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
71  const HeaderSearchOptions &HSO,
72  const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73  llvm::LLVMContext &C,
74  CoverageSourceInfo *CoverageInfo = nullptr)
75  : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76  PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
77  CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78  C.setDiscardValueNames(CGO.DiscardValueNames);
79  }
80 
81  ~CodeGeneratorImpl() override {
82  // There should normally not be any leftover inline method definitions.
83  assert(DeferredInlineMemberFuncDefs.empty() ||
84  Diags.hasErrorOccurred());
85  }
86 
87  CodeGenModule &CGM() {
88  return *Builder;
89  }
90 
91  llvm::Module *GetModule() {
92  return M.get();
93  }
94 
95  CGDebugInfo *getCGDebugInfo() {
96  return Builder->getModuleDebugInfo();
97  }
98 
99  llvm::Module *ReleaseModule() {
100  return M.release();
101  }
102 
103  const Decl *GetDeclForMangledName(StringRef MangledName) {
104  GlobalDecl Result;
105  if (!Builder->lookupRepresentativeDecl(MangledName, Result))
106  return nullptr;
107  const Decl *D = Result.getCanonicalDecl().getDecl();
108  if (auto FD = dyn_cast<FunctionDecl>(D)) {
109  if (FD->hasBody(FD))
110  return FD;
111  } else if (auto TD = dyn_cast<TagDecl>(D)) {
112  if (auto Def = TD->getDefinition())
113  return Def;
114  }
115  return D;
116  }
117 
118  llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
119  return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
120  }
121 
122  llvm::Module *StartModule(llvm::StringRef ModuleName,
123  llvm::LLVMContext &C) {
124  assert(!M && "Replacing existing Module?");
125  M.reset(new llvm::Module(ModuleName, C));
126  Initialize(*Ctx);
127  return M.get();
128  }
129 
130  void Initialize(ASTContext &Context) override {
131  Ctx = &Context;
132 
133  M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
134  M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
135  Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
136  PreprocessorOpts, CodeGenOpts,
137  *M, Diags, CoverageInfo));
138 
139  for (auto &&Lib : CodeGenOpts.DependentLibraries)
140  Builder->AddDependentLib(Lib);
141  for (auto &&Opt : CodeGenOpts.LinkerOptions)
142  Builder->AppendLinkerOptions(Opt);
143  }
144 
145  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
146  if (Diags.hasErrorOccurred())
147  return;
148 
149  Builder->HandleCXXStaticMemberVarInstantiation(VD);
150  }
151 
152  bool HandleTopLevelDecl(DeclGroupRef DG) override {
153  if (Diags.hasErrorOccurred())
154  return true;
155 
156  HandlingTopLevelDeclRAII HandlingDecl(*this);
157 
158  // Make sure to emit all elements of a Decl.
159  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
160  Builder->EmitTopLevelDecl(*I);
161 
162  return true;
163  }
164 
165  void EmitDeferredDecls() {
166  if (DeferredInlineMemberFuncDefs.empty())
167  return;
168 
169  // Emit any deferred inline method definitions. Note that more deferred
170  // methods may be added during this loop, since ASTConsumer callbacks
171  // can be invoked if AST inspection results in declarations being added.
172  HandlingTopLevelDeclRAII HandlingDecl(*this);
173  for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
174  Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
175  DeferredInlineMemberFuncDefs.clear();
176  }
177 
178  void HandleInlineFunctionDefinition(FunctionDecl *D) override {
179  if (Diags.hasErrorOccurred())
180  return;
181 
182  assert(D->doesThisDeclarationHaveABody());
183 
184  // We may want to emit this definition. However, that decision might be
185  // based on computing the linkage, and we have to defer that in case we
186  // are inside of something that will change the method's final linkage,
187  // e.g.
188  // typedef struct {
189  // void bar();
190  // void foo() { bar(); }
191  // } A;
192  DeferredInlineMemberFuncDefs.push_back(D);
193 
194  // Provide some coverage mapping even for methods that aren't emitted.
195  // Don't do this for templated classes though, as they may not be
196  // instantiable.
198  Builder->AddDeferredUnusedCoverageMapping(D);
199  }
200 
201  /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
202  /// to (e.g. struct, union, enum, class) is completed. This allows the
203  /// client hack on the type, which can occur at any point in the file
204  /// (because these can be defined in declspecs).
205  void HandleTagDeclDefinition(TagDecl *D) override {
206  if (Diags.hasErrorOccurred())
207  return;
208 
209  // Don't allow re-entrant calls to CodeGen triggered by PCH
210  // deserialization to emit deferred decls.
211  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
212 
213  Builder->UpdateCompletedType(D);
214 
215  // For MSVC compatibility, treat declarations of static data members with
216  // inline initializers as definitions.
217  if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
218  for (Decl *Member : D->decls()) {
219  if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
221  Ctx->DeclMustBeEmitted(VD)) {
222  Builder->EmitGlobal(VD);
223  }
224  }
225  }
226  }
227  // For OpenMP emit declare reduction functions, if required.
228  if (Ctx->getLangOpts().OpenMP) {
229  for (Decl *Member : D->decls()) {
230  if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
231  if (Ctx->DeclMustBeEmitted(DRD))
232  Builder->EmitGlobal(DRD);
233  }
234  }
235  }
236  }
237 
238  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
239  if (Diags.hasErrorOccurred())
240  return;
241 
242  // Don't allow re-entrant calls to CodeGen triggered by PCH
243  // deserialization to emit deferred decls.
244  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
245 
246  if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
247  if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
248  DI->completeRequiredType(RD);
249  }
250 
251  void HandleTranslationUnit(ASTContext &Ctx) override {
252  // Release the Builder when there is no error.
253  if (!Diags.hasErrorOccurred() && Builder)
254  Builder->Release();
255 
256  // If there are errors before or when releasing the Builder, reset
257  // the module to stop here before invoking the backend.
258  if (Diags.hasErrorOccurred()) {
259  if (Builder)
260  Builder->clear();
261  M.reset();
262  return;
263  }
264  }
265 
266  void AssignInheritanceModel(CXXRecordDecl *RD) override {
267  if (Diags.hasErrorOccurred())
268  return;
269 
270  Builder->RefreshTypeCacheForClass(RD);
271  }
272 
273  void CompleteTentativeDefinition(VarDecl *D) override {
274  if (Diags.hasErrorOccurred())
275  return;
276 
277  Builder->EmitTentativeDefinition(D);
278  }
279 
280  void HandleVTable(CXXRecordDecl *RD) override {
281  if (Diags.hasErrorOccurred())
282  return;
283 
284  Builder->EmitVTable(RD);
285  }
286  };
287 }
288 
289 void CodeGenerator::anchor() { }
290 
292  return static_cast<CodeGeneratorImpl*>(this)->CGM();
293 }
294 
295 llvm::Module *CodeGenerator::GetModule() {
296  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
297 }
298 
300  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
301 }
302 
304  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
305 }
306 
307 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
308  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
309 }
310 
312  bool isForDefinition) {
313  return static_cast<CodeGeneratorImpl*>(this)
314  ->GetAddrOfGlobal(global, isForDefinition);
315 }
316 
317 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
318  llvm::LLVMContext &C) {
319  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
320 }
321 
323  DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
324  const HeaderSearchOptions &HeaderSearchOpts,
325  const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
326  llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
327  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
328  PreprocessorOpts, CGO, C, CoverageInfo);
329 }
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:1739
bool hasErrorOccurred() const
Definition: Diagnostic.h:744
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
iterator end()
Definition: DeclGroup.h:106
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:60
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:689
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:1997
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:3602
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
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:65
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
iterator begin()
Definition: DeclGroup.h:100
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:821
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:44
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:1078
llvm::Module * GetModule()
Return the module that this code generator is building into.
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
CodeGen::CodeGenModule & CGM()
Return an opaque reference to the CodeGenModule object, which can be used in various secondary APIs...
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:3073
const Decl * getDecl() const
Definition: GlobalDecl.h:69
const llvm::DataLayout & getDataLayout() const
Definition: TargetInfo.h:953
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:154
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:1990
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:706