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 <string>
23 #include <vector>
24 
25 namespace clang {
26 class ASTConsumer;
27 class DiagnosticsEngine;
28 class Preprocessor;
29 class LangOptions;
30 
31 namespace ento {
32 class CheckerBase;
33 }
34 
35 /// Analysis - Set of available source code analyses.
36 enum Analyses {
37 #define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME,
38 #include "clang/StaticAnalyzer/Core/Analyses.def"
39 NumAnalyses
40 };
41 
42 /// AnalysisStores - Set of available analysis store models.
43 enum AnalysisStores {
44 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
45 #include "clang/StaticAnalyzer/Core/Analyses.def"
46 NumStores
47 };
48 
49 /// AnalysisConstraints - Set of available constraint models.
50 enum AnalysisConstraints {
51 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
52 #include "clang/StaticAnalyzer/Core/Analyses.def"
53 NumConstraints
54 };
55 
56 /// AnalysisDiagClients - Set of available diagnostic clients for rendering
57 ///  analysis results.
58 enum AnalysisDiagClients {
59 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) PD_##NAME,
60 #include "clang/StaticAnalyzer/Core/Analyses.def"
61 PD_NONE,
62 NUM_ANALYSIS_DIAG_CLIENTS
63 };
64 
65 /// AnalysisPurgeModes - Set of available strategies for dead symbol removal.
66 enum AnalysisPurgeMode {
67 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) NAME,
68 #include "clang/StaticAnalyzer/Core/Analyses.def"
69 NumPurgeModes
70 };
71 
72 /// AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
73 enum AnalysisInliningMode {
74 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) NAME,
75 #include "clang/StaticAnalyzer/Core/Analyses.def"
76 NumInliningModes
77 };
78 
79 /// \brief 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.
84 enum CXXInlineableMemberKind {
85   // Uninitialized = 0,
86 
87   /// A dummy mode in which no C++ inlining is enabled.
88   CIMK_None = 1,
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 /// \brief Describes the different modes of inter-procedural analysis.
104 enum IPAKind {
105   IPAK_NotSet = 0,
106 
107   /// Perform only intra-procedural analysis.
108   IPAK_None = 1,
109 
110   /// Inline C functions and blocks when their definitions are available.
111   IPAK_BasicInlining = 2,
112 
113   /// Inline callees(C, C++, ObjC) when their definitions are available.
114   IPAK_Inlining = 3,
115 
116   /// Enable inlining of dynamically dispatched methods.
117   IPAK_DynamicDispatch = 4,
118 
119   /// Enable inlining of dynamically dispatched methods, bifurcate paths when
120   /// exact type info is unavailable.
121   IPAK_DynamicDispatchBifurcate = 5
122 };
123 
124 class AnalyzerOptions : public RefCountedBase<AnalyzerOptions> {
125 public:
126   typedef llvm::StringMap<std::string> ConfigTable;
127 
128   /// \brief Pair of checker name and enable/disable.
129   std::vector<std::pair<std::string, bool> > CheckersControlList;
130 
131   /// \brief A key-value table of use-specified configuration values.
132   ConfigTable Config;
133   AnalysisStores AnalysisStoreOpt;
134   AnalysisConstraints AnalysisConstraintsOpt;
135   AnalysisDiagClients AnalysisDiagOpt;
136   AnalysisPurgeMode AnalysisPurgeOpt;
137 
138   std::string AnalyzeSpecificFunction;
139 
140   /// \brief The maximum number of times the analyzer visits a block.
141   unsigned maxBlockVisitOnPath;
142 
143 
144   /// \brief Disable all analyzer checks.
145   ///
146   /// This flag allows one to disable analyzer checks on the code processed by
147   /// the given analysis consumer. Note, the code will get parsed and the
148   /// command-line options will get checked.
149   unsigned DisableAllChecks : 1;
150 
151   unsigned ShowCheckerHelp : 1;
152   unsigned AnalyzeAll : 1;
153   unsigned AnalyzerDisplayProgress : 1;
154   unsigned AnalyzeNestedBlocks : 1;
155 
156   /// \brief The flag regulates if we should eagerly assume evaluations of
157   /// conditionals, thus, bifurcating the path.
158   ///
159   /// This flag indicates how the engine should handle expressions such as: 'x =
160   /// (y != 0)'.  When this flag is true then the subexpression 'y != 0' will be
161   /// eagerly assumed to be true or false, thus evaluating it to the integers 0
162   /// or 1 respectively.  The upside is that this can increase analysis
163   /// precision until we have a better way to lazily evaluate such logic.  The
164   /// downside is that it eagerly bifurcates paths.
165   unsigned eagerlyAssumeBinOpBifurcation : 1;
166 
167   unsigned TrimGraph : 1;
168   unsigned visualizeExplodedGraphWithGraphViz : 1;
169   unsigned visualizeExplodedGraphWithUbiGraph : 1;
170   unsigned UnoptimizedCFG : 1;
171   unsigned PrintStats : 1;
172 
173   /// \brief Do not re-analyze paths leading to exhausted nodes with a different
174   /// strategy. We get better code coverage when retry is enabled.
175   unsigned NoRetryExhausted : 1;
176 
177   /// \brief The inlining stack depth limit.
178   unsigned InlineMaxStackDepth;
179 
180   /// \brief The mode of function selection used during inlining.
181   AnalysisInliningMode InliningMode;
182 
183 private:
184   /// \brief Describes the kinds for high-level analyzer mode.
185   enum UserModeKind {
186     UMK_NotSet = 0,
187     /// Perform shallow but fast analyzes.
188     UMK_Shallow = 1,
189     /// Perform deep analyzes.
190     UMK_Deep = 2
191   };
192 
193   /// Controls the high-level analyzer mode, which influences the default
194   /// settings for some of the lower-level config options (such as IPAMode).
195   /// \sa getUserMode
196   UserModeKind UserMode;
197 
198   /// Controls the mode of inter-procedural analysis.
199   IPAKind IPAMode;
200 
201   /// Controls which C++ member functions will be considered for inlining.
202   CXXInlineableMemberKind CXXMemberInliningMode;
203 
204   /// \sa includeTemporaryDtorsInCFG
205   Optional<bool> IncludeTemporaryDtorsInCFG;
206 
207   /// \sa mayInlineCXXStandardLibrary
208   Optional<bool> InlineCXXStandardLibrary;
209 
210   /// \sa mayInlineTemplateFunctions
211   Optional<bool> InlineTemplateFunctions;
212 
213   /// \sa mayInlineCXXAllocator
214   Optional<bool> InlineCXXAllocator;
215 
216   /// \sa mayInlineCXXContainerMethods
217   Optional<bool> InlineCXXContainerMethods;
218 
219   /// \sa mayInlineCXXSharedPtrDtor
220   Optional<bool> InlineCXXSharedPtrDtor;
221 
222   /// \sa mayInlineObjCMethod
223   Optional<bool> ObjCInliningMode;
224 
225   // Cache of the "ipa-always-inline-size" setting.
226   // \sa getAlwaysInlineSize
227   Optional<unsigned> AlwaysInlineSize;
228 
229   /// \sa shouldSuppressNullReturnPaths
230   Optional<bool> SuppressNullReturnPaths;
231 
232   // \sa getMaxInlinableSize
233   Optional<unsigned> MaxInlinableSize;
234 
235   /// \sa shouldAvoidSuppressingNullArgumentPaths
236   Optional<bool> AvoidSuppressingNullArgumentPaths;
237 
238   /// \sa shouldSuppressInlinedDefensiveChecks
239   Optional<bool> SuppressInlinedDefensiveChecks;
240 
241   /// \sa shouldSuppressFromCXXStandardLibrary
242   Optional<bool> SuppressFromCXXStandardLibrary;
243 
244   /// \sa reportIssuesInMainSourceFile
245   Optional<bool> ReportIssuesInMainSourceFile;
246 
247   /// \sa StableReportFilename
248   Optional<bool> StableReportFilename;
249 
250   /// \sa getGraphTrimInterval
251   Optional<unsigned> GraphTrimInterval;
252 
253   /// \sa getMaxTimesInlineLarge
254   Optional<unsigned> MaxTimesInlineLarge;
255 
256   /// \sa getMaxNodesPerTopLevelFunction
257   Optional<unsigned> MaxNodesPerTopLevelFunction;
258 
259   /// A helper function that retrieves option for a given full-qualified
260   /// checker name.
261   /// Options for checkers can be specified via 'analyzer-config' command-line
262   /// option.
263   /// Example:
264   /// @code-analyzer-config unix.Malloc:OptionName=CheckerOptionValue @endcode
265   /// or @code-analyzer-config unix:OptionName=GroupOptionValue @endcode
266   /// for groups of checkers.
267   /// @param [in] CheckerName  Full-qualified checker name, like
268   /// alpha.unix.StreamChecker.
269   /// @param [in] OptionName  Name of the option to get.
270   /// @param [in] Default  Default value if no option is specified.
271   /// @param [in] SearchInParents If set to true and the searched option was not
272   /// specified for the given checker the options for the parent packages will
273   /// be searched as well. The inner packages take precedence over the outer
274   /// ones.
275   /// @retval CheckerOptionValue  An option for a checker if it was specified.
276   /// @retval GroupOptionValue  An option for group if it was specified and no
277   /// checker-specific options were found. The closer group to checker,
278   /// the more priority it has. For example, @c coregroup.subgroup has more
279   /// priority than @c coregroup for @c coregroup.subgroup.CheckerName checker.
280   /// @retval Default  If nor checker option, nor group option was found.
281   StringRef getCheckerOption(StringRef CheckerName, StringRef OptionName,
282                              StringRef Default,
283                              bool SearchInParents = false);
284 
285 public:
286   /// Interprets an option's string value as a boolean. The "true" string is
287   /// interpreted as true and the "false" string is interpreted as false.
288   ///
289   /// If an option value is not provided, returns the given \p DefaultVal.
290   /// @param [in] Name Name for option to retrieve.
291   /// @param [in] DefaultVal Default value returned if no such option was
292   /// specified.
293   /// @param [in] C The optional checker parameter that can be used to restrict
294   /// the search to the options of this particular checker (and its parents
295   /// dependening on search mode).
296   /// @param [in] SearchInParents If set to true and the searched option was not
297   /// specified for the given checker the options for the parent packages will
298   /// be searched as well. The inner packages take precedence over the outer
299   /// ones.
300   bool getBooleanOption(StringRef Name, bool DefaultVal,
301                         const ento::CheckerBase *C = nullptr,
302                         bool SearchInParents = false);
303 
304   /// Variant that accepts a Optional value to cache the result.
305   ///
306   /// @param [in,out] V Return value storage, returned if parameter contains
307   /// an existing valid option, else it is used to store a return value
308   /// @param [in] Name Name for option to retrieve.
309   /// @param [in] DefaultVal Default value returned if no such option was
310   /// specified.
311   /// @param [in] C The optional checker parameter that can be used to restrict
312   /// the search to the options of this particular checker (and its parents
313   /// dependening on search mode).
314   /// @param [in] SearchInParents If set to true and the searched option was not
315   /// specified for the given checker the options for the parent packages will
316   /// be searched as well. The inner packages take precedence over the outer
317   /// ones.
318   bool getBooleanOption(Optional<bool> &V, StringRef Name, bool DefaultVal,
319                         const ento::CheckerBase *C  = nullptr,
320                         bool SearchInParents = false);
321 
322   /// Interprets an option's string value as an integer value.
323   ///
324   /// If an option value is not provided, returns the given \p DefaultVal.
325   /// @param [in] Name Name for option to retrieve.
326   /// @param [in] DefaultVal Default value returned if no such option was
327   /// specified.
328   /// @param [in] C The optional checker parameter that can be used to restrict
329   /// the search to the options of this particular checker (and its parents
330   /// dependening on search mode).
331   /// @param [in] SearchInParents If set to true and the searched option was not
332   /// specified for the given checker the options for the parent packages will
333   /// be searched as well. The inner packages take precedence over the outer
334   /// ones.
335   int getOptionAsInteger(StringRef Name, int DefaultVal,
336                          const ento::CheckerBase *C = nullptr,
337                          bool SearchInParents = false);
338 
339   /// Query an option's string value.
340   ///
341   /// If an option value is not provided, returns the given \p DefaultVal.
342   /// @param [in] Name Name for option to retrieve.
343   /// @param [in] DefaultVal Default value returned if no such option was
344   /// specified.
345   /// @param [in] C The optional checker parameter that can be used to restrict
346   /// the search to the options of this particular checker (and its parents
347   /// dependening on search mode).
348   /// @param [in] SearchInParents If set to true and the searched option was not
349   /// specified for the given checker the options for the parent packages will
350   /// be searched as well. The inner packages take precedence over the outer
351   /// ones.
352   StringRef getOptionAsString(StringRef Name, StringRef DefaultVal,
353                               const ento::CheckerBase *C = nullptr,
354                               bool SearchInParents = false);
355 
356   /// \brief Retrieves and sets the UserMode. This is a high-level option,
357   /// which is used to set other low-level options. It is not accessible
358   /// outside of AnalyzerOptions.
359   UserModeKind getUserMode();
360 
361   /// \brief Returns the inter-procedural analysis mode.
362   IPAKind getIPAMode();
363 
364   /// Returns the option controlling which C++ member functions will be
365   /// considered for inlining.
366   ///
367   /// This is controlled by the 'c++-inlining' config option.
368   ///
369   /// \sa CXXMemberInliningMode
370   bool mayInlineCXXMemberFunction(CXXInlineableMemberKind K);
371 
372   /// Returns true if ObjectiveC inlining is enabled, false otherwise.
373   bool mayInlineObjCMethod();
374 
375   /// Returns whether or not the destructors for C++ temporary objects should
376   /// be included in the CFG.
377   ///
378   /// This is controlled by the 'cfg-temporary-dtors' config option, which
379   /// accepts the values "true" and "false".
380   bool includeTemporaryDtorsInCFG();
381 
382   /// Returns whether or not C++ standard library functions may be considered
383   /// for inlining.
384   ///
385   /// This is controlled by the 'c++-stdlib-inlining' config option, which
386   /// accepts the values "true" and "false".
387   bool mayInlineCXXStandardLibrary();
388 
389   /// Returns whether or not templated functions may be considered for inlining.
390   ///
391   /// This is controlled by the 'c++-template-inlining' config option, which
392   /// accepts the values "true" and "false".
393   bool mayInlineTemplateFunctions();
394 
395   /// Returns whether or not allocator call may be considered for inlining.
396   ///
397   /// This is controlled by the 'c++-allocator-inlining' config option, which
398   /// accepts the values "true" and "false".
399   bool mayInlineCXXAllocator();
400 
401   /// Returns whether or not methods of C++ container objects may be considered
402   /// for inlining.
403   ///
404   /// This is controlled by the 'c++-container-inlining' config option, which
405   /// accepts the values "true" and "false".
406   bool mayInlineCXXContainerMethods();
407 
408   /// Returns whether or not the destructor of C++ 'shared_ptr' may be
409   /// considered for inlining.
410   ///
411   /// This covers std::shared_ptr, std::tr1::shared_ptr, and boost::shared_ptr,
412   /// and indeed any destructor named "~shared_ptr".
413   ///
414   /// This is controlled by the 'c++-shared_ptr-inlining' config option, which
415   /// accepts the values "true" and "false".
416   bool mayInlineCXXSharedPtrDtor();
417 
418   /// Returns whether or not paths that go through null returns should be
419   /// suppressed.
420   ///
421   /// This is a heuristic for avoiding bug reports with paths that go through
422   /// inlined functions that are more defensive than their callers.
423   ///
424   /// This is controlled by the 'suppress-null-return-paths' config option,
425   /// which accepts the values "true" and "false".
426   bool shouldSuppressNullReturnPaths();
427 
428   /// Returns whether a bug report should \em not be suppressed if its path
429   /// includes a call with a null argument, even if that call has a null return.
430   ///
431   /// This option has no effect when #shouldSuppressNullReturnPaths() is false.
432   ///
433   /// This is a counter-heuristic to avoid false negatives.
434   ///
435   /// This is controlled by the 'avoid-suppressing-null-argument-paths' config
436   /// option, which accepts the values "true" and "false".
437   bool shouldAvoidSuppressingNullArgumentPaths();
438 
439   /// Returns whether or not diagnostics containing inlined defensive NULL
440   /// checks should be suppressed.
441   ///
442   /// This is controlled by the 'suppress-inlined-defensive-checks' config
443   /// option, which accepts the values "true" and "false".
444   bool shouldSuppressInlinedDefensiveChecks();
445 
446   /// Returns whether or not diagnostics reported within the C++ standard
447   /// library should be suppressed.
448   ///
449   /// This is controlled by the 'suppress-c++-stdlib' config option,
450   /// which accepts the values "true" and "false".
451   bool shouldSuppressFromCXXStandardLibrary();
452 
453   /// Returns whether or not the diagnostic report should be always reported
454   /// in the main source file and not the headers.
455   ///
456   /// This is controlled by the 'report-in-main-source-file' config option,
457   /// which accepts the values "true" and "false".
458   bool shouldReportIssuesInMainSourceFile();
459 
460   /// Returns whether or not the report filename should be random or not.
461   ///
462   /// This is controlled by the 'stable-report-filename' config option,
463   /// which accepts the values "true" and "false". Default = false
464   bool shouldWriteStableReportFilename();
465 
466   /// Returns whether irrelevant parts of a bug report path should be pruned
467   /// out of the final output.
468   ///
469   /// This is controlled by the 'prune-paths' config option, which accepts the
470   /// values "true" and "false".
471   bool shouldPrunePaths();
472 
473   /// Returns true if 'static' initializers should be in conditional logic
474   /// in the CFG.
475   bool shouldConditionalizeStaticInitializers();
476 
477   // Returns the size of the functions (in basic blocks), which should be
478   // considered to be small enough to always inline.
479   //
480   // This is controlled by "ipa-always-inline-size" analyzer-config option.
481   unsigned getAlwaysInlineSize();
482 
483   // Returns the bound on the number of basic blocks in an inlined function
484   // (50 by default).
485   //
486   // This is controlled by "-analyzer-config max-inlinable-size" option.
487   unsigned getMaxInlinableSize();
488 
489   /// Returns true if the analyzer engine should synthesize fake bodies
490   /// for well-known functions.
491   bool shouldSynthesizeBodies();
492 
493   /// Returns how often nodes in the ExplodedGraph should be recycled to save
494   /// memory.
495   ///
496   /// This is controlled by the 'graph-trim-interval' config option. To disable
497   /// node reclamation, set the option to "0".
498   unsigned getGraphTrimInterval();
499 
500   /// Returns the maximum times a large function could be inlined.
501   ///
502   /// This is controlled by the 'max-times-inline-large' config option.
503   unsigned getMaxTimesInlineLarge();
504 
505   /// Returns the maximum number of nodes the analyzer can generate while
506   /// exploring a top level function (for each exploded graph).
507   /// 150000 is default; 0 means no limit.
508   ///
509   /// This is controlled by the 'max-nodes' config option.
510   unsigned getMaxNodesPerTopLevelFunction();
511 
512 public:
AnalyzerOptions()513   AnalyzerOptions() :
514     AnalysisStoreOpt(RegionStoreModel),
515     AnalysisConstraintsOpt(RangeConstraintsModel),
516     AnalysisDiagOpt(PD_HTML),
517     AnalysisPurgeOpt(PurgeStmt),
518     DisableAllChecks(0),
519     ShowCheckerHelp(0),
520     AnalyzeAll(0),
521     AnalyzerDisplayProgress(0),
522     AnalyzeNestedBlocks(0),
523     eagerlyAssumeBinOpBifurcation(0),
524     TrimGraph(0),
525     visualizeExplodedGraphWithGraphViz(0),
526     visualizeExplodedGraphWithUbiGraph(0),
527     UnoptimizedCFG(0),
528     PrintStats(0),
529     NoRetryExhausted(0),
530     // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
531     InlineMaxStackDepth(5),
532     InliningMode(NoRedundancy),
533     UserMode(UMK_NotSet),
534     IPAMode(IPAK_NotSet),
535     CXXMemberInliningMode() {}
536 
537 };
538 
539 typedef IntrusiveRefCntPtr<AnalyzerOptions> AnalyzerOptionsRef;
540 
541 }
542 
543 #endif
544