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