RetainCountChecker.cpp revision 15d18e15384c9e992bd294fc56f4fdf770763d71
1//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- 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 defines the methods for RetainCountChecker, which implements
11//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
26#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/ImmutableList.h"
33#include "llvm/ADT/ImmutableMap.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include <cstdarg>
38
39using namespace clang;
40using namespace ento;
41using llvm::StrInStrNoCase;
42
43namespace {
44/// Wrapper around different kinds of node builder, so that helper functions
45/// can have a common interface.
46class GenericNodeBuilderRefCount {
47  CheckerContext *C;
48  const ProgramPointTag *tag;
49public:
50  GenericNodeBuilderRefCount(CheckerContext &c,
51                             const ProgramPointTag *t = 0)
52  : C(&c), tag(t){}
53
54  ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
55                         bool MarkAsSink = false) {
56    return C->addTransition(state, Pred, tag, MarkAsSink);
57  }
58};
59} // end anonymous namespace
60
61//===----------------------------------------------------------------------===//
62// Primitives used for constructing summaries for function/method calls.
63//===----------------------------------------------------------------------===//
64
65/// ArgEffect is used to summarize a function/method call's effect on a
66/// particular argument.
67enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
68                 DecRefBridgedTransfered,
69                 DecRefAndStopTracking, DecRefMsgAndStopTracking,
70                 IncRefMsg, IncRef, MakeCollectable, MayEscape,
71                 NewAutoreleasePool, StopTracking };
72
73namespace llvm {
74template <> struct FoldingSetTrait<ArgEffect> {
75static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
76  ID.AddInteger((unsigned) X);
77}
78};
79} // end llvm namespace
80
81/// ArgEffects summarizes the effects of a function/method call on all of
82/// its arguments.
83typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
84
85namespace {
86
87///  RetEffect is used to summarize a function/method call's behavior with
88///  respect to its return value.
89class RetEffect {
90public:
91  enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
92              NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
93              OwnedWhenTrackedReceiver };
94
95  enum ObjKind { CF, ObjC, AnyObj };
96
97private:
98  Kind K;
99  ObjKind O;
100
101  RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
102
103public:
104  Kind getKind() const { return K; }
105
106  ObjKind getObjKind() const { return O; }
107
108  bool isOwned() const {
109    return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
110           K == OwnedWhenTrackedReceiver;
111  }
112
113  bool operator==(const RetEffect &Other) const {
114    return K == Other.K && O == Other.O;
115  }
116
117  static RetEffect MakeOwnedWhenTrackedReceiver() {
118    return RetEffect(OwnedWhenTrackedReceiver, ObjC);
119  }
120
121  static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
122    return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
123  }
124  static RetEffect MakeNotOwned(ObjKind o) {
125    return RetEffect(NotOwnedSymbol, o);
126  }
127  static RetEffect MakeGCNotOwned() {
128    return RetEffect(GCNotOwnedSymbol, ObjC);
129  }
130  static RetEffect MakeARCNotOwned() {
131    return RetEffect(ARCNotOwnedSymbol, ObjC);
132  }
133  static RetEffect MakeNoRet() {
134    return RetEffect(NoRet);
135  }
136
137  void Profile(llvm::FoldingSetNodeID& ID) const {
138    ID.AddInteger((unsigned) K);
139    ID.AddInteger((unsigned) O);
140  }
141};
142
143//===----------------------------------------------------------------------===//
144// Reference-counting logic (typestate + counts).
145//===----------------------------------------------------------------------===//
146
147class RefVal {
148public:
149  enum Kind {
150    Owned = 0, // Owning reference.
151    NotOwned,  // Reference is not owned by still valid (not freed).
152    Released,  // Object has been released.
153    ReturnedOwned, // Returned object passes ownership to caller.
154    ReturnedNotOwned, // Return object does not pass ownership to caller.
155    ERROR_START,
156    ErrorDeallocNotOwned, // -dealloc called on non-owned object.
157    ErrorDeallocGC, // Calling -dealloc with GC enabled.
158    ErrorUseAfterRelease, // Object used after released.
159    ErrorReleaseNotOwned, // Release of an object that was not owned.
160    ERROR_LEAK_START,
161    ErrorLeak,  // A memory leak due to excessive reference counts.
162    ErrorLeakReturned, // A memory leak due to the returning method not having
163                       // the correct naming conventions.
164    ErrorGCLeakReturned,
165    ErrorOverAutorelease,
166    ErrorReturnedNotOwned
167  };
168
169private:
170  Kind kind;
171  RetEffect::ObjKind okind;
172  unsigned Cnt;
173  unsigned ACnt;
174  QualType T;
175
176  RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
177  : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
178
179public:
180  Kind getKind() const { return kind; }
181
182  RetEffect::ObjKind getObjKind() const { return okind; }
183
184  unsigned getCount() const { return Cnt; }
185  unsigned getAutoreleaseCount() const { return ACnt; }
186  unsigned getCombinedCounts() const { return Cnt + ACnt; }
187  void clearCounts() { Cnt = 0; ACnt = 0; }
188  void setCount(unsigned i) { Cnt = i; }
189  void setAutoreleaseCount(unsigned i) { ACnt = i; }
190
191  QualType getType() const { return T; }
192
193  bool isOwned() const {
194    return getKind() == Owned;
195  }
196
197  bool isNotOwned() const {
198    return getKind() == NotOwned;
199  }
200
201  bool isReturnedOwned() const {
202    return getKind() == ReturnedOwned;
203  }
204
205  bool isReturnedNotOwned() const {
206    return getKind() == ReturnedNotOwned;
207  }
208
209  static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
210                          unsigned Count = 1) {
211    return RefVal(Owned, o, Count, 0, t);
212  }
213
214  static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
215                             unsigned Count = 0) {
216    return RefVal(NotOwned, o, Count, 0, t);
217  }
218
219  // Comparison, profiling, and pretty-printing.
220
221  bool operator==(const RefVal& X) const {
222    return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
223  }
224
225  RefVal operator-(size_t i) const {
226    return RefVal(getKind(), getObjKind(), getCount() - i,
227                  getAutoreleaseCount(), getType());
228  }
229
230  RefVal operator+(size_t i) const {
231    return RefVal(getKind(), getObjKind(), getCount() + i,
232                  getAutoreleaseCount(), getType());
233  }
234
235  RefVal operator^(Kind k) const {
236    return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
237                  getType());
238  }
239
240  RefVal autorelease() const {
241    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
242                  getType());
243  }
244
245  void Profile(llvm::FoldingSetNodeID& ID) const {
246    ID.AddInteger((unsigned) kind);
247    ID.AddInteger(Cnt);
248    ID.AddInteger(ACnt);
249    ID.Add(T);
250  }
251
252  void print(raw_ostream &Out) const;
253};
254
255void RefVal::print(raw_ostream &Out) const {
256  if (!T.isNull())
257    Out << "Tracked " << T.getAsString() << '/';
258
259  switch (getKind()) {
260    default: llvm_unreachable("Invalid RefVal kind");
261    case Owned: {
262      Out << "Owned";
263      unsigned cnt = getCount();
264      if (cnt) Out << " (+ " << cnt << ")";
265      break;
266    }
267
268    case NotOwned: {
269      Out << "NotOwned";
270      unsigned cnt = getCount();
271      if (cnt) Out << " (+ " << cnt << ")";
272      break;
273    }
274
275    case ReturnedOwned: {
276      Out << "ReturnedOwned";
277      unsigned cnt = getCount();
278      if (cnt) Out << " (+ " << cnt << ")";
279      break;
280    }
281
282    case ReturnedNotOwned: {
283      Out << "ReturnedNotOwned";
284      unsigned cnt = getCount();
285      if (cnt) Out << " (+ " << cnt << ")";
286      break;
287    }
288
289    case Released:
290      Out << "Released";
291      break;
292
293    case ErrorDeallocGC:
294      Out << "-dealloc (GC)";
295      break;
296
297    case ErrorDeallocNotOwned:
298      Out << "-dealloc (not-owned)";
299      break;
300
301    case ErrorLeak:
302      Out << "Leaked";
303      break;
304
305    case ErrorLeakReturned:
306      Out << "Leaked (Bad naming)";
307      break;
308
309    case ErrorGCLeakReturned:
310      Out << "Leaked (GC-ed at return)";
311      break;
312
313    case ErrorUseAfterRelease:
314      Out << "Use-After-Release [ERROR]";
315      break;
316
317    case ErrorReleaseNotOwned:
318      Out << "Release of Not-Owned [ERROR]";
319      break;
320
321    case RefVal::ErrorOverAutorelease:
322      Out << "Over autoreleased";
323      break;
324
325    case RefVal::ErrorReturnedNotOwned:
326      Out << "Non-owned object returned instead of owned";
327      break;
328  }
329
330  if (ACnt) {
331    Out << " [ARC +" << ACnt << ']';
332  }
333}
334} //end anonymous namespace
335
336//===----------------------------------------------------------------------===//
337// RefBindings - State used to track object reference counts.
338//===----------------------------------------------------------------------===//
339
340typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
341
342namespace clang {
343namespace ento {
344template<>
345struct ProgramStateTrait<RefBindings>
346  : public ProgramStatePartialTrait<RefBindings> {
347  static void *GDMIndex() {
348    static int RefBIndex = 0;
349    return &RefBIndex;
350  }
351};
352}
353}
354
355//===----------------------------------------------------------------------===//
356// Function/Method behavior summaries.
357//===----------------------------------------------------------------------===//
358
359namespace {
360class RetainSummary {
361  /// Args - a map of (index, ArgEffect) pairs, where index
362  ///  specifies the argument (starting from 0).  This can be sparsely
363  ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
364  ArgEffects Args;
365
366  /// DefaultArgEffect - The default ArgEffect to apply to arguments that
367  ///  do not have an entry in Args.
368  ArgEffect DefaultArgEffect;
369
370  /// Receiver - If this summary applies to an Objective-C message expression,
371  ///  this is the effect applied to the state of the receiver.
372  ArgEffect Receiver;
373
374  /// Ret - The effect on the return value.  Used to indicate if the
375  ///  function/method call returns a new tracked symbol.
376  RetEffect Ret;
377
378public:
379  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
380                ArgEffect ReceiverEff)
381    : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
382
383  /// getArg - Return the argument effect on the argument specified by
384  ///  idx (starting from 0).
385  ArgEffect getArg(unsigned idx) const {
386    if (const ArgEffect *AE = Args.lookup(idx))
387      return *AE;
388
389    return DefaultArgEffect;
390  }
391
392  void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
393    Args = af.add(Args, idx, e);
394  }
395
396  /// setDefaultArgEffect - Set the default argument effect.
397  void setDefaultArgEffect(ArgEffect E) {
398    DefaultArgEffect = E;
399  }
400
401  /// getRetEffect - Returns the effect on the return value of the call.
402  RetEffect getRetEffect() const { return Ret; }
403
404  /// setRetEffect - Set the effect of the return value of the call.
405  void setRetEffect(RetEffect E) { Ret = E; }
406
407
408  /// Sets the effect on the receiver of the message.
409  void setReceiverEffect(ArgEffect e) { Receiver = e; }
410
411  /// getReceiverEffect - Returns the effect on the receiver of the call.
412  ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
413  ArgEffect getReceiverEffect() const { return Receiver; }
414
415  /// Test if two retain summaries are identical. Note that merely equivalent
416  /// summaries are not necessarily identical (for example, if an explicit
417  /// argument effect matches the default effect).
418  bool operator==(const RetainSummary &Other) const {
419    return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
420           Receiver == Other.Receiver && Ret == Other.Ret;
421  }
422
423  /// Profile this summary for inclusion in a FoldingSet.
424  void Profile(llvm::FoldingSetNodeID& ID) const {
425    ID.Add(Args);
426    ID.Add(DefaultArgEffect);
427    ID.Add(Receiver);
428    ID.Add(Ret);
429  }
430
431  /// A retain summary is simple if it has no ArgEffects other than the default.
432  bool isSimple() const {
433    return Args.isEmpty();
434  }
435
436private:
437  ArgEffects getArgEffects() const { return Args; }
438  ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
439
440  friend class RetainSummaryManager;
441};
442} // end anonymous namespace
443
444//===----------------------------------------------------------------------===//
445// Data structures for constructing summaries.
446//===----------------------------------------------------------------------===//
447
448namespace {
449class ObjCSummaryKey {
450  IdentifierInfo* II;
451  Selector S;
452public:
453  ObjCSummaryKey(IdentifierInfo* ii, Selector s)
454    : II(ii), S(s) {}
455
456  ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
457    : II(d ? d->getIdentifier() : 0), S(s) {}
458
459  ObjCSummaryKey(Selector s)
460    : II(0), S(s) {}
461
462  IdentifierInfo *getIdentifier() const { return II; }
463  Selector getSelector() const { return S; }
464};
465}
466
467namespace llvm {
468template <> struct DenseMapInfo<ObjCSummaryKey> {
469  static inline ObjCSummaryKey getEmptyKey() {
470    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
471                          DenseMapInfo<Selector>::getEmptyKey());
472  }
473
474  static inline ObjCSummaryKey getTombstoneKey() {
475    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
476                          DenseMapInfo<Selector>::getTombstoneKey());
477  }
478
479  static unsigned getHashValue(const ObjCSummaryKey &V) {
480    typedef std::pair<IdentifierInfo*, Selector> PairTy;
481    return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
482                                                     V.getSelector()));
483  }
484
485  static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
486    return LHS.getIdentifier() == RHS.getIdentifier() &&
487           LHS.getSelector() == RHS.getSelector();
488  }
489
490};
491template <>
492struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
493} // end llvm namespace
494
495namespace {
496class ObjCSummaryCache {
497  typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
498  MapTy M;
499public:
500  ObjCSummaryCache() {}
501
502  const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
503    // Do a lookup with the (D,S) pair.  If we find a match return
504    // the iterator.
505    ObjCSummaryKey K(D, S);
506    MapTy::iterator I = M.find(K);
507
508    if (I != M.end())
509      return I->second;
510    if (!D)
511      return NULL;
512
513    // Walk the super chain.  If we find a hit with a parent, we'll end
514    // up returning that summary.  We actually allow that key (null,S), as
515    // we cache summaries for the null ObjCInterfaceDecl* to allow us to
516    // generate initial summaries without having to worry about NSObject
517    // being declared.
518    // FIXME: We may change this at some point.
519    for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
520      if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
521        break;
522
523      if (!C)
524        return NULL;
525    }
526
527    // Cache the summary with original key to make the next lookup faster
528    // and return the iterator.
529    const RetainSummary *Summ = I->second;
530    M[K] = Summ;
531    return Summ;
532  }
533
534  const RetainSummary *find(IdentifierInfo* II, Selector S) {
535    // FIXME: Class method lookup.  Right now we dont' have a good way
536    // of going between IdentifierInfo* and the class hierarchy.
537    MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
538
539    if (I == M.end())
540      I = M.find(ObjCSummaryKey(S));
541
542    return I == M.end() ? NULL : I->second;
543  }
544
545  const RetainSummary *& operator[](ObjCSummaryKey K) {
546    return M[K];
547  }
548
549  const RetainSummary *& operator[](Selector S) {
550    return M[ ObjCSummaryKey(S) ];
551  }
552};
553} // end anonymous namespace
554
555//===----------------------------------------------------------------------===//
556// Data structures for managing collections of summaries.
557//===----------------------------------------------------------------------===//
558
559namespace {
560class RetainSummaryManager {
561
562  //==-----------------------------------------------------------------==//
563  //  Typedefs.
564  //==-----------------------------------------------------------------==//
565
566  typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
567          FuncSummariesTy;
568
569  typedef ObjCSummaryCache ObjCMethodSummariesTy;
570
571  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
572
573  //==-----------------------------------------------------------------==//
574  //  Data.
575  //==-----------------------------------------------------------------==//
576
577  /// Ctx - The ASTContext object for the analyzed ASTs.
578  ASTContext &Ctx;
579
580  /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
581  const bool GCEnabled;
582
583  /// Records whether or not the analyzed code runs in ARC mode.
584  const bool ARCEnabled;
585
586  /// FuncSummaries - A map from FunctionDecls to summaries.
587  FuncSummariesTy FuncSummaries;
588
589  /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
590  ///  to summaries.
591  ObjCMethodSummariesTy ObjCClassMethodSummaries;
592
593  /// ObjCMethodSummaries - A map from selectors to summaries.
594  ObjCMethodSummariesTy ObjCMethodSummaries;
595
596  /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
597  ///  and all other data used by the checker.
598  llvm::BumpPtrAllocator BPAlloc;
599
600  /// AF - A factory for ArgEffects objects.
601  ArgEffects::Factory AF;
602
603  /// ScratchArgs - A holding buffer for construct ArgEffects.
604  ArgEffects ScratchArgs;
605
606  /// ObjCAllocRetE - Default return effect for methods returning Objective-C
607  ///  objects.
608  RetEffect ObjCAllocRetE;
609
610  /// ObjCInitRetE - Default return effect for init methods returning
611  ///   Objective-C objects.
612  RetEffect ObjCInitRetE;
613
614  /// SimpleSummaries - Used for uniquing summaries that don't have special
615  /// effects.
616  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
617
618  //==-----------------------------------------------------------------==//
619  //  Methods.
620  //==-----------------------------------------------------------------==//
621
622  /// getArgEffects - Returns a persistent ArgEffects object based on the
623  ///  data in ScratchArgs.
624  ArgEffects getArgEffects();
625
626  enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
627
628  const RetainSummary *getUnarySummary(const FunctionType* FT,
629                                       UnaryFuncKind func);
630
631  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
632  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
633  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
634
635  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
636
637  const RetainSummary *getPersistentSummary(RetEffect RetEff,
638                                            ArgEffect ReceiverEff = DoNothing,
639                                            ArgEffect DefaultEff = MayEscape) {
640    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
641    return getPersistentSummary(Summ);
642  }
643
644  const RetainSummary *getDoNothingSummary() {
645    return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
646  }
647
648  const RetainSummary *getDefaultSummary() {
649    return getPersistentSummary(RetEffect::MakeNoRet(),
650                                DoNothing, MayEscape);
651  }
652
653  const RetainSummary *getPersistentStopSummary() {
654    return getPersistentSummary(RetEffect::MakeNoRet(),
655                                StopTracking, StopTracking);
656  }
657
658  void InitializeClassMethodSummaries();
659  void InitializeMethodSummaries();
660private:
661  void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
662    ObjCClassMethodSummaries[S] = Summ;
663  }
664
665  void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
666    ObjCMethodSummaries[S] = Summ;
667  }
668
669  void addClassMethSummary(const char* Cls, const char* name,
670                           const RetainSummary *Summ, bool isNullary = true) {
671    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
672    Selector S = isNullary ? GetNullarySelector(name, Ctx)
673                           : GetUnarySelector(name, Ctx);
674    ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
675  }
676
677  void addInstMethSummary(const char* Cls, const char* nullaryName,
678                          const RetainSummary *Summ) {
679    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
680    Selector S = GetNullarySelector(nullaryName, Ctx);
681    ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
682  }
683
684  Selector generateSelector(va_list argp) {
685    SmallVector<IdentifierInfo*, 10> II;
686
687    while (const char* s = va_arg(argp, const char*))
688      II.push_back(&Ctx.Idents.get(s));
689
690    return Ctx.Selectors.getSelector(II.size(), &II[0]);
691  }
692
693  void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
694                        const RetainSummary * Summ, va_list argp) {
695    Selector S = generateSelector(argp);
696    Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
697  }
698
699  void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
700    va_list argp;
701    va_start(argp, Summ);
702    addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
703    va_end(argp);
704  }
705
706  void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
707    va_list argp;
708    va_start(argp, Summ);
709    addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
710    va_end(argp);
711  }
712
713  void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
714    va_list argp;
715    va_start(argp, Summ);
716    addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
717    va_end(argp);
718  }
719
720public:
721
722  RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
723   : Ctx(ctx),
724     GCEnabled(gcenabled),
725     ARCEnabled(usesARC),
726     AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
727     ObjCAllocRetE(gcenabled
728                    ? RetEffect::MakeGCNotOwned()
729                    : (usesARC ? RetEffect::MakeARCNotOwned()
730                               : RetEffect::MakeOwned(RetEffect::ObjC, true))),
731     ObjCInitRetE(gcenabled
732                    ? RetEffect::MakeGCNotOwned()
733                    : (usesARC ? RetEffect::MakeARCNotOwned()
734                               : RetEffect::MakeOwnedWhenTrackedReceiver())) {
735    InitializeClassMethodSummaries();
736    InitializeMethodSummaries();
737  }
738
739  const RetainSummary *getSummary(const CallEvent &Call,
740                                  ProgramStateRef State = 0);
741
742  const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
743
744  const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
745                                        const ObjCMethodDecl *MD,
746                                        QualType RetTy,
747                                        ObjCMethodSummariesTy &CachedSummaries);
748
749  const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
750                                                ProgramStateRef State);
751
752  const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
753    assert(!M.isInstanceMessage());
754    const ObjCInterfaceDecl *Class = M.getReceiverInterface();
755
756    return getMethodSummary(M.getSelector(), Class, M.getDecl(),
757                            M.getResultType(), ObjCClassMethodSummaries);
758  }
759
760  /// getMethodSummary - This version of getMethodSummary is used to query
761  ///  the summary for the current method being analyzed.
762  const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
763    const ObjCInterfaceDecl *ID = MD->getClassInterface();
764    Selector S = MD->getSelector();
765    QualType ResultTy = MD->getResultType();
766
767    ObjCMethodSummariesTy *CachedSummaries;
768    if (MD->isInstanceMethod())
769      CachedSummaries = &ObjCMethodSummaries;
770    else
771      CachedSummaries = &ObjCClassMethodSummaries;
772
773    return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
774  }
775
776  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
777                                                Selector S, QualType RetTy);
778
779  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
780                                    const ObjCMethodDecl *MD);
781
782  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
783                                    const FunctionDecl *FD);
784
785  void updateSummaryForCall(const RetainSummary *&Summ,
786                            const CallEvent &Call);
787
788  bool isGCEnabled() const { return GCEnabled; }
789
790  bool isARCEnabled() const { return ARCEnabled; }
791
792  bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
793
794  RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
795
796  friend class RetainSummaryTemplate;
797};
798
799// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
800// summaries. If a function or method looks like it has a default summary, but
801// it has annotations, the annotations are added to the stack-based template
802// and then copied into managed memory.
803class RetainSummaryTemplate {
804  RetainSummaryManager &Manager;
805  const RetainSummary *&RealSummary;
806  RetainSummary ScratchSummary;
807  bool Accessed;
808public:
809  RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
810    : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
811
812  ~RetainSummaryTemplate() {
813    if (Accessed)
814      RealSummary = Manager.getPersistentSummary(ScratchSummary);
815  }
816
817  RetainSummary &operator*() {
818    Accessed = true;
819    return ScratchSummary;
820  }
821
822  RetainSummary *operator->() {
823    Accessed = true;
824    return &ScratchSummary;
825  }
826};
827
828} // end anonymous namespace
829
830//===----------------------------------------------------------------------===//
831// Implementation of checker data structures.
832//===----------------------------------------------------------------------===//
833
834ArgEffects RetainSummaryManager::getArgEffects() {
835  ArgEffects AE = ScratchArgs;
836  ScratchArgs = AF.getEmptyMap();
837  return AE;
838}
839
840const RetainSummary *
841RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
842  // Unique "simple" summaries -- those without ArgEffects.
843  if (OldSumm.isSimple()) {
844    llvm::FoldingSetNodeID ID;
845    OldSumm.Profile(ID);
846
847    void *Pos;
848    CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
849
850    if (!N) {
851      N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
852      new (N) CachedSummaryNode(OldSumm);
853      SimpleSummaries.InsertNode(N, Pos);
854    }
855
856    return &N->getValue();
857  }
858
859  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
860  new (Summ) RetainSummary(OldSumm);
861  return Summ;
862}
863
864//===----------------------------------------------------------------------===//
865// Summary creation for functions (largely uses of Core Foundation).
866//===----------------------------------------------------------------------===//
867
868static bool isRetain(const FunctionDecl *FD, StringRef FName) {
869  return FName.endswith("Retain");
870}
871
872static bool isRelease(const FunctionDecl *FD, StringRef FName) {
873  return FName.endswith("Release");
874}
875
876static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
877  // FIXME: Remove FunctionDecl parameter.
878  // FIXME: Is it really okay if MakeCollectable isn't a suffix?
879  return FName.find("MakeCollectable") != StringRef::npos;
880}
881
882static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
883  switch (E) {
884  case DoNothing:
885  case Autorelease:
886  case DecRefBridgedTransfered:
887  case IncRef:
888  case IncRefMsg:
889  case MakeCollectable:
890  case MayEscape:
891  case NewAutoreleasePool:
892  case StopTracking:
893    return StopTracking;
894  case DecRef:
895  case DecRefAndStopTracking:
896    return DecRefAndStopTracking;
897  case DecRefMsg:
898  case DecRefMsgAndStopTracking:
899    return DecRefMsgAndStopTracking;
900  case Dealloc:
901    return Dealloc;
902  }
903
904  llvm_unreachable("Unknown ArgEffect kind");
905}
906
907void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
908                                                const CallEvent &Call) {
909  if (Call.hasNonZeroCallbackArg()) {
910    ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
911    ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
912
913    ArgEffects CustomArgEffects = S->getArgEffects();
914    for (ArgEffects::iterator I = CustomArgEffects.begin(),
915                              E = CustomArgEffects.end();
916         I != E; ++I) {
917      ArgEffect Translated = getStopTrackingEquivalent(I->second);
918      if (Translated != DefEffect)
919        ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
920    }
921
922    RetEffect RE = RetEffect::MakeNoRet();
923
924    // Special cases where the callback argument CANNOT free the return value.
925    // This can generally only happen if we know that the callback will only be
926    // called when the return value is already being deallocated.
927    if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
928      IdentifierInfo *Name = FC->getDecl()->getIdentifier();
929
930      // This callback frees the associated buffer.
931      if (Name->isStr("CGBitmapContextCreateWithData"))
932        RE = S->getRetEffect();
933    }
934
935    S = getPersistentSummary(RE, RecEffect, DefEffect);
936  }
937}
938
939const RetainSummary *
940RetainSummaryManager::getSummary(const CallEvent &Call,
941                                 ProgramStateRef State) {
942  const RetainSummary *Summ;
943  switch (Call.getKind()) {
944  case CE_Function:
945    Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
946    break;
947  case CE_CXXMember:
948  case CE_CXXMemberOperator:
949  case CE_Block:
950  case CE_CXXConstructor:
951  case CE_CXXDestructor:
952  case CE_CXXAllocator:
953    // FIXME: These calls are currently unsupported.
954    return getPersistentStopSummary();
955  case CE_ObjCMessage: {
956    const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
957    if (Msg.isInstanceMessage())
958      Summ = getInstanceMethodSummary(Msg, State);
959    else
960      Summ = getClassMethodSummary(Msg);
961    break;
962  }
963  }
964
965  updateSummaryForCall(Summ, Call);
966
967  assert(Summ && "Unknown call type?");
968  return Summ;
969}
970
971const RetainSummary *
972RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
973  // If we don't know what function we're calling, use our default summary.
974  if (!FD)
975    return getDefaultSummary();
976
977  // Look up a summary in our cache of FunctionDecls -> Summaries.
978  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
979  if (I != FuncSummaries.end())
980    return I->second;
981
982  // No summary?  Generate one.
983  const RetainSummary *S = 0;
984  bool AllowAnnotations = true;
985
986  do {
987    // We generate "stop" summaries for implicitly defined functions.
988    if (FD->isImplicit()) {
989      S = getPersistentStopSummary();
990      break;
991    }
992
993    // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
994    // function's type.
995    const FunctionType* FT = FD->getType()->getAs<FunctionType>();
996    const IdentifierInfo *II = FD->getIdentifier();
997    if (!II)
998      break;
999
1000    StringRef FName = II->getName();
1001
1002    // Strip away preceding '_'.  Doing this here will effect all the checks
1003    // down below.
1004    FName = FName.substr(FName.find_first_not_of('_'));
1005
1006    // Inspect the result type.
1007    QualType RetTy = FT->getResultType();
1008
1009    // FIXME: This should all be refactored into a chain of "summary lookup"
1010    //  filters.
1011    assert(ScratchArgs.isEmpty());
1012
1013    if (FName == "pthread_create" || FName == "pthread_setspecific") {
1014      // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1015      // This will be addressed better with IPA.
1016      S = getPersistentStopSummary();
1017    } else if (FName == "NSMakeCollectable") {
1018      // Handle: id NSMakeCollectable(CFTypeRef)
1019      S = (RetTy->isObjCIdType())
1020          ? getUnarySummary(FT, cfmakecollectable)
1021          : getPersistentStopSummary();
1022      // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1023      // but we can fully model NSMakeCollectable ourselves.
1024      AllowAnnotations = false;
1025    } else if (FName == "IOBSDNameMatching" ||
1026               FName == "IOServiceMatching" ||
1027               FName == "IOServiceNameMatching" ||
1028               FName == "IORegistryEntrySearchCFProperty" ||
1029               FName == "IORegistryEntryIDMatching" ||
1030               FName == "IOOpenFirmwarePathMatching") {
1031      // Part of <rdar://problem/6961230>. (IOKit)
1032      // This should be addressed using a API table.
1033      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1034                               DoNothing, DoNothing);
1035    } else if (FName == "IOServiceGetMatchingService" ||
1036               FName == "IOServiceGetMatchingServices") {
1037      // FIXES: <rdar://problem/6326900>
1038      // This should be addressed using a API table.  This strcmp is also
1039      // a little gross, but there is no need to super optimize here.
1040      ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1041      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1042    } else if (FName == "IOServiceAddNotification" ||
1043               FName == "IOServiceAddMatchingNotification") {
1044      // Part of <rdar://problem/6961230>. (IOKit)
1045      // This should be addressed using a API table.
1046      ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1047      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1048    } else if (FName == "CVPixelBufferCreateWithBytes") {
1049      // FIXES: <rdar://problem/7283567>
1050      // Eventually this can be improved by recognizing that the pixel
1051      // buffer passed to CVPixelBufferCreateWithBytes is released via
1052      // a callback and doing full IPA to make sure this is done correctly.
1053      // FIXME: This function has an out parameter that returns an
1054      // allocated object.
1055      ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1056      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1057    } else if (FName == "CGBitmapContextCreateWithData") {
1058      // FIXES: <rdar://problem/7358899>
1059      // Eventually this can be improved by recognizing that 'releaseInfo'
1060      // passed to CGBitmapContextCreateWithData is released via
1061      // a callback and doing full IPA to make sure this is done correctly.
1062      ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1063      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1064                               DoNothing, DoNothing);
1065    } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1066      // FIXES: <rdar://problem/7283567>
1067      // Eventually this can be improved by recognizing that the pixel
1068      // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1069      // via a callback and doing full IPA to make sure this is done
1070      // correctly.
1071      ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1072      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1073    } else if (FName == "dispatch_set_context") {
1074      // <rdar://problem/11059275> - The analyzer currently doesn't have
1075      // a good way to reason about the finalizer function for libdispatch.
1076      // If we pass a context object that is memory managed, stop tracking it.
1077      // FIXME: this hack should possibly go away once we can handle
1078      // libdispatch finalizers.
1079      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1080      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1081    } else if (FName.startswith("NSLog")) {
1082      S = getDoNothingSummary();
1083    } else if (FName.startswith("NS") &&
1084                (FName.find("Insert") != StringRef::npos)) {
1085      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1086      // be deallocated by NSMapRemove. (radar://11152419)
1087      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1088      ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1089      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1090    }
1091
1092    // Did we get a summary?
1093    if (S)
1094      break;
1095
1096    // Enable this code once the semantics of NSDeallocateObject are resolved
1097    // for GC.  <rdar://problem/6619988>
1098#if 0
1099    // Handle: NSDeallocateObject(id anObject);
1100    // This method does allow 'nil' (although we don't check it now).
1101    if (strcmp(FName, "NSDeallocateObject") == 0) {
1102      return RetTy == Ctx.VoidTy
1103        ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1104        : getPersistentStopSummary();
1105    }
1106#endif
1107
1108    if (RetTy->isPointerType()) {
1109      // For CoreFoundation ('CF') types.
1110      if (cocoa::isRefType(RetTy, "CF", FName)) {
1111        if (isRetain(FD, FName))
1112          S = getUnarySummary(FT, cfretain);
1113        else if (isMakeCollectable(FD, FName))
1114          S = getUnarySummary(FT, cfmakecollectable);
1115        else
1116          S = getCFCreateGetRuleSummary(FD);
1117
1118        break;
1119      }
1120
1121      // For CoreGraphics ('CG') types.
1122      if (cocoa::isRefType(RetTy, "CG", FName)) {
1123        if (isRetain(FD, FName))
1124          S = getUnarySummary(FT, cfretain);
1125        else
1126          S = getCFCreateGetRuleSummary(FD);
1127
1128        break;
1129      }
1130
1131      // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1132      if (cocoa::isRefType(RetTy, "DADisk") ||
1133          cocoa::isRefType(RetTy, "DADissenter") ||
1134          cocoa::isRefType(RetTy, "DASessionRef")) {
1135        S = getCFCreateGetRuleSummary(FD);
1136        break;
1137      }
1138
1139      break;
1140    }
1141
1142    // Check for release functions, the only kind of functions that we care
1143    // about that don't return a pointer type.
1144    if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1145      // Test for 'CGCF'.
1146      FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1147
1148      if (isRelease(FD, FName))
1149        S = getUnarySummary(FT, cfrelease);
1150      else {
1151        assert (ScratchArgs.isEmpty());
1152        // Remaining CoreFoundation and CoreGraphics functions.
1153        // We use to assume that they all strictly followed the ownership idiom
1154        // and that ownership cannot be transferred.  While this is technically
1155        // correct, many methods allow a tracked object to escape.  For example:
1156        //
1157        //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1158        //   CFDictionaryAddValue(y, key, x);
1159        //   CFRelease(x);
1160        //   ... it is okay to use 'x' since 'y' has a reference to it
1161        //
1162        // We handle this and similar cases with the follow heuristic.  If the
1163        // function name contains "InsertValue", "SetValue", "AddValue",
1164        // "AppendValue", or "SetAttribute", then we assume that arguments may
1165        // "escape."  This means that something else holds on to the object,
1166        // allowing it be used even after its local retain count drops to 0.
1167        ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1168                       StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1169                       StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1170                       StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1171                       StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1172                      ? MayEscape : DoNothing;
1173
1174        S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1175      }
1176    }
1177  }
1178  while (0);
1179
1180  // If we got all the way here without any luck, use a default summary.
1181  if (!S)
1182    S = getDefaultSummary();
1183
1184  // Annotations override defaults.
1185  if (AllowAnnotations)
1186    updateSummaryFromAnnotations(S, FD);
1187
1188  FuncSummaries[FD] = S;
1189  return S;
1190}
1191
1192const RetainSummary *
1193RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1194  if (coreFoundation::followsCreateRule(FD))
1195    return getCFSummaryCreateRule(FD);
1196
1197  return getCFSummaryGetRule(FD);
1198}
1199
1200const RetainSummary *
1201RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1202                                      UnaryFuncKind func) {
1203
1204  // Sanity check that this is *really* a unary function.  This can
1205  // happen if people do weird things.
1206  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1207  if (!FTP || FTP->getNumArgs() != 1)
1208    return getPersistentStopSummary();
1209
1210  assert (ScratchArgs.isEmpty());
1211
1212  ArgEffect Effect;
1213  switch (func) {
1214    case cfretain: Effect = IncRef; break;
1215    case cfrelease: Effect = DecRef; break;
1216    case cfmakecollectable: Effect = MakeCollectable; break;
1217  }
1218
1219  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1220  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1221}
1222
1223const RetainSummary *
1224RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1225  assert (ScratchArgs.isEmpty());
1226
1227  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1228}
1229
1230const RetainSummary *
1231RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1232  assert (ScratchArgs.isEmpty());
1233  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1234                              DoNothing, DoNothing);
1235}
1236
1237//===----------------------------------------------------------------------===//
1238// Summary creation for Selectors.
1239//===----------------------------------------------------------------------===//
1240
1241void
1242RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1243                                                   const FunctionDecl *FD) {
1244  if (!FD)
1245    return;
1246
1247  assert(Summ && "Must have a summary to add annotations to.");
1248  RetainSummaryTemplate Template(Summ, *this);
1249
1250  // Effects on the parameters.
1251  unsigned parm_idx = 0;
1252  for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1253         pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1254    const ParmVarDecl *pd = *pi;
1255    if (pd->getAttr<NSConsumedAttr>()) {
1256      if (!GCEnabled) {
1257        Template->addArg(AF, parm_idx, DecRef);
1258      }
1259    } else if (pd->getAttr<CFConsumedAttr>()) {
1260      Template->addArg(AF, parm_idx, DecRef);
1261    }
1262  }
1263
1264  QualType RetTy = FD->getResultType();
1265
1266  // Determine if there is a special return effect for this method.
1267  if (cocoa::isCocoaObjectRef(RetTy)) {
1268    if (FD->getAttr<NSReturnsRetainedAttr>()) {
1269      Template->setRetEffect(ObjCAllocRetE);
1270    }
1271    else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1272      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1273    }
1274    else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
1275      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1276    }
1277    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1278      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1279    }
1280  } else if (RetTy->getAs<PointerType>()) {
1281    if (FD->getAttr<CFReturnsRetainedAttr>()) {
1282      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1283    }
1284    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1285      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1286    }
1287  }
1288}
1289
1290void
1291RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1292                                                   const ObjCMethodDecl *MD) {
1293  if (!MD)
1294    return;
1295
1296  assert(Summ && "Must have a valid summary to add annotations to");
1297  RetainSummaryTemplate Template(Summ, *this);
1298  bool isTrackedLoc = false;
1299
1300  // Effects on the receiver.
1301  if (MD->getAttr<NSConsumesSelfAttr>()) {
1302    if (!GCEnabled)
1303      Template->setReceiverEffect(DecRefMsg);
1304  }
1305
1306  // Effects on the parameters.
1307  unsigned parm_idx = 0;
1308  for (ObjCMethodDecl::param_const_iterator
1309         pi=MD->param_begin(), pe=MD->param_end();
1310       pi != pe; ++pi, ++parm_idx) {
1311    const ParmVarDecl *pd = *pi;
1312    if (pd->getAttr<NSConsumedAttr>()) {
1313      if (!GCEnabled)
1314        Template->addArg(AF, parm_idx, DecRef);
1315    }
1316    else if(pd->getAttr<CFConsumedAttr>()) {
1317      Template->addArg(AF, parm_idx, DecRef);
1318    }
1319  }
1320
1321  // Determine if there is a special return effect for this method.
1322  if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1323    if (MD->getAttr<NSReturnsRetainedAttr>()) {
1324      Template->setRetEffect(ObjCAllocRetE);
1325      return;
1326    }
1327    if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
1328      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1329      return;
1330    }
1331
1332    isTrackedLoc = true;
1333  } else {
1334    isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1335  }
1336
1337  if (isTrackedLoc) {
1338    if (MD->getAttr<CFReturnsRetainedAttr>())
1339      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1340    else if (MD->getAttr<CFReturnsNotRetainedAttr>())
1341      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1342  }
1343}
1344
1345const RetainSummary *
1346RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1347                                               Selector S, QualType RetTy) {
1348
1349  if (MD) {
1350    // Scan the method decl for 'void*' arguments.  These should be treated
1351    // as 'StopTracking' because they are often used with delegates.
1352    // Delegates are a frequent form of false positives with the retain
1353    // count checker.
1354    unsigned i = 0;
1355    for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
1356         E = MD->param_end(); I != E; ++I, ++i)
1357      if (const ParmVarDecl *PD = *I) {
1358        QualType Ty = Ctx.getCanonicalType(PD->getType());
1359        if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
1360          ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
1361      }
1362  }
1363
1364  // Any special effects?
1365  ArgEffect ReceiverEff = DoNothing;
1366  RetEffect ResultEff = RetEffect::MakeNoRet();
1367
1368  // Check the method family, and apply any default annotations.
1369  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1370    case OMF_None:
1371    case OMF_performSelector:
1372      // Assume all Objective-C methods follow Cocoa Memory Management rules.
1373      // FIXME: Does the non-threaded performSelector family really belong here?
1374      // The selector could be, say, @selector(copy).
1375      if (cocoa::isCocoaObjectRef(RetTy))
1376        ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1377      else if (coreFoundation::isCFObjectRef(RetTy)) {
1378        // ObjCMethodDecl currently doesn't consider CF objects as valid return
1379        // values for alloc, new, copy, or mutableCopy, so we have to
1380        // double-check with the selector. This is ugly, but there aren't that
1381        // many Objective-C methods that return CF objects, right?
1382        if (MD) {
1383          switch (S.getMethodFamily()) {
1384          case OMF_alloc:
1385          case OMF_new:
1386          case OMF_copy:
1387          case OMF_mutableCopy:
1388            ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1389            break;
1390          default:
1391            ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1392            break;
1393          }
1394        } else {
1395          ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1396        }
1397      }
1398      break;
1399    case OMF_init:
1400      ResultEff = ObjCInitRetE;
1401      ReceiverEff = DecRefMsg;
1402      break;
1403    case OMF_alloc:
1404    case OMF_new:
1405    case OMF_copy:
1406    case OMF_mutableCopy:
1407      if (cocoa::isCocoaObjectRef(RetTy))
1408        ResultEff = ObjCAllocRetE;
1409      else if (coreFoundation::isCFObjectRef(RetTy))
1410        ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1411      break;
1412    case OMF_autorelease:
1413      ReceiverEff = Autorelease;
1414      break;
1415    case OMF_retain:
1416      ReceiverEff = IncRefMsg;
1417      break;
1418    case OMF_release:
1419      ReceiverEff = DecRefMsg;
1420      break;
1421    case OMF_dealloc:
1422      ReceiverEff = Dealloc;
1423      break;
1424    case OMF_self:
1425      // -self is handled specially by the ExprEngine to propagate the receiver.
1426      break;
1427    case OMF_retainCount:
1428    case OMF_finalize:
1429      // These methods don't return objects.
1430      break;
1431  }
1432
1433  // If one of the arguments in the selector has the keyword 'delegate' we
1434  // should stop tracking the reference count for the receiver.  This is
1435  // because the reference count is quite possibly handled by a delegate
1436  // method.
1437  if (S.isKeywordSelector()) {
1438    for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1439      StringRef Slot = S.getNameForSlot(i);
1440      if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1441        if (ResultEff == ObjCInitRetE)
1442          ResultEff = RetEffect::MakeNoRet();
1443        else
1444          ReceiverEff = StopTracking;
1445      }
1446    }
1447  }
1448
1449  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1450      ResultEff.getKind() == RetEffect::NoRet)
1451    return getDefaultSummary();
1452
1453  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1454}
1455
1456const RetainSummary *
1457RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1458                                               ProgramStateRef State) {
1459  const ObjCInterfaceDecl *ReceiverClass = 0;
1460
1461  // We do better tracking of the type of the object than the core ExprEngine.
1462  // See if we have its type in our private state.
1463  // FIXME: Eventually replace the use of state->get<RefBindings> with
1464  // a generic API for reasoning about the Objective-C types of symbolic
1465  // objects.
1466  SVal ReceiverV = Msg.getReceiverSVal();
1467  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1468    if (const RefVal *T = State->get<RefBindings>(Sym))
1469      if (const ObjCObjectPointerType *PT =
1470            T->getType()->getAs<ObjCObjectPointerType>())
1471        ReceiverClass = PT->getInterfaceDecl();
1472
1473  // If we don't know what kind of object this is, fall back to its static type.
1474  if (!ReceiverClass)
1475    ReceiverClass = Msg.getReceiverInterface();
1476
1477  // FIXME: The receiver could be a reference to a class, meaning that
1478  //  we should use the class method.
1479  // id x = [NSObject class];
1480  // [x performSelector:... withObject:... afterDelay:...];
1481  Selector S = Msg.getSelector();
1482  const ObjCMethodDecl *Method = Msg.getDecl();
1483  if (!Method && ReceiverClass)
1484    Method = ReceiverClass->getInstanceMethod(S);
1485
1486  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1487                          ObjCMethodSummaries);
1488}
1489
1490const RetainSummary *
1491RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1492                                       const ObjCMethodDecl *MD, QualType RetTy,
1493                                       ObjCMethodSummariesTy &CachedSummaries) {
1494
1495  // Look up a summary in our summary cache.
1496  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1497
1498  if (!Summ) {
1499    Summ = getStandardMethodSummary(MD, S, RetTy);
1500
1501    // Annotations override defaults.
1502    updateSummaryFromAnnotations(Summ, MD);
1503
1504    // Memoize the summary.
1505    CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1506  }
1507
1508  return Summ;
1509}
1510
1511void RetainSummaryManager::InitializeClassMethodSummaries() {
1512  assert(ScratchArgs.isEmpty());
1513  // Create the [NSAssertionHandler currentHander] summary.
1514  addClassMethSummary("NSAssertionHandler", "currentHandler",
1515                getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1516
1517  // Create the [NSAutoreleasePool addObject:] summary.
1518  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1519  addClassMethSummary("NSAutoreleasePool", "addObject",
1520                      getPersistentSummary(RetEffect::MakeNoRet(),
1521                                           DoNothing, Autorelease));
1522}
1523
1524void RetainSummaryManager::InitializeMethodSummaries() {
1525
1526  assert (ScratchArgs.isEmpty());
1527
1528  // Create the "init" selector.  It just acts as a pass-through for the
1529  // receiver.
1530  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1531  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1532
1533  // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1534  // claims the receiver and returns a retained object.
1535  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1536                         InitSumm);
1537
1538  // The next methods are allocators.
1539  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1540  const RetainSummary *CFAllocSumm =
1541    getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1542
1543  // Create the "retain" selector.
1544  RetEffect NoRet = RetEffect::MakeNoRet();
1545  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1546  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1547
1548  // Create the "release" selector.
1549  Summ = getPersistentSummary(NoRet, DecRefMsg);
1550  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1551
1552  // Create the "drain" selector.
1553  Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
1554  addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
1555
1556  // Create the -dealloc summary.
1557  Summ = getPersistentSummary(NoRet, Dealloc);
1558  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1559
1560  // Create the "autorelease" selector.
1561  Summ = getPersistentSummary(NoRet, Autorelease);
1562  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1563
1564  // Specially handle NSAutoreleasePool.
1565  addInstMethSummary("NSAutoreleasePool", "init",
1566                     getPersistentSummary(NoRet, NewAutoreleasePool));
1567
1568  // For NSWindow, allocated objects are (initially) self-owned.
1569  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1570  //  self-own themselves.  However, they only do this once they are displayed.
1571  //  Thus, we need to track an NSWindow's display status.
1572  //  This is tracked in <rdar://problem/6062711>.
1573  //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1574  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1575                                                   StopTracking,
1576                                                   StopTracking);
1577
1578  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1579
1580#if 0
1581  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1582                     "styleMask", "backing", "defer", NULL);
1583
1584  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1585                     "styleMask", "backing", "defer", "screen", NULL);
1586#endif
1587
1588  // For NSPanel (which subclasses NSWindow), allocated objects are not
1589  //  self-owned.
1590  // FIXME: For now we don't track NSPanels. object for the same reason
1591  //   as for NSWindow objects.
1592  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1593
1594#if 0
1595  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1596                     "styleMask", "backing", "defer", NULL);
1597
1598  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1599                     "styleMask", "backing", "defer", "screen", NULL);
1600#endif
1601
1602  // Don't track allocated autorelease pools yet, as it is okay to prematurely
1603  // exit a method.
1604  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1605  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1606
1607  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1608  addInstMethSummary("QCRenderer", AllocSumm,
1609                     "createSnapshotImageOfType", NULL);
1610  addInstMethSummary("QCView", AllocSumm,
1611                     "createSnapshotImageOfType", NULL);
1612
1613  // Create summaries for CIContext, 'createCGImage' and
1614  // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1615  // automatically garbage collected.
1616  addInstMethSummary("CIContext", CFAllocSumm,
1617                     "createCGImage", "fromRect", NULL);
1618  addInstMethSummary("CIContext", CFAllocSumm,
1619                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
1620  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1621           "info", NULL);
1622}
1623
1624//===----------------------------------------------------------------------===//
1625// AutoreleaseBindings - State used to track objects in autorelease pools.
1626//===----------------------------------------------------------------------===//
1627
1628typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1629typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1630typedef llvm::ImmutableList<SymbolRef> ARStack;
1631
1632static int AutoRCIndex = 0;
1633static int AutoRBIndex = 0;
1634
1635namespace { class AutoreleasePoolContents {}; }
1636namespace { class AutoreleaseStack {}; }
1637
1638namespace clang {
1639namespace ento {
1640template<> struct ProgramStateTrait<AutoreleaseStack>
1641  : public ProgramStatePartialTrait<ARStack> {
1642  static inline void *GDMIndex() { return &AutoRBIndex; }
1643};
1644
1645template<> struct ProgramStateTrait<AutoreleasePoolContents>
1646  : public ProgramStatePartialTrait<ARPoolContents> {
1647  static inline void *GDMIndex() { return &AutoRCIndex; }
1648};
1649} // end GR namespace
1650} // end clang namespace
1651
1652static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
1653  ARStack stack = state->get<AutoreleaseStack>();
1654  return stack.isEmpty() ? SymbolRef() : stack.getHead();
1655}
1656
1657static ProgramStateRef
1658SendAutorelease(ProgramStateRef state,
1659                ARCounts::Factory &F,
1660                SymbolRef sym) {
1661  SymbolRef pool = GetCurrentAutoreleasePool(state);
1662  const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
1663  ARCounts newCnts(0);
1664
1665  if (cnts) {
1666    const unsigned *cnt = (*cnts).lookup(sym);
1667    newCnts = F.add(*cnts, sym, cnt ? *cnt  + 1 : 1);
1668  }
1669  else
1670    newCnts = F.add(F.getEmptyMap(), sym, 1);
1671
1672  return state->set<AutoreleasePoolContents>(pool, newCnts);
1673}
1674
1675//===----------------------------------------------------------------------===//
1676// Error reporting.
1677//===----------------------------------------------------------------------===//
1678namespace {
1679  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1680    SummaryLogTy;
1681
1682  //===-------------===//
1683  // Bug Descriptions. //
1684  //===-------------===//
1685
1686  class CFRefBug : public BugType {
1687  protected:
1688    CFRefBug(StringRef name)
1689    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
1690  public:
1691
1692    // FIXME: Eventually remove.
1693    virtual const char *getDescription() const = 0;
1694
1695    virtual bool isLeak() const { return false; }
1696  };
1697
1698  class UseAfterRelease : public CFRefBug {
1699  public:
1700    UseAfterRelease() : CFRefBug("Use-after-release") {}
1701
1702    const char *getDescription() const {
1703      return "Reference-counted object is used after it is released";
1704    }
1705  };
1706
1707  class BadRelease : public CFRefBug {
1708  public:
1709    BadRelease() : CFRefBug("Bad release") {}
1710
1711    const char *getDescription() const {
1712      return "Incorrect decrement of the reference count of an object that is "
1713             "not owned at this point by the caller";
1714    }
1715  };
1716
1717  class DeallocGC : public CFRefBug {
1718  public:
1719    DeallocGC()
1720    : CFRefBug("-dealloc called while using garbage collection") {}
1721
1722    const char *getDescription() const {
1723      return "-dealloc called while using garbage collection";
1724    }
1725  };
1726
1727  class DeallocNotOwned : public CFRefBug {
1728  public:
1729    DeallocNotOwned()
1730    : CFRefBug("-dealloc sent to non-exclusively owned object") {}
1731
1732    const char *getDescription() const {
1733      return "-dealloc sent to object that may be referenced elsewhere";
1734    }
1735  };
1736
1737  class OverAutorelease : public CFRefBug {
1738  public:
1739    OverAutorelease()
1740    : CFRefBug("Object sent -autorelease too many times") {}
1741
1742    const char *getDescription() const {
1743      return "Object sent -autorelease too many times";
1744    }
1745  };
1746
1747  class ReturnedNotOwnedForOwned : public CFRefBug {
1748  public:
1749    ReturnedNotOwnedForOwned()
1750    : CFRefBug("Method should return an owned object") {}
1751
1752    const char *getDescription() const {
1753      return "Object with a +0 retain count returned to caller where a +1 "
1754             "(owning) retain count is expected";
1755    }
1756  };
1757
1758  class Leak : public CFRefBug {
1759  public:
1760    Leak(StringRef name)
1761    : CFRefBug(name) {
1762      // Leaks should not be reported if they are post-dominated by a sink.
1763      setSuppressOnSink(true);
1764    }
1765
1766    const char *getDescription() const { return ""; }
1767
1768    bool isLeak() const { return true; }
1769  };
1770
1771  //===---------===//
1772  // Bug Reports.  //
1773  //===---------===//
1774
1775  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1776  protected:
1777    SymbolRef Sym;
1778    const SummaryLogTy &SummaryLog;
1779    bool GCEnabled;
1780
1781  public:
1782    CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1783       : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1784
1785    virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1786      static int x = 0;
1787      ID.AddPointer(&x);
1788      ID.AddPointer(Sym);
1789    }
1790
1791    virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1792                                           const ExplodedNode *PrevN,
1793                                           BugReporterContext &BRC,
1794                                           BugReport &BR);
1795
1796    virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1797                                            const ExplodedNode *N,
1798                                            BugReport &BR);
1799  };
1800
1801  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1802  public:
1803    CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1804                           const SummaryLogTy &log)
1805       : CFRefReportVisitor(sym, GCEnabled, log) {}
1806
1807    PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1808                                    const ExplodedNode *N,
1809                                    BugReport &BR);
1810
1811    virtual BugReporterVisitor *clone() const {
1812      // The curiously-recurring template pattern only works for one level of
1813      // subclassing. Rather than make a new template base for
1814      // CFRefReportVisitor, we simply override clone() to do the right thing.
1815      // This could be trouble someday if BugReporterVisitorImpl is ever
1816      // used for something else besides a convenient implementation of clone().
1817      return new CFRefLeakReportVisitor(*this);
1818    }
1819  };
1820
1821  class CFRefReport : public BugReport {
1822    void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1823
1824  public:
1825    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1826                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1827                bool registerVisitor = true)
1828      : BugReport(D, D.getDescription(), n) {
1829      if (registerVisitor)
1830        addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1831      addGCModeDescription(LOpts, GCEnabled);
1832    }
1833
1834    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1835                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1836                StringRef endText)
1837      : BugReport(D, D.getDescription(), endText, n) {
1838      addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1839      addGCModeDescription(LOpts, GCEnabled);
1840    }
1841
1842    virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
1843      const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1844      if (!BugTy.isLeak())
1845        return BugReport::getRanges();
1846      else
1847        return std::make_pair(ranges_iterator(), ranges_iterator());
1848    }
1849  };
1850
1851  class CFRefLeakReport : public CFRefReport {
1852    const MemRegion* AllocBinding;
1853
1854  public:
1855    CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1856                    const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1857                    CheckerContext &Ctx);
1858
1859    PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1860      assert(Location.isValid());
1861      return Location;
1862    }
1863  };
1864} // end anonymous namespace
1865
1866void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1867                                       bool GCEnabled) {
1868  const char *GCModeDescription = 0;
1869
1870  switch (LOpts.getGC()) {
1871  case LangOptions::GCOnly:
1872    assert(GCEnabled);
1873    GCModeDescription = "Code is compiled to only use garbage collection";
1874    break;
1875
1876  case LangOptions::NonGC:
1877    assert(!GCEnabled);
1878    GCModeDescription = "Code is compiled to use reference counts";
1879    break;
1880
1881  case LangOptions::HybridGC:
1882    if (GCEnabled) {
1883      GCModeDescription = "Code is compiled to use either garbage collection "
1884                          "(GC) or reference counts (non-GC).  The bug occurs "
1885                          "with GC enabled";
1886      break;
1887    } else {
1888      GCModeDescription = "Code is compiled to use either garbage collection "
1889                          "(GC) or reference counts (non-GC).  The bug occurs "
1890                          "in non-GC mode";
1891      break;
1892    }
1893  }
1894
1895  assert(GCModeDescription && "invalid/unknown GC mode");
1896  addExtraText(GCModeDescription);
1897}
1898
1899// FIXME: This should be a method on SmallVector.
1900static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
1901                            ArgEffect X) {
1902  for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1903       I!=E; ++I)
1904    if (*I == X) return true;
1905
1906  return false;
1907}
1908
1909static bool isNumericLiteralExpression(const Expr *E) {
1910  // FIXME: This set of cases was copied from SemaExprObjC.
1911  return isa<IntegerLiteral>(E) ||
1912         isa<CharacterLiteral>(E) ||
1913         isa<FloatingLiteral>(E) ||
1914         isa<ObjCBoolLiteralExpr>(E) ||
1915         isa<CXXBoolLiteralExpr>(E);
1916}
1917
1918PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1919                                                   const ExplodedNode *PrevN,
1920                                                   BugReporterContext &BRC,
1921                                                   BugReport &BR) {
1922  // FIXME: We will eventually need to handle non-statement-based events
1923  // (__attribute__((cleanup))).
1924  if (!isa<StmtPoint>(N->getLocation()))
1925    return NULL;
1926
1927  // Check if the type state has changed.
1928  ProgramStateRef PrevSt = PrevN->getState();
1929  ProgramStateRef CurrSt = N->getState();
1930  const LocationContext *LCtx = N->getLocationContext();
1931
1932  const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
1933  if (!CurrT) return NULL;
1934
1935  const RefVal &CurrV = *CurrT;
1936  const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
1937
1938  // Create a string buffer to constain all the useful things we want
1939  // to tell the user.
1940  std::string sbuf;
1941  llvm::raw_string_ostream os(sbuf);
1942
1943  // This is the allocation site since the previous node had no bindings
1944  // for this symbol.
1945  if (!PrevT) {
1946    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1947
1948    if (isa<ObjCArrayLiteral>(S)) {
1949      os << "NSArray literal is an object with a +0 retain count";
1950    }
1951    else if (isa<ObjCDictionaryLiteral>(S)) {
1952      os << "NSDictionary literal is an object with a +0 retain count";
1953    }
1954    else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1955      if (isNumericLiteralExpression(BL->getSubExpr()))
1956        os << "NSNumber literal is an object with a +0 retain count";
1957      else {
1958        const ObjCInterfaceDecl *BoxClass = 0;
1959        if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1960          BoxClass = Method->getClassInterface();
1961
1962        // We should always be able to find the boxing class interface,
1963        // but consider this future-proofing.
1964        if (BoxClass)
1965          os << *BoxClass << " b";
1966        else
1967          os << "B";
1968
1969        os << "oxed expression produces an object with a +0 retain count";
1970      }
1971    }
1972    else {
1973      if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1974        // Get the name of the callee (if it is available).
1975        SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1976        if (const FunctionDecl *FD = X.getAsFunctionDecl())
1977          os << "Call to function '" << *FD << '\'';
1978        else
1979          os << "function call";
1980      }
1981      else {
1982        assert(isa<ObjCMessageExpr>(S));
1983        CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1984        CallEventRef<ObjCMethodCall> Call
1985          = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1986
1987        switch (Call->getMessageKind()) {
1988        case OCM_Message:
1989          os << "Method";
1990          break;
1991        case OCM_PropertyAccess:
1992          os << "Property";
1993          break;
1994        case OCM_Subscript:
1995          os << "Subscript";
1996          break;
1997        }
1998      }
1999
2000      if (CurrV.getObjKind() == RetEffect::CF) {
2001        os << " returns a Core Foundation object with a ";
2002      }
2003      else {
2004        assert (CurrV.getObjKind() == RetEffect::ObjC);
2005        os << " returns an Objective-C object with a ";
2006      }
2007
2008      if (CurrV.isOwned()) {
2009        os << "+1 retain count";
2010
2011        if (GCEnabled) {
2012          assert(CurrV.getObjKind() == RetEffect::CF);
2013          os << ".  "
2014          "Core Foundation objects are not automatically garbage collected.";
2015        }
2016      }
2017      else {
2018        assert (CurrV.isNotOwned());
2019        os << "+0 retain count";
2020      }
2021    }
2022
2023    PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2024                                  N->getLocationContext());
2025    return new PathDiagnosticEventPiece(Pos, os.str());
2026  }
2027
2028  // Gather up the effects that were performed on the object at this
2029  // program point
2030  SmallVector<ArgEffect, 2> AEffects;
2031
2032  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2033  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
2034    // We only have summaries attached to nodes after evaluating CallExpr and
2035    // ObjCMessageExprs.
2036    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2037
2038    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
2039      // Iterate through the parameter expressions and see if the symbol
2040      // was ever passed as an argument.
2041      unsigned i = 0;
2042
2043      for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2044           AI!=AE; ++AI, ++i) {
2045
2046        // Retrieve the value of the argument.  Is it the symbol
2047        // we are interested in?
2048        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2049          continue;
2050
2051        // We have an argument.  Get the effect!
2052        AEffects.push_back(Summ->getArg(i));
2053      }
2054    }
2055    else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2056      if (const Expr *receiver = ME->getInstanceReceiver())
2057        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2058              .getAsLocSymbol() == Sym) {
2059          // The symbol we are tracking is the receiver.
2060          AEffects.push_back(Summ->getReceiverEffect());
2061        }
2062    }
2063  }
2064
2065  do {
2066    // Get the previous type state.
2067    RefVal PrevV = *PrevT;
2068
2069    // Specially handle -dealloc.
2070    if (!GCEnabled && contains(AEffects, Dealloc)) {
2071      // Determine if the object's reference count was pushed to zero.
2072      assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2073      // We may not have transitioned to 'release' if we hit an error.
2074      // This case is handled elsewhere.
2075      if (CurrV.getKind() == RefVal::Released) {
2076        assert(CurrV.getCombinedCounts() == 0);
2077        os << "Object released by directly sending the '-dealloc' message";
2078        break;
2079      }
2080    }
2081
2082    // Specially handle CFMakeCollectable and friends.
2083    if (contains(AEffects, MakeCollectable)) {
2084      // Get the name of the function.
2085      const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2086      SVal X =
2087        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2088      const FunctionDecl *FD = X.getAsFunctionDecl();
2089
2090      if (GCEnabled) {
2091        // Determine if the object's reference count was pushed to zero.
2092        assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2093
2094        os << "In GC mode a call to '" << *FD
2095        <<  "' decrements an object's retain count and registers the "
2096        "object with the garbage collector. ";
2097
2098        if (CurrV.getKind() == RefVal::Released) {
2099          assert(CurrV.getCount() == 0);
2100          os << "Since it now has a 0 retain count the object can be "
2101          "automatically collected by the garbage collector.";
2102        }
2103        else
2104          os << "An object must have a 0 retain count to be garbage collected. "
2105          "After this call its retain count is +" << CurrV.getCount()
2106          << '.';
2107      }
2108      else
2109        os << "When GC is not enabled a call to '" << *FD
2110        << "' has no effect on its argument.";
2111
2112      // Nothing more to say.
2113      break;
2114    }
2115
2116    // Determine if the typestate has changed.
2117    if (!(PrevV == CurrV))
2118      switch (CurrV.getKind()) {
2119        case RefVal::Owned:
2120        case RefVal::NotOwned:
2121
2122          if (PrevV.getCount() == CurrV.getCount()) {
2123            // Did an autorelease message get sent?
2124            if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2125              return 0;
2126
2127            assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2128            os << "Object sent -autorelease message";
2129            break;
2130          }
2131
2132          if (PrevV.getCount() > CurrV.getCount())
2133            os << "Reference count decremented.";
2134          else
2135            os << "Reference count incremented.";
2136
2137          if (unsigned Count = CurrV.getCount())
2138            os << " The object now has a +" << Count << " retain count.";
2139
2140          if (PrevV.getKind() == RefVal::Released) {
2141            assert(GCEnabled && CurrV.getCount() > 0);
2142            os << " The object is not eligible for garbage collection until "
2143                  "the retain count reaches 0 again.";
2144          }
2145
2146          break;
2147
2148        case RefVal::Released:
2149          os << "Object released.";
2150          break;
2151
2152        case RefVal::ReturnedOwned:
2153          // Autoreleases can be applied after marking a node ReturnedOwned.
2154          if (CurrV.getAutoreleaseCount())
2155            return NULL;
2156
2157          os << "Object returned to caller as an owning reference (single "
2158                "retain count transferred to caller)";
2159          break;
2160
2161        case RefVal::ReturnedNotOwned:
2162          os << "Object returned to caller with a +0 retain count";
2163          break;
2164
2165        default:
2166          return NULL;
2167      }
2168
2169    // Emit any remaining diagnostics for the argument effects (if any).
2170    for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2171         E=AEffects.end(); I != E; ++I) {
2172
2173      // A bunch of things have alternate behavior under GC.
2174      if (GCEnabled)
2175        switch (*I) {
2176          default: break;
2177          case Autorelease:
2178            os << "In GC mode an 'autorelease' has no effect.";
2179            continue;
2180          case IncRefMsg:
2181            os << "In GC mode the 'retain' message has no effect.";
2182            continue;
2183          case DecRefMsg:
2184            os << "In GC mode the 'release' message has no effect.";
2185            continue;
2186        }
2187    }
2188  } while (0);
2189
2190  if (os.str().empty())
2191    return 0; // We have nothing to say!
2192
2193  const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2194  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2195                                N->getLocationContext());
2196  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2197
2198  // Add the range by scanning the children of the statement for any bindings
2199  // to Sym.
2200  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2201       I!=E; ++I)
2202    if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2203      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2204        P->addRange(Exp->getSourceRange());
2205        break;
2206      }
2207
2208  return P;
2209}
2210
2211// Find the first node in the current function context that referred to the
2212// tracked symbol and the memory location that value was stored to. Note, the
2213// value is only reported if the allocation occurred in the same function as
2214// the leak.
2215static std::pair<const ExplodedNode*,const MemRegion*>
2216GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2217                  SymbolRef Sym) {
2218  const ExplodedNode *Last = N;
2219  const MemRegion* FirstBinding = 0;
2220  const LocationContext *LeakContext = N->getLocationContext();
2221
2222  while (N) {
2223    ProgramStateRef St = N->getState();
2224    RefBindings B = St->get<RefBindings>();
2225
2226    if (!B.lookup(Sym))
2227      break;
2228
2229    StoreManager::FindUniqueBinding FB(Sym);
2230    StateMgr.iterBindings(St, FB);
2231    if (FB) FirstBinding = FB.getRegion();
2232
2233    // Allocation node, is the last node in the current context in which the
2234    // symbol was tracked.
2235    if (N->getLocationContext() == LeakContext)
2236      Last = N;
2237
2238    N = N->pred_empty() ? NULL : *(N->pred_begin());
2239  }
2240
2241  // If allocation happened in a function different from the leak node context,
2242  // do not report the binding.
2243  if (N->getLocationContext() != LeakContext) {
2244    FirstBinding = 0;
2245  }
2246
2247  return std::make_pair(Last, FirstBinding);
2248}
2249
2250PathDiagnosticPiece*
2251CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2252                               const ExplodedNode *EndN,
2253                               BugReport &BR) {
2254  BR.markInteresting(Sym);
2255  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2256}
2257
2258PathDiagnosticPiece*
2259CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2260                                   const ExplodedNode *EndN,
2261                                   BugReport &BR) {
2262
2263  // Tell the BugReporterContext to report cases when the tracked symbol is
2264  // assigned to different variables, etc.
2265  BR.markInteresting(Sym);
2266
2267  // We are reporting a leak.  Walk up the graph to get to the first node where
2268  // the symbol appeared, and also get the first VarDecl that tracked object
2269  // is stored to.
2270  const ExplodedNode *AllocNode = 0;
2271  const MemRegion* FirstBinding = 0;
2272
2273  llvm::tie(AllocNode, FirstBinding) =
2274    GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2275
2276  SourceManager& SM = BRC.getSourceManager();
2277
2278  // Compute an actual location for the leak.  Sometimes a leak doesn't
2279  // occur at an actual statement (e.g., transition between blocks; end
2280  // of function) so we need to walk the graph and compute a real location.
2281  const ExplodedNode *LeakN = EndN;
2282  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2283
2284  std::string sbuf;
2285  llvm::raw_string_ostream os(sbuf);
2286
2287  os << "Object leaked: ";
2288
2289  if (FirstBinding) {
2290    os << "object allocated and stored into '"
2291       << FirstBinding->getString() << '\'';
2292  }
2293  else
2294    os << "allocated object";
2295
2296  // Get the retain count.
2297  const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2298
2299  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2300    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2301    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2302    // to the caller for NS objects.
2303    const Decl *D = &EndN->getCodeDecl();
2304    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2305      os << " is returned from a method whose name ('"
2306         << MD->getSelector().getAsString()
2307         << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2308            "  This violates the naming convention rules"
2309            " given in the Memory Management Guide for Cocoa";
2310    }
2311    else {
2312      const FunctionDecl *FD = cast<FunctionDecl>(D);
2313      os << " is returned from a function whose name ('"
2314         << *FD
2315         << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2316            " convention rules given in the Memory Management Guide for Core"
2317            " Foundation";
2318    }
2319  }
2320  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2321    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2322    os << " and returned from method '" << MD.getSelector().getAsString()
2323       << "' is potentially leaked when using garbage collection.  Callers "
2324          "of this method do not expect a returned object with a +1 retain "
2325          "count since they expect the object to be managed by the garbage "
2326          "collector";
2327  }
2328  else
2329    os << " is not referenced later in this execution path and has a retain "
2330          "count of +" << RV->getCount();
2331
2332  return new PathDiagnosticEventPiece(L, os.str());
2333}
2334
2335CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2336                                 bool GCEnabled, const SummaryLogTy &Log,
2337                                 ExplodedNode *n, SymbolRef sym,
2338                                 CheckerContext &Ctx)
2339: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2340
2341  // Most bug reports are cached at the location where they occurred.
2342  // With leaks, we want to unique them by the location where they were
2343  // allocated, and only report a single path.  To do this, we need to find
2344  // the allocation site of a piece of tracked memory, which we do via a
2345  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2346  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2347  // that all ancestor nodes that represent the allocation site have the
2348  // same SourceLocation.
2349  const ExplodedNode *AllocNode = 0;
2350
2351  const SourceManager& SMgr = Ctx.getSourceManager();
2352
2353  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2354    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2355
2356  // Get the SourceLocation for the allocation site.
2357  // FIXME: This will crash the analyzer if an allocation comes from an
2358  // implicit call. (Currently there are no such allocations in Cocoa, though.)
2359  const Stmt *AllocStmt;
2360  ProgramPoint P = AllocNode->getLocation();
2361  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2362    AllocStmt = Exit->getCalleeContext()->getCallSite();
2363  else
2364    AllocStmt = cast<PostStmt>(P).getStmt();
2365  assert(AllocStmt && "All allocations must come from explicit calls");
2366  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2367                                                  n->getLocationContext());
2368  // Fill in the description of the bug.
2369  Description.clear();
2370  llvm::raw_string_ostream os(Description);
2371  os << "Potential leak ";
2372  if (GCEnabled)
2373    os << "(when using garbage collection) ";
2374  os << "of an object";
2375
2376  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2377  if (AllocBinding)
2378    os << " stored into '" << AllocBinding->getString() << '\'';
2379
2380  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2381}
2382
2383//===----------------------------------------------------------------------===//
2384// Main checker logic.
2385//===----------------------------------------------------------------------===//
2386
2387namespace {
2388class RetainCountChecker
2389  : public Checker< check::Bind,
2390                    check::DeadSymbols,
2391                    check::EndAnalysis,
2392                    check::EndPath,
2393                    check::PostStmt<BlockExpr>,
2394                    check::PostStmt<CastExpr>,
2395                    check::PostStmt<ObjCArrayLiteral>,
2396                    check::PostStmt<ObjCDictionaryLiteral>,
2397                    check::PostStmt<ObjCBoxedExpr>,
2398                    check::PostCall,
2399                    check::PreStmt<ReturnStmt>,
2400                    check::RegionChanges,
2401                    eval::Assume,
2402                    eval::Call > {
2403  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2404  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2405  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2406  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2407  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2408
2409  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2410
2411  // This map is only used to ensure proper deletion of any allocated tags.
2412  mutable SymbolTagMap DeadSymbolTags;
2413
2414  mutable OwningPtr<RetainSummaryManager> Summaries;
2415  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2416
2417  mutable ARCounts::Factory ARCountFactory;
2418
2419  mutable SummaryLogTy SummaryLog;
2420  mutable bool ShouldResetSummaryLog;
2421
2422public:
2423  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2424
2425  virtual ~RetainCountChecker() {
2426    DeleteContainerSeconds(DeadSymbolTags);
2427  }
2428
2429  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2430                        ExprEngine &Eng) const {
2431    // FIXME: This is a hack to make sure the summary log gets cleared between
2432    // analyses of different code bodies.
2433    //
2434    // Why is this necessary? Because a checker's lifetime is tied to a
2435    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2436    // Once in a blue moon, a new ExplodedNode will have the same address as an
2437    // old one with an associated summary, and the bug report visitor gets very
2438    // confused. (To make things worse, the summary lifetime is currently also
2439    // tied to a code body, so we get a crash instead of incorrect results.)
2440    //
2441    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2442    // changes, things will start going wrong again. Really the lifetime of this
2443    // log needs to be tied to either the specific nodes in it or the entire
2444    // ExplodedGraph, not to a specific part of the code being analyzed.
2445    //
2446    // (Also, having stateful local data means that the same checker can't be
2447    // used from multiple threads, but a lot of checkers have incorrect
2448    // assumptions about that anyway. So that wasn't a priority at the time of
2449    // this fix.)
2450    //
2451    // This happens at the end of analysis, but bug reports are emitted /after/
2452    // this point. So we can't just clear the summary log now. Instead, we mark
2453    // that the next time we access the summary log, it should be cleared.
2454
2455    // If we never reset the summary log during /this/ code body analysis,
2456    // there were no new summaries. There might still have been summaries from
2457    // the /last/ analysis, so clear them out to make sure the bug report
2458    // visitors don't get confused.
2459    if (ShouldResetSummaryLog)
2460      SummaryLog.clear();
2461
2462    ShouldResetSummaryLog = !SummaryLog.empty();
2463  }
2464
2465  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2466                                     bool GCEnabled) const {
2467    if (GCEnabled) {
2468      if (!leakWithinFunctionGC)
2469        leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2470                                             "garbage collection"));
2471      return leakWithinFunctionGC.get();
2472    } else {
2473      if (!leakWithinFunction) {
2474        if (LOpts.getGC() == LangOptions::HybridGC) {
2475          leakWithinFunction.reset(new Leak("Leak of object when not using "
2476                                            "garbage collection (GC) in "
2477                                            "dual GC/non-GC code"));
2478        } else {
2479          leakWithinFunction.reset(new Leak("Leak"));
2480        }
2481      }
2482      return leakWithinFunction.get();
2483    }
2484  }
2485
2486  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2487    if (GCEnabled) {
2488      if (!leakAtReturnGC)
2489        leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2490                                      "garbage collection"));
2491      return leakAtReturnGC.get();
2492    } else {
2493      if (!leakAtReturn) {
2494        if (LOpts.getGC() == LangOptions::HybridGC) {
2495          leakAtReturn.reset(new Leak("Leak of returned object when not using "
2496                                      "garbage collection (GC) in dual "
2497                                      "GC/non-GC code"));
2498        } else {
2499          leakAtReturn.reset(new Leak("Leak of returned object"));
2500        }
2501      }
2502      return leakAtReturn.get();
2503    }
2504  }
2505
2506  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2507                                          bool GCEnabled) const {
2508    // FIXME: We don't support ARC being turned on and off during one analysis.
2509    // (nor, for that matter, do we support changing ASTContexts)
2510    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2511    if (GCEnabled) {
2512      if (!SummariesGC)
2513        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2514      else
2515        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2516      return *SummariesGC;
2517    } else {
2518      if (!Summaries)
2519        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2520      else
2521        assert(Summaries->isARCEnabled() == ARCEnabled);
2522      return *Summaries;
2523    }
2524  }
2525
2526  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2527    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2528  }
2529
2530  void printState(raw_ostream &Out, ProgramStateRef State,
2531                  const char *NL, const char *Sep) const;
2532
2533  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2534  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2535  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2536
2537  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2538  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2539  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2540
2541  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2542
2543  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2544                    CheckerContext &C) const;
2545
2546  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2547
2548  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2549                                 bool Assumption) const;
2550
2551  ProgramStateRef
2552  checkRegionChanges(ProgramStateRef state,
2553                     const StoreManager::InvalidatedSymbols *invalidated,
2554                     ArrayRef<const MemRegion *> ExplicitRegions,
2555                     ArrayRef<const MemRegion *> Regions,
2556                     const CallEvent *Call) const;
2557
2558  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2559    return true;
2560  }
2561
2562  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2563  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2564                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2565                                SymbolRef Sym, ProgramStateRef state) const;
2566
2567  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2568  void checkEndPath(CheckerContext &C) const;
2569
2570  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2571                                   RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2572                                   CheckerContext &C) const;
2573
2574  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2575                           RefVal::Kind ErrorKind, SymbolRef Sym,
2576                           CheckerContext &C) const;
2577
2578  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2579
2580  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2581
2582  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2583                                        SymbolRef sid, RefVal V,
2584                                      SmallVectorImpl<SymbolRef> &Leaked) const;
2585
2586  std::pair<ExplodedNode *, ProgramStateRef >
2587  handleAutoreleaseCounts(ProgramStateRef state,
2588                          GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
2589                          CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
2590
2591  ExplodedNode *processLeaks(ProgramStateRef state,
2592                             SmallVectorImpl<SymbolRef> &Leaked,
2593                             GenericNodeBuilderRefCount &Builder,
2594                             CheckerContext &Ctx,
2595                             ExplodedNode *Pred = 0) const;
2596};
2597} // end anonymous namespace
2598
2599namespace {
2600class StopTrackingCallback : public SymbolVisitor {
2601  ProgramStateRef state;
2602public:
2603  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2604  ProgramStateRef getState() const { return state; }
2605
2606  bool VisitSymbol(SymbolRef sym) {
2607    state = state->remove<RefBindings>(sym);
2608    return true;
2609  }
2610};
2611} // end anonymous namespace
2612
2613//===----------------------------------------------------------------------===//
2614// Handle statements that may have an effect on refcounts.
2615//===----------------------------------------------------------------------===//
2616
2617void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2618                                       CheckerContext &C) const {
2619
2620  // Scan the BlockDecRefExprs for any object the retain count checker
2621  // may be tracking.
2622  if (!BE->getBlockDecl()->hasCaptures())
2623    return;
2624
2625  ProgramStateRef state = C.getState();
2626  const BlockDataRegion *R =
2627    cast<BlockDataRegion>(state->getSVal(BE,
2628                                         C.getLocationContext()).getAsRegion());
2629
2630  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2631                                            E = R->referenced_vars_end();
2632
2633  if (I == E)
2634    return;
2635
2636  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2637  // via captured variables, even though captured variables result in a copy
2638  // and in implicit increment/decrement of a retain count.
2639  SmallVector<const MemRegion*, 10> Regions;
2640  const LocationContext *LC = C.getLocationContext();
2641  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2642
2643  for ( ; I != E; ++I) {
2644    const VarRegion *VR = *I;
2645    if (VR->getSuperRegion() == R) {
2646      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2647    }
2648    Regions.push_back(VR);
2649  }
2650
2651  state =
2652    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2653                                    Regions.data() + Regions.size()).getState();
2654  C.addTransition(state);
2655}
2656
2657void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2658                                       CheckerContext &C) const {
2659  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2660  if (!BE)
2661    return;
2662
2663  ArgEffect AE = IncRef;
2664
2665  switch (BE->getBridgeKind()) {
2666    case clang::OBC_Bridge:
2667      // Do nothing.
2668      return;
2669    case clang::OBC_BridgeRetained:
2670      AE = IncRef;
2671      break;
2672    case clang::OBC_BridgeTransfer:
2673      AE = DecRefBridgedTransfered;
2674      break;
2675  }
2676
2677  ProgramStateRef state = C.getState();
2678  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2679  if (!Sym)
2680    return;
2681  const RefVal* T = state->get<RefBindings>(Sym);
2682  if (!T)
2683    return;
2684
2685  RefVal::Kind hasErr = (RefVal::Kind) 0;
2686  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2687
2688  if (hasErr) {
2689    // FIXME: If we get an error during a bridge cast, should we report it?
2690    // Should we assert that there is no error?
2691    return;
2692  }
2693
2694  C.addTransition(state);
2695}
2696
2697void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2698                                             const Expr *Ex) const {
2699  ProgramStateRef state = C.getState();
2700  const ExplodedNode *pred = C.getPredecessor();
2701  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2702       it != et ; ++it) {
2703    const Stmt *child = *it;
2704    SVal V = state->getSVal(child, pred->getLocationContext());
2705    if (SymbolRef sym = V.getAsSymbol())
2706      if (const RefVal* T = state->get<RefBindings>(sym)) {
2707        RefVal::Kind hasErr = (RefVal::Kind) 0;
2708        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2709        if (hasErr) {
2710          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2711          return;
2712        }
2713      }
2714  }
2715
2716  // Return the object as autoreleased.
2717  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2718  if (SymbolRef sym =
2719        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2720    QualType ResultTy = Ex->getType();
2721    state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2722                                                              ResultTy));
2723  }
2724
2725  C.addTransition(state);
2726}
2727
2728void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2729                                       CheckerContext &C) const {
2730  // Apply the 'MayEscape' to all values.
2731  processObjCLiterals(C, AL);
2732}
2733
2734void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2735                                       CheckerContext &C) const {
2736  // Apply the 'MayEscape' to all keys and values.
2737  processObjCLiterals(C, DL);
2738}
2739
2740void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2741                                       CheckerContext &C) const {
2742  const ExplodedNode *Pred = C.getPredecessor();
2743  const LocationContext *LCtx = Pred->getLocationContext();
2744  ProgramStateRef State = Pred->getState();
2745
2746  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2747    QualType ResultTy = Ex->getType();
2748    State = State->set<RefBindings>(Sym, RefVal::makeNotOwned(RetEffect::ObjC,
2749                                                              ResultTy));
2750  }
2751
2752  C.addTransition(State);
2753}
2754
2755void RetainCountChecker::checkPostCall(const CallEvent &Call,
2756                                       CheckerContext &C) const {
2757  if (C.wasInlined)
2758    return;
2759
2760  RetainSummaryManager &Summaries = getSummaryManager(C);
2761  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2762  checkSummary(*Summ, Call, C);
2763}
2764
2765/// GetReturnType - Used to get the return type of a message expression or
2766///  function call with the intention of affixing that type to a tracked symbol.
2767///  While the return type can be queried directly from RetEx, when
2768///  invoking class methods we augment to the return type to be that of
2769///  a pointer to the class (as opposed it just being id).
2770// FIXME: We may be able to do this with related result types instead.
2771// This function is probably overestimating.
2772static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2773  QualType RetTy = RetE->getType();
2774  // If RetE is not a message expression just return its type.
2775  // If RetE is a message expression, return its types if it is something
2776  /// more specific than id.
2777  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2778    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2779      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2780          PT->isObjCClassType()) {
2781        // At this point we know the return type of the message expression is
2782        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2783        // is a call to a class method whose type we can resolve.  In such
2784        // cases, promote the return type to XXX* (where XXX is the class).
2785        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2786        return !D ? RetTy :
2787                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2788      }
2789
2790  return RetTy;
2791}
2792
2793void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2794                                      const CallEvent &CallOrMsg,
2795                                      CheckerContext &C) const {
2796  ProgramStateRef state = C.getState();
2797
2798  // Evaluate the effect of the arguments.
2799  RefVal::Kind hasErr = (RefVal::Kind) 0;
2800  SourceRange ErrorRange;
2801  SymbolRef ErrorSym = 0;
2802
2803  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2804    SVal V = CallOrMsg.getArgSVal(idx);
2805
2806    if (SymbolRef Sym = V.getAsLocSymbol()) {
2807      if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
2808        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2809        if (hasErr) {
2810          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2811          ErrorSym = Sym;
2812          break;
2813        }
2814      }
2815    }
2816  }
2817
2818  // Evaluate the effect on the message receiver.
2819  bool ReceiverIsTracked = false;
2820  if (!hasErr) {
2821    const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2822    if (MsgInvocation) {
2823      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2824        if (const RefVal *T = state->get<RefBindings>(Sym)) {
2825          ReceiverIsTracked = true;
2826          state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2827                               hasErr, C);
2828          if (hasErr) {
2829            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2830            ErrorSym = Sym;
2831          }
2832        }
2833      }
2834    }
2835  }
2836
2837  // Process any errors.
2838  if (hasErr) {
2839    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2840    return;
2841  }
2842
2843  // Consult the summary for the return value.
2844  RetEffect RE = Summ.getRetEffect();
2845
2846  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2847    if (ReceiverIsTracked)
2848      RE = getSummaryManager(C).getObjAllocRetEffect();
2849    else
2850      RE = RetEffect::MakeNoRet();
2851  }
2852
2853  switch (RE.getKind()) {
2854    default:
2855      llvm_unreachable("Unhandled RetEffect.");
2856
2857    case RetEffect::NoRet:
2858      // No work necessary.
2859      break;
2860
2861    case RetEffect::OwnedAllocatedSymbol:
2862    case RetEffect::OwnedSymbol: {
2863      SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2864                                     C.getLocationContext()).getAsSymbol();
2865      if (!Sym)
2866        break;
2867
2868      // Use the result type from the CallEvent as it automatically adjusts
2869      // for methods/functions that return references.
2870      QualType ResultTy = CallOrMsg.getResultType();
2871      state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2872                                                             ResultTy));
2873
2874      // FIXME: Add a flag to the checker where allocations are assumed to
2875      // *not* fail. (The code below is out-of-date, though.)
2876#if 0
2877      if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2878        bool isFeasible;
2879        state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2880        assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2881      }
2882#endif
2883
2884      break;
2885    }
2886
2887    case RetEffect::GCNotOwnedSymbol:
2888    case RetEffect::ARCNotOwnedSymbol:
2889    case RetEffect::NotOwnedSymbol: {
2890      const Expr *Ex = CallOrMsg.getOriginExpr();
2891      SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
2892      if (!Sym)
2893        break;
2894
2895      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2896      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2897      state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2898                                                                ResultTy));
2899      break;
2900    }
2901  }
2902
2903  // This check is actually necessary; otherwise the statement builder thinks
2904  // we've hit a previously-found path.
2905  // Normally addTransition takes care of this, but we want the node pointer.
2906  ExplodedNode *NewNode;
2907  if (state == C.getState()) {
2908    NewNode = C.getPredecessor();
2909  } else {
2910    NewNode = C.addTransition(state);
2911  }
2912
2913  // Annotate the node with summary we used.
2914  if (NewNode) {
2915    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2916    if (ShouldResetSummaryLog) {
2917      SummaryLog.clear();
2918      ShouldResetSummaryLog = false;
2919    }
2920    SummaryLog[NewNode] = &Summ;
2921  }
2922}
2923
2924
2925ProgramStateRef
2926RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2927                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2928                                 CheckerContext &C) const {
2929  // In GC mode [... release] and [... retain] do nothing.
2930  // In ARC mode they shouldn't exist at all, but we just ignore them.
2931  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2932  if (!IgnoreRetainMsg)
2933    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2934
2935  switch (E) {
2936  default:
2937    break;
2938  case IncRefMsg:
2939    E = IgnoreRetainMsg ? DoNothing : IncRef;
2940    break;
2941  case DecRefMsg:
2942    E = IgnoreRetainMsg ? DoNothing : DecRef;
2943    break;
2944  case DecRefMsgAndStopTracking:
2945    E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2946    break;
2947  case MakeCollectable:
2948    E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2949    break;
2950  case NewAutoreleasePool:
2951    E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2952    break;
2953  }
2954
2955  // Handle all use-after-releases.
2956  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2957    V = V ^ RefVal::ErrorUseAfterRelease;
2958    hasErr = V.getKind();
2959    return state->set<RefBindings>(sym, V);
2960  }
2961
2962  switch (E) {
2963    case DecRefMsg:
2964    case IncRefMsg:
2965    case MakeCollectable:
2966    case DecRefMsgAndStopTracking:
2967      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2968
2969    case Dealloc:
2970      // Any use of -dealloc in GC is *bad*.
2971      if (C.isObjCGCEnabled()) {
2972        V = V ^ RefVal::ErrorDeallocGC;
2973        hasErr = V.getKind();
2974        break;
2975      }
2976
2977      switch (V.getKind()) {
2978        default:
2979          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2980        case RefVal::Owned:
2981          // The object immediately transitions to the released state.
2982          V = V ^ RefVal::Released;
2983          V.clearCounts();
2984          return state->set<RefBindings>(sym, V);
2985        case RefVal::NotOwned:
2986          V = V ^ RefVal::ErrorDeallocNotOwned;
2987          hasErr = V.getKind();
2988          break;
2989      }
2990      break;
2991
2992    case NewAutoreleasePool:
2993      assert(!C.isObjCGCEnabled());
2994      return state->add<AutoreleaseStack>(sym);
2995
2996    case MayEscape:
2997      if (V.getKind() == RefVal::Owned) {
2998        V = V ^ RefVal::NotOwned;
2999        break;
3000      }
3001
3002      // Fall-through.
3003
3004    case DoNothing:
3005      return state;
3006
3007    case Autorelease:
3008      if (C.isObjCGCEnabled())
3009        return state;
3010
3011      // Update the autorelease counts.
3012      state = SendAutorelease(state, ARCountFactory, sym);
3013      V = V.autorelease();
3014      break;
3015
3016    case StopTracking:
3017      return state->remove<RefBindings>(sym);
3018
3019    case IncRef:
3020      switch (V.getKind()) {
3021        default:
3022          llvm_unreachable("Invalid RefVal state for a retain.");
3023        case RefVal::Owned:
3024        case RefVal::NotOwned:
3025          V = V + 1;
3026          break;
3027        case RefVal::Released:
3028          // Non-GC cases are handled above.
3029          assert(C.isObjCGCEnabled());
3030          V = (V ^ RefVal::Owned) + 1;
3031          break;
3032      }
3033      break;
3034
3035    case DecRef:
3036    case DecRefBridgedTransfered:
3037    case DecRefAndStopTracking:
3038      switch (V.getKind()) {
3039        default:
3040          // case 'RefVal::Released' handled above.
3041          llvm_unreachable("Invalid RefVal state for a release.");
3042
3043        case RefVal::Owned:
3044          assert(V.getCount() > 0);
3045          if (V.getCount() == 1)
3046            V = V ^ (E == DecRefBridgedTransfered ?
3047                      RefVal::NotOwned : RefVal::Released);
3048          else if (E == DecRefAndStopTracking)
3049            return state->remove<RefBindings>(sym);
3050
3051          V = V - 1;
3052          break;
3053
3054        case RefVal::NotOwned:
3055          if (V.getCount() > 0) {
3056            if (E == DecRefAndStopTracking)
3057              return state->remove<RefBindings>(sym);
3058            V = V - 1;
3059          } else {
3060            V = V ^ RefVal::ErrorReleaseNotOwned;
3061            hasErr = V.getKind();
3062          }
3063          break;
3064
3065        case RefVal::Released:
3066          // Non-GC cases are handled above.
3067          assert(C.isObjCGCEnabled());
3068          V = V ^ RefVal::ErrorUseAfterRelease;
3069          hasErr = V.getKind();
3070          break;
3071      }
3072      break;
3073  }
3074  return state->set<RefBindings>(sym, V);
3075}
3076
3077void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3078                                             SourceRange ErrorRange,
3079                                             RefVal::Kind ErrorKind,
3080                                             SymbolRef Sym,
3081                                             CheckerContext &C) const {
3082  ExplodedNode *N = C.generateSink(St);
3083  if (!N)
3084    return;
3085
3086  CFRefBug *BT;
3087  switch (ErrorKind) {
3088    default:
3089      llvm_unreachable("Unhandled error.");
3090    case RefVal::ErrorUseAfterRelease:
3091      if (!useAfterRelease)
3092        useAfterRelease.reset(new UseAfterRelease());
3093      BT = &*useAfterRelease;
3094      break;
3095    case RefVal::ErrorReleaseNotOwned:
3096      if (!releaseNotOwned)
3097        releaseNotOwned.reset(new BadRelease());
3098      BT = &*releaseNotOwned;
3099      break;
3100    case RefVal::ErrorDeallocGC:
3101      if (!deallocGC)
3102        deallocGC.reset(new DeallocGC());
3103      BT = &*deallocGC;
3104      break;
3105    case RefVal::ErrorDeallocNotOwned:
3106      if (!deallocNotOwned)
3107        deallocNotOwned.reset(new DeallocNotOwned());
3108      BT = &*deallocNotOwned;
3109      break;
3110  }
3111
3112  assert(BT);
3113  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3114                                        C.isObjCGCEnabled(), SummaryLog,
3115                                        N, Sym);
3116  report->addRange(ErrorRange);
3117  C.EmitReport(report);
3118}
3119
3120//===----------------------------------------------------------------------===//
3121// Handle the return values of retain-count-related functions.
3122//===----------------------------------------------------------------------===//
3123
3124bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3125  // Get the callee. We're only interested in simple C functions.
3126  ProgramStateRef state = C.getState();
3127  const FunctionDecl *FD = C.getCalleeDecl(CE);
3128  if (!FD)
3129    return false;
3130
3131  IdentifierInfo *II = FD->getIdentifier();
3132  if (!II)
3133    return false;
3134
3135  // For now, we're only handling the functions that return aliases of their
3136  // arguments: CFRetain and CFMakeCollectable (and their families).
3137  // Eventually we should add other functions we can model entirely,
3138  // such as CFRelease, which don't invalidate their arguments or globals.
3139  if (CE->getNumArgs() != 1)
3140    return false;
3141
3142  // Get the name of the function.
3143  StringRef FName = II->getName();
3144  FName = FName.substr(FName.find_first_not_of('_'));
3145
3146  // See if it's one of the specific functions we know how to eval.
3147  bool canEval = false;
3148
3149  QualType ResultTy = CE->getCallReturnType();
3150  if (ResultTy->isObjCIdType()) {
3151    // Handle: id NSMakeCollectable(CFTypeRef)
3152    canEval = II->isStr("NSMakeCollectable");
3153  } else if (ResultTy->isPointerType()) {
3154    // Handle: (CF|CG)Retain
3155    //         CFMakeCollectable
3156    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3157    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3158        cocoa::isRefType(ResultTy, "CG", FName)) {
3159      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3160    }
3161  }
3162
3163  if (!canEval)
3164    return false;
3165
3166  // Bind the return value.
3167  const LocationContext *LCtx = C.getLocationContext();
3168  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3169  if (RetVal.isUnknown()) {
3170    // If the receiver is unknown, conjure a return value.
3171    SValBuilder &SVB = C.getSValBuilder();
3172    unsigned Count = C.getCurrentBlockCount();
3173    RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
3174  }
3175  state = state->BindExpr(CE, LCtx, RetVal, false);
3176
3177  // FIXME: This should not be necessary, but otherwise the argument seems to be
3178  // considered alive during the next statement.
3179  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3180    // Save the refcount status of the argument.
3181    SymbolRef Sym = RetVal.getAsLocSymbol();
3182    RefBindings::data_type *Binding = 0;
3183    if (Sym)
3184      Binding = state->get<RefBindings>(Sym);
3185
3186    // Invalidate the argument region.
3187    unsigned Count = C.getCurrentBlockCount();
3188    state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
3189
3190    // Restore the refcount status of the argument.
3191    if (Binding)
3192      state = state->set<RefBindings>(Sym, *Binding);
3193  }
3194
3195  C.addTransition(state);
3196  return true;
3197}
3198
3199//===----------------------------------------------------------------------===//
3200// Handle return statements.
3201//===----------------------------------------------------------------------===//
3202
3203// Return true if the current LocationContext has no caller context.
3204static bool inTopFrame(CheckerContext &C) {
3205  const LocationContext *LC = C.getLocationContext();
3206  return LC->getParent() == 0;
3207}
3208
3209void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3210                                      CheckerContext &C) const {
3211
3212  // Only adjust the reference count if this is the top-level call frame,
3213  // and not the result of inlining.  In the future, we should do
3214  // better checking even for inlined calls, and see if they match
3215  // with their expected semantics (e.g., the method should return a retained
3216  // object, etc.).
3217  if (!inTopFrame(C))
3218    return;
3219
3220  const Expr *RetE = S->getRetValue();
3221  if (!RetE)
3222    return;
3223
3224  ProgramStateRef state = C.getState();
3225  SymbolRef Sym =
3226    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3227  if (!Sym)
3228    return;
3229
3230  // Get the reference count binding (if any).
3231  const RefVal *T = state->get<RefBindings>(Sym);
3232  if (!T)
3233    return;
3234
3235  // Change the reference count.
3236  RefVal X = *T;
3237
3238  switch (X.getKind()) {
3239    case RefVal::Owned: {
3240      unsigned cnt = X.getCount();
3241      assert(cnt > 0);
3242      X.setCount(cnt - 1);
3243      X = X ^ RefVal::ReturnedOwned;
3244      break;
3245    }
3246
3247    case RefVal::NotOwned: {
3248      unsigned cnt = X.getCount();
3249      if (cnt) {
3250        X.setCount(cnt - 1);
3251        X = X ^ RefVal::ReturnedOwned;
3252      }
3253      else {
3254        X = X ^ RefVal::ReturnedNotOwned;
3255      }
3256      break;
3257    }
3258
3259    default:
3260      return;
3261  }
3262
3263  // Update the binding.
3264  state = state->set<RefBindings>(Sym, X);
3265  ExplodedNode *Pred = C.addTransition(state);
3266
3267  // At this point we have updated the state properly.
3268  // Everything after this is merely checking to see if the return value has
3269  // been over- or under-retained.
3270
3271  // Did we cache out?
3272  if (!Pred)
3273    return;
3274
3275  // Update the autorelease counts.
3276  static SimpleProgramPointTag
3277         AutoreleaseTag("RetainCountChecker : Autorelease");
3278  GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
3279  llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
3280
3281  // Did we cache out?
3282  if (!Pred)
3283    return;
3284
3285  // Get the updated binding.
3286  T = state->get<RefBindings>(Sym);
3287  assert(T);
3288  X = *T;
3289
3290  // Consult the summary of the enclosing method.
3291  RetainSummaryManager &Summaries = getSummaryManager(C);
3292  const Decl *CD = &Pred->getCodeDecl();
3293  RetEffect RE = RetEffect::MakeNoRet();
3294
3295  // FIXME: What is the convention for blocks? Is there one?
3296  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3297    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3298    RE = Summ->getRetEffect();
3299  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3300    if (!isa<CXXMethodDecl>(FD)) {
3301      const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3302      RE = Summ->getRetEffect();
3303    }
3304  }
3305
3306  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3307}
3308
3309void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3310                                                  CheckerContext &C,
3311                                                  ExplodedNode *Pred,
3312                                                  RetEffect RE, RefVal X,
3313                                                  SymbolRef Sym,
3314                                              ProgramStateRef state) const {
3315  // Any leaks or other errors?
3316  if (X.isReturnedOwned() && X.getCount() == 0) {
3317    if (RE.getKind() != RetEffect::NoRet) {
3318      bool hasError = false;
3319      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3320        // Things are more complicated with garbage collection.  If the
3321        // returned object is suppose to be an Objective-C object, we have
3322        // a leak (as the caller expects a GC'ed object) because no
3323        // method should return ownership unless it returns a CF object.
3324        hasError = true;
3325        X = X ^ RefVal::ErrorGCLeakReturned;
3326      }
3327      else if (!RE.isOwned()) {
3328        // Either we are using GC and the returned object is a CF type
3329        // or we aren't using GC.  In either case, we expect that the
3330        // enclosing method is expected to return ownership.
3331        hasError = true;
3332        X = X ^ RefVal::ErrorLeakReturned;
3333      }
3334
3335      if (hasError) {
3336        // Generate an error node.
3337        state = state->set<RefBindings>(Sym, X);
3338
3339        static SimpleProgramPointTag
3340               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3341        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3342        if (N) {
3343          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3344          bool GCEnabled = C.isObjCGCEnabled();
3345          CFRefReport *report =
3346            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3347                                LOpts, GCEnabled, SummaryLog,
3348                                N, Sym, C);
3349          C.EmitReport(report);
3350        }
3351      }
3352    }
3353  } else if (X.isReturnedNotOwned()) {
3354    if (RE.isOwned()) {
3355      // Trying to return a not owned object to a caller expecting an
3356      // owned object.
3357      state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3358
3359      static SimpleProgramPointTag
3360             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3361      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3362      if (N) {
3363        if (!returnNotOwnedForOwned)
3364          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3365
3366        CFRefReport *report =
3367            new CFRefReport(*returnNotOwnedForOwned,
3368                            C.getASTContext().getLangOpts(),
3369                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3370        C.EmitReport(report);
3371      }
3372    }
3373  }
3374}
3375
3376//===----------------------------------------------------------------------===//
3377// Check various ways a symbol can be invalidated.
3378//===----------------------------------------------------------------------===//
3379
3380void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3381                                   CheckerContext &C) const {
3382  // Are we storing to something that causes the value to "escape"?
3383  bool escapes = true;
3384
3385  // A value escapes in three possible cases (this may change):
3386  //
3387  // (1) we are binding to something that is not a memory region.
3388  // (2) we are binding to a memregion that does not have stack storage
3389  // (3) we are binding to a memregion with stack storage that the store
3390  //     does not understand.
3391  ProgramStateRef state = C.getState();
3392
3393  if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3394    escapes = !regionLoc->getRegion()->hasStackStorage();
3395
3396    if (!escapes) {
3397      // To test (3), generate a new state with the binding added.  If it is
3398      // the same state, then it escapes (since the store cannot represent
3399      // the binding).
3400      // Do this only if we know that the store is not supposed to generate the
3401      // same state.
3402      SVal StoredVal = state->getSVal(regionLoc->getRegion());
3403      if (StoredVal != val)
3404        escapes = (state == (state->bindLoc(*regionLoc, val)));
3405    }
3406    if (!escapes) {
3407      // Case 4: We do not currently model what happens when a symbol is
3408      // assigned to a struct field, so be conservative here and let the symbol
3409      // go. TODO: This could definitely be improved upon.
3410      escapes = !isa<VarRegion>(regionLoc->getRegion());
3411    }
3412  }
3413
3414  // If our store can represent the binding and we aren't storing to something
3415  // that doesn't have local storage then just return and have the simulation
3416  // state continue as is.
3417  if (!escapes)
3418      return;
3419
3420  // Otherwise, find all symbols referenced by 'val' that we are tracking
3421  // and stop tracking them.
3422  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3423  C.addTransition(state);
3424}
3425
3426ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3427                                                   SVal Cond,
3428                                                   bool Assumption) const {
3429
3430  // FIXME: We may add to the interface of evalAssume the list of symbols
3431  //  whose assumptions have changed.  For now we just iterate through the
3432  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3433  //  too bad since the number of symbols we will track in practice are
3434  //  probably small and evalAssume is only called at branches and a few
3435  //  other places.
3436  RefBindings B = state->get<RefBindings>();
3437
3438  if (B.isEmpty())
3439    return state;
3440
3441  bool changed = false;
3442  RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3443
3444  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3445    // Check if the symbol is null (or equal to any constant).
3446    // If this is the case, stop tracking the symbol.
3447    if (state->getSymVal(I.getKey())) {
3448      changed = true;
3449      B = RefBFactory.remove(B, I.getKey());
3450    }
3451  }
3452
3453  if (changed)
3454    state = state->set<RefBindings>(B);
3455
3456  return state;
3457}
3458
3459ProgramStateRef
3460RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3461                            const StoreManager::InvalidatedSymbols *invalidated,
3462                                    ArrayRef<const MemRegion *> ExplicitRegions,
3463                                    ArrayRef<const MemRegion *> Regions,
3464                                    const CallEvent *Call) const {
3465  if (!invalidated)
3466    return state;
3467
3468  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3469  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3470       E = ExplicitRegions.end(); I != E; ++I) {
3471    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3472      WhitelistedSymbols.insert(SR->getSymbol());
3473  }
3474
3475  for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3476       E = invalidated->end(); I!=E; ++I) {
3477    SymbolRef sym = *I;
3478    if (WhitelistedSymbols.count(sym))
3479      continue;
3480    // Remove any existing reference-count binding.
3481    state = state->remove<RefBindings>(sym);
3482  }
3483  return state;
3484}
3485
3486//===----------------------------------------------------------------------===//
3487// Handle dead symbols and end-of-path.
3488//===----------------------------------------------------------------------===//
3489
3490std::pair<ExplodedNode *, ProgramStateRef >
3491RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3492                                            GenericNodeBuilderRefCount Bd,
3493                                            ExplodedNode *Pred,
3494                                            CheckerContext &Ctx,
3495                                            SymbolRef Sym, RefVal V) const {
3496  unsigned ACnt = V.getAutoreleaseCount();
3497
3498  // No autorelease counts?  Nothing to be done.
3499  if (!ACnt)
3500    return std::make_pair(Pred, state);
3501
3502  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3503  unsigned Cnt = V.getCount();
3504
3505  // FIXME: Handle sending 'autorelease' to already released object.
3506
3507  if (V.getKind() == RefVal::ReturnedOwned)
3508    ++Cnt;
3509
3510  if (ACnt <= Cnt) {
3511    if (ACnt == Cnt) {
3512      V.clearCounts();
3513      if (V.getKind() == RefVal::ReturnedOwned)
3514        V = V ^ RefVal::ReturnedNotOwned;
3515      else
3516        V = V ^ RefVal::NotOwned;
3517    } else {
3518      V.setCount(Cnt - ACnt);
3519      V.setAutoreleaseCount(0);
3520    }
3521    state = state->set<RefBindings>(Sym, V);
3522    ExplodedNode *N = Bd.MakeNode(state, Pred);
3523    if (N == 0)
3524      state = 0;
3525    return std::make_pair(N, state);
3526  }
3527
3528  // Woah!  More autorelease counts then retain counts left.
3529  // Emit hard error.
3530  V = V ^ RefVal::ErrorOverAutorelease;
3531  state = state->set<RefBindings>(Sym, V);
3532
3533  if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
3534    SmallString<128> sbuf;
3535    llvm::raw_svector_ostream os(sbuf);
3536    os << "Object over-autoreleased: object was sent -autorelease ";
3537    if (V.getAutoreleaseCount() > 1)
3538      os << V.getAutoreleaseCount() << " times ";
3539    os << "but the object has a +" << V.getCount() << " retain count";
3540
3541    if (!overAutorelease)
3542      overAutorelease.reset(new OverAutorelease());
3543
3544    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3545    CFRefReport *report =
3546      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3547                      SummaryLog, N, Sym, os.str());
3548    Ctx.EmitReport(report);
3549  }
3550
3551  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
3552}
3553
3554ProgramStateRef
3555RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3556                                      SymbolRef sid, RefVal V,
3557                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3558  bool hasLeak = false;
3559  if (V.isOwned())
3560    hasLeak = true;
3561  else if (V.isNotOwned() || V.isReturnedOwned())
3562    hasLeak = (V.getCount() > 0);
3563
3564  if (!hasLeak)
3565    return state->remove<RefBindings>(sid);
3566
3567  Leaked.push_back(sid);
3568  return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3569}
3570
3571ExplodedNode *
3572RetainCountChecker::processLeaks(ProgramStateRef state,
3573                                 SmallVectorImpl<SymbolRef> &Leaked,
3574                                 GenericNodeBuilderRefCount &Builder,
3575                                 CheckerContext &Ctx,
3576                                 ExplodedNode *Pred) const {
3577  if (Leaked.empty())
3578    return Pred;
3579
3580  // Generate an intermediate node representing the leak point.
3581  ExplodedNode *N = Builder.MakeNode(state, Pred);
3582
3583  if (N) {
3584    for (SmallVectorImpl<SymbolRef>::iterator
3585         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3586
3587      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3588      bool GCEnabled = Ctx.isObjCGCEnabled();
3589      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3590                          : getLeakAtReturnBug(LOpts, GCEnabled);
3591      assert(BT && "BugType not initialized.");
3592
3593      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3594                                                    SummaryLog, N, *I, Ctx);
3595      Ctx.EmitReport(report);
3596    }
3597  }
3598
3599  return N;
3600}
3601
3602void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
3603  ProgramStateRef state = Ctx.getState();
3604  GenericNodeBuilderRefCount Bd(Ctx);
3605  RefBindings B = state->get<RefBindings>();
3606  ExplodedNode *Pred = Ctx.getPredecessor();
3607
3608  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3609    llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
3610                                                     I->first, I->second);
3611    if (!state)
3612      return;
3613  }
3614
3615  // If the current LocationContext has a parent, don't check for leaks.
3616  // We will do that later.
3617  // FIXME: we should instead check for imblances of the retain/releases,
3618  // and suggest annotations.
3619  if (Ctx.getLocationContext()->getParent())
3620    return;
3621
3622  B = state->get<RefBindings>();
3623  SmallVector<SymbolRef, 10> Leaked;
3624
3625  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3626    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3627
3628  processLeaks(state, Leaked, Bd, Ctx, Pred);
3629}
3630
3631const ProgramPointTag *
3632RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3633  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3634  if (!tag) {
3635    SmallString<64> buf;
3636    llvm::raw_svector_ostream out(buf);
3637    out << "RetainCountChecker : Dead Symbol : ";
3638    sym->dumpToStream(out);
3639    tag = new SimpleProgramPointTag(out.str());
3640  }
3641  return tag;
3642}
3643
3644void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3645                                          CheckerContext &C) const {
3646  ExplodedNode *Pred = C.getPredecessor();
3647
3648  ProgramStateRef state = C.getState();
3649  RefBindings B = state->get<RefBindings>();
3650
3651  // Update counts from autorelease pools
3652  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3653       E = SymReaper.dead_end(); I != E; ++I) {
3654    SymbolRef Sym = *I;
3655    if (const RefVal *T = B.lookup(Sym)){
3656      // Use the symbol as the tag.
3657      // FIXME: This might not be as unique as we would like.
3658      GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
3659      llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
3660                                                       Sym, *T);
3661      if (!state)
3662        return;
3663    }
3664  }
3665
3666  B = state->get<RefBindings>();
3667  SmallVector<SymbolRef, 10> Leaked;
3668
3669  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3670       E = SymReaper.dead_end(); I != E; ++I) {
3671    if (const RefVal *T = B.lookup(*I))
3672      state = handleSymbolDeath(state, *I, *T, Leaked);
3673  }
3674
3675  {
3676    GenericNodeBuilderRefCount Bd(C, this);
3677    Pred = processLeaks(state, Leaked, Bd, C, Pred);
3678  }
3679
3680  // Did we cache out?
3681  if (!Pred)
3682    return;
3683
3684  // Now generate a new node that nukes the old bindings.
3685  RefBindings::Factory &F = state->get_context<RefBindings>();
3686
3687  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3688       E = SymReaper.dead_end(); I != E; ++I)
3689    B = F.remove(B, *I);
3690
3691  state = state->set<RefBindings>(B);
3692  C.addTransition(state, Pred);
3693}
3694
3695//===----------------------------------------------------------------------===//
3696// Debug printing of refcount bindings and autorelease pools.
3697//===----------------------------------------------------------------------===//
3698
3699static void PrintPool(raw_ostream &Out, SymbolRef Sym,
3700                      ProgramStateRef State) {
3701  Out << ' ';
3702  if (Sym)
3703    Sym->dumpToStream(Out);
3704  else
3705    Out << "<pool>";
3706  Out << ":{";
3707
3708  // Get the contents of the pool.
3709  if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3710    for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3711      Out << '(' << I.getKey() << ',' << I.getData() << ')';
3712
3713  Out << '}';
3714}
3715
3716static bool UsesAutorelease(ProgramStateRef state) {
3717  // A state uses autorelease if it allocated an autorelease pool or if it has
3718  // objects in the caller's autorelease pool.
3719  return !state->get<AutoreleaseStack>().isEmpty() ||
3720          state->get<AutoreleasePoolContents>(SymbolRef());
3721}
3722
3723void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3724                                    const char *NL, const char *Sep) const {
3725
3726  RefBindings B = State->get<RefBindings>();
3727
3728  if (!B.isEmpty())
3729    Out << Sep << NL;
3730
3731  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3732    Out << I->first << " : ";
3733    I->second.print(Out);
3734    Out << NL;
3735  }
3736
3737  // Print the autorelease stack.
3738  if (UsesAutorelease(State)) {
3739    Out << Sep << NL << "AR pool stack:";
3740    ARStack Stack = State->get<AutoreleaseStack>();
3741
3742    PrintPool(Out, SymbolRef(), State);  // Print the caller's pool.
3743    for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3744      PrintPool(Out, *I, State);
3745
3746    Out << NL;
3747  }
3748}
3749
3750//===----------------------------------------------------------------------===//
3751// Checker registration.
3752//===----------------------------------------------------------------------===//
3753
3754void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3755  Mgr.registerChecker<RetainCountChecker>();
3756}
3757
3758