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