Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/clang-check/ClangCheck.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- tools/clang-check/ClangCheck.cpp - Clang check tool --------------===//
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 file implements a clang-check tool that runs clang based on the info
10
//  stored in a compilation database.
11
//
12
//  This tool uses the Clang Tooling infrastructure, see
13
//    http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14
//  for details on setting it up with LLVM source tree.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "clang/AST/ASTConsumer.h"
19
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
20
#include "clang/Driver/Options.h"
21
#include "clang/Frontend/ASTConsumers.h"
22
#include "clang/Frontend/CompilerInstance.h"
23
#include "clang/Rewrite/Frontend/FixItRewriter.h"
24
#include "clang/Rewrite/Frontend/FrontendActions.h"
25
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
26
#include "clang/Tooling/CommonOptionsParser.h"
27
#include "clang/Tooling/Syntax/BuildTree.h"
28
#include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
29
#include "clang/Tooling/Syntax/Tokens.h"
30
#include "clang/Tooling/Syntax/Tree.h"
31
#include "clang/Tooling/Tooling.h"
32
#include "llvm/ADT/STLExtras.h"
33
#include "llvm/Option/OptTable.h"
34
#include "llvm/Support/Path.h"
35
#include "llvm/Support/Signals.h"
36
#include "llvm/Support/TargetSelect.h"
37
38
using namespace clang::driver;
39
using namespace clang::tooling;
40
using namespace llvm;
41
42
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
43
static cl::extrahelp MoreHelp(
44
    "\tFor example, to run clang-check on all files in a subtree of the\n"
45
    "\tsource tree, use:\n"
46
    "\n"
47
    "\t  find path/in/subtree -name '*.cpp'|xargs clang-check\n"
48
    "\n"
49
    "\tor using a specific build path:\n"
50
    "\n"
51
    "\t  find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
52
    "\n"
53
    "\tNote, that path/in/subtree and current directory should follow the\n"
54
    "\trules described above.\n"
55
    "\n"
56
);
57
58
static cl::OptionCategory ClangCheckCategory("clang-check options");
59
static const opt::OptTable &Options = getDriverOptTable();
60
static cl::opt<bool>
61
    ASTDump("ast-dump",
62
            cl::desc(Options.getOptionHelpText(options::OPT_ast_dump)),
63
            cl::cat(ClangCheckCategory));
64
static cl::opt<bool>
65
    ASTList("ast-list",
66
            cl::desc(Options.getOptionHelpText(options::OPT_ast_list)),
67
            cl::cat(ClangCheckCategory));
68
static cl::opt<bool>
69
    ASTPrint("ast-print",
70
             cl::desc(Options.getOptionHelpText(options::OPT_ast_print)),
71
             cl::cat(ClangCheckCategory));
72
static cl::opt<std::string> ASTDumpFilter(
73
    "ast-dump-filter",
74
    cl::desc(Options.getOptionHelpText(options::OPT_ast_dump_filter)),
75
    cl::cat(ClangCheckCategory));
76
static cl::opt<bool>
77
    Analyze("analyze",
78
            cl::desc(Options.getOptionHelpText(options::OPT_analyze)),
79
            cl::cat(ClangCheckCategory));
80
static cl::opt<std::string>
81
    AnalyzerOutput("analyzer-output-path",
82
                   cl::desc(Options.getOptionHelpText(options::OPT_o)),
83
                   cl::cat(ClangCheckCategory));
84
85
static cl::opt<bool>
86
    Fixit("fixit", cl::desc(Options.getOptionHelpText(options::OPT_fixit)),
87
          cl::cat(ClangCheckCategory));
88
static cl::opt<bool> FixWhatYouCan(
89
    "fix-what-you-can",
90
    cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
91
    cl::cat(ClangCheckCategory));
92
93
static cl::opt<bool> SyntaxTreeDump("syntax-tree-dump",
94
                                    cl::desc("dump the syntax tree"),
95
                                    cl::cat(ClangCheckCategory));
96
static cl::opt<bool> TokensDump("tokens-dump",
97
                                cl::desc("dump the preprocessed tokens"),
98
                                cl::cat(ClangCheckCategory));
99
100
namespace {
101
102
// FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
103
// into a header file and reuse that.
104
class FixItOptions : public clang::FixItOptions {
105
public:
106
4
  FixItOptions() {
107
4
    FixWhatYouCan = ::FixWhatYouCan;
108
4
  }
109
110
4
  std::string RewriteFilename(const std::string& filename, int &fd) override {
111
    // We don't need to do permission checking here since clang will diagnose
112
    // any I/O errors itself.
113
114
4
    fd = -1;  // No file descriptor for file.
115
116
4
    return filename;
117
4
  }
118
};
119
120
/// Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
121
/// in the final error counts.
122
///
123
/// This has the side-effect that clang-check -fixit exits with code 0 on
124
/// successfully fixing all errors.
125
class FixItRewriter : public clang::FixItRewriter {
126
public:
127
  FixItRewriter(clang::DiagnosticsEngine& Diags,
128
                clang::SourceManager& SourceMgr,
129
                const clang::LangOptions& LangOpts,
130
                clang::FixItOptions* FixItOpts)
131
4
      : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
132
4
  }
133
134
12
  bool IncludeInDiagnosticCounts() const override { return false; }
135
};
136
137
/// Subclasses \c clang::FixItAction so that we can install the custom
138
/// \c FixItRewriter.
139
class ClangCheckFixItAction : public clang::FixItAction {
140
public:
141
4
  bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
142
4
    FixItOpts.reset(new FixItOptions);
143
4
    Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
144
4
                                     CI.getLangOpts(), FixItOpts.get()));
145
4
    return true;
146
4
  }
147
};
148
149
class DumpSyntaxTree : public clang::ASTFrontendAction {
150
public:
151
  std::unique_ptr<clang::ASTConsumer>
152
1
  CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
153
1
    class Consumer : public clang::ASTConsumer {
154
1
    public:
155
1
      Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
156
157
1
      void HandleTranslationUnit(clang::ASTContext &AST) override {
158
1
        clang::syntax::TokenBuffer TB = std::move(Collector).consume();
159
1
        if (TokensDump)
160
0
          llvm::outs() << TB.dumpForTests();
161
1
        clang::syntax::TokenBufferTokenManager TBTM(TB, AST.getLangOpts(),
162
1
                                                    AST.getSourceManager());
163
1
        clang::syntax::Arena A;
164
1
        llvm::outs()
165
1
            << clang::syntax::buildSyntaxTree(A, TBTM, AST)->dump(TBTM);
166
1
      }
167
168
1
    private:
169
1
      clang::syntax::TokenCollector Collector;
170
1
    };
171
1
    return std::make_unique<Consumer>(CI);
172
1
  }
173
};
174
175
class ClangCheckActionFactory {
176
public:
177
29
  std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
178
29
    if (ASTList)
179
1
      return clang::CreateASTDeclNodeLister();
180
28
    if (ASTDump)
181
6
      return clang::CreateASTDumper(nullptr /*Dump to stdout.*/, ASTDumpFilter,
182
6
                                    /*DumpDecls=*/true,
183
6
                                    /*Deserialize=*/false,
184
6
                                    /*DumpLookups=*/false,
185
6
                                    /*DumpDeclTypes=*/false,
186
6
                                    clang::ADOF_Default);
187
22
    if (ASTPrint)
188
1
      return clang::CreateASTPrinter(nullptr, ASTDumpFilter);
189
21
    return std::make_unique<clang::ASTConsumer>();
190
22
  }
191
};
192
193
} // namespace
194
195
40
int main(int argc, const char **argv) {
196
40
  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
197
198
  // Initialize targets for clang module support.
199
40
  llvm::InitializeAllTargets();
200
40
  llvm::InitializeAllTargetMCs();
201
40
  llvm::InitializeAllAsmPrinters();
202
40
  llvm::InitializeAllAsmParsers();
203
204
40
  auto ExpectedParser =
205
40
      CommonOptionsParser::create(argc, argv, ClangCheckCategory);
206
40
  if (!ExpectedParser) {
207
0
    llvm::errs() << ExpectedParser.takeError();
208
0
    return 1;
209
0
  }
210
40
  CommonOptionsParser &OptionsParser = ExpectedParser.get();
211
40
  ClangTool Tool(OptionsParser.getCompilations(),
212
40
                 OptionsParser.getSourcePathList());
213
214
40
  if (Analyze) {
215
    // Set output path if is provided by user.
216
    //
217
    // As the original -o options have been removed by default via the
218
    // strip-output adjuster, we only need to add the analyzer -o options here
219
    // when it is provided by users.
220
7
    if (!AnalyzerOutput.empty())
221
1
      Tool.appendArgumentsAdjuster(
222
1
          getInsertArgumentAdjuster(CommandLineArguments{"-o", AnalyzerOutput},
223
1
                                    ArgumentInsertPosition::END));
224
225
    // Running the analyzer requires --analyze. Other modes can work with the
226
    // -fsyntax-only option.
227
    //
228
    // The syntax-only adjuster is installed by default.
229
    // Good: It also strips options that trigger extra output, like -save-temps.
230
    // Bad:  We don't want the -fsyntax-only when executing the static analyzer.
231
    //
232
    // To enable the static analyzer, we first strip all -fsyntax-only options
233
    // and then add an --analyze option to the front.
234
7
    Tool.appendArgumentsAdjuster(
235
7
        [&](const CommandLineArguments &Args, StringRef /*unused*/) {
236
7
          CommandLineArguments AdjustedArgs;
237
7
          for (const std::string &Arg : Args)
238
42
            if (Arg != "-fsyntax-only")
239
34
              AdjustedArgs.emplace_back(Arg);
240
7
          return AdjustedArgs;
241
7
        });
242
7
    Tool.appendArgumentsAdjuster(
243
7
        getInsertArgumentAdjuster("--analyze", ArgumentInsertPosition::BEGIN));
244
7
  }
245
246
40
  ClangCheckActionFactory CheckFactory;
247
40
  std::unique_ptr<FrontendActionFactory> FrontendFactory;
248
249
  // Choose the correct factory based on the selected mode.
250
40
  if (Analyze)
251
7
    FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
252
33
  else if (Fixit)
253
4
    FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
254
29
  else if (SyntaxTreeDump || 
TokensDump28
)
255
1
    FrontendFactory = newFrontendActionFactory<DumpSyntaxTree>();
256
28
  else
257
28
    FrontendFactory = newFrontendActionFactory(&CheckFactory);
258
259
40
  return Tool.run(FrontendFactory.get());
260
40
}