clang 24.0.0git
SSAFAnalysesCommon.h
Go to the documentation of this file.
1//===- SSAFAnalysesCommon.h -------------------------------------*- 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// Common code in SSAF analyses implementations
10//
11//===----------------------------------------------------------------------===//
12#ifndef LLVM_CLANG_SCALABLESTATICANALYSIS_ANALYSES_SSAFANALYSESCOMMON_H
13#define LLVM_CLANG_SCALABLESTATICANALYSIS_ANALYSES_SSAFANALYSESCOMMON_H
14
17#include "clang/AST/Decl.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLFunctionalExtras.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/JSON.h"
26#include "llvm/Support/raw_ostream.h"
27#include <memory>
28
29namespace clang::ssaf {
30class SSAFOptions;
31
32///\return a short descriptions of a json::Value
33std::string describeJSONValue(const llvm::json::Value &V);
34///\return a short descriptions of a json::Array
35std::string describeJSONValue(const llvm::json::Array &A);
36///\return a short descriptions of a json::Object
37std::string describeJSONValue(const llvm::json::Object &O);
38
39template <typename NodeTy, typename... Ts>
40llvm::Error makeErrAtNode(clang::ASTContext &Ctx, const NodeTy *N,
41 llvm::StringRef Fmt, const Ts &...Args) {
42 std::string LocStr = N->getBeginLoc().printToString(Ctx.getSourceManager());
43 return llvm::createStringError((Fmt + " at %s").str().c_str(), Args...,
44 LocStr.c_str());
45}
46
47template <typename JSONTy, typename... Ts>
48llvm::Error makeSawButExpectedError(const JSONTy &Saw, llvm::StringRef Expected,
49 const Ts &...ExpectedArgs) {
50 std::string Fmt = ("saw %s but expected " + Expected).str();
51 std::string SawStr = describeJSONValue(Saw);
52
53 return llvm::createStringError(Fmt.c_str(), SawStr.c_str(), ExpectedArgs...);
54}
55
56///\return true iff expression `E` has pointer or array type.
57inline bool hasPtrOrArrType(const Expr *E) {
58 return llvm::isa<clang::PointerType, clang::ArrayType>(
60}
61
62///\return true iff Decl `D` has (reference-to) pointer or array type.
63inline bool hasPtrOrArrType(const ValueDecl *D) {
64 return llvm::isa<clang::PointerType, clang::ArrayType>(
66}
67
69 const clang::NamedDecl *D);
70
71/// Log a warning from an llvm::Error
72inline void logWarningFromError(llvm::Error Err) {
73 DEBUG_WITH_TYPE("ssaf-analyses", llvm::errs() << Err);
74 llvm::consumeError(std::move(Err));
75}
76
77/// Find all contributors in an AST. The found contributors are organized as a
78/// map from the canonical declaration of each entity to all of its
79/// declarations.
80///
81/// \p Options controls which declarations qualify as contributors. By default
82/// the visitor preserves the original SSAF behavior of skipping block-scope
83/// (function-local) variable declarations; setting
84/// \c Options.IncludeLocalEntities to \c true also collects local variables
85/// (excluding function parameters, which are addressed via their parent
86/// function's USR).
88 ASTContext &Ctx, const SSAFOptions &Options,
89 llvm::DenseMap<const NamedDecl *, std::vector<const NamedDecl *>>
90 &Contributors);
91
92/// Perform "MatchAction" on each Stmt and Decl belonging to the `Contributor`.
93/// \param Contributor
94/// \param MatchActionRef a reference (view) to a "MatchAction"
95void findMatchesIn(
96 const NamedDecl *Contributor,
97 llvm::function_ref<void(const DynTypedNode &)> MatchActionRef);
98
99/// The standard contributor-summary extraction procedure:
100/// 1. Find and group all contributor decls by their canonical decls.
101/// 2. Use \p Extract to get an EntitySummary of a contributor from all of its
102/// decls.
103/// 3. Insert the EntitySummary into the \p Builder.
104///
105/// \param ExtractorFnT the template parameter that should be a function type
106/// 'std::unique_ptr<SummaryT>(std::vector<const NamedDecl *>)' for different
107/// entity summary type `SummaryT`s
108/// \param ExtractFn The function that extracts summaries of a contributor from
109/// its decls.
110/// \param ExtractorName The optional information inserted into the warning
111/// message when duplicate contributor names (EntityNames) are seen.
112template <typename ExtractorFnT>
114 TUSummaryBuilder &Builder, ASTContext &Ctx,
115 ExtractorFnT ExtractFn,
116 llvm::StringRef ExtractorName = "") {
117 llvm::DenseMap<const NamedDecl *, std::vector<const NamedDecl *>>
118 Contributors;
119 findContributors(Ctx, Extractor.getOptions(), Contributors);
120 for (const auto &[Cano, Decls] : Contributors) {
121 assert(!Decls.empty() &&
122 "'findContributors' guarantees that 'Decls' are non-empty");
123 assert(!Decls[0]->isImplicit() &&
124 "'findContributors' guarantees that 'Decls' are non-implicit");
125
126 // Templates are skipped, but their instantiations are handled. The idea
127 // is that we can conclude facts about a template through all of its
128 // instantiations.
129 if (Decls[0]->isTemplated())
130 continue;
131
132 auto Summary = ExtractFn(Decls);
133 assert(Summary);
134 if (Summary->empty())
135 continue;
136
137 if (auto Id = Extractor.addEntity(Decls[0])) {
138 if (!Builder.addSummary(*Id, std::move(Summary)).second)
140 Ctx, Decls[0], "dropping duplicate %s summary for entity %s",
141 ExtractorName.str().c_str(), Decls[0]->getNameAsString().c_str()));
142 } else
144 }
145}
146
147} // namespace clang::ssaf
148
149#endif // LLVM_CLANG_SCALABLESTATICANALYSIS_ANALYSES_SSAFANALYSESCOMMON_H
Defines the clang::ASTContext interface.
#define V(N, I)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
A dynamically typed AST node container.
This represents one expression.
Definition Expr.h:112
QualType getType() const
Definition Expr.h:144
This represents a decl that may have a name.
Definition Decl.h:274
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
const SSAFOptions & getOptions() const
std::optional< EntityId > addEntity(const NamedDecl *D)
Creates EntityName from the Decl, registers the entity, and sets its linkage atomically.
void extractAndAddSummaries(TUSummaryExtractor &Extractor, TUSummaryBuilder &Builder, ASTContext &Ctx, ExtractorFnT ExtractFn, llvm::StringRef ExtractorName="")
The standard contributor-summary extraction procedure:
bool hasPtrOrArrType(const Expr *E)
void logWarningFromError(llvm::Error Err)
Log a warning from an llvm::Error.
llvm::Error makeErrAtNode(clang::ASTContext &Ctx, const NodeTy *N, llvm::StringRef Fmt, const Ts &...Args)
llvm::Error makeEntityNameErr(clang::ASTContext &Ctx, const clang::NamedDecl *D)
void findMatchesIn(const NamedDecl *Contributor, llvm::function_ref< void(const DynTypedNode &)> MatchActionRef)
Perform "MatchAction" on each Stmt and Decl belonging to the Contributor.
llvm::Error makeSawButExpectedError(const JSONTy &Saw, llvm::StringRef Expected, const Ts &...ExpectedArgs)
std::string describeJSONValue(const llvm::json::Value &V)
void findContributors(ASTContext &Ctx, const SSAFOptions &Options, llvm::DenseMap< const NamedDecl *, std::vector< const NamedDecl * > > &Contributors)
Find all contributors in an AST.