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