ProgramState.cpp revision 8bef8238181a30e52dea380789a7e2d760eac532
1//= ProgramState.cpp - Path-Sensitive "State" for tracking values --*- C++ -*--=
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements ProgramState and ProgramStateManager.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/CFG.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
19#include "llvm/Support/raw_ostream.h"
20
21using namespace clang;
22using namespace ento;
23
24// Give the vtable for ConstraintManager somewhere to live.
25// FIXME: Move this elsewhere.
26ConstraintManager::~ConstraintManager() {}
27
28ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& env,
29                 StoreRef st, GenericDataMap gdm)
30  : stateMgr(mgr),
31    Env(env),
32    store(st.getStore()),
33    GDM(gdm),
34    refCount(0) {
35  stateMgr->getStoreManager().incrementReferenceCount(store);
36}
37
38ProgramState::ProgramState(const ProgramState &RHS)
39    : llvm::FoldingSetNode(),
40      stateMgr(RHS.stateMgr),
41      Env(RHS.Env),
42      store(RHS.store),
43      GDM(RHS.GDM),
44      refCount(0) {
45  stateMgr->getStoreManager().incrementReferenceCount(store);
46}
47
48ProgramState::~ProgramState() {
49  if (store)
50    stateMgr->getStoreManager().decrementReferenceCount(store);
51}
52
53ProgramStateManager::~ProgramStateManager() {
54  for (GDMContextsTy::iterator I=GDMContexts.begin(), E=GDMContexts.end();
55       I!=E; ++I)
56    I->second.second(I->second.first);
57}
58
59ProgramStateRef
60ProgramStateManager::removeDeadBindings(ProgramStateRef state,
61                                   const StackFrameContext *LCtx,
62                                   SymbolReaper& SymReaper) {
63
64  // This code essentially performs a "mark-and-sweep" of the VariableBindings.
65  // The roots are any Block-level exprs and Decls that our liveness algorithm
66  // tells us are live.  We then see what Decls they may reference, and keep
67  // those around.  This code more than likely can be made faster, and the
68  // frequency of which this method is called should be experimented with
69  // for optimum performance.
70  ProgramState NewState = *state;
71
72  NewState.Env = EnvMgr.removeDeadBindings(NewState.Env, SymReaper, state);
73
74  // Clean up the store.
75  StoreRef newStore = StoreMgr->removeDeadBindings(NewState.getStore(), LCtx,
76                                                   SymReaper);
77  NewState.setStore(newStore);
78  SymReaper.setReapedStore(newStore);
79
80  return getPersistentState(NewState);
81}
82
83ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state,
84                                            const StackFrameContext *InitLoc) {
85  // make up an empty state for now.
86  ProgramState State(this,
87                EnvMgr.getInitialEnvironment(),
88                StoreMgr->getInitialStore(InitLoc),
89                GDMFactory.getEmptyMap());
90
91  return getPersistentState(State);
92}
93
94ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExpr *CL,
95                                            const LocationContext *LC,
96                                            SVal V) const {
97  const StoreRef &newStore =
98    getStateManager().StoreMgr->BindCompoundLiteral(getStore(), CL, LC, V);
99  return makeWithStore(newStore);
100}
101
102ProgramStateRef ProgramState::bindDecl(const VarRegion* VR, SVal IVal) const {
103  const StoreRef &newStore =
104    getStateManager().StoreMgr->BindDecl(getStore(), VR, IVal);
105  return makeWithStore(newStore);
106}
107
108ProgramStateRef ProgramState::bindDeclWithNoInit(const VarRegion* VR) const {
109  const StoreRef &newStore =
110    getStateManager().StoreMgr->BindDeclWithNoInit(getStore(), VR);
111  return makeWithStore(newStore);
112}
113
114ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V) const {
115  ProgramStateManager &Mgr = getStateManager();
116  ProgramStateRef newState = makeWithStore(Mgr.StoreMgr->Bind(getStore(),
117                                                             LV, V));
118  const MemRegion *MR = LV.getAsRegion();
119  if (MR && Mgr.getOwningEngine())
120    return Mgr.getOwningEngine()->processRegionChange(newState, MR);
121
122  return newState;
123}
124
125ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
126  ProgramStateManager &Mgr = getStateManager();
127  const MemRegion *R = cast<loc::MemRegionVal>(loc).getRegion();
128  const StoreRef &newStore = Mgr.StoreMgr->BindDefault(getStore(), R, V);
129  ProgramStateRef new_state = makeWithStore(newStore);
130  return Mgr.getOwningEngine() ?
131           Mgr.getOwningEngine()->processRegionChange(new_state, R) :
132           new_state;
133}
134
135ProgramStateRef
136ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions,
137                                const Expr *E, unsigned Count,
138                                StoreManager::InvalidatedSymbols *IS,
139                                const CallOrObjCMessage *Call) const {
140  if (!IS) {
141    StoreManager::InvalidatedSymbols invalidated;
142    return invalidateRegionsImpl(Regions, E, Count,
143                                 invalidated, Call);
144  }
145  return invalidateRegionsImpl(Regions, E, Count, *IS, Call);
146}
147
148ProgramStateRef
149ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
150                                    const Expr *E, unsigned Count,
151                                    StoreManager::InvalidatedSymbols &IS,
152                                    const CallOrObjCMessage *Call) const {
153  ProgramStateManager &Mgr = getStateManager();
154  SubEngine* Eng = Mgr.getOwningEngine();
155
156  if (Eng && Eng->wantsRegionChangeUpdate(this)) {
157    StoreManager::InvalidatedRegions Invalidated;
158    const StoreRef &newStore
159      = Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
160                                        Call, &Invalidated);
161    ProgramStateRef newState = makeWithStore(newStore);
162    return Eng->processRegionChanges(newState, &IS, Regions, Invalidated);
163  }
164
165  const StoreRef &newStore =
166    Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
167                                    Call, NULL);
168  return makeWithStore(newStore);
169}
170
171ProgramStateRef ProgramState::unbindLoc(Loc LV) const {
172  assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
173
174  Store OldStore = getStore();
175  const StoreRef &newStore = getStateManager().StoreMgr->Remove(OldStore, LV);
176
177  if (newStore.getStore() == OldStore)
178    return this;
179
180  return makeWithStore(newStore);
181}
182
183ProgramStateRef
184ProgramState::enterStackFrame(const LocationContext *callerCtx,
185                              const StackFrameContext *calleeCtx) const {
186  const StoreRef &new_store =
187    getStateManager().StoreMgr->enterStackFrame(this, callerCtx, calleeCtx);
188  return makeWithStore(new_store);
189}
190
191SVal ProgramState::getSValAsScalarOrLoc(const MemRegion *R) const {
192  // We only want to do fetches from regions that we can actually bind
193  // values.  For example, SymbolicRegions of type 'id<...>' cannot
194  // have direct bindings (but their can be bindings on their subregions).
195  if (!R->isBoundable())
196    return UnknownVal();
197
198  if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
199    QualType T = TR->getValueType();
200    if (Loc::isLocType(T) || T->isIntegerType())
201      return getSVal(R);
202  }
203
204  return UnknownVal();
205}
206
207SVal ProgramState::getSVal(Loc location, QualType T) const {
208  SVal V = getRawSVal(cast<Loc>(location), T);
209
210  // If 'V' is a symbolic value that is *perfectly* constrained to
211  // be a constant value, use that value instead to lessen the burden
212  // on later analysis stages (so we have less symbolic values to reason
213  // about).
214  if (!T.isNull()) {
215    if (SymbolRef sym = V.getAsSymbol()) {
216      if (const llvm::APSInt *Int = getSymVal(sym)) {
217        // FIXME: Because we don't correctly model (yet) sign-extension
218        // and truncation of symbolic values, we need to convert
219        // the integer value to the correct signedness and bitwidth.
220        //
221        // This shows up in the following:
222        //
223        //   char foo();
224        //   unsigned x = foo();
225        //   if (x == 54)
226        //     ...
227        //
228        //  The symbolic value stored to 'x' is actually the conjured
229        //  symbol for the call to foo(); the type of that symbol is 'char',
230        //  not unsigned.
231        const llvm::APSInt &NewV = getBasicVals().Convert(T, *Int);
232
233        if (isa<Loc>(V))
234          return loc::ConcreteInt(NewV);
235        else
236          return nonloc::ConcreteInt(NewV);
237      }
238    }
239  }
240
241  return V;
242}
243
244ProgramStateRef ProgramState::BindExpr(const Stmt *S,
245                                           const LocationContext *LCtx,
246                                           SVal V, bool Invalidate) const{
247  Environment NewEnv =
248    getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
249                                      Invalidate);
250  if (NewEnv == Env)
251    return this;
252
253  ProgramState NewSt = *this;
254  NewSt.Env = NewEnv;
255  return getStateManager().getPersistentState(NewSt);
256}
257
258ProgramStateRef
259ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LCtx,
260                                  SVal location,
261                                  SVal V) const {
262  Environment NewEnv =
263    getStateManager().EnvMgr.bindExprAndLocation(Env,
264                                                 EnvironmentEntry(S, LCtx),
265                                                 location, V);
266
267  if (NewEnv == Env)
268    return this;
269
270  ProgramState NewSt = *this;
271  NewSt.Env = NewEnv;
272  return getStateManager().getPersistentState(NewSt);
273}
274
275ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
276                                      DefinedOrUnknownSVal UpperBound,
277                                      bool Assumption) const {
278  if (Idx.isUnknown() || UpperBound.isUnknown())
279    return this;
280
281  // Build an expression for 0 <= Idx < UpperBound.
282  // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
283  // FIXME: This should probably be part of SValBuilder.
284  ProgramStateManager &SM = getStateManager();
285  SValBuilder &svalBuilder = SM.getSValBuilder();
286  ASTContext &Ctx = svalBuilder.getContext();
287
288  // Get the offset: the minimum value of the array index type.
289  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
290  // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
291  QualType indexTy = Ctx.IntTy;
292  nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
293
294  // Adjust the index.
295  SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
296                                        cast<NonLoc>(Idx), Min, indexTy);
297  if (newIdx.isUnknownOrUndef())
298    return this;
299
300  // Adjust the upper bound.
301  SVal newBound =
302    svalBuilder.evalBinOpNN(this, BO_Add, cast<NonLoc>(UpperBound),
303                            Min, indexTy);
304
305  if (newBound.isUnknownOrUndef())
306    return this;
307
308  // Build the actual comparison.
309  SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT,
310                                cast<NonLoc>(newIdx), cast<NonLoc>(newBound),
311                                Ctx.IntTy);
312  if (inBound.isUnknownOrUndef())
313    return this;
314
315  // Finally, let the constraint manager take care of it.
316  ConstraintManager &CM = SM.getConstraintManager();
317  return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
318}
319
320ProgramStateRef ProgramStateManager::getInitialState(const LocationContext *InitLoc) {
321  ProgramState State(this,
322                EnvMgr.getInitialEnvironment(),
323                StoreMgr->getInitialStore(InitLoc),
324                GDMFactory.getEmptyMap());
325
326  return getPersistentState(State);
327}
328
329void ProgramStateManager::recycleUnusedStates() {
330  for (std::vector<ProgramState*>::iterator i = recentlyAllocatedStates.begin(),
331       e = recentlyAllocatedStates.end(); i != e; ++i) {
332    ProgramState *state = *i;
333    if (state->referencedByExplodedNode())
334      continue;
335    StateSet.RemoveNode(state);
336    freeStates.push_back(state);
337    state->~ProgramState();
338  }
339  recentlyAllocatedStates.clear();
340}
341
342ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
343                                                     ProgramStateRef FromState,
344                                                     ProgramStateRef GDMState) {
345  ProgramState NewState = *FromState;
346  NewState.GDM = GDMState->GDM;
347  return getPersistentState(NewState);
348}
349
350ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &State) {
351
352  llvm::FoldingSetNodeID ID;
353  State.Profile(ID);
354  void *InsertPos;
355
356  if (ProgramState *I = StateSet.FindNodeOrInsertPos(ID, InsertPos))
357    return I;
358
359  ProgramState *newState = 0;
360  if (!freeStates.empty()) {
361    newState = freeStates.back();
362    freeStates.pop_back();
363  }
364  else {
365    newState = (ProgramState*) Alloc.Allocate<ProgramState>();
366  }
367  new (newState) ProgramState(State);
368  StateSet.InsertNode(newState, InsertPos);
369  recentlyAllocatedStates.push_back(newState);
370  return newState;
371}
372
373ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
374  ProgramState NewSt = *this;
375  NewSt.setStore(store);
376  return getStateManager().getPersistentState(NewSt);
377}
378
379void ProgramState::setStore(const StoreRef &newStore) {
380  Store newStoreStore = newStore.getStore();
381  if (newStoreStore)
382    stateMgr->getStoreManager().incrementReferenceCount(newStoreStore);
383  if (store)
384    stateMgr->getStoreManager().decrementReferenceCount(store);
385  store = newStoreStore;
386}
387
388//===----------------------------------------------------------------------===//
389//  State pretty-printing.
390//===----------------------------------------------------------------------===//
391
392void ProgramState::print(raw_ostream &Out,
393                         const char *NL, const char *Sep) const {
394  // Print the store.
395  ProgramStateManager &Mgr = getStateManager();
396  Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
397
398  // Print out the environment.
399  Env.print(Out, NL, Sep);
400
401  // Print out the constraints.
402  Mgr.getConstraintManager().print(this, Out, NL, Sep);
403
404  // Print checker-specific data.
405  Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
406}
407
408void ProgramState::printDOT(raw_ostream &Out) const {
409  print(Out, "\\l", "\\|");
410}
411
412void ProgramState::dump() const {
413  print(llvm::errs());
414}
415
416void ProgramState::printTaint(raw_ostream &Out,
417                              const char *NL, const char *Sep) const {
418  TaintMapImpl TM = get<TaintMap>();
419
420  if (!TM.isEmpty())
421    Out <<"Tainted Symbols:" << NL;
422
423  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
424    Out << I->first << " : " << I->second << NL;
425  }
426}
427
428void ProgramState::dumpTaint() const {
429  printTaint(llvm::errs());
430}
431
432//===----------------------------------------------------------------------===//
433// Generic Data Map.
434//===----------------------------------------------------------------------===//
435
436void *const* ProgramState::FindGDM(void *K) const {
437  return GDM.lookup(K);
438}
439
440void*
441ProgramStateManager::FindGDMContext(void *K,
442                               void *(*CreateContext)(llvm::BumpPtrAllocator&),
443                               void (*DeleteContext)(void*)) {
444
445  std::pair<void*, void (*)(void*)>& p = GDMContexts[K];
446  if (!p.first) {
447    p.first = CreateContext(Alloc);
448    p.second = DeleteContext;
449  }
450
451  return p.first;
452}
453
454ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key, void *Data){
455  ProgramState::GenericDataMap M1 = St->getGDM();
456  ProgramState::GenericDataMap M2 = GDMFactory.add(M1, Key, Data);
457
458  if (M1 == M2)
459    return St;
460
461  ProgramState NewSt = *St;
462  NewSt.GDM = M2;
463  return getPersistentState(NewSt);
464}
465
466ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void *Key) {
467  ProgramState::GenericDataMap OldM = state->getGDM();
468  ProgramState::GenericDataMap NewM = GDMFactory.remove(OldM, Key);
469
470  if (NewM == OldM)
471    return state;
472
473  ProgramState NewState = *state;
474  NewState.GDM = NewM;
475  return getPersistentState(NewState);
476}
477
478void ScanReachableSymbols::anchor() { }
479
480bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
481  for (nonloc::CompoundVal::iterator I=val.begin(), E=val.end(); I!=E; ++I)
482    if (!scan(*I))
483      return false;
484
485  return true;
486}
487
488bool ScanReachableSymbols::scan(const SymExpr *sym) {
489  unsigned &isVisited = visited[sym];
490  if (isVisited)
491    return true;
492  isVisited = 1;
493
494  if (!visitor.VisitSymbol(sym))
495    return false;
496
497  // TODO: should be rewritten using SymExpr::symbol_iterator.
498  switch (sym->getKind()) {
499    case SymExpr::RegionValueKind:
500    case SymExpr::ConjuredKind:
501    case SymExpr::DerivedKind:
502    case SymExpr::ExtentKind:
503    case SymExpr::MetadataKind:
504      break;
505    case SymExpr::CastSymbolKind:
506      return scan(cast<SymbolCast>(sym)->getOperand());
507    case SymExpr::SymIntKind:
508      return scan(cast<SymIntExpr>(sym)->getLHS());
509    case SymExpr::IntSymKind:
510      return scan(cast<IntSymExpr>(sym)->getRHS());
511    case SymExpr::SymSymKind: {
512      const SymSymExpr *x = cast<SymSymExpr>(sym);
513      return scan(x->getLHS()) && scan(x->getRHS());
514    }
515  }
516  return true;
517}
518
519bool ScanReachableSymbols::scan(SVal val) {
520  if (loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&val))
521    return scan(X->getRegion());
522
523  if (nonloc::LocAsInteger *X = dyn_cast<nonloc::LocAsInteger>(&val))
524    return scan(X->getLoc());
525
526  if (SymbolRef Sym = val.getAsSymbol())
527    return scan(Sym);
528
529  if (const SymExpr *Sym = val.getAsSymbolicExpression())
530    return scan(Sym);
531
532  if (nonloc::CompoundVal *X = dyn_cast<nonloc::CompoundVal>(&val))
533    return scan(*X);
534
535  return true;
536}
537
538bool ScanReachableSymbols::scan(const MemRegion *R) {
539  if (isa<MemSpaceRegion>(R))
540    return true;
541
542  unsigned &isVisited = visited[R];
543  if (isVisited)
544    return true;
545  isVisited = 1;
546
547  // If this is a symbolic region, visit the symbol for the region.
548  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
549    if (!visitor.VisitSymbol(SR->getSymbol()))
550      return false;
551
552  // If this is a subregion, also visit the parent regions.
553  if (const SubRegion *SR = dyn_cast<SubRegion>(R))
554    if (!scan(SR->getSuperRegion()))
555      return false;
556
557  // Now look at the binding to this region (if any).
558  if (!scan(state->getSValAsScalarOrLoc(R)))
559    return false;
560
561  // Now look at the subregions.
562  if (!SRM.get())
563    SRM.reset(state->getStateManager().getStoreManager().
564                                           getSubRegionMap(state->getStore()));
565
566  return SRM->iterSubRegions(R, *this);
567}
568
569bool ProgramState::scanReachableSymbols(SVal val, SymbolVisitor& visitor) const {
570  ScanReachableSymbols S(this, visitor);
571  return S.scan(val);
572}
573
574bool ProgramState::scanReachableSymbols(const SVal *I, const SVal *E,
575                                   SymbolVisitor &visitor) const {
576  ScanReachableSymbols S(this, visitor);
577  for ( ; I != E; ++I) {
578    if (!S.scan(*I))
579      return false;
580  }
581  return true;
582}
583
584bool ProgramState::scanReachableSymbols(const MemRegion * const *I,
585                                   const MemRegion * const *E,
586                                   SymbolVisitor &visitor) const {
587  ScanReachableSymbols S(this, visitor);
588  for ( ; I != E; ++I) {
589    if (!S.scan(*I))
590      return false;
591  }
592  return true;
593}
594
595ProgramStateRef ProgramState::addTaint(const Stmt *S,
596                                           const LocationContext *LCtx,
597                                           TaintTagType Kind) const {
598  if (const Expr *E = dyn_cast_or_null<Expr>(S))
599    S = E->IgnoreParens();
600
601  SymbolRef Sym = getSVal(S, LCtx).getAsSymbol();
602  if (Sym)
603    return addTaint(Sym, Kind);
604
605  const MemRegion *R = getSVal(S, LCtx).getAsRegion();
606  addTaint(R, Kind);
607
608  // Cannot add taint, so just return the state.
609  return this;
610}
611
612ProgramStateRef ProgramState::addTaint(const MemRegion *R,
613                                           TaintTagType Kind) const {
614  if (const SymbolicRegion *SR = dyn_cast_or_null<SymbolicRegion>(R))
615    return addTaint(SR->getSymbol(), Kind);
616  return this;
617}
618
619ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
620                                           TaintTagType Kind) const {
621  // If this is a symbol cast, remove the cast before adding the taint. Taint
622  // is cast agnostic.
623  while (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
624    Sym = SC->getOperand();
625
626  ProgramStateRef NewState = set<TaintMap>(Sym, Kind);
627  assert(NewState);
628  return NewState;
629}
630
631bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
632                             TaintTagType Kind) const {
633  if (const Expr *E = dyn_cast_or_null<Expr>(S))
634    S = E->IgnoreParens();
635
636  SVal val = getSVal(S, LCtx);
637  return isTainted(val, Kind);
638}
639
640bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
641  if (const SymExpr *Sym = V.getAsSymExpr())
642    return isTainted(Sym, Kind);
643  if (const MemRegion *Reg = V.getAsRegion())
644    return isTainted(Reg, Kind);
645  return false;
646}
647
648bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
649  if (!Reg)
650    return false;
651
652  // Element region (array element) is tainted if either the base or the offset
653  // are tainted.
654  if (const ElementRegion *ER = dyn_cast<ElementRegion>(Reg))
655    return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(), K);
656
657  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(Reg))
658    return isTainted(SR->getSymbol(), K);
659
660  if (const SubRegion *ER = dyn_cast<SubRegion>(Reg))
661    return isTainted(ER->getSuperRegion(), K);
662
663  return false;
664}
665
666bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
667  if (!Sym)
668    return false;
669
670  // Traverse all the symbols this symbol depends on to see if any are tainted.
671  bool Tainted = false;
672  for (SymExpr::symbol_iterator SI = Sym->symbol_begin(), SE =Sym->symbol_end();
673       SI != SE; ++SI) {
674    assert(isa<SymbolData>(*SI));
675    const TaintTagType *Tag = get<TaintMap>(*SI);
676    Tainted = (Tag && *Tag == Kind);
677
678    // If this is a SymbolDerived with a tainted parent, it's also tainted.
679    if (const SymbolDerived *SD = dyn_cast<SymbolDerived>(*SI))
680      Tainted = Tainted || isTainted(SD->getParentSymbol(), Kind);
681
682    // If memory region is tainted, data is also tainted.
683    if (const SymbolRegionValue *SRV = dyn_cast<SymbolRegionValue>(*SI))
684      Tainted = Tainted || isTainted(SRV->getRegion(), Kind);
685
686    // If If this is a SymbolCast from a tainted value, it's also tainted.
687    if (const SymbolCast *SC = dyn_cast<SymbolCast>(*SI))
688      Tainted = Tainted || isTainted(SC->getOperand(), Kind);
689
690    if (Tainted)
691      return true;
692  }
693
694  return Tainted;
695}
696