Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp
Line
Count
Source (jump to first uncovered line)
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
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"
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
16.2M
          : Self(Self), EmitDeferred(EmitDeferred) {
50
16.2M
        ++Self.HandlingTopLevelDecls;
51
16.2M
      }
52
16.2M
      ~HandlingTopLevelDeclRAII() {
53
16.2M
        unsigned Level = --Self.HandlingTopLevelDecls;
54
16.2M
        if (Level == 0 && 
EmitDeferred16.2M
)
55
13.0M
          Self.EmitDeferredDecls();
56
16.2M
      }
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
    static llvm::StringRef ExpandModuleName(llvm::StringRef ModuleName,
69
29.6k
                                            const CodeGenOptions &CGO) {
70
29.6k
      if (ModuleName == "-" && 
!CGO.MainFileName.empty()272
)
71
104
        return CGO.MainFileName;
72
29.5k
      return ModuleName;
73
29.5k
    }
74
75
  public:
76
    CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
77
                      const HeaderSearchOptions &HSO,
78
                      const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
79
                      llvm::LLVMContext &C,
80
                      CoverageSourceInfo *CoverageInfo = nullptr)
81
        : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
82
          PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
83
          CoverageInfo(CoverageInfo),
84
29.6k
          M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
85
29.6k
      C.setDiscardValueNames(CGO.DiscardValueNames);
86
29.6k
    }
87
88
29.5k
    ~CodeGeneratorImpl() override {
89
      // There should normally not be any leftover inline method definitions.
90
29.5k
      assert(DeferredInlineMemberFuncDefs.empty() ||
91
29.5k
             Diags.hasErrorOccurred());
92
29.5k
    }
93
94
23
    CodeGenModule &CGM() {
95
23
      return *Builder;
96
23
    }
97
98
68.3k
    llvm::Module *GetModule() {
99
68.3k
      return M.get();
100
68.3k
    }
101
102
1.36k
    CGDebugInfo *getCGDebugInfo() {
103
1.36k
      return Builder->getModuleDebugInfo();
104
1.36k
    }
105
106
28.5k
    llvm::Module *ReleaseModule() {
107
28.5k
      return M.release();
108
28.5k
    }
109
110
49
    const Decl *GetDeclForMangledName(StringRef MangledName) {
111
49
      GlobalDecl Result;
112
49
      if (!Builder->lookupRepresentativeDecl(MangledName, Result))
113
17
        return nullptr;
114
32
      const Decl *D = Result.getCanonicalDecl().getDecl();
115
32
      if (auto FD = dyn_cast<FunctionDecl>(D)) {
116
30
        if (FD->hasBody(FD))
117
30
          return FD;
118
2
      } else if (auto TD = dyn_cast<TagDecl>(D)) {
119
0
        if (auto Def = TD->getDefinition())
120
0
          return Def;
121
2
      }
122
2
      return D;
123
2
    }
124
125
1
    llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
126
1
      return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
127
1
    }
128
129
    llvm::Module *StartModule(llvm::StringRef ModuleName,
130
3
                              llvm::LLVMContext &C) {
131
3
      assert(!M && "Replacing existing Module?");
132
3
      M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
133
3
      Initialize(*Ctx);
134
3
      return M.get();
135
3
    }
136
137
29.4k
    void Initialize(ASTContext &Context) override {
138
29.4k
      Ctx = &Context;
139
29.4k
140
29.4k
      M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
141
29.4k
      M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
142
29.4k
      const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
143
29.4k
      if (!SDKVersion.empty())
144
3.25k
        M->setSDKVersion(SDKVersion);
145
29.4k
      Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
146
29.4k
                                               PreprocessorOpts, CodeGenOpts,
147
29.4k
                                               *M, Diags, CoverageInfo));
148
29.4k
149
29.4k
      for (auto &&Lib : CodeGenOpts.DependentLibraries)
150
54
        Builder->AddDependentLib(Lib);
151
29.4k
      for (auto &&Opt : CodeGenOpts.LinkerOptions)
152
1
        Builder->AppendLinkerOptions(Opt);
153
29.4k
    }
154
155
536k
    void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
156
536k
      if (Diags.hasErrorOccurred())
157
47
        return;
158
536k
159
536k
      Builder->HandleCXXStaticMemberVarInstantiation(VD);
160
536k
    }
161
162
13.0M
    bool HandleTopLevelDecl(DeclGroupRef DG) override {
163
13.0M
      if (Diags.hasErrorOccurred())
164
5.39k
        return true;
165
13.0M
166
13.0M
      HandlingTopLevelDeclRAII HandlingDecl(*this);
167
13.0M
168
      // Make sure to emit all elements of a Decl.
169
26.7M
      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; 
++I13.7M
)
170
13.7M
        Builder->EmitTopLevelDecl(*I);
171
13.0M
172
13.0M
      return true;
173
13.0M
    }
174
175
13.0M
    void EmitDeferredDecls() {
176
13.0M
      if (DeferredInlineMemberFuncDefs.empty())
177
13.0M
        return;
178
19.3k
179
      // Emit any deferred inline method definitions. Note that more deferred
180
      // methods may be added during this loop, since ASTConsumer callbacks
181
      // can be invoked if AST inspection results in declarations being added.
182
19.3k
      HandlingTopLevelDeclRAII HandlingDecl(*this);
183
432k
      for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); 
++I413k
)
184
413k
        Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
185
19.3k
      DeferredInlineMemberFuncDefs.clear();
186
19.3k
    }
187
188
413k
    void HandleInlineFunctionDefinition(FunctionDecl *D) override {
189
413k
      if (Diags.hasErrorOccurred())
190
255
        return;
191
413k
192
413k
      assert(D->doesThisDeclarationHaveABody());
193
413k
194
      // We may want to emit this definition. However, that decision might be
195
      // based on computing the linkage, and we have to defer that in case we
196
      // are inside of something that will change the method's final linkage,
197
      // e.g.
198
      //   typedef struct {
199
      //     void bar();
200
      //     void foo() { bar(); }
201
      //   } A;
202
413k
      DeferredInlineMemberFuncDefs.push_back(D);
203
413k
204
      // Provide some coverage mapping even for methods that aren't emitted.
205
      // Don't do this for templated classes though, as they may not be
206
      // instantiable.
207
413k
      if (!D->getLexicalDeclContext()->isDependentContext())
208
98.7k
        Builder->AddDeferredUnusedCoverageMapping(D);
209
413k
    }
210
211
    /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
212
    /// to (e.g. struct, union, enum, class) is completed. This allows the
213
    /// client hack on the type, which can occur at any point in the file
214
    /// (because these can be defined in declspecs).
215
2.22M
    void HandleTagDeclDefinition(TagDecl *D) override {
216
2.22M
      if (Diags.hasErrorOccurred())
217
370
        return;
218
2.22M
219
      // Don't allow re-entrant calls to CodeGen triggered by PCH
220
      // deserialization to emit deferred decls.
221
2.22M
      HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
222
2.22M
223
2.22M
      Builder->UpdateCompletedType(D);
224
2.22M
225
      // For MSVC compatibility, treat declarations of static data members with
226
      // inline initializers as definitions.
227
2.22M
      if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
228
23.8k
        for (Decl *Member : D->decls()) {
229
23.8k
          if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
230
322
            if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
231
83
                Ctx->DeclMustBeEmitted(VD)) {
232
38
              Builder->EmitGlobal(VD);
233
38
            }
234
322
          }
235
23.8k
        }
236
5.94k
      }
237
      // For OpenMP emit declare reduction functions, if required.
238
2.22M
      if (Ctx->getLangOpts().OpenMP) {
239
31.4k
        for (Decl *Member : D->decls()) {
240
31.4k
          if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
241
16
            if (Ctx->DeclMustBeEmitted(DRD))
242
10
              Builder->EmitGlobal(DRD);
243
31.4k
          } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
244
0
            if (Ctx->DeclMustBeEmitted(DMD))
245
0
              Builder->EmitGlobal(DMD);
246
0
          }
247
31.4k
        }
248
6.24k
      }
249
2.22M
    }
250
251
992k
    void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
252
992k
      if (Diags.hasErrorOccurred())
253
922
        return;
254
991k
255
      // Don't allow re-entrant calls to CodeGen triggered by PCH
256
      // deserialization to emit deferred decls.
257
991k
      HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
258
991k
259
991k
      if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
260
935k
        if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
261
924k
          DI->completeRequiredType(RD);
262
991k
    }
263
264
29.4k
    void HandleTranslationUnit(ASTContext &Ctx) override {
265
      // Release the Builder when there is no error.
266
29.4k
      if (!Diags.hasErrorOccurred() && 
Builder28.5k
)
267
28.5k
        Builder->Release();
268
29.4k
269
      // If there are errors before or when releasing the Builder, reset
270
      // the module to stop here before invoking the backend.
271
29.4k
      if (Diags.hasErrorOccurred()) {
272
887
        if (Builder)
273
887
          Builder->clear();
274
887
        M.reset();
275
887
        return;
276
887
      }
277
29.4k
    }
278
279
478
    void AssignInheritanceModel(CXXRecordDecl *RD) override {
280
478
      if (Diags.hasErrorOccurred())
281
18
        return;
282
460
283
460
      Builder->RefreshTypeCacheForClass(RD);
284
460
    }
285
286
4.37k
    void CompleteTentativeDefinition(VarDecl *D) override {
287
4.37k
      if (Diags.hasErrorOccurred())
288
62
        return;
289
4.31k
290
4.31k
      Builder->EmitTentativeDefinition(D);
291
4.31k
    }
292
293
7
    void CompleteExternalDeclaration(VarDecl *D) override {
294
7
      Builder->EmitExternalDeclaration(D);
295
7
    }
296
297
777
    void HandleVTable(CXXRecordDecl *RD) override {
298
777
      if (Diags.hasErrorOccurred())
299
0
        return;
300
777
301
777
      Builder->EmitVTable(RD);
302
777
    }
303
  };
304
}
305
306
0
void CodeGenerator::anchor() { }
307
308
23
CodeGenModule &CodeGenerator::CGM() {
309
23
  return static_cast<CodeGeneratorImpl*>(this)->CGM();
310
23
}
311
312
68.3k
llvm::Module *CodeGenerator::GetModule() {
313
68.3k
  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
314
68.3k
}
315
316
28.5k
llvm::Module *CodeGenerator::ReleaseModule() {
317
28.5k
  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
318
28.5k
}
319
320
1.36k
CGDebugInfo *CodeGenerator::getCGDebugInfo() {
321
1.36k
  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
322
1.36k
}
323
324
49
const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
325
49
  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
326
49
}
327
328
llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
329
1
                                               bool isForDefinition) {
330
1
  return static_cast<CodeGeneratorImpl*>(this)
331
1
           ->GetAddrOfGlobal(global, isForDefinition);
332
1
}
333
334
llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
335
3
                                         llvm::LLVMContext &C) {
336
3
  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
337
3
}
338
339
CodeGenerator *clang::CreateLLVMCodeGen(
340
    DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
341
    const HeaderSearchOptions &HeaderSearchOpts,
342
    const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
343
29.6k
    llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
344
29.6k
  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
345
29.6k
                               PreprocessorOpts, CGO, C, CoverageInfo);
346
29.6k
}