clang 24.0.0git
SymbolManager.cpp
Go to the documentation of this file.
1//===- SymbolManager.h - Management of Symbolic 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 defines SymbolManager, a class that manages symbolic values
10// created for use by ExprEngine and related classes.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Expr.h"
19#include "clang/Basic/LLVM.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27#include <cassert>
28
29using namespace clang;
30using namespace ento;
31
32void SymExpr::anchor() {}
33
34StringRef SymbolConjured::getKindStr() const { return "conj_$"; }
35StringRef SymbolDerived::getKindStr() const { return "derived_$"; }
36StringRef SymbolExtent::getKindStr() const { return "extent_$"; }
37StringRef SymbolMetadata::getKindStr() const { return "meta_$"; }
38StringRef SymbolRegionValue::getKindStr() const { return "reg_$"; }
39
40LLVM_DUMP_METHOD void SymExpr::dump() const { dumpToStream(llvm::errs()); }
41
42void BinarySymExpr::dumpToStreamImpl(raw_ostream &OS, const SymExpr *Sym) {
43 OS << '(';
44 Sym->dumpToStream(OS);
45 OS << ')';
46}
47
49 const llvm::APSInt &Value) {
50 if (Value.isUnsigned())
51 OS << Value.getZExtValue();
52 else
53 OS << Value.getSExtValue();
54 if (Value.isUnsigned())
55 OS << 'U';
56}
57
60 OS << ' ' << BinaryOperator::getOpcodeStr(Op) << ' ';
61}
62
63void SymbolCast::dumpToStream(raw_ostream &os) const {
64 os << '(' << ToTy << ") (";
65 Operand->dumpToStream(os);
66 os << ')';
67}
68
69void UnarySymExpr::dumpToStream(raw_ostream &os) const {
71 bool Binary = isa<BinarySymExpr>(Operand);
72 if (Binary)
73 os << '(';
74 Operand->dumpToStream(os);
75 if (Binary)
76 os << ')';
77}
78
80 // Sometimes the CFG element is invalid, avoid dereferencing it.
81 if (Elem.getParent() == nullptr ||
82 Elem.getIndexInBlock() >= Elem.getParent()->size())
83 return nullptr;
84 switch (Elem->getKind()) {
86 if (const auto *Init = Elem->castAs<CFGInitializer>().getInitializer()) {
87 return Init->getInit();
88 }
89 return nullptr;
91 return Elem->castAs<CFGScopeBegin>().getTriggerStmt();
93 return Elem->castAs<CFGScopeEnd>().getTriggerStmt();
95 return Elem->castAs<CFGNewAllocator>().getAllocatorExpr();
97 return Elem->castAs<CFGLifetimeEnds>().getTriggerStmt();
99 return Elem->castAs<CFGLoopExit>().getLoopStmt();
101 return Elem->castAs<CFGStmt>().getStmt();
103 return Elem->castAs<CFGConstructor>().getStmt();
105 return Elem->castAs<CFGCXXRecordTypedCall>().getStmt();
107 return Elem->castAs<CFGAutomaticObjDtor>().getTriggerStmt();
109 return Elem->castAs<CFGDeleteDtor>().getDeleteExpr();
111 return nullptr;
113 return nullptr;
115 return Elem->castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
117 return nullptr;
119 return nullptr;
120 }
121 return nullptr;
122}
123
124void SymbolConjured::dumpToStream(raw_ostream &os) const {
125 os << getKindStr() << getSymbolID() << '{' << T << ", LC" << SF->getID();
126 if (auto *S = getStmt())
127 os << ", S" << S->getID(SF->getDecl()->getASTContext());
128 else
129 os << ", no stmt";
130 os << ", #" << Count << '}';
131}
132
133void SymbolDerived::dumpToStream(raw_ostream &os) const {
134 os << getKindStr() << getSymbolID() << '{' << getParentSymbol() << ','
135 << getRegion() << '}';
136}
137
138void SymbolExtent::dumpToStream(raw_ostream &os) const {
139 os << getKindStr() << getSymbolID() << '{' << getRegion() << '}';
140}
141
142void SymbolMetadata::dumpToStream(raw_ostream &os) const {
143 os << getKindStr() << getSymbolID() << '{' << getRegion() << ',' << T << '}';
144}
145
146void SymbolData::anchor() {}
147
148void SymbolRegionValue::dumpToStream(raw_ostream &os) const {
149 os << getKindStr() << getSymbolID() << '<' << getType() << ' ' << R << '>';
150}
151
152void SymExpr::symbol_iterator::expand(const SymExpr *SE) {
153 switch (SE->getKind()) {
154 case SymExpr::SymbolRegionValueKind:
155 case SymExpr::SymbolConjuredKind:
156 case SymExpr::SymbolDerivedKind:
157 case SymExpr::SymbolExtentKind:
158 case SymExpr::SymbolMetadataKind:
159 return;
160 case SymExpr::SymbolCastKind:
161 WL->push_back(cast<SymbolCast>(SE)->getOperand());
162 return;
163 case SymExpr::UnarySymExprKind:
164 WL->push_back(cast<UnarySymExpr>(SE)->getOperand());
165 return;
166 case SymExpr::SymIntExprKind:
167 WL->push_back(cast<SymIntExpr>(SE)->getLHS());
168 return;
169 case SymExpr::IntSymExprKind:
170 WL->push_back(cast<IntSymExpr>(SE)->getRHS());
171 return;
172 case SymExpr::SymSymExprKind: {
173 const auto *x = cast<SymSymExpr>(SE);
174 WL->push_back(x->getLHS());
175 WL->push_back(x->getRHS());
176 return;
177 }
178 }
179 llvm_unreachable("unhandled expansion case");
180}
181
183 return T;
184}
185
187 return R->getValueType();
188}
189
191 ASTContext &Ctx = R->getMemRegionManager().getContext();
192 return Ctx.getSizeType();
193}
194
196 return T;
197}
198
200 return R->getValueType();
201}
202
204 T = T.getCanonicalType();
205
206 if (Loc::isLocType(T))
207 return true;
208
209 if (T->isIntegralOrEnumerationType())
210 return true;
211
212 if (T->isRecordType() && !T->isUnionType())
213 return true;
214
215 return false;
216}
217
219 const SymbolRef Dependent) {
220 auto &dependencies = SymbolDependencies[Primary];
221 if (!dependencies) {
222 dependencies = std::make_unique<SymbolRefSmallVectorTy>();
223 }
224 dependencies->push_back(Dependent);
225}
226
228 const SymbolRef Primary) {
229 SymbolDependTy::const_iterator I = SymbolDependencies.find(Primary);
230 if (I == SymbolDependencies.end())
231 return nullptr;
232 return I->second.get();
233}
234
235void SymbolReaper::markDependentsLive(SymbolMapTy::iterator LI) {
236 // Do not mark dependents more then once.
237 if (LI->second == HaveMarkedDependents)
238 return;
239 LI->second = HaveMarkedDependents;
240
241 // Marking the dependents inserts into TheLiving, invalidating LI.
242 if (const auto *Deps = SymMgr.getDependentSymbols(LI->first)) {
243 for (const auto I : *Deps) {
244 if (TheLiving.contains(I))
245 continue;
246 markLive(I);
247 }
248 }
249}
250
252 markDependentsLive(TheLiving.try_emplace(Sym, NotProcessed).first);
253}
254
256 LiveRegionRoots.insert(region->getBaseRegion());
258}
259
261 LazilyCopiedRegionRoots.insert(region->getBaseRegion());
262}
263
265 for (auto SR = dyn_cast<SubRegion>(region); SR;
266 SR = dyn_cast<SubRegion>(SR->getSuperRegion())) {
267 if (const auto ER = dyn_cast<ElementRegion>(SR)) {
268 SVal Idx = ER->getIndex();
269 for (SymbolRef Sym : Idx.symbols())
270 markLive(Sym);
271 }
272 }
273}
274
276 if (isa<SymbolMetadata>(sym))
277 MetadataInUse.insert(sym);
278}
279
281 // TODO: For now, liveness of a memory region is equivalent to liveness of its
282 // base region. In fact we can do a bit better: say, if a particular FieldDecl
283 // is not used later in the path, we can diagnose a leak of a value within
284 // that field earlier than, say, the variable that contains the field dies.
285 MR = MR->getBaseRegion();
286 if (LiveRegionRoots.count(MR))
287 return true;
288
289 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
290 return isLive(SR->getSymbol());
291
292 if (const auto *VR = dyn_cast<VarRegion>(MR))
293 return isLive(VR, true);
294
295 // FIXME: This is a gross over-approximation. What we really need is a way to
296 // tell if anything still refers to this region. Unlike SymbolicRegions,
297 // AllocaRegions don't have associated symbols, though, so we don't actually
298 // have a way to track their liveness.
300}
301
302bool SymbolReaper::isLazilyCopiedRegion(const MemRegion *MR) const {
303 // TODO: See comment in isLiveRegion.
304 return LazilyCopiedRegionRoots.count(MR->getBaseRegion());
305}
306
307bool SymbolReaper::isReadableRegion(const MemRegion *MR) {
308 return isLiveRegion(MR) || isLazilyCopiedRegion(MR);
309}
310
312 if (auto LI = TheLiving.find(Sym); LI != TheLiving.end()) {
313 markDependentsLive(LI);
314 return true;
315 }
316
317 bool KnownLive;
318
319 switch (Sym->getKind()) {
320 case SymExpr::SymbolRegionValueKind:
321 KnownLive = isReadableRegion(cast<SymbolRegionValue>(Sym)->getRegion());
322 break;
323 case SymExpr::SymbolConjuredKind:
324 KnownLive = false;
325 break;
326 case SymExpr::SymbolDerivedKind:
327 KnownLive = isLive(cast<SymbolDerived>(Sym)->getParentSymbol());
328 break;
329 case SymExpr::SymbolExtentKind:
330 KnownLive = isLiveRegion(cast<SymbolExtent>(Sym)->getRegion());
331 break;
332 case SymExpr::SymbolMetadataKind:
333 KnownLive = MetadataInUse.count(Sym) &&
334 isLiveRegion(cast<SymbolMetadata>(Sym)->getRegion());
335 if (KnownLive)
336 MetadataInUse.erase(Sym);
337 break;
338 case SymExpr::SymIntExprKind:
339 KnownLive = isLive(cast<SymIntExpr>(Sym)->getLHS());
340 break;
341 case SymExpr::IntSymExprKind:
342 KnownLive = isLive(cast<IntSymExpr>(Sym)->getRHS());
343 break;
344 case SymExpr::SymSymExprKind:
345 KnownLive = isLive(cast<SymSymExpr>(Sym)->getLHS()) &&
346 isLive(cast<SymSymExpr>(Sym)->getRHS());
347 break;
348 case SymExpr::SymbolCastKind:
349 KnownLive = isLive(cast<SymbolCast>(Sym)->getOperand());
350 break;
351 case SymExpr::UnarySymExprKind:
352 KnownLive = isLive(cast<UnarySymExpr>(Sym)->getOperand());
353 break;
354 }
355
356 if (KnownLive)
357 markLive(Sym);
358
359 return KnownLive;
360}
361
362bool SymbolReaper::isLive(const Expr *ExprVal, const StackFrame *ESF) const {
363 if (SF == nullptr)
364 return false;
365
366 if (SF != ESF) {
367 // If the reaper's stack frame is a parent of the expression's
368 // stack frame, then the expression value is now "out of scope".
369 if (SF->isParentOf(ESF))
370 return false;
371 return true;
372 }
373
374 // If no statement is provided, everything in this and parent contexts is
375 // live.
376 if (!Loc)
377 return true;
378
379 return SF->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, ExprVal);
380}
381
382bool SymbolReaper::isLive(const VarRegion *VR, bool includeStoreBindings) const{
383 const StackFrame *VarSF = VR->getStackFrame();
384
385 if (!VarSF)
386 return true;
387
388 if (!SF)
389 return false;
390 const StackFrame *CurrentSF = SF;
391
392 if (VarSF == CurrentSF) {
393 // If no statement is provided, everything is live.
394 if (!Loc)
395 return true;
396
397 // Anonymous parameters of an inheriting constructor are live for the entire
398 // duration of the constructor.
400 return true;
401
402 if (SF->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, VR->getDecl()))
403 return true;
404
405 if (!includeStoreBindings)
406 return false;
407
408 unsigned &cachedQuery =
409 const_cast<SymbolReaper *>(this)->includedRegionCache[VR];
410
411 if (cachedQuery) {
412 return cachedQuery == 1;
413 }
414
415 // Query the store to see if the region occurs in any live bindings.
416 if (Store store = reapedStore.getStore()) {
417 bool hasRegion =
418 reapedStore.getStoreManager().includedInBindings(store, VR);
419 cachedQuery = hasRegion ? 1 : 2;
420 return hasRegion;
421 }
422
423 return false;
424 }
425
426 return VarSF->isParentOf(CurrentSF);
427}
Defines the clang::ASTContext interface.
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
StringRef getOpcodeStr() const
Definition Expr.h:4173
BinaryOperatorKind Opcode
Definition Expr.h:4112
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
Definition CFG.h:464
Represents a function call that returns a C++ object by value.
Definition CFG.h:190
Represents C++ constructor call.
Definition CFG.h:161
Represents C++ object destructor generated from a call to delete.
Definition CFG.h:489
@ CleanupFunction
Definition CFG.h:83
@ CXXRecordTypedCall
Definition CFG.h:72
@ FullExprCleanup
Definition CFG.h:62
@ AutomaticObjectDtor
Definition CFG.h:76
Represents C++ base or member initializer from constructor's initialization list.
Definition CFG.h:232
const CXXCtorInitializer * getInitializer() const
Definition CFG.h:237
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:321
Represents the point where a loop ends.
Definition CFG.h:278
Represents C++ allocator call.
Definition CFG.h:252
Represents beginning of a scope implicitly generated by the compiler on encountering a CompoundStmt.
Definition CFG.h:375
Represents end of a scope implicitly generated by the compiler after the last Stmt in a CompoundStmt'...
Definition CFG.h:395
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Definition CFG.h:557
This represents one expression.
Definition Expr.h:114
bool isLive(const CFGBlock *B, const VarDecl *D)
Return true if a variable is live at the end of a specified block.
A (possibly-)qualified type.
Definition TypeBase.h:938
It represents a stack frame of the call stack.
bool isParentOf(const StackFrame *SF) const
Stmt - This represents one statement.
Definition Stmt.h:85
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1438
static void dumpToStreamImpl(raw_ostream &os, const SymExpr *Value)
static bool isLocType(QualType T)
Definition SVals.h:265
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
SymExpr::symbol_range symbols() const
Definition SVals.h:162
Symbolic value.
Definition SymExpr.h:33
virtual void dumpToStream(raw_ostream &os) const
Definition SymExpr.h:82
SymExpr(Kind k, SymbolID Sym)
Definition SymExpr.h:57
Kind getKind() const
Definition SymExpr.h:70
virtual void dump() const
SymbolID getSymbolID() const
Get a unique identifier for this symbol.
Definition SymExpr.h:78
void dumpToStream(raw_ostream &os) const override
const Stmt * getStmt() const
StringRef getKindStr() const override
Get a string representation of the kind of the region.
void dumpToStream(raw_ostream &os) const override
QualType getType() const override
LLVM_ATTRIBUTE_RETURNS_NONNULL SymbolRef getParentSymbol() const
StringRef getKindStr() const override
Get a string representation of the kind of the region.
void dumpToStream(raw_ostream &os) const override
QualType getType() const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
LLVM_ATTRIBUTE_RETURNS_NONNULL const SubRegion * getRegion() const
void dumpToStream(raw_ostream &os) const override
QualType getType() const override
StringRef getKindStr() const override
Get a string representation of the kind of the region.
void addSymbolDependency(const SymbolRef Primary, const SymbolRef Dependent)
Add artificial symbol dependency.
const SymbolRefSmallVectorTy * getDependentSymbols(const SymbolRef Primary)
static bool canSymbolicate(QualType T)
void dumpToStream(raw_ostream &os) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getRegion() const
StringRef getKindStr() const override
Get a string representation of the kind of the region.
QualType getType() const override
void markElementIndicesLive(const MemRegion *region)
void markInUse(SymbolRef sym)
Marks a symbol as important to a checker.
bool isLiveRegion(const MemRegion *region)
void markLazilyCopied(const MemRegion *region)
void markLive(SymbolRef Sym)
Unconditionally marks a symbol as live.
bool isLive(SymbolRef Sym)
SymbolReaper(const StackFrame *SF, const Stmt *s, SymbolManager &symmgr, StoreManager &storeMgr)
Construct a reaper object, which removes everything which is not live before we execute statements in...
void dumpToStream(raw_ostream &os) const override
QualType getType() const override
StringRef getKindStr() const override
Get a string representation of the kind of the region.
void dumpToStream(raw_ostream &os) const override
const VarDecl * getDecl() const override=0
const StackFrame * getStackFrame() const
It might return null.
SmallVector< SymbolRef, 2 > SymbolRefSmallVectorTy
Definition SymExpr.h:163
const SymExpr * SymbolRef
Definition SymExpr.h:162
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition StoreRef.h:27
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327