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 getMinCFGSizeTreatFunctionsAsLarge
257   Optional<unsigned> MinCFGSizeTreatFunctionsAsLarge;
258 
259   /// \sa getMaxNodesPerTopLevelFunction
260   Optional<unsigned> MaxNodesPerTopLevelFunction;
261 
262   /// \sa shouldInlineLambdas
263   Optional<bool> InlineLambdas;
264 
265   /// \sa shouldWidenLoops
266   Optional<bool> WidenLoops;
267 
268   /// A helper function that retrieves option for a given full-qualified
269   /// checker name.
270   /// Options for checkers can be specified via 'analyzer-config' command-line
271   /// option.
272   /// Example:
273   /// @code-analyzer-config unix.Malloc:OptionName=CheckerOptionValue @endcode
274   /// or @code-analyzer-config unix:OptionName=GroupOptionValue @endcode
275   /// for groups of checkers.
276   /// @param [in] CheckerName  Full-qualified checker name, like
277   /// alpha.unix.StreamChecker.
278   /// @param [in] OptionName  Name of the option to get.
279   /// @param [in] Default  Default value if no option is specified.
280   /// @param [in] SearchInParents If set to true and the searched option was not
281   /// specified for the given checker the options for the parent packages will
282   /// be searched as well. The inner packages take precedence over the outer
283   /// ones.
284   /// @retval CheckerOptionValue  An option for a checker if it was specified.
285   /// @retval GroupOptionValue  An option for group if it was specified and no
286   /// checker-specific options were found. The closer group to checker,
287   /// the more priority it has. For example, @c coregroup.subgroup has more
288   /// priority than @c coregroup for @c coregroup.subgroup.CheckerName checker.
289   /// @retval Default  If nor checker option, nor group option was found.
290   StringRef getCheckerOption(StringRef CheckerName, StringRef OptionName,
291                              StringRef Default,
292                              bool SearchInParents = false);
293 
294 public:
295   /// Interprets an option's string value as a boolean. The "true" string is
296   /// interpreted as true and the "false" string is interpreted as false.
297   ///
298   /// If an option value is not provided, returns the given \p DefaultVal.
299   /// @param [in] Name Name for option to retrieve.
300   /// @param [in] DefaultVal Default value returned if no such option was
301   /// specified.
302   /// @param [in] C The optional checker parameter that can be used to restrict
303   /// the search to the options of this particular checker (and its parents
304   /// dependening on search mode).
305   /// @param [in] SearchInParents If set to true and the searched option was not
306   /// specified for the given checker the options for the parent packages will
307   /// be searched as well. The inner packages take precedence over the outer
308   /// ones.
309   bool getBooleanOption(StringRef Name, bool DefaultVal,
310                         const ento::CheckerBase *C = nullptr,
311                         bool SearchInParents = false);
312 
313   /// Variant that accepts a Optional value to cache the result.
314   ///
315   /// @param [in,out] V Return value storage, returned if parameter contains
316   /// an existing valid option, else it is used to store a return value
317   /// @param [in] Name Name for option to retrieve.
318   /// @param [in] DefaultVal Default value returned if no such option was
319   /// specified.
320   /// @param [in] C The optional checker parameter that can be used to restrict
321   /// the search to the options of this particular checker (and its parents
322   /// dependening on search mode).
323   /// @param [in] SearchInParents If set to true and the searched option was not
324   /// specified for the given checker the options for the parent packages will
325   /// be searched as well. The inner packages take precedence over the outer
326   /// ones.
327   bool getBooleanOption(Optional<bool> &V, StringRef Name, bool DefaultVal,
328                         const ento::CheckerBase *C  = nullptr,
329                         bool SearchInParents = false);
330 
331   /// Interprets an option's string value as an integer value.
332   ///
333   /// If an option value is not provided, returns the given \p DefaultVal.
334   /// @param [in] Name Name for option to retrieve.
335   /// @param [in] DefaultVal Default value returned if no such option was
336   /// specified.
337   /// @param [in] C The optional checker parameter that can be used to restrict
338   /// the search to the options of this particular checker (and its parents
339   /// dependening on search mode).
340   /// @param [in] SearchInParents If set to true and the searched option was not
341   /// specified for the given checker the options for the parent packages will
342   /// be searched as well. The inner packages take precedence over the outer
343   /// ones.
344   int getOptionAsInteger(StringRef Name, int DefaultVal,
345                          const ento::CheckerBase *C = nullptr,
346                          bool SearchInParents = false);
347 
348   /// Query an option's string value.
349   ///
350   /// If an option value is not provided, returns the given \p DefaultVal.
351   /// @param [in] Name Name for option to retrieve.
352   /// @param [in] DefaultVal Default value returned if no such option was
353   /// specified.
354   /// @param [in] C The optional checker parameter that can be used to restrict
355   /// the search to the options of this particular checker (and its parents
356   /// dependening on search mode).
357   /// @param [in] SearchInParents If set to true and the searched option was not
358   /// specified for the given checker the options for the parent packages will
359   /// be searched as well. The inner packages take precedence over the outer
360   /// ones.
361   StringRef getOptionAsString(StringRef Name, StringRef DefaultVal,
362                               const ento::CheckerBase *C = nullptr,
363                               bool SearchInParents = false);
364 
365   /// \brief Retrieves and sets the UserMode. This is a high-level option,
366   /// which is used to set other low-level options. It is not accessible
367   /// outside of AnalyzerOptions.
368   UserModeKind getUserMode();
369 
370   /// \brief Returns the inter-procedural analysis mode.
371   IPAKind getIPAMode();
372 
373   /// Returns the option controlling which C++ member functions will be
374   /// considered for inlining.
375   ///
376   /// This is controlled by the 'c++-inlining' config option.
377   ///
378   /// \sa CXXMemberInliningMode
379   bool mayInlineCXXMemberFunction(CXXInlineableMemberKind K);
380 
381   /// Returns true if ObjectiveC inlining is enabled, false otherwise.
382   bool mayInlineObjCMethod();
383 
384   /// Returns whether or not the destructors for C++ temporary objects should
385   /// be included in the CFG.
386   ///
387   /// This is controlled by the 'cfg-temporary-dtors' config option, which
388   /// accepts the values "true" and "false".
389   bool includeTemporaryDtorsInCFG();
390 
391   /// Returns whether or not C++ standard library functions may be considered
392   /// for inlining.
393   ///
394   /// This is controlled by the 'c++-stdlib-inlining' config option, which
395   /// accepts the values "true" and "false".
396   bool mayInlineCXXStandardLibrary();
397 
398   /// Returns whether or not templated functions may be considered for inlining.
399   ///
400   /// This is controlled by the 'c++-template-inlining' config option, which
401   /// accepts the values "true" and "false".
402   bool mayInlineTemplateFunctions();
403 
404   /// Returns whether or not allocator call may be considered for inlining.
405   ///
406   /// This is controlled by the 'c++-allocator-inlining' config option, which
407   /// accepts the values "true" and "false".
408   bool mayInlineCXXAllocator();
409 
410   /// Returns whether or not methods of C++ container objects may be considered
411   /// for inlining.
412   ///
413   /// This is controlled by the 'c++-container-inlining' config option, which
414   /// accepts the values "true" and "false".
415   bool mayInlineCXXContainerMethods();
416 
417   /// Returns whether or not the destructor of C++ 'shared_ptr' may be
418   /// considered for inlining.
419   ///
420   /// This covers std::shared_ptr, std::tr1::shared_ptr, and boost::shared_ptr,
421   /// and indeed any destructor named "~shared_ptr".
422   ///
423   /// This is controlled by the 'c++-shared_ptr-inlining' config option, which
424   /// accepts the values "true" and "false".
425   bool mayInlineCXXSharedPtrDtor();
426 
427   /// Returns whether or not paths that go through null returns should be
428   /// suppressed.
429   ///
430   /// This is a heuristic for avoiding bug reports with paths that go through
431   /// inlined functions that are more defensive than their callers.
432   ///
433   /// This is controlled by the 'suppress-null-return-paths' config option,
434   /// which accepts the values "true" and "false".
435   bool shouldSuppressNullReturnPaths();
436 
437   /// Returns whether a bug report should \em not be suppressed if its path
438   /// includes a call with a null argument, even if that call has a null return.
439   ///
440   /// This option has no effect when #shouldSuppressNullReturnPaths() is false.
441   ///
442   /// This is a counter-heuristic to avoid false negatives.
443   ///
444   /// This is controlled by the 'avoid-suppressing-null-argument-paths' config
445   /// option, which accepts the values "true" and "false".
446   bool shouldAvoidSuppressingNullArgumentPaths();
447 
448   /// Returns whether or not diagnostics containing inlined defensive NULL
449   /// checks should be suppressed.
450   ///
451   /// This is controlled by the 'suppress-inlined-defensive-checks' config
452   /// option, which accepts the values "true" and "false".
453   bool shouldSuppressInlinedDefensiveChecks();
454 
455   /// Returns whether or not diagnostics reported within the C++ standard
456   /// library should be suppressed.
457   ///
458   /// This is controlled by the 'suppress-c++-stdlib' config option,
459   /// which accepts the values "true" and "false".
460   bool shouldSuppressFromCXXStandardLibrary();
461 
462   /// Returns whether or not the diagnostic report should be always reported
463   /// in the main source file and not the headers.
464   ///
465   /// This is controlled by the 'report-in-main-source-file' config option,
466   /// which accepts the values "true" and "false".
467   bool shouldReportIssuesInMainSourceFile();
468 
469   /// Returns whether or not the report filename should be random or not.
470   ///
471   /// This is controlled by the 'stable-report-filename' config option,
472   /// which accepts the values "true" and "false". Default = false
473   bool shouldWriteStableReportFilename();
474 
475   /// Returns whether irrelevant parts of a bug report path should be pruned
476   /// out of the final output.
477   ///
478   /// This is controlled by the 'prune-paths' config option, which accepts the
479   /// values "true" and "false".
480   bool shouldPrunePaths();
481 
482   /// Returns true if 'static' initializers should be in conditional logic
483   /// in the CFG.
484   bool shouldConditionalizeStaticInitializers();
485 
486   // Returns the size of the functions (in basic blocks), which should be
487   // considered to be small enough to always inline.
488   //
489   // This is controlled by "ipa-always-inline-size" analyzer-config option.
490   unsigned getAlwaysInlineSize();
491 
492   // Returns the bound on the number of basic blocks in an inlined function
493   // (50 by default).
494   //
495   // This is controlled by "-analyzer-config max-inlinable-size" option.
496   unsigned getMaxInlinableSize();
497 
498   /// Returns true if the analyzer engine should synthesize fake bodies
499   /// for well-known functions.
500   bool shouldSynthesizeBodies();
501 
502   /// Returns how often nodes in the ExplodedGraph should be recycled to save
503   /// memory.
504   ///
505   /// This is controlled by the 'graph-trim-interval' config option. To disable
506   /// node reclamation, set the option to "0".
507   unsigned getGraphTrimInterval();
508 
509   /// Returns the maximum times a large function could be inlined.
510   ///
511   /// This is controlled by the 'max-times-inline-large' config option.
512   unsigned getMaxTimesInlineLarge();
513 
514   /// Returns the number of basic blocks a function needs to have to be
515   /// considered large for the 'max-times-inline-large' config option.
516   ///
517   /// This is controlled by the 'min-cfg-size-treat-functions-as-large' config
518   /// option.
519   unsigned getMinCFGSizeTreatFunctionsAsLarge();
520 
521   /// Returns the maximum number of nodes the analyzer can generate while
522   /// exploring a top level function (for each exploded graph).
523   /// 150000 is default; 0 means no limit.
524   ///
525   /// This is controlled by the 'max-nodes' config option.
526   unsigned getMaxNodesPerTopLevelFunction();
527 
528   /// Returns true if lambdas should be inlined. Otherwise a sink node will be
529   /// generated each time a LambdaExpr is visited.
530   bool shouldInlineLambdas();
531 
532   /// Returns true if the analysis should try to widen loops.
533   /// This is controlled by the 'widen-loops' config option.
534   bool shouldWidenLoops();
535 
536 public:
AnalyzerOptions()537   AnalyzerOptions() :
538     AnalysisStoreOpt(RegionStoreModel),
539     AnalysisConstraintsOpt(RangeConstraintsModel),
540     AnalysisDiagOpt(PD_HTML),
541     AnalysisPurgeOpt(PurgeStmt),
542     DisableAllChecks(0),
543     ShowCheckerHelp(0),
544     AnalyzeAll(0),
545     AnalyzerDisplayProgress(0),
546     AnalyzeNestedBlocks(0),
547     eagerlyAssumeBinOpBifurcation(0),
548     TrimGraph(0),
549     visualizeExplodedGraphWithGraphViz(0),
550     visualizeExplodedGraphWithUbiGraph(0),
551     UnoptimizedCFG(0),
552     PrintStats(0),
553     NoRetryExhausted(0),
554     // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
555     InlineMaxStackDepth(5),
556     InliningMode(NoRedundancy),
557     UserMode(UMK_NotSet),
558     IPAMode(IPAK_NotSet),
559     CXXMemberInliningMode() {}
560 
561 };
562 
563 typedef IntrusiveRefCntPtr<AnalyzerOptions> AnalyzerOptionsRef;
564 
565 }
566 
567 #endif
568