Clang Project

clang_source_code/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
1//===- AnalyzerOptions.h - Analysis Engine Options --------------*- C++ -*-===//
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 header defines various options for the static analyzer that are set
10// by the frontend and are consulted throughout the analyzer.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
15#define LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/IntrusiveRefCntPtr.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/StringSwitch.h"
23#include <string>
24#include <utility>
25#include <vector>
26
27namespace clang {
28
29namespace ento {
30
31class CheckerBase;
32
33// namespace ento
34
35/// Analysis - Set of available source code analyses.
36enum Analyses {
37#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME,
38#include "clang/StaticAnalyzer/Core/Analyses.def"
39NumAnalyses
40};
41
42/// AnalysisStores - Set of available analysis store models.
43enum AnalysisStores {
44#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
45#include "clang/StaticAnalyzer/Core/Analyses.def"
46NumStores
47};
48
49/// AnalysisConstraints - Set of available constraint models.
50enum AnalysisConstraints {
51#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
52#include "clang/StaticAnalyzer/Core/Analyses.def"
53NumConstraints
54};
55
56/// AnalysisDiagClients - Set of available diagnostic clients for rendering
57///  analysis results.
58enum AnalysisDiagClients {
59#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) PD_##NAME,
60#include "clang/StaticAnalyzer/Core/Analyses.def"
61PD_NONE,
62NUM_ANALYSIS_DIAG_CLIENTS
63};
64
65/// AnalysisPurgeModes - Set of available strategies for dead symbol removal.
66enum AnalysisPurgeMode {
67#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) NAME,
68#include "clang/StaticAnalyzer/Core/Analyses.def"
69NumPurgeModes
70};
71
72/// AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
73enum AnalysisInliningMode {
74#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) NAME,
75#include "clang/StaticAnalyzer/Core/Analyses.def"
76NumInliningModes
77};
78
79/// Describes the different kinds of C++ member functions which can be
80/// considered for inlining by the analyzer.
81///
82/// These options are cumulative; enabling one kind of member function will
83/// enable all kinds with lower enum values.
84enum CXXInlineableMemberKind {
85  // Uninitialized = 0,
86
87  /// A dummy mode in which no C++ inlining is enabled.
88  CIMK_None,
89
90  /// Refers to regular member function and operator calls.
91  CIMK_MemberFunctions,
92
93  /// Refers to constructors (implicit or explicit).
94  ///
95  /// Note that a constructor will not be inlined if the corresponding
96  /// destructor is non-trivial.
97  CIMK_Constructors,
98
99  /// Refers to destructors (implicit or explicit).
100  CIMK_Destructors
101};
102
103/// Describes the different modes of inter-procedural analysis.
104enum IPAKind {
105  /// Perform only intra-procedural analysis.
106  IPAK_None = 1,
107
108  /// Inline C functions and blocks when their definitions are available.
109  IPAK_BasicInlining = 2,
110
111  /// Inline callees(C, C++, ObjC) when their definitions are available.
112  IPAK_Inlining = 3,
113
114  /// Enable inlining of dynamically dispatched methods.
115  IPAK_DynamicDispatch = 4,
116
117  /// Enable inlining of dynamically dispatched methods, bifurcate paths when
118  /// exact type info is unavailable.
119  IPAK_DynamicDispatchBifurcate = 5
120};
121
122enum class ExplorationStrategyKind {
123  DFS,
124  BFS,
125  UnexploredFirst,
126  UnexploredFirstQueue,
127  UnexploredFirstLocationQueue,
128  BFSBlockDFSContents,
129};
130
131/// Describes the kinds for high-level analyzer mode.
132enum UserModeKind {
133  /// Perform shallow but fast analyzes.
134  UMK_Shallow = 1,
135
136  /// Perform deep analyzes.
137  UMK_Deep = 2
138};
139
140/// Stores options for the analyzer from the command line.
141///
142/// Some options are frontend flags (e.g.: -analyzer-output), but some are
143/// analyzer configuration options, which are preceded by -analyzer-config
144/// (e.g.: -analyzer-config notes-as-events=true).
145///
146/// If you'd like to add a new frontend flag, add it to
147/// include/clang/Driver/CC1Options.td, add a new field to store the value of
148/// that flag in this class, and initialize it in
149/// lib/Frontend/CompilerInvocation.cpp.
150///
151/// If you'd like to add a new non-checker configuration, register it in
152/// include/clang/StaticAnalyzer/Core/AnalyzerOptions.def, and refer to the
153/// top of the file for documentation.
154///
155/// If you'd like to add a new checker option, call getChecker*Option()
156/// whenever.
157///
158/// Some of the options are controlled by raw frontend flags for no good reason,
159/// and should be eventually converted into -analyzer-config flags. New analyzer
160/// options should not be implemented as frontend flags. Frontend flags still
161/// make sense for things that do not affect the actual analysis.
162class AnalyzerOptions : public RefCountedBase<AnalyzerOptions> {
163public:
164  using ConfigTable = llvm::StringMap<std::string>;
165
166  static std::vector<StringRef>
167  getRegisteredCheckers(bool IncludeExperimental = false);
168
169  /// Pair of checker name and enable/disable.
170  std::vector<std::pair<std::stringbool>> CheckersControlList;
171
172  /// A key-value table of use-specified configuration values.
173  // TODO: This shouldn't be public.
174  ConfigTable Config;
175  AnalysisStores AnalysisStoreOpt = RegionStoreModel;
176  AnalysisConstraints AnalysisConstraintsOpt = RangeConstraintsModel;
177  AnalysisDiagClients AnalysisDiagOpt = PD_HTML;
178  AnalysisPurgeMode AnalysisPurgeOpt = PurgeStmt;
179
180  std::string AnalyzeSpecificFunction;
181
182  /// File path to which the exploded graph should be dumped.
183  std::string DumpExplodedGraphTo;
184
185  /// Store full compiler invocation for reproducible instructions in the
186  /// generated report.
187  std::string FullCompilerInvocation;
188
189  /// The maximum number of times the analyzer visits a block.
190  unsigned maxBlockVisitOnPath;
191
192  /// Disable all analyzer checks.
193  ///
194  /// This flag allows one to disable analyzer checks on the code processed by
195  /// the given analysis consumer. Note, the code will get parsed and the
196  /// command-line options will get checked.
197  unsigned DisableAllChecks : 1;
198
199  unsigned ShowCheckerHelp : 1;
200  unsigned ShowEnabledCheckerList : 1;
201  unsigned ShowConfigOptionsList : 1;
202  unsigned ShouldEmitErrorsOnInvalidConfigValue : 1;
203  unsigned AnalyzeAll : 1;
204  unsigned AnalyzerDisplayProgress : 1;
205  unsigned AnalyzeNestedBlocks : 1;
206
207  unsigned eagerlyAssumeBinOpBifurcation : 1;
208
209  unsigned TrimGraph : 1;
210  unsigned visualizeExplodedGraphWithGraphViz : 1;
211  unsigned UnoptimizedCFG : 1;
212  unsigned PrintStats : 1;
213
214  /// Do not re-analyze paths leading to exhausted nodes with a different
215  /// strategy. We get better code coverage when retry is enabled.
216  unsigned NoRetryExhausted : 1;
217
218  /// The inlining stack depth limit.
219  // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
220  unsigned InlineMaxStackDepth = 5;
221
222  /// The mode of function selection used during inlining.
223  AnalysisInliningMode InliningMode = NoRedundancy;
224
225  // Create a field for each -analyzer-config option.
226#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
227                                             SHALLOW_VAL, DEEP_VAL)            \
228  ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, SHALLOW_VAL)
229
230#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
231  TYPE NAME;
232
233#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
234#undef ANALYZER_OPTION
235#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
236
237  // Create an array of all -analyzer-config command line options. Sort it in
238  // the constructor.
239  std::vector<StringRefAnalyzerConfigCmdFlags = {
240#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
241                                             SHALLOW_VAL, DEEP_VAL)            \
242  ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, SHALLOW_VAL)
243
244#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
245    CMDFLAG,
246
247#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
248#undef ANALYZER_OPTION
249#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
250  };
251
252  bool isUnknownAnalyzerConfig(StringRef Nameconst {
253
254    assert(std::is_sorted(AnalyzerConfigCmdFlags.begin(),
255                          AnalyzerConfigCmdFlags.end()));
256
257    return !std::binary_search(AnalyzerConfigCmdFlags.begin(),
258                               AnalyzerConfigCmdFlags.end(), Name);
259  }
260
261  AnalyzerOptions()
262      : DisableAllChecks(false), ShowCheckerHelp(false),
263        ShowEnabledCheckerList(false), ShowConfigOptionsList(false),
264        AnalyzeAll(false), AnalyzerDisplayProgress(false),
265        AnalyzeNestedBlocks(false), eagerlyAssumeBinOpBifurcation(false),
266        TrimGraph(false), visualizeExplodedGraphWithGraphViz(false),
267        UnoptimizedCFG(false), PrintStats(false), NoRetryExhausted(false) {
268    llvm::sort(AnalyzerConfigCmdFlags);
269  }
270
271  /// Interprets an option's string value as a boolean. The "true" string is
272  /// interpreted as true and the "false" string is interpreted as false.
273  ///
274  /// If an option value is not provided, returns the given \p DefaultVal.
275  /// @param [in] CheckerName The *full name* of the checker. One may retrieve
276  /// this from the checker object's field \c Name, or through \c
277  /// CheckerManager::getCurrentCheckName within the checker's registry
278  /// function.
279  /// Checker options are retrieved in the following format:
280  /// `-analyzer-config CheckerName:OptionName=Value.
281  /// @param [in] OptionName Name for option to retrieve.
282  /// @param [in] DefaultVal Default value returned if no such option was
283  /// specified.
284  /// @param [in] SearchInParents If set to true and the searched option was not
285  /// specified for the given checker the options for the parent packages will
286  /// be searched as well. The inner packages take precedence over the outer
287  /// ones.
288  bool getCheckerBooleanOption(StringRef CheckerNameStringRef OptionName,
289                               bool DefaultVal,
290                               bool SearchInParents = falseconst;
291
292  bool getCheckerBooleanOption(const ento::CheckerBase *CStringRef OptionName,
293                               bool DefaultVal,
294                               bool SearchInParents = falseconst;
295
296  /// Interprets an option's string value as an integer value.
297  ///
298  /// If an option value is not provided, returns the given \p DefaultVal.
299  /// @param [in] CheckerName The *full name* of the checker. One may retrieve
300  /// this from the checker object's field \c Name, or through \c
301  /// CheckerManager::getCurrentCheckName within the checker's registry
302  /// function.
303  /// Checker options are retrieved in the following format:
304  /// `-analyzer-config CheckerName:OptionName=Value.
305  /// @param [in] OptionName Name for option to retrieve.
306  /// @param [in] DefaultVal Default value returned if no such option was
307  /// specified.
308  /// @param [in] SearchInParents If set to true and the searched option was not
309  /// specified for the given checker the options for the parent packages will
310  /// be searched as well. The inner packages take precedence over the outer
311  /// ones.
312  int getCheckerIntegerOption(StringRef CheckerNameStringRef OptionName,
313                              int DefaultVal,
314                              bool SearchInParents = falseconst;
315
316  int getCheckerIntegerOption(const ento::CheckerBase *CStringRef OptionName,
317                              int DefaultVal,
318                              bool SearchInParents = falseconst;
319
320  /// Query an option's string value.
321  ///
322  /// If an option value is not provided, returns the given \p DefaultVal.
323  /// @param [in] CheckerName The *full name* of the checker. One may retrieve
324  /// this from the checker object's field \c Name, or through \c
325  /// CheckerManager::getCurrentCheckName within the checker's registry
326  /// function.
327  /// Checker options are retrieved in the following format:
328  /// `-analyzer-config CheckerName:OptionName=Value.
329  /// @param [in] OptionName Name for option to retrieve.
330  /// @param [in] DefaultVal Default value returned if no such option was
331  /// specified.
332  /// @param [in] SearchInParents If set to true and the searched option was not
333  /// specified for the given checker the options for the parent packages will
334  /// be searched as well. The inner packages take precedence over the outer
335  /// ones.
336  StringRef getCheckerStringOption(StringRef CheckerNameStringRef OptionName,
337                                   StringRef DefaultVal,
338                                   bool SearchInParents = falseconst;
339
340  StringRef getCheckerStringOption(const ento::CheckerBase *C,
341                                   StringRef OptionNameStringRef DefaultVal,
342                                   bool SearchInParents = falseconst;
343
344  /// Retrieves and sets the UserMode. This is a high-level option,
345  /// which is used to set other low-level options. It is not accessible
346  /// outside of AnalyzerOptions.
347  UserModeKind getUserMode() const;
348
349  ExplorationStrategyKind getExplorationStrategy() const;
350
351  /// Returns the inter-procedural analysis mode.
352  IPAKind getIPAMode() const;
353
354  /// Returns the option controlling which C++ member functions will be
355  /// considered for inlining.
356  ///
357  /// This is controlled by the 'c++-inlining' config option.
358  ///
359  /// \sa CXXMemberInliningMode
360  bool mayInlineCXXMemberFunction(CXXInlineableMemberKind Kconst;
361};
362
363using AnalyzerOptionsRef = IntrusiveRefCntPtr<AnalyzerOptions>;
364
365//===----------------------------------------------------------------------===//
366// We'll use AnalyzerOptions in the frontend, but we can't link the frontend
367// with clangStaticAnalyzerCore, because clangStaticAnalyzerCore depends on
368// clangFrontend.
369//
370// For this reason, implement some methods in this header file.
371//===----------------------------------------------------------------------===//
372
373inline UserModeKind AnalyzerOptions::getUserMode() const {
374  auto K = llvm::StringSwitch<llvm::Optional<UserModeKind>>(UserMode)
375    .Case("shallow", UMK_Shallow)
376    .Case("deep", UMK_Deep)
377    .Default(None);
378   (0) . __assert_fail ("K.hasValue() && \"User mode is invalid.\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h", 378, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">assert(K.hasValue() && "User mode is invalid.");
379  return K.getValue();
380}
381
382// namespace clang
383
384#endif // LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
385
clang::AnalyzerOptions::getRegisteredCheckers
clang::AnalyzerOptions::CheckersControlList
clang::AnalyzerOptions::Config
clang::AnalyzerOptions::AnalysisStoreOpt
clang::AnalyzerOptions::AnalysisConstraintsOpt
clang::AnalyzerOptions::AnalysisDiagOpt
clang::AnalyzerOptions::AnalysisPurgeOpt
clang::AnalyzerOptions::AnalyzeSpecificFunction
clang::AnalyzerOptions::DumpExplodedGraphTo
clang::AnalyzerOptions::FullCompilerInvocation
clang::AnalyzerOptions::maxBlockVisitOnPath
clang::AnalyzerOptions::DisableAllChecks
clang::AnalyzerOptions::ShowCheckerHelp
clang::AnalyzerOptions::ShowEnabledCheckerList
clang::AnalyzerOptions::ShowConfigOptionsList
clang::AnalyzerOptions::ShouldEmitErrorsOnInvalidConfigValue
clang::AnalyzerOptions::AnalyzeAll
clang::AnalyzerOptions::AnalyzerDisplayProgress
clang::AnalyzerOptions::AnalyzeNestedBlocks
clang::AnalyzerOptions::eagerlyAssumeBinOpBifurcation
clang::AnalyzerOptions::TrimGraph
clang::AnalyzerOptions::visualizeExplodedGraphWithGraphViz
clang::AnalyzerOptions::UnoptimizedCFG
clang::AnalyzerOptions::PrintStats
clang::AnalyzerOptions::NoRetryExhausted
clang::AnalyzerOptions::InlineMaxStackDepth
clang::AnalyzerOptions::InliningMode
clang::AnalyzerOptions::AnalyzerConfigCmdFlags
clang::AnalyzerOptions::isUnknownAnalyzerConfig
clang::AnalyzerOptions::getCheckerBooleanOption
clang::AnalyzerOptions::getCheckerBooleanOption
clang::AnalyzerOptions::getCheckerIntegerOption
clang::AnalyzerOptions::getCheckerIntegerOption
clang::AnalyzerOptions::getCheckerStringOption
clang::AnalyzerOptions::getCheckerStringOption
clang::AnalyzerOptions::getUserMode
clang::AnalyzerOptions::getExplorationStrategy
clang::AnalyzerOptions::getIPAMode
clang::AnalyzerOptions::mayInlineCXXMemberFunction
clang::AnalyzerOptions::getUserMode