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