1 //== SymbolManager.h - Management of Symbolic Values ------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines SymbolManager, a class that manages symbolic values
11 // created for use by ExprEngine and related classes.
13 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
16 #include "clang/Analysis/Analyses/LiveVariables.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
19 #include "llvm/Support/raw_ostream.h"
21 using namespace clang;
24 void SymExpr::anchor() { }
26 void SymExpr::dump() const {
27 dumpToStream(llvm::errs());
30 static void print(raw_ostream &os, BinaryOperator::Opcode Op) {
33 llvm_unreachable("operator printing not implemented");
34 case BO_Mul: os << '*' ; break;
35 case BO_Div: os << '/' ; break;
36 case BO_Rem: os << '%' ; break;
37 case BO_Add: os << '+' ; break;
38 case BO_Sub: os << '-' ; break;
39 case BO_Shl: os << "<<" ; break;
40 case BO_Shr: os << ">>" ; break;
41 case BO_LT: os << "<" ; break;
42 case BO_GT: os << '>' ; break;
43 case BO_LE: os << "<=" ; break;
44 case BO_GE: os << ">=" ; break;
45 case BO_EQ: os << "==" ; break;
46 case BO_NE: os << "!=" ; break;
47 case BO_And: os << '&' ; break;
48 case BO_Xor: os << '^' ; break;
49 case BO_Or: os << '|' ; break;
53 void SymIntExpr::dumpToStream(raw_ostream &os) const {
55 getLHS()->dumpToStream(os);
57 print(os, getOpcode());
58 os << ' ' << getRHS().getZExtValue();
59 if (getRHS().isUnsigned()) os << 'U';
62 void IntSymExpr::dumpToStream(raw_ostream &os) const {
63 os << ' ' << getLHS().getZExtValue();
64 if (getLHS().isUnsigned()) os << 'U';
65 print(os, getOpcode());
67 getRHS()->dumpToStream(os);
71 void SymSymExpr::dumpToStream(raw_ostream &os) const {
73 getLHS()->dumpToStream(os);
76 getRHS()->dumpToStream(os);
80 void SymbolCast::dumpToStream(raw_ostream &os) const {
81 os << '(' << ToTy.getAsString() << ") (";
82 Operand->dumpToStream(os);
86 void SymbolConjured::dumpToStream(raw_ostream &os) const {
87 os << "conj_$" << getSymbolID() << '{' << T.getAsString() << '}';
90 void SymbolDerived::dumpToStream(raw_ostream &os) const {
91 os << "derived_$" << getSymbolID() << '{'
92 << getParentSymbol() << ',' << getRegion() << '}';
95 void SymbolExtent::dumpToStream(raw_ostream &os) const {
96 os << "extent_$" << getSymbolID() << '{' << getRegion() << '}';
99 void SymbolMetadata::dumpToStream(raw_ostream &os) const {
100 os << "meta_$" << getSymbolID() << '{'
101 << getRegion() << ',' << T.getAsString() << '}';
104 void SymbolData::anchor() { }
106 void SymbolRegionValue::dumpToStream(raw_ostream &os) const {
107 os << "reg_$" << getSymbolID() << "<" << R << ">";
110 bool SymExpr::symbol_iterator::operator==(const symbol_iterator &X) const {
114 bool SymExpr::symbol_iterator::operator!=(const symbol_iterator &X) const {
118 SymExpr::symbol_iterator::symbol_iterator(const SymExpr *SE) {
120 while (!isa<SymbolData>(itr.back())) expand();
123 SymExpr::symbol_iterator &SymExpr::symbol_iterator::operator++() {
124 assert(!itr.empty() && "attempting to iterate on an 'end' iterator");
125 assert(isa<SymbolData>(itr.back()));
128 while (!isa<SymbolData>(itr.back())) expand();
132 SymbolRef SymExpr::symbol_iterator::operator*() {
133 assert(!itr.empty() && "attempting to dereference an 'end' iterator");
134 return cast<SymbolData>(itr.back());
137 void SymExpr::symbol_iterator::expand() {
138 const SymExpr *SE = itr.back();
141 switch (SE->getKind()) {
142 case SymExpr::RegionValueKind:
143 case SymExpr::ConjuredKind:
144 case SymExpr::DerivedKind:
145 case SymExpr::ExtentKind:
146 case SymExpr::MetadataKind:
148 case SymExpr::CastSymbolKind:
149 itr.push_back(cast<SymbolCast>(SE)->getOperand());
151 case SymExpr::SymIntKind:
152 itr.push_back(cast<SymIntExpr>(SE)->getLHS());
154 case SymExpr::IntSymKind:
155 itr.push_back(cast<IntSymExpr>(SE)->getRHS());
157 case SymExpr::SymSymKind: {
158 const SymSymExpr *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*
184 SymbolManager::getConjuredSymbol(const Stmt *E, const LocationContext *LCtx,
185 QualType T, unsigned Count,
186 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) {
206 llvm::FoldingSetNodeID profile;
207 SymbolDerived::Profile(profile, parentSymbol, R);
209 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
211 SD = (SymExpr*) BPAlloc.Allocate<SymbolDerived>();
212 new (SD) SymbolDerived(SymbolCounter, parentSymbol, R);
213 DataSet.InsertNode(SD, InsertPos);
217 return cast<SymbolDerived>(SD);
221 SymbolManager::getExtentSymbol(const SubRegion *R) {
222 llvm::FoldingSetNodeID profile;
223 SymbolExtent::Profile(profile, R);
225 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
227 SD = (SymExpr*) BPAlloc.Allocate<SymbolExtent>();
228 new (SD) SymbolExtent(SymbolCounter, R);
229 DataSet.InsertNode(SD, InsertPos);
233 return cast<SymbolExtent>(SD);
236 const SymbolMetadata*
237 SymbolManager::getMetadataSymbol(const MemRegion* R, const Stmt *S, QualType T,
238 unsigned Count, const void *SymbolTag) {
240 llvm::FoldingSetNodeID profile;
241 SymbolMetadata::Profile(profile, R, S, T, Count, SymbolTag);
243 SymExpr *SD = DataSet.FindNodeOrInsertPos(profile, InsertPos);
245 SD = (SymExpr*) BPAlloc.Allocate<SymbolMetadata>();
246 new (SD) SymbolMetadata(SymbolCounter, R, S, T, Count, SymbolTag);
247 DataSet.InsertNode(SD, InsertPos);
251 return cast<SymbolMetadata>(SD);
255 SymbolManager::getCastSymbol(const SymExpr *Op,
256 QualType From, QualType To) {
257 llvm::FoldingSetNodeID ID;
258 SymbolCast::Profile(ID, Op, From, To);
260 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
262 data = (SymbolCast*) BPAlloc.Allocate<SymbolCast>();
263 new (data) SymbolCast(Op, From, To);
264 DataSet.InsertNode(data, InsertPos);
267 return cast<SymbolCast>(data);
270 const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs,
271 BinaryOperator::Opcode op,
272 const llvm::APSInt& v,
274 llvm::FoldingSetNodeID ID;
275 SymIntExpr::Profile(ID, lhs, op, v, t);
277 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
280 data = (SymIntExpr*) BPAlloc.Allocate<SymIntExpr>();
281 new (data) SymIntExpr(lhs, op, v, t);
282 DataSet.InsertNode(data, InsertPos);
285 return cast<SymIntExpr>(data);
288 const IntSymExpr *SymbolManager::getIntSymExpr(const llvm::APSInt& lhs,
289 BinaryOperator::Opcode op,
292 llvm::FoldingSetNodeID ID;
293 IntSymExpr::Profile(ID, lhs, op, rhs, t);
295 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
298 data = (IntSymExpr*) BPAlloc.Allocate<IntSymExpr>();
299 new (data) IntSymExpr(lhs, op, rhs, t);
300 DataSet.InsertNode(data, InsertPos);
303 return cast<IntSymExpr>(data);
306 const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs,
307 BinaryOperator::Opcode op,
310 llvm::FoldingSetNodeID ID;
311 SymSymExpr::Profile(ID, lhs, op, rhs, t);
313 SymExpr *data = DataSet.FindNodeOrInsertPos(ID, InsertPos);
316 data = (SymSymExpr*) BPAlloc.Allocate<SymSymExpr>();
317 new (data) SymSymExpr(lhs, op, rhs, t);
318 DataSet.InsertNode(data, InsertPos);
321 return cast<SymSymExpr>(data);
324 QualType SymbolConjured::getType(ASTContext&) const {
328 QualType SymbolDerived::getType(ASTContext &Ctx) const {
329 return R->getValueType();
332 QualType SymbolExtent::getType(ASTContext &Ctx) const {
333 return Ctx.getSizeType();
336 QualType SymbolMetadata::getType(ASTContext&) const {
340 QualType SymbolRegionValue::getType(ASTContext &C) const {
341 return R->getValueType();
344 SymbolManager::~SymbolManager() {
345 for (SymbolDependTy::const_iterator I = SymbolDependencies.begin(),
346 E = SymbolDependencies.end(); I != E; ++I) {
352 bool SymbolManager::canSymbolicate(QualType T) {
353 T = T.getCanonicalType();
355 if (Loc::isLocType(T))
358 if (T->isIntegerType())
359 return T->isScalarType();
361 if (T->isRecordType() && !T->isUnionType())
367 void SymbolManager::addSymbolDependency(const SymbolRef Primary,
368 const SymbolRef Dependent) {
369 SymbolDependTy::iterator I = SymbolDependencies.find(Primary);
370 SymbolRefSmallVectorTy *dependencies = 0;
371 if (I == SymbolDependencies.end()) {
372 dependencies = new SymbolRefSmallVectorTy();
373 SymbolDependencies[Primary] = dependencies;
375 dependencies = I->second;
377 dependencies->push_back(Dependent);
380 const SymbolRefSmallVectorTy *SymbolManager::getDependentSymbols(
381 const SymbolRef Primary) {
382 SymbolDependTy::const_iterator I = SymbolDependencies.find(Primary);
383 if (I == SymbolDependencies.end())
388 void SymbolReaper::markDependentsLive(SymbolRef sym) {
389 // Do not mark dependents more then once.
390 SymbolMapTy::iterator LI = TheLiving.find(sym);
391 assert(LI != TheLiving.end() && "The primary symbol is not live.");
392 if (LI->second == HaveMarkedDependents)
394 LI->second = HaveMarkedDependents;
396 if (const SymbolRefSmallVectorTy *Deps = SymMgr.getDependentSymbols(sym)) {
397 for (SymbolRefSmallVectorTy::const_iterator I = Deps->begin(),
398 E = Deps->end(); I != E; ++I) {
399 if (TheLiving.find(*I) != TheLiving.end())
406 void SymbolReaper::markLive(SymbolRef sym) {
407 TheLiving[sym] = NotProcessed;
409 markDependentsLive(sym);
412 void SymbolReaper::markLive(const MemRegion *region) {
413 RegionRoots.insert(region);
416 void SymbolReaper::markInUse(SymbolRef sym) {
417 if (isa<SymbolMetadata>(sym))
418 MetadataInUse.insert(sym);
421 bool SymbolReaper::maybeDead(SymbolRef sym) {
429 bool SymbolReaper::isLiveRegion(const MemRegion *MR) {
430 if (RegionRoots.count(MR))
433 MR = MR->getBaseRegion();
435 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
436 return isLive(SR->getSymbol());
438 if (const VarRegion *VR = dyn_cast<VarRegion>(MR))
439 return isLive(VR, true);
441 // FIXME: This is a gross over-approximation. What we really need is a way to
442 // tell if anything still refers to this region. Unlike SymbolicRegions,
443 // AllocaRegions don't have associated symbols, though, so we don't actually
444 // have a way to track their liveness.
445 if (isa<AllocaRegion>(MR))
448 if (isa<CXXThisRegion>(MR))
451 if (isa<MemSpaceRegion>(MR))
457 bool SymbolReaper::isLive(SymbolRef sym) {
458 if (TheLiving.count(sym)) {
459 markDependentsLive(sym);
463 if (const SymbolDerived *derived = dyn_cast<SymbolDerived>(sym)) {
464 if (isLive(derived->getParentSymbol())) {
471 if (const SymbolExtent *extent = dyn_cast<SymbolExtent>(sym)) {
472 if (isLiveRegion(extent->getRegion())) {
479 if (const SymbolMetadata *metadata = dyn_cast<SymbolMetadata>(sym)) {
480 if (MetadataInUse.count(sym)) {
481 if (isLiveRegion(metadata->getRegion())) {
483 MetadataInUse.erase(sym);
490 // Interogate the symbol. It may derive from an input value to
491 // the analyzed function/method.
492 return isa<SymbolRegionValue>(sym);
496 SymbolReaper::isLive(const Stmt *ExprVal, const LocationContext *ELCtx) const {
498 // If the reaper's location context is a parent of the expression's
499 // location context, then the expression value is now "out of scope".
500 if (LCtx->isParentOf(ELCtx))
505 return LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, ExprVal);
508 bool SymbolReaper::isLive(const VarRegion *VR, bool includeStoreBindings) const{
509 const StackFrameContext *VarContext = VR->getStackFrame();
510 const StackFrameContext *CurrentContext = LCtx->getCurrentStackFrame();
512 if (VarContext == CurrentContext) {
513 if (LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, VR->getDecl()))
516 if (!includeStoreBindings)
519 unsigned &cachedQuery =
520 const_cast<SymbolReaper*>(this)->includedRegionCache[VR];
523 return cachedQuery == 1;
526 // Query the store to see if the region occurs in any live bindings.
527 if (Store store = reapedStore.getStore()) {
529 reapedStore.getStoreManager().includedInBindings(store, VR);
530 cachedQuery = hasRegion ? 1 : 2;
537 return VarContext->isParentOf(CurrentContext);
540 SymbolVisitor::~SymbolVisitor() {}