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