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