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