1 //===- SymbolManager.h - Management of Symbolic Values --------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines SymbolManager, a class that manages symbolic values
10 // created for use by ExprEngine and related classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/Analysis/Analyses/LiveVariables.h"
18 #include "clang/Analysis/AnalysisDeclContext.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
32 using namespace clang;
35 void SymExpr::anchor() {}
37 LLVM_DUMP_METHOD void SymExpr::dump() const {
38 dumpToStream(llvm::errs());
41 void SymIntExpr::dumpToStream(raw_ostream &os) const {
43 getLHS()->dumpToStream(os);
45 << BinaryOperator::getOpcodeStr(getOpcode()) << ' ';
46 if (getRHS().isUnsigned())
47 os << getRHS().getZExtValue();
49 os << getRHS().getSExtValue();
50 if (getRHS().isUnsigned())
54 void IntSymExpr::dumpToStream(raw_ostream &os) const {
55 if (getLHS().isUnsigned())
56 os << getLHS().getZExtValue();
58 os << getLHS().getSExtValue();
59 if (getLHS().isUnsigned())
62 << BinaryOperator::getOpcodeStr(getOpcode())
64 getRHS()->dumpToStream(os);
68 void SymSymExpr::dumpToStream(raw_ostream &os) const {
70 getLHS()->dumpToStream(os);
72 << BinaryOperator::getOpcodeStr(getOpcode())
74 getRHS()->dumpToStream(os);
78 void SymbolCast::dumpToStream(raw_ostream &os) const {
79 os << '(' << ToTy.getAsString() << ") (";
80 Operand->dumpToStream(os);
84 void SymbolConjured::dumpToStream(raw_ostream &os) const {
85 os << "conj_$" << getSymbolID() << '{' << T.getAsString() << ", LC"
88 os << ", S" << S->getID(LCtx->getDecl()->getASTContext());
91 os << ", #" << Count << '}';
94 void SymbolDerived::dumpToStream(raw_ostream &os) const {
95 os << "derived_$" << getSymbolID() << '{'
96 << getParentSymbol() << ',' << getRegion() << '}';
99 void SymbolExtent::dumpToStream(raw_ostream &os) const {
100 os << "extent_$" << getSymbolID() << '{' << getRegion() << '}';
103 void SymbolMetadata::dumpToStream(raw_ostream &os) const {
104 os << "meta_$" << getSymbolID() << '{'
105 << getRegion() << ',' << T.getAsString() << '}';
108 void SymbolData::anchor() {}
110 void SymbolRegionValue::dumpToStream(raw_ostream &os) const {
111 os << "reg_$" << getSymbolID()
112 << '<' << getType().getAsString() << ' ' << R << '>';
115 bool SymExpr::symbol_iterator::operator==(const symbol_iterator &X) const {
119 bool SymExpr::symbol_iterator::operator!=(const symbol_iterator &X) const {
123 SymExpr::symbol_iterator::symbol_iterator(const SymExpr *SE) {
127 SymExpr::symbol_iterator &SymExpr::symbol_iterator::operator++() {
128 assert(!itr.empty() && "attempting to iterate on an 'end' iterator");
133 SymbolRef SymExpr::symbol_iterator::operator*() {
134 assert(!itr.empty() && "attempting to dereference an 'end' iterator");
138 void SymExpr::symbol_iterator::expand() {
139 const SymExpr *SE = itr.pop_back_val();
141 switch (SE->getKind()) {
142 case SymExpr::SymbolRegionValueKind:
143 case SymExpr::SymbolConjuredKind:
144 case SymExpr::SymbolDerivedKind:
145 case SymExpr::SymbolExtentKind:
146 case SymExpr::SymbolMetadataKind:
148 case SymExpr::SymbolCastKind:
149 itr.push_back(cast<SymbolCast>(SE)->getOperand());
151 case SymExpr::SymIntExprKind:
152 itr.push_back(cast<SymIntExpr>(SE)->getLHS());
154 case SymExpr::IntSymExprKind:
155 itr.push_back(cast<IntSymExpr>(SE)->getRHS());
157 case SymExpr::SymSymExprKind: {
158 const auto *x = cast<SymSymExpr>(SE);
159 itr.push_back(x->getLHS());
160 itr.push_back(x->getRHS());
164 llvm_unreachable("unhandled expansion case");
167 const SymbolRegionValue*
168 SymbolManager::getRegionValueSymbol(const TypedValueRegion* R) {
169 llvm::FoldingSetNodeID profile;
170 SymbolRegionValue::Profile(profile, R);
172 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
174 SD = (SymExpr*) BPAlloc.Allocate<SymbolRegionValue>();
175 new (SD) SymbolRegionValue(SymbolCounter, R);
176 DataSet.InsertNode(SD, InsertPos);
180 return cast<SymbolRegionValue>(SD);
183 const SymbolConjured* SymbolManager::conjureSymbol(const Stmt *E,
184 const LocationContext *LCtx,
187 const void *SymbolTag) {
188 llvm::FoldingSetNodeID profile;
189 SymbolConjured::Profile(profile, E, T, Count, LCtx, SymbolTag);
191 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
193 SD = (SymExpr*) BPAlloc.Allocate<SymbolConjured>();
194 new (SD) SymbolConjured(SymbolCounter, E, LCtx, T, Count, SymbolTag);
195 DataSet.InsertNode(SD, InsertPos);
199 return cast<SymbolConjured>(SD);
203 SymbolManager::getDerivedSymbol(SymbolRef parentSymbol,
204 const TypedValueRegion *R) {
205 llvm::FoldingSetNodeID profile;
206 SymbolDerived::Profile(profile, parentSymbol, R);
208 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
210 SD = (SymExpr*) BPAlloc.Allocate<SymbolDerived>();
211 new (SD) SymbolDerived(SymbolCounter, parentSymbol, R);
212 DataSet.InsertNode(SD, InsertPos);
216 return cast<SymbolDerived>(SD);
220 SymbolManager::getExtentSymbol(const SubRegion *R) {
221 llvm::FoldingSetNodeID profile;
222 SymbolExtent::Profile(profile, R);
224 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
226 SD = (SymExpr*) BPAlloc.Allocate<SymbolExtent>();
227 new (SD) SymbolExtent(SymbolCounter, R);
228 DataSet.InsertNode(SD, InsertPos);
232 return cast<SymbolExtent>(SD);
235 const SymbolMetadata *
236 SymbolManager::getMetadataSymbol(const MemRegion* R, const Stmt *S, QualType T,
237 const LocationContext *LCtx,
238 unsigned Count, const void *SymbolTag) {
239 llvm::FoldingSetNodeID profile;
240 SymbolMetadata::Profile(profile, R, S, T, LCtx, Count, SymbolTag);
242 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
244 SD = (SymExpr*) BPAlloc.Allocate<SymbolMetadata>();
245 new (SD) SymbolMetadata(SymbolCounter, R, S, T, LCtx, Count, SymbolTag);
246 DataSet.InsertNode(SD, InsertPos);
250 return cast<SymbolMetadata>(SD);
254 SymbolManager::getCastSymbol(const SymExpr *Op,
255 QualType From, QualType To) {
256 llvm::FoldingSetNodeID ID;
257 SymbolCast::Profile(ID, Op, From, To);
259 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
261 data = (SymbolCast*) BPAlloc.Allocate<SymbolCast>();
262 new (data) SymbolCast(Op, From, To);
263 DataSet.InsertNode(data, InsertPos);
266 return cast<SymbolCast>(data);
269 const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs,
270 BinaryOperator::Opcode op,
271 const llvm::APSInt& v,
273 llvm::FoldingSetNodeID ID;
274 SymIntExpr::Profile(ID, lhs, op, v, t);
276 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
279 data = (SymIntExpr*) BPAlloc.Allocate<SymIntExpr>();
280 new (data) SymIntExpr(lhs, op, v, t);
281 DataSet.InsertNode(data, InsertPos);
284 return cast<SymIntExpr>(data);
287 const IntSymExpr *SymbolManager::getIntSymExpr(const llvm::APSInt& lhs,
288 BinaryOperator::Opcode op,
291 llvm::FoldingSetNodeID ID;
292 IntSymExpr::Profile(ID, lhs, op, rhs, t);
294 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
297 data = (IntSymExpr*) BPAlloc.Allocate<IntSymExpr>();
298 new (data) IntSymExpr(lhs, op, rhs, t);
299 DataSet.InsertNode(data, InsertPos);
302 return cast<IntSymExpr>(data);
305 const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs,
306 BinaryOperator::Opcode op,
309 llvm::FoldingSetNodeID ID;
310 SymSymExpr::Profile(ID, lhs, op, rhs, t);
312 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
315 data = (SymSymExpr*) BPAlloc.Allocate<SymSymExpr>();
316 new (data) SymSymExpr(lhs, op, rhs, t);
317 DataSet.InsertNode(data, InsertPos);
320 return cast<SymSymExpr>(data);
323 QualType SymbolConjured::getType() const {
327 QualType SymbolDerived::getType() const {
328 return R->getValueType();
331 QualType SymbolExtent::getType() const {
332 ASTContext &Ctx = R->getMemRegionManager()->getContext();
333 return Ctx.getSizeType();
336 QualType SymbolMetadata::getType() const {
340 QualType SymbolRegionValue::getType() const {
341 return R->getValueType();
344 SymbolManager::~SymbolManager() {
345 llvm::DeleteContainerSeconds(SymbolDependencies);
348 bool SymbolManager::canSymbolicate(QualType T) {
349 T = T.getCanonicalType();
351 if (Loc::isLocType(T))
354 if (T->isIntegralOrEnumerationType())
357 if (T->isRecordType() && !T->isUnionType())
363 void SymbolManager::addSymbolDependency(const SymbolRef Primary,
364 const SymbolRef Dependent) {
365 SymbolDependTy::iterator I = SymbolDependencies.find(Primary);
366 SymbolRefSmallVectorTy *dependencies = nullptr;
367 if (I == SymbolDependencies.end()) {
368 dependencies = new SymbolRefSmallVectorTy();
369 SymbolDependencies[Primary] = dependencies;
371 dependencies = I->second;
373 dependencies->push_back(Dependent);
376 const SymbolRefSmallVectorTy *SymbolManager::getDependentSymbols(
377 const SymbolRef Primary) {
378 SymbolDependTy::const_iterator I = SymbolDependencies.find(Primary);
379 if (I == SymbolDependencies.end())
384 void SymbolReaper::markDependentsLive(SymbolRef sym) {
385 // Do not mark dependents more then once.
386 SymbolMapTy::iterator LI = TheLiving.find(sym);
387 assert(LI != TheLiving.end() && "The primary symbol is not live.");
388 if (LI->second == HaveMarkedDependents)
390 LI->second = HaveMarkedDependents;
392 if (const SymbolRefSmallVectorTy *Deps = SymMgr.getDependentSymbols(sym)) {
393 for (const auto I : *Deps) {
394 if (TheLiving.find(I) != TheLiving.end())
401 void SymbolReaper::markLive(SymbolRef sym) {
402 TheLiving[sym] = NotProcessed;
403 markDependentsLive(sym);
406 void SymbolReaper::markLive(const MemRegion *region) {
407 RegionRoots.insert(region->getBaseRegion());
408 markElementIndicesLive(region);
411 void SymbolReaper::markElementIndicesLive(const MemRegion *region) {
412 for (auto SR = dyn_cast<SubRegion>(region); SR;
413 SR = dyn_cast<SubRegion>(SR->getSuperRegion())) {
414 if (const auto ER = dyn_cast<ElementRegion>(SR)) {
415 SVal Idx = ER->getIndex();
416 for (auto SI = Idx.symbol_begin(), SE = Idx.symbol_end(); SI != SE; ++SI)
422 void SymbolReaper::markInUse(SymbolRef sym) {
423 if (isa<SymbolMetadata>(sym))
424 MetadataInUse.insert(sym);
427 bool SymbolReaper::isLiveRegion(const MemRegion *MR) {
428 // TODO: For now, liveness of a memory region is equivalent to liveness of its
429 // base region. In fact we can do a bit better: say, if a particular FieldDecl
430 // is not used later in the path, we can diagnose a leak of a value within
431 // that field earlier than, say, the variable that contains the field dies.
432 MR = MR->getBaseRegion();
434 if (RegionRoots.count(MR))
437 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
438 return isLive(SR->getSymbol());
440 if (const auto *VR = dyn_cast<VarRegion>(MR))
441 return isLive(VR, true);
443 // FIXME: This is a gross over-approximation. What we really need is a way to
444 // tell if anything still refers to this region. Unlike SymbolicRegions,
445 // AllocaRegions don't have associated symbols, though, so we don't actually
446 // have a way to track their liveness.
447 if (isa<AllocaRegion>(MR))
450 if (isa<CXXThisRegion>(MR))
453 if (isa<MemSpaceRegion>(MR))
456 if (isa<CodeTextRegion>(MR))
462 bool SymbolReaper::isLive(SymbolRef sym) {
463 if (TheLiving.count(sym)) {
464 markDependentsLive(sym);
470 switch (sym->getKind()) {
471 case SymExpr::SymbolRegionValueKind:
472 KnownLive = isLiveRegion(cast<SymbolRegionValue>(sym)->getRegion());
474 case SymExpr::SymbolConjuredKind:
477 case SymExpr::SymbolDerivedKind:
478 KnownLive = isLive(cast<SymbolDerived>(sym)->getParentSymbol());
480 case SymExpr::SymbolExtentKind:
481 KnownLive = isLiveRegion(cast<SymbolExtent>(sym)->getRegion());
483 case SymExpr::SymbolMetadataKind:
484 KnownLive = MetadataInUse.count(sym) &&
485 isLiveRegion(cast<SymbolMetadata>(sym)->getRegion());
487 MetadataInUse.erase(sym);
489 case SymExpr::SymIntExprKind:
490 KnownLive = isLive(cast<SymIntExpr>(sym)->getLHS());
492 case SymExpr::IntSymExprKind:
493 KnownLive = isLive(cast<IntSymExpr>(sym)->getRHS());
495 case SymExpr::SymSymExprKind:
496 KnownLive = isLive(cast<SymSymExpr>(sym)->getLHS()) &&
497 isLive(cast<SymSymExpr>(sym)->getRHS());
499 case SymExpr::SymbolCastKind:
500 KnownLive = isLive(cast<SymbolCast>(sym)->getOperand());
511 SymbolReaper::isLive(const Stmt *ExprVal, const LocationContext *ELCtx) const {
516 // If the reaper's location context is a parent of the expression's
517 // location context, then the expression value is now "out of scope".
518 if (LCtx->isParentOf(ELCtx))
523 // If no statement is provided, everything is this and parent contexts is live.
527 return LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, ExprVal);
530 bool SymbolReaper::isLive(const VarRegion *VR, bool includeStoreBindings) const{
531 const StackFrameContext *VarContext = VR->getStackFrame();
538 const StackFrameContext *CurrentContext = LCtx->getStackFrame();
540 if (VarContext == CurrentContext) {
541 // If no statement is provided, everything is live.
545 if (LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, VR->getDecl()))
548 if (!includeStoreBindings)
551 unsigned &cachedQuery =
552 const_cast<SymbolReaper *>(this)->includedRegionCache[VR];
555 return cachedQuery == 1;
558 // Query the store to see if the region occurs in any live bindings.
559 if (Store store = reapedStore.getStore()) {
561 reapedStore.getStoreManager().includedInBindings(store, VR);
562 cachedQuery = hasRegion ? 1 : 2;
569 return VarContext->isParentOf(CurrentContext);