Reusables.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //===- unittests/StaticAnalyzer/Reusables.h -------------------------------===//
  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. #ifndef LLVM_CLANG_UNITTESTS_STATICANALYZER_REUSABLES_H
  9. #define LLVM_CLANG_UNITTESTS_STATICANALYZER_REUSABLES_H
  10. #include "clang/ASTMatchers/ASTMatchFinder.h"
  11. #include "clang/Frontend/CompilerInstance.h"
  12. #include "clang/CrossTU/CrossTranslationUnit.h"
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  14. namespace clang {
  15. namespace ento {
  16. // Find a node in the current AST that matches a matcher.
  17. template <typename T, typename MatcherT>
  18. const T *findNode(const Decl *Where, MatcherT What) {
  19. using namespace ast_matchers;
  20. auto Matches = match(decl(hasDescendant(What.bind("root"))),
  21. *Where, Where->getASTContext());
  22. assert(Matches.size() <= 1 && "Ambiguous match!");
  23. assert(Matches.size() >= 1 && "Match not found!");
  24. const T *Node = selectFirst<T>("root", Matches);
  25. assert(Node && "Type mismatch!");
  26. return Node;
  27. }
  28. // Find a declaration in the current AST by name.
  29. template <typename T>
  30. const T *findDeclByName(const Decl *Where, StringRef Name) {
  31. using namespace ast_matchers;
  32. return findNode<T>(Where, namedDecl(hasName(Name)));
  33. }
  34. // A re-usable consumer that constructs ExprEngine out of CompilerInvocation.
  35. class ExprEngineConsumer : public ASTConsumer {
  36. protected:
  37. CompilerInstance &C;
  38. private:
  39. // We need to construct all of these in order to construct ExprEngine.
  40. CheckerManager ChkMgr;
  41. cross_tu::CrossTranslationUnitContext CTU;
  42. PathDiagnosticConsumers Consumers;
  43. AnalysisManager AMgr;
  44. SetOfConstDecls VisitedCallees;
  45. FunctionSummariesTy FS;
  46. protected:
  47. ExprEngine Eng;
  48. public:
  49. ExprEngineConsumer(CompilerInstance &C)
  50. : C(C), ChkMgr(C.getASTContext(), *C.getAnalyzerOpts()), CTU(C),
  51. Consumers(),
  52. AMgr(C.getASTContext(), Consumers,
  53. CreateRegionStoreManager, CreateRangeConstraintManager, &ChkMgr,
  54. *C.getAnalyzerOpts()),
  55. VisitedCallees(), FS(),
  56. Eng(CTU, AMgr, &VisitedCallees, &FS, ExprEngine::Inline_Regular) {}
  57. };
  58. } // namespace ento
  59. } // namespace clang
  60. #endif