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