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