clang 24.0.0git
Environment.cpp
Go to the documentation of this file.
1//===- Environment.cpp - Map from Stmt* to Locations/Values ---------------===//
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// This file defined the Environment and EnvironmentManager classes.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Expr.h"
15#include "clang/AST/ExprCXX.h"
17#include "clang/AST/Stmt.h"
18#include "clang/AST/StmtObjC.h"
21#include "clang/Basic/LLVM.h"
27#include "llvm/ADT/ImmutableMap.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32#include <cassert>
33
34using namespace clang;
35using namespace ento;
36
37static const Expr *ignoreTransparentExprs(const Expr *E) {
38 E = E->IgnoreParens();
39
40 switch (E->getStmtClass()) {
41 case Stmt::OpaqueValueExprClass:
42 if (const Expr *SE = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
43 E = SE;
44 break;
45 }
46 return E;
47 case Stmt::ExprWithCleanupsClass:
48 E = cast<ExprWithCleanups>(E)->getSubExpr();
49 break;
50 case Stmt::ConstantExprClass:
51 E = cast<ConstantExpr>(E)->getSubExpr();
52 break;
53 case Stmt::CXXBindTemporaryExprClass:
54 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
55 break;
56 case Stmt::SubstNonTypeTemplateParmExprClass:
57 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
58 break;
59 default:
60 // This is the base case: we can't look through more than we already have.
61 return E;
62 }
63
64 return ignoreTransparentExprs(E);
65}
66
68 : std::pair<const Expr *, const StackFrame *>(ignoreTransparentExprs(E),
69 SF) {}
70
71SVal Environment::lookupExpr(const EnvironmentEntry &E) const {
72 const SVal* X = ExprBindings.lookup(E);
73 if (X) {
74 SVal V = *X;
75 return V;
76 }
77 return UnknownVal();
78}
79
81 SValBuilder& svalBuilder) const {
82 const Expr *Ex = Entry.getExpr();
83 const StackFrame *SF = Entry.getStackFrame();
84
85 switch (Ex->getStmtClass()) {
86 case Stmt::CXXBindTemporaryExprClass:
87 case Stmt::ExprWithCleanupsClass:
88 case Stmt::GenericSelectionExprClass:
89 case Stmt::ConstantExprClass:
90 case Stmt::ParenExprClass:
91 case Stmt::SubstNonTypeTemplateParmExprClass:
92 llvm_unreachable("Should have been handled by ignoreTransparentExprs");
93
94 case Stmt::AddrLabelExprClass:
95 case Stmt::CharacterLiteralClass:
96 case Stmt::CXXBoolLiteralExprClass:
97 case Stmt::CXXScalarValueInitExprClass:
98 case Stmt::ImplicitValueInitExprClass:
99 case Stmt::IntegerLiteralClass:
100 case Stmt::ObjCBoolLiteralExprClass:
101 case Stmt::CXXNullPtrLiteralExprClass:
102 case Stmt::ObjCStringLiteralClass:
103 case Stmt::StringLiteralClass:
104 case Stmt::TypeTraitExprClass:
105 case Stmt::SizeOfPackExprClass:
106 case Stmt::PredefinedExprClass:
107 // Known constants; defer to SValBuilder.
108 return *svalBuilder.getConstantVal(Ex);
109
110 // Handle all other Expr* using a lookup.
111 default:
112 return lookupExpr(EnvironmentEntry(Ex, SF));
113 }
114}
115
117 const EnvironmentEntry &E,
118 SVal V,
119 bool Invalidate) {
120 if (V.isUnknown()) {
121 if (Invalidate)
122 return Environment(F.remove(Env.ExprBindings, E));
123 else
124 return Env;
125 }
126 return Environment(F.add(Env.ExprBindings, E, V));
127}
128
129namespace {
130
131class MarkLiveCallback final : public SymbolVisitor {
132 SymbolReaper &SymReaper;
133
134public:
135 MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {}
136
137 bool VisitSymbol(SymbolRef sym) override {
138 SymReaper.markLive(sym);
139 return true;
140 }
141
142 bool VisitMemRegion(const MemRegion *R) override {
143 SymReaper.markLive(R);
144 return true;
145 }
146};
147
148} // namespace
149
150// removeDeadBindings:
151// - Remove subexpression bindings.
152// - Remove dead block expression bindings.
153// - Keep live block expression bindings:
154// - Mark their reachable symbols live in SymbolReaper,
155// see ScanReachableSymbols.
156// - Mark the region in DRoots if the binding is a loc::MemRegionVal.
159 SymbolReaper &SymReaper,
160 ProgramStateRef ST) {
161 // We construct a new Environment object entirely, as this is cheaper than
162 // individually removing all the subexpression bindings (which will greatly
163 // outnumber block-level expression bindings).
165
166 MarkLiveCallback CB(SymReaper);
167 ScanReachableSymbols RSScaner(ST, CB);
168
169 llvm::ImmutableMapRef<EnvironmentEntry, SVal>
170 EBMapRef(NewEnv.ExprBindings.getRootWithoutRetain(),
171 F.getTreeFactory());
172
173 // Iterate over the block-expr bindings.
174 for (Environment::iterator I = Env.begin(), End = Env.end(); I != End; ++I) {
175 const EnvironmentEntry &BlkExpr = I.getKey();
176 SVal X = I.getData();
177
178 if (SymReaper.isLive(BlkExpr.getExpr(), BlkExpr.getStackFrame())) {
179 // Copy the binding to the new map.
180 EBMapRef = EBMapRef.add(BlkExpr, X);
181
182 // Mark all symbols in the block expr's value live.
183 RSScaner.scan(X);
184 }
185 }
186
187 NewEnv.ExprBindings = EBMapRef.asImmutableMap();
188 return NewEnv;
189}
190
191void Environment::printJson(raw_ostream &Out, const ASTContext &Ctx,
192 const StackFrame *SF, const char *NL,
193 unsigned int Space, bool IsDot) const {
194 Indent(Out, Space, IsDot) << "\"environment\": ";
195
196 if (ExprBindings.isEmpty()) {
197 Out << "null," << NL;
198 return;
199 }
200
201 ++Space;
202 if (!SF) {
203 // Find the freshest stack frame.
205 for (const auto &I : *this) {
206 const StackFrame *CurrentSF = I.first.getStackFrame();
207 if (FoundStackFrames.count(CurrentSF) == 0) {
208 // This stack frame is fresher than all other stack frames so far.
209 SF = CurrentSF;
210 FoundStackFrames.insert_range(
211 llvm::make_pointer_range(CurrentSF->parentsIncludingSelf()));
212 }
213 }
214 }
215
216 assert(SF);
217
218 Out << "{ \"pointer\": \"" << (const void *)SF << "\", \"items\": [" << NL;
220
221 SF->printJson(Out, NL, Space, IsDot, [&](const StackFrame *SF) {
222 // SF items begin
223 bool HasItem = false;
224 unsigned int InnerSpace = Space + 1;
225
226 // Store the last ExprBinding which we will print.
227 BindingsTy::iterator LastI = ExprBindings.end();
228 for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
229 ++I) {
230 if (I->first.getStackFrame() != SF)
231 continue;
232
233 if (!HasItem) {
234 HasItem = true;
235 Out << '[' << NL;
236 }
237
238 const Expr *Ex = I->first.getExpr();
239 (void)Ex;
240 assert(Ex != nullptr && "Expected non-null Expr");
241
242 LastI = I;
243 }
244
245 for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
246 ++I) {
247 if (I->first.getStackFrame() != SF)
248 continue;
249
250 const Expr *Ex = I->first.getExpr();
251 Indent(Out, InnerSpace, IsDot)
252 << "{ \"stmt_id\": " << Ex->getID(Ctx) << ", \"kind\": \""
253 << Ex->getStmtClassName() << "\", \"pretty\": ";
254 Ex->printJson(Out, nullptr, PP, /*AddQuotes=*/true);
255
256 Out << ", \"value\": ";
257 I->second.printJson(Out, /*AddQuotes=*/true);
258
259 Out << " }";
260
261 if (I != LastI)
262 Out << ',';
263 Out << NL;
264 }
265
266 if (HasItem)
267 Indent(Out, --InnerSpace, IsDot) << ']';
268 else
269 Out << "null ";
270 });
271
272 Indent(Out, --Space, IsDot) << "]}," << NL;
273}
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static const Expr * ignoreTransparentExprs(const Expr *E)
Defines the clang::Expr interface and subclasses for C++ expressions.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the Objective-C statement AST node classes.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:861
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
It represents a stack frame of the call stack.
void printJson(raw_ostream &Out, const char *NL="\n", unsigned int Space=0, bool IsDot=false, std::function< void(const StackFrame *)> printMoreInfoPerStackFrame=[](const StackFrame *) {}) const
Prints out the call stack in json format.
llvm::iterator_range< parent_iterator > parentsIncludingSelf() const
Iterates over this frame followed by all of its ancestors.
void printJson(raw_ostream &Out, PrinterHelper *Helper, const PrintingPolicy &Policy, bool AddQuotes) const
Pretty-prints in JSON format.
StmtClass getStmtClass() const
Definition Stmt.h:1502
const char * getStmtClassName() const
Definition Stmt.cpp:86
int64_t getID(const ASTContext &Context) const
Definition Stmt.cpp:379
An entry in the environment consists of a Stmt and an StackFrame.
Definition Environment.h:35
const Expr * getExpr() const
Definition Environment.h:39
const StackFrame * getStackFrame() const
Definition Environment.h:40
EnvironmentEntry(const Expr *E, const StackFrame *SF)
Environment bindExpr(Environment Env, const EnvironmentEntry &E, SVal V, bool Invalidate)
Bind a symbolic value to the given environment entry.
Environment removeDeadBindings(Environment Env, SymbolReaper &SymReaper, ProgramStateRef state)
An immutable map from EnvironmentEntries to SVals.
Definition Environment.h:55
SVal getSVal(const EnvironmentEntry &E, SValBuilder &svalBuilder) const
Fetches the current binding of the expression in the Environment.
void printJson(raw_ostream &Out, const ASTContext &Ctx, const StackFrame *SF=nullptr, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const
iterator end() const
Definition Environment.h:71
iterator begin() const
Definition Environment.h:70
BindingsTy::iterator iterator
Definition Environment.h:68
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
std::optional< SVal > getConstantVal(const Expr *E)
Returns the value of E, if it can be determined in a non-path-sensitive manner.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
A utility class that visits the reachable symbols using a custom SymbolVisitor.
bool scan(nonloc::LazyCompoundVal val)
A class responsible for cleaning up unused symbols.
bool isLive(SymbolRef sym)
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
The JSON file list parser is used to communicate input to InstallAPI.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
U cast(CodeGen::Address addr)
Definition Address.h:327
Describes how types, statements, expressions, and declarations should be printed.