Coverage Report

Created: 2022-01-25 06:29

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