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