Coverage Report

Created: 2022-07-16 07:03

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