RetainCountChecker.cpp revision dc84cd5efdd3430efb22546b4ac656aa0540b210
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
82a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//  This file defines the methods for RetainCountChecker, which implements
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "ClangSACheckers.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/Attr.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclCXX.h"
187d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)#include "clang/AST/DeclObjC.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/ParentMap.h"
20c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Basic/LangOptions.h"
225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Basic/SourceManager.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/Checker.h"
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/CheckerManager.h"
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/DenseMap.h"
3258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)#include "llvm/ADT/FoldingSet.h"
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/ImmutableList.h"
34868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)#include "llvm/ADT/ImmutableMap.h"
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/STLExtras.h"
36a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/ADT/SmallString.h"
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/StringExtras.h"
385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <cstdarg>
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using namespace clang;
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using namespace ento;
422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using llvm::StrInStrNoCase;
43b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
44b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)//===----------------------------------------------------------------------===//
45b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)// Primitives used for constructing summaries for function/method calls.
46b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)//===----------------------------------------------------------------------===//
475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
485d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// ArgEffect is used to summarize a function/method call's effect on a
495d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/// particular argument.
50424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                 DecRefBridgedTransfered,
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                 IncRefMsg, IncRef, MakeCollectable, MayEscape,
530f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
540f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 // Stop tracking the argument - the effect of the call is
550f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 // unknown.
56a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)                 StopTracking,
57a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
58a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)                 // In some cases, we obtain a better summary for this checker
59a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)                 // by looking at the call site than by inlining the function.
600f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 // Signifies that we should stop tracking the symbol even if
610f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 // the function is inlined.
620f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 StopTrackingHard,
63a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
640f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                 // The function decrements the reference count and the checker
65f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                 // should stop tracking the argument.
66f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
67f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)               };
68f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
690f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)namespace llvm {
70f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)template <> struct FoldingSetTrait<ArgEffect> {
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ID.AddInteger((unsigned) X);
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)};
752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)} // end llvm namespace
762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// ArgEffects summarizes the effects of a function/method call on all of
782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// its arguments.
792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)namespace {
822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
835d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)///  RetEffect is used to summarize a function/method call's behavior with
842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)///  respect to its return value.
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)class RetEffect {
862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)public:
872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)              NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)              OwnedWhenTrackedReceiver,
902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)              // Treat this function as returning a non-tracked symbol even if
912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)              // the function has been inlined. This is used where the call
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)              // site summary is more presise than the summary indirectly produced
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)              // by inlining the function
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)              NoRetHard
95b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)            };
96b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  enum ObjKind { CF, ObjC, AnyObj };
985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)private:
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Kind K;
1015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ObjKind O;
1025d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
10490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
10590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)public:
106868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Kind getKind() const { return K; }
10790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
108868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  ObjKind getObjKind() const { return O; }
1095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1101e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  bool isOwned() const {
1111e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
1121e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)           K == OwnedWhenTrackedReceiver;
1131e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  }
1141e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
1151e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  bool operator==(const RetEffect &Other) const {
1161e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    return K == Other.K && O == Other.O;
1171e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  }
1181e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
1191e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  static RetEffect MakeOwnedWhenTrackedReceiver() {
1201e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    return RetEffect(OwnedWhenTrackedReceiver, ObjC);
1211e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  }
1221e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
1231e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
1241e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
1251e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  }
1261e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)  static RetEffect MakeNotOwned(ObjKind o) {
12768043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)    return RetEffect(NotOwnedSymbol, o);
128b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)  }
12968043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)  static RetEffect MakeGCNotOwned() {
13068043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)    return RetEffect(GCNotOwnedSymbol, ObjC);
1315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
132c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  static RetEffect MakeARCNotOwned() {
133c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    return RetEffect(ARCNotOwnedSymbol, ObjC);
134a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  }
135a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  static RetEffect MakeNoRet() {
136a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)    return RetEffect(NoRet);
137a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  }
138a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  static RetEffect MakeNoRetHard() {
139c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    return RetEffect(NoRetHard);
140b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)  }
141b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
142c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  void Profile(llvm::FoldingSetNodeID& ID) const {
143c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    ID.AddInteger((unsigned) K);
144a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)    ID.AddInteger((unsigned) O);
145a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)  }
146a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)};
147a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)
148a36e5920737c6adbddd3e43b760e5de8431db6e0Torne (Richard Coles)//===----------------------------------------------------------------------===//
1495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Reference-counting logic (typestate + counts).
1505d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
1515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
1522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)class RefVal {
1535d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)public:
1545d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  enum Kind {
1555d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Owned = 0, // Owning reference.
1565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    NotOwned,  // Reference is not owned by still valid (not freed).
1575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Released,  // Object has been released.
158a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    ReturnedOwned, // Returned object passes ownership to caller.
1595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ReturnedNotOwned, // Return object does not pass ownership to caller.
1605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ERROR_START,
1615d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ErrorDeallocNotOwned, // -dealloc called on non-owned object.
16258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    ErrorDeallocGC, // Calling -dealloc with GC enabled.
16358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    ErrorUseAfterRelease, // Object used after released.
16458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    ErrorReleaseNotOwned, // Release of an object that was not owned.
1655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ERROR_LEAK_START,
1665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ErrorLeak,  // A memory leak due to excessive reference counts.
1675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ErrorLeakReturned, // A memory leak due to the returning method not having
168a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                       // the correct naming conventions.
169a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    ErrorGCLeakReturned,
170a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    ErrorOverAutorelease,
171a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    ErrorReturnedNotOwned
172a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  };
173868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
174868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)private:
175868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Kind kind;
176868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  RetEffect::ObjKind okind;
177868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  unsigned Cnt;
178868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  unsigned ACnt;
179868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  QualType T;
180868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
181868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
182868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
183868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
184868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)public:
185868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  Kind getKind() const { return kind; }
186868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
1870f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  RetEffect::ObjKind getObjKind() const { return okind; }
1880f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
1890f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  unsigned getCount() const { return Cnt; }
1900f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  unsigned getAutoreleaseCount() const { return ACnt; }
1910f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  unsigned getCombinedCounts() const { return Cnt + ACnt; }
1920f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  void clearCounts() { Cnt = 0; ACnt = 0; }
1930f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  void setCount(unsigned i) { Cnt = i; }
1940f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  void setAutoreleaseCount(unsigned i) { ACnt = i; }
1957dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
1962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  QualType getType() const { return T; }
1972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1987dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  bool isOwned() const {
1997dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return getKind() == Owned;
2007dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
2017dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
2027dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  bool isNotOwned() const {
2037dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return getKind() == NotOwned;
2047dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
205a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
2067dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  bool isReturnedOwned() const {
2077dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return getKind() == ReturnedOwned;
2087dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
2097dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
210a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  bool isReturnedNotOwned() const {
211a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return getKind() == ReturnedNotOwned;
212a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
213a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
2147dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
2157dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch                          unsigned Count = 1) {
2167dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return RefVal(Owned, o, Count, 0, t);
2177dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
2187dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
2197dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
2200f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)                             unsigned Count = 0) {
2210f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)    return RefVal(NotOwned, o, Count, 0, t);
2220f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  }
2230f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
2247dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  // Comparison, profiling, and pretty-printing.
2257dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
2267dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  bool operator==(const RefVal& X) const {
2272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
2285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
2297dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
2302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  RefVal operator-(size_t i) const {
2312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return RefVal(getKind(), getObjKind(), getCount() - i,
2327dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch                  getAutoreleaseCount(), getType());
2337dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
234868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
2357dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  RefVal operator+(size_t i) const {
2367dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return RefVal(getKind(), getObjKind(), getCount() + i,
2377dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch                  getAutoreleaseCount(), getType());
2387dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
2397dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
2407dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  RefVal operator^(Kind k) const {
2417dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch    return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
2427dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch                  getType());
2437dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch  }
2445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RefVal autorelease() const {
246558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
247558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch                  getType());
248558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch  }
249ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch
250ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch  void Profile(llvm::FoldingSetNodeID& ID) const {
251ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    ID.AddInteger((unsigned) kind);
252558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    ID.AddInteger(Cnt);
253558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    ID.AddInteger(ACnt);
254558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    ID.Add(T);
255558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch  }
2565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
257a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  void print(raw_ostream &Out) const;
258a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)};
259558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
260558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdochvoid RefVal::print(raw_ostream &Out) const {
261558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch  if (!T.isNull())
262558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    Out << "Tracked " << T.getAsString() << '/';
263558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
264558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch  switch (getKind()) {
265f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    default: llvm_unreachable("Invalid RefVal kind");
266f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    case Owned: {
267f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      Out << "Owned";
268a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      unsigned cnt = getCount();
269a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      if (cnt) Out << " (+ " << cnt << ")";
270a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      break;
271558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    }
272558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
273558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case NotOwned: {
2741e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)      Out << "NotOwned";
2751e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)      unsigned cnt = getCount();
276c2db58bd994c04d98e4ee2cd7565b71548655fe3Ben Murdoch      if (cnt) Out << " (+ " << cnt << ")";
277558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
278558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    }
279558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
280558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case ReturnedOwned: {
281558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      Out << "ReturnedOwned";
282558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      unsigned cnt = getCount();
283558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      if (cnt) Out << " (+ " << cnt << ")";
284558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
285558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    }
286558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
287558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case ReturnedNotOwned: {
288558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      Out << "ReturnedNotOwned";
289558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      unsigned cnt = getCount();
290558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      if (cnt) Out << " (+ " << cnt << ")";
291558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
2921e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    }
2931e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)
2941e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)    case Released:
295558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      Out << "Released";
296558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
297558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
298558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case ErrorDeallocGC:
299558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      Out << "-dealloc (GC)";
300558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
301558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
302558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case ErrorDeallocNotOwned:
303558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      Out << "-dealloc (not-owned)";
304558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch      break;
305558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch
306558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdoch    case ErrorLeak:
307868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      Out << "Leaked";
3085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      break;
309868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
310868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    case ErrorLeakReturned:
311a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      Out << "Leaked (Bad naming)";
312868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      break;
313868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
314868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    case ErrorGCLeakReturned:
315868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      Out << "Leaked (GC-ed at return)";
316868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      break;
317868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
318a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    case ErrorUseAfterRelease:
319868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      Out << "Use-After-Release [ERROR]";
320868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      break;
321868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
322868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    case ErrorReleaseNotOwned:
323a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      Out << "Release of Not-Owned [ERROR]";
324868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      break;
325868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
326868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    case RefVal::ErrorOverAutorelease:
327c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)      Out << "Over autoreleased";
328c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)      break;
3292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
330d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)    case RefVal::ErrorReturnedNotOwned:
331d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)      Out << "Non-owned object returned instead of owned";
3325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      break;
3335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
3345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (ACnt) {
336c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    Out << " [ARC +" << ACnt << ']';
337c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  }
338c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
339c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)} //end anonymous namespace
340c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
341424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)//===----------------------------------------------------------------------===//
342424c4d7b64af9d0d8fd9624f381f469654d5e3d2Torne (Richard Coles)// RefBindings - State used to track object reference counts.
343c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)//===----------------------------------------------------------------------===//
344c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
345c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
346c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
3475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static inline const RefVal *getRefBinding(ProgramStateRef State,
3483551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)                                          SymbolRef Sym) {
3493551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  return State->get<RefBindings>(Sym);
3503551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)}
351c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
352c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)static inline ProgramStateRef setRefBinding(ProgramStateRef State,
3535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                            SymbolRef Sym, RefVal Val) {
354c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  return State->set<RefBindings>(Sym, Val);
3553551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)}
356c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
3573551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
3585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return State->remove<RefBindings>(Sym);
3593551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)}
3605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3613551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)//===----------------------------------------------------------------------===//
3623551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)// Function/Method behavior summaries.
3633551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)//===----------------------------------------------------------------------===//
3645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3653551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)namespace {
3663551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)class RetainSummary {
3673551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// Args - a map of (index, ArgEffect) pairs, where index
3683551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ///  specifies the argument (starting from 0).  This can be sparsely
3693551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
3703551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ArgEffects Args;
3713551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
3723551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// DefaultArgEffect - The default ArgEffect to apply to arguments that
3733551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ///  do not have an entry in Args.
3745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ArgEffect DefaultArgEffect;
3755d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  /// Receiver - If this summary applies to an Objective-C message expression,
3775d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ///  this is the effect applied to the state of the receiver.
378a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  ArgEffect Receiver;
379a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
3803551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// Ret - The effect on the return value.  Used to indicate if the
3813551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ///  function/method call returns a new tracked symbol.
3823551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  RetEffect Ret;
3833551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
3842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)public:
3853551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
38690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)                ArgEffect ReceiverEff)
3873551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)    : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
3885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3893551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// getArg - Return the argument effect on the argument specified by
3905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ///  idx (starting from 0).
3913551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ArgEffect getArg(unsigned idx) const {
3925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (const ArgEffect *AE = Args.lookup(idx))
3933551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)      return *AE;
3945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
3953551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)    return DefaultArgEffect;
3962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3973551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
3985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
3993551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)    Args = af.add(Args, idx, e);
400d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)  }
401d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)
4025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// setDefaultArgEffect - Set the default argument effect.
4033551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  void setDefaultArgEffect(ArgEffect E) {
4042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    DefaultArgEffect = E;
4053551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  }
406b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
4073551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// getRetEffect - Returns the effect on the return value of the call.
408a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  RetEffect getRetEffect() const { return Ret; }
409a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
410a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  /// setRetEffect - Set the effect of the return value of the call.
411b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)  void setRetEffect(RetEffect E) { Ret = E; }
4123551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
41390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
4143551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// Sets the effect on the receiver of the message.
41590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  void setReceiverEffect(ArgEffect e) { Receiver = e; }
4163551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
4175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// getReceiverEffect - Returns the effect on the receiver of the call.
4183551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
41990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  ArgEffect getReceiverEffect() const { return Receiver; }
4203551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
42158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  /// Test if two retain summaries are identical. Note that merely equivalent
4223551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// summaries are not necessarily identical (for example, if an explicit
42358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  /// argument effect matches the default effect).
42458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  bool operator==(const RetainSummary &Other) const {
425d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)    return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
426d0247b1b59f9c528cb6df88b4f2b9afaf80d181eTorne (Richard Coles)           Receiver == Other.Receiver && Ret == Other.Ret;
4275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
4285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
4295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  /// Profile this summary for inclusion in a FoldingSet.
4305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  void Profile(llvm::FoldingSetNodeID& ID) const {
4315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.Add(Args);
4325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.Add(DefaultArgEffect);
4335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ID.Add(Receiver);
43490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    ID.Add(Ret);
4353551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  }
4365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4373551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  /// A retain summary is simple if it has no ArgEffects other than the default.
4382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool isSimple() const {
4393551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)    return Args.isEmpty();
4405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
4413551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
4425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)private:
4433551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ArgEffects getArgEffects() const { return Args; }
4442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
4453551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
4462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  friend class RetainSummaryManager;
4473551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)};
4484e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)} // end anonymous namespace
4494e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
4502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
4513551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)// Data structures for constructing summaries.
4522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
4532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4543551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)namespace {
4552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)class ObjCSummaryKey {
4562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  IdentifierInfo* II;
4573551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  Selector S;
458c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)public:
4593551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  ObjCSummaryKey(IdentifierInfo* ii, Selector s)
460c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    : II(ii), S(s) {}
4613551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
462c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
463c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    : II(d ? d->getIdentifier() : 0), S(s) {}
4643551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)
465c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  ObjCSummaryKey(Selector s)
4663551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)    : II(0), S(s) {}
467c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
4683551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  IdentifierInfo *getIdentifier() const { return II; }
469c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  Selector getSelector() const { return S; }
4703551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)};
471b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)}
472b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)
4733551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)namespace llvm {
474b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)template <> struct DenseMapInfo<ObjCSummaryKey> {
4753551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  static inline ObjCSummaryKey getEmptyKey() {
4764e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
4774e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)                          DenseMapInfo<Selector>::getEmptyKey());
478f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
479f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
480f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  static inline ObjCSummaryKey getTombstoneKey() {
481f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
482f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                          DenseMapInfo<Selector>::getTombstoneKey());
483f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
484c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
485c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  static unsigned getHashValue(const ObjCSummaryKey &V) {
486a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    typedef std::pair<IdentifierInfo*, Selector> PairTy;
4875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
4885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                     V.getSelector()));
4892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
4902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
4922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return LHS.getIdentifier() == RHS.getIdentifier() &&
4932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)           LHS.getSelector() == RHS.getSelector();
494a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
495a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
496a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)};
497a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)template <>
4982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
4992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)} // end llvm namespace
500868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
501558790d6acca3451cf3a6b497803a5f07d0bec58Ben Murdochnamespace {
5022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)class ObjCSummaryCache {
5032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
5042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  MapTy M;
505c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)public:
506c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  ObjCSummaryCache() {}
507c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
5082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
5092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Do a lookup with the (D,S) pair.  If we find a match return
5102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // the iterator.
5112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    ObjCSummaryKey K(D, S);
5122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    MapTy::iterator I = M.find(K);
5132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (I != M.end())
5152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      return I->second;
5165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (!D)
517868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)      return NULL;
5185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Walk the super chain.  If we find a hit with a parent, we'll end
5205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // up returning that summary.  We actually allow that key (null,S), as
521c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    // we cache summaries for the null ObjCInterfaceDecl* to allow us to
5225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // generate initial summaries without having to worry about NSObject
5235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // being declared.
5245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // FIXME: We may change this at some point.
5252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
5262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
5275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        break;
5285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (!C)
5302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        return NULL;
5312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
5322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
533ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    // Cache the summary with original key to make the next lookup faster
534ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    // and return the iterator.
535ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    const RetainSummary *Summ = I->second;
536ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    M[K] = Summ;
537ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    return Summ;
538ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch  }
539ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch
540ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch  const RetainSummary *find(IdentifierInfo* II, Selector S) {
541ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16Ben Murdoch    // FIXME: Class method lookup.  Right now we dont' have a good way
5422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // of going between IdentifierInfo* and the class hierarchy.
5432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
5442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (I == M.end())
5462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      I = M.find(ObjCSummaryKey(S));
5472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return I == M.end() ? NULL : I->second;
5492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
5502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const RetainSummary *& operator[](ObjCSummaryKey K) {
5525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return M[K];
553f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
5545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const RetainSummary *& operator[](Selector S) {
5562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return M[ ObjCSummaryKey(S) ];
557f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
558f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)};
5595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)} // end anonymous namespace
5605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5615d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
562f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// Data structures for managing collections of summaries.
563f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)//===----------------------------------------------------------------------===//
564f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
5655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace {
5665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class RetainSummaryManager {
5675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //==-----------------------------------------------------------------==//
569f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  //  Typedefs.
57058537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  //==-----------------------------------------------------------------==//
57158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
57258537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
57358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)          FuncSummariesTy;
5745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  typedef ObjCSummaryCache ObjCMethodSummariesTy;
5762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
5782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //==-----------------------------------------------------------------==//
5802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //  Data.
5812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //==-----------------------------------------------------------------==//
5825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// Ctx - The ASTContext object for the analyzed ASTs.
5845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ASTContext &Ctx;
5855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
5862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
5872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const bool GCEnabled;
5882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// Records whether or not the analyzed code runs in ARC mode.
5902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const bool ARCEnabled;
5912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// FuncSummaries - A map from FunctionDecls to summaries.
5932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  FuncSummariesTy FuncSummaries;
5942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
5962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ///  to summaries.
5972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCMethodSummariesTy ObjCClassMethodSummaries;
5982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// ObjCMethodSummaries - A map from selectors to summaries.
6002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCMethodSummariesTy ObjCMethodSummaries;
6012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
6032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ///  and all other data used by the checker.
6042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::BumpPtrAllocator BPAlloc;
6052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// AF - A factory for ArgEffects objects.
6072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ArgEffects::Factory AF;
6082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  /// ScratchArgs - A holding buffer for construct ArgEffects.
6102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ArgEffects ScratchArgs;
6110f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)
6120f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  /// ObjCAllocRetE - Default return effect for methods returning Objective-C
6130f1bc08d4cfcc34181b0b5cbf065c40f687bf740Torne (Richard Coles)  ///  objects.
6145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetEffect ObjCAllocRetE;
6155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
6165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  /// ObjCInitRetE - Default return effect for init methods returning
6175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ///   Objective-C objects.
6185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RetEffect ObjCInitRetE;
6195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
6202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// SimpleSummaries - Used for uniquing summaries that don't have special
6212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// effects.
6222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
6232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //==-----------------------------------------------------------------==//
6252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //  Methods.
6262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  //==-----------------------------------------------------------------==//
6272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  /// getArgEffects - Returns a persistent ArgEffects object based on the
6292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ///  data in ScratchArgs.
6302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ArgEffects getArgEffects();
6312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
633a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
634a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  const RetainSummary *getUnarySummary(const FunctionType* FT,
635a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                       UnaryFuncKind func);
6365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
6372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
638a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
639a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
6402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
6422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const RetainSummary *getPersistentSummary(RetEffect RetEff,
6445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                            ArgEffect ReceiverEff = DoNothing,
6452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                            ArgEffect DefaultEff = MayEscape) {
6462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
6472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return getPersistentSummary(Summ);
6485d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
6492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getDoNothingSummary() {
6512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
6522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
6532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getDefaultSummary() {
6552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return getPersistentSummary(RetEffect::MakeNoRet(),
6562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                DoNothing, MayEscape);
6572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
658a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
6592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getPersistentStopSummary() {
6605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return getPersistentSummary(RetEffect::MakeNoRet(),
6615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                StopTracking, StopTracking);
6625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
6637dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch
6645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void InitializeClassMethodSummaries();
6655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void InitializeMethodSummaries();
6665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)private:
6675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
6685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ObjCClassMethodSummaries[S] = Summ;
6695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
6705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
6715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
6725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ObjCMethodSummaries[S] = Summ;
6735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
6742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void addClassMethSummary(const char* Cls, const char* name,
6765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                           const RetainSummary *Summ, bool isNullary = true) {
6775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
6782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Selector S = isNullary ? GetNullarySelector(name, Ctx)
6792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                           : GetUnarySelector(name, Ctx);
6805d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
6812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
6822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void addInstMethSummary(const char* Cls, const char* nullaryName,
6845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                          const RetainSummary *Summ) {
6855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
6865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Selector S = GetNullarySelector(nullaryName, Ctx);
6872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
6882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
6895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
6905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Selector generateSelector(va_list argp) {
6912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    SmallVector<IdentifierInfo*, 10> II;
6922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    while (const char* s = va_arg(argp, const char*))
6945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      II.push_back(&Ctx.Idents.get(s));
6952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return Ctx.Selectors.getSelector(II.size(), &II[0]);
6975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
6982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
7002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                        const RetainSummary * Summ, va_list argp) {
7012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Selector S = generateSelector(argp);
7022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
7032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
7045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
7065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    va_list argp;
7075d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_start(argp, Summ);
7085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
7095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_end(argp);
7105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
7115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
7135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_list argp;
7145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    va_start(argp, Summ);
7155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
716c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    va_end(argp);
7175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
7205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_list argp;
7215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_start(argp, Summ);
7225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
7235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    va_end(argp);
7245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
7255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)public:
7275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
7295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)   : Ctx(ctx),
7305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)     GCEnabled(gcenabled),
7315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)     ARCEnabled(usesARC),
7325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)     AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
7335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)     ObjCAllocRetE(gcenabled
7342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                    ? RetEffect::MakeGCNotOwned()
7352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                    : (usesARC ? RetEffect::MakeARCNotOwned()
7362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                               : RetEffect::MakeOwned(RetEffect::ObjC, true))),
7375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)     ObjCInitRetE(gcenabled
7382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                    ? RetEffect::MakeGCNotOwned()
7392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                    : (usesARC ? RetEffect::MakeARCNotOwned()
7402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                               : RetEffect::MakeOwnedWhenTrackedReceiver())) {
7412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    InitializeClassMethodSummaries();
7425d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    InitializeMethodSummaries();
7435d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
7445d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *getSummary(const CallEvent &Call,
7462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                  ProgramStateRef State = 0);
7472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
7495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
7505d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
7515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                        const ObjCMethodDecl *MD,
7525d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                        QualType RetTy,
7535d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                        ObjCMethodSummariesTy &CachedSummaries);
7545d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7555d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
7565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                                ProgramStateRef State);
7575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
7595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    assert(!M.isInstanceMessage());
7605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    const ObjCInterfaceDecl *Class = M.getReceiverInterface();
7615d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7625d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    return getMethodSummary(M.getSelector(), Class, M.getDecl(),
7635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                            M.getResultType(), ObjCClassMethodSummaries);
7645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
7655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  /// getMethodSummary - This version of getMethodSummary is used to query
7675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ///  the summary for the current method being analyzed.
7685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
7695d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    const ObjCInterfaceDecl *ID = MD->getClassInterface();
7705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Selector S = MD->getSelector();
7715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    QualType ResultTy = MD->getResultType();
7725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ObjCMethodSummariesTy *CachedSummaries;
7745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (MD->isInstanceMethod())
7755d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      CachedSummaries = &ObjCMethodSummaries;
7765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    else
7775d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      CachedSummaries = &ObjCClassMethodSummaries;
7785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7795d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
7805d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
7815d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7825d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
7835d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                                Selector S, QualType RetTy);
7845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
7855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
7865d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                    const ObjCMethodDecl *MD);
787c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
788c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
789c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)                                    const FunctionDecl *FD);
790c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
791c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  void updateSummaryForCall(const RetainSummary *&Summ,
792c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)                            const CallEvent &Call);
793c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
794c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  bool isGCEnabled() const { return GCEnabled; }
795c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
796c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  bool isARCEnabled() const { return ARCEnabled; }
797c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
798c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
7995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
8015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
8025d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  friend class RetainSummaryTemplate;
8035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)};
8045d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
8055d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
8065d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// summaries. If a function or method looks like it has a default summary, but
807a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// it has annotations, the annotations are added to the stack-based template
8085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// and then copied into managed memory.
8095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)class RetainSummaryTemplate {
8105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetainSummaryManager &Manager;
8115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const RetainSummary *&RealSummary;
8125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  RetainSummary ScratchSummary;
8135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  bool Accessed;
8145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)public:
8155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
8165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
8172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ~RetainSummaryTemplate() {
8195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (Accessed)
8202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      RealSummary = Manager.getPersistentSummary(ScratchSummary);
821a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
8225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RetainSummary &operator*() {
8242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Accessed = true;
8255d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    return ScratchSummary;
8265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
8275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  RetainSummary *operator->() {
8295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Accessed = true;
8305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return &ScratchSummary;
8315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
8325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)};
8335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} // end anonymous namespace
8352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
8372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Implementation of checker data structures.
8385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
8395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ArgEffects RetainSummaryManager::getArgEffects() {
8415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ArgEffects AE = ScratchArgs;
8425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ScratchArgs = AF.getEmptyMap();
8435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return AE;
8445d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
8455d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
8465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)const RetainSummary *
8475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
8485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Unique "simple" summaries -- those without ArgEffects.
8495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (OldSumm.isSimple()) {
8505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    llvm::FoldingSetNodeID ID;
8515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    OldSumm.Profile(ID);
8525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    void *Pos;
8545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
8555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (!N) {
8575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
8585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      new (N) CachedSummaryNode(OldSumm);
8595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      SimpleSummaries.InsertNode(N, Pos);
8605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
8615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
8625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return &N->getValue();
8635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
8645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
865868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
866868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  new (Summ) RetainSummary(OldSumm);
867868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  return Summ;
868868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
869a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
870868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)//===----------------------------------------------------------------------===//
871868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)// Summary creation for functions (largely uses of Core Foundation).
872a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
873868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
8745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static bool isRetain(const FunctionDecl *FD, StringRef FName) {
8755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return FName.endswith("Retain");
876868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)}
877868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
878868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)static bool isRelease(const FunctionDecl *FD, StringRef FName) {
879868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  return FName.endswith("Release");
880a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
881868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
882868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
883a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // FIXME: Remove FunctionDecl parameter.
884868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)  // FIXME: Is it really okay if MakeCollectable isn't a suffix?
8855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return FName.find("MakeCollectable") != StringRef::npos;
8865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
8872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
8882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
8892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (E) {
8902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case DoNothing:
8915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Autorelease:
8922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case DecRefBridgedTransfered:
8932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case IncRef:
8945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case IncRefMsg:
8955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case MakeCollectable:
8965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case MayEscape:
8972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case StopTracking:
8982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case StopTrackingHard:
8992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return StopTrackingHard;
900a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  case DecRef:
9012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case DecRefAndStopTrackingHard:
902868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)    return DecRefAndStopTrackingHard;
9035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  case DecRefMsg:
9042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case DecRefMsgAndStopTrackingHard:
9055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return DecRefMsgAndStopTrackingHard;
9062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Dealloc:
907a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return Dealloc;
9082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
909868fa2fe829687343ffae624259930155e16dbd8Torne (Richard Coles)
9105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  llvm_unreachable("Unknown ArgEffect kind");
9115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
9125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
9135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
9145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                const CallEvent &Call) {
9155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Call.hasNonZeroCallbackArg()) {
9165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ArgEffect RecEffect =
9175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      getStopTrackingHardEquivalent(S->getReceiverEffect());
9185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ArgEffect DefEffect =
919f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      getStopTrackingHardEquivalent(S->getDefaultArgEffect());
920f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
921f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    ArgEffects CustomArgEffects = S->getArgEffects();
9222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    for (ArgEffects::iterator I = CustomArgEffects.begin(),
9232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                              E = CustomArgEffects.end();
9242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         I != E; ++I) {
9252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
9262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (Translated != DefEffect)
9272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
9285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
9295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
9305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    RetEffect RE = RetEffect::MakeNoRetHard();
9315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
9325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Special cases where the callback argument CANNOT free the return value.
9332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // This can generally only happen if we know that the callback will only be
9342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // called when the return value is already being deallocated.
9352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
9362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
9372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        // When the CGBitmapContext is deallocated, the callback here will free
9382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        // the associated data buffer.
9392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (Name->isStr("CGBitmapContextCreateWithData"))
9402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          RE = S->getRetEffect();
9412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
9422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
9432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
9442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    S = getPersistentSummary(RE, RecEffect, DefEffect);
9452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
9465d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
9475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Special case '[super init];' and '[self init];'
948c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  //
949c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  // Even though calling '[super init]' without assigning the result to self
950c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  // and checking if the parent returns 'nil' is a bad pattern, it is common.
951c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  // Additionally, our Self Init checker already warns about it. To avoid
952c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  // overwhelming the user with messages from both checkers, we model the case
9532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // of '[super init]' in cases when it is not consumed by another expression
9542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // as if the call preserves the value of 'self'; essentially, assuming it can
955c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  // never fail and return 'nil'.
9562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Note, we don't want to just stop tracking the value since we want the
9572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // RetainCount checker to report leaks and use-after-free if SelfInit checker
9582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // is turned off.
9592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
9602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
9612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
9622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Check if the message is not consumed, we know it will not be used in
9632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // an assignment, ex: "self = [super init]".
9643551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)      const Expr *ME = MC->getOriginExpr();
9652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      const LocationContext *LCtx = MC->getLocationContext();
9662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
96758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)      if (!PM.isConsumedExpr(ME)) {
96858537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)        RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
9692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
9702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
9713551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)      }
9722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
9732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
9742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
97558537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)}
97658537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)
97758537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)const RetainSummary *
9782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)RetainSummaryManager::getSummary(const CallEvent &Call,
9792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                 ProgramStateRef State) {
9802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const RetainSummary *Summ;
9815d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  switch (Call.getKind()) {
9825d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  case CE_Function:
9835d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
9842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
9852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_CXXMember:
9862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_CXXMemberOperator:
9872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_Block:
9882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_CXXConstructor:
9892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_CXXDestructor:
9902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CE_CXXAllocator:
99158537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    // FIXME: These calls are currently unsupported.
9922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return getPersistentStopSummary();
99358537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)  case CE_ObjCMessage: {
99458537e28ecd584eab876aee8be7156509866d23aTorne (Richard Coles)    const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
9952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Msg.isInstanceMessage())
9962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Summ = getInstanceMethodSummary(Msg, State);
9972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    else
9984e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)      Summ = getClassMethodSummary(Msg);
9994e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    break;
10004e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  }
10014e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  }
10024e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
10034e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  updateSummaryForCall(Summ, Call);
10044e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
10054e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  assert(Summ && "Unknown call type?");
10064e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  return Summ;
10075d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
10084e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
10094e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)const RetainSummary *
10104e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
10114e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // If we don't know what function we're calling, use our default summary.
10124e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  if (!FD)
10134e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    return getDefaultSummary();
10144e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
10154e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // Look up a summary in our cache of FunctionDecls -> Summaries.
10165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
10175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (I != FuncSummaries.end())
10185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return I->second;
1019
1020  // No summary?  Generate one.
1021  const RetainSummary *S = 0;
1022  bool AllowAnnotations = true;
1023
1024  do {
1025    // We generate "stop" summaries for implicitly defined functions.
1026    if (FD->isImplicit()) {
1027      S = getPersistentStopSummary();
1028      break;
1029    }
1030
1031    // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1032    // function's type.
1033    const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1034    const IdentifierInfo *II = FD->getIdentifier();
1035    if (!II)
1036      break;
1037
1038    StringRef FName = II->getName();
1039
1040    // Strip away preceding '_'.  Doing this here will effect all the checks
1041    // down below.
1042    FName = FName.substr(FName.find_first_not_of('_'));
1043
1044    // Inspect the result type.
1045    QualType RetTy = FT->getResultType();
1046
1047    // FIXME: This should all be refactored into a chain of "summary lookup"
1048    //  filters.
1049    assert(ScratchArgs.isEmpty());
1050
1051    if (FName == "pthread_create" || FName == "pthread_setspecific") {
1052      // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1053      // This will be addressed better with IPA.
1054      S = getPersistentStopSummary();
1055    } else if (FName == "NSMakeCollectable") {
1056      // Handle: id NSMakeCollectable(CFTypeRef)
1057      S = (RetTy->isObjCIdType())
1058          ? getUnarySummary(FT, cfmakecollectable)
1059          : getPersistentStopSummary();
1060      // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1061      // but we can fully model NSMakeCollectable ourselves.
1062      AllowAnnotations = false;
1063    } else if (FName == "CFPlugInInstanceCreate") {
1064      S = getPersistentSummary(RetEffect::MakeNoRet());
1065    } else if (FName == "IOBSDNameMatching" ||
1066               FName == "IOServiceMatching" ||
1067               FName == "IOServiceNameMatching" ||
1068               FName == "IORegistryEntrySearchCFProperty" ||
1069               FName == "IORegistryEntryIDMatching" ||
1070               FName == "IOOpenFirmwarePathMatching") {
1071      // Part of <rdar://problem/6961230>. (IOKit)
1072      // This should be addressed using a API table.
1073      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1074                               DoNothing, DoNothing);
1075    } else if (FName == "IOServiceGetMatchingService" ||
1076               FName == "IOServiceGetMatchingServices") {
1077      // FIXES: <rdar://problem/6326900>
1078      // This should be addressed using a API table.  This strcmp is also
1079      // a little gross, but there is no need to super optimize here.
1080      ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1081      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1082    } else if (FName == "IOServiceAddNotification" ||
1083               FName == "IOServiceAddMatchingNotification") {
1084      // Part of <rdar://problem/6961230>. (IOKit)
1085      // This should be addressed using a API table.
1086      ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1087      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1088    } else if (FName == "CVPixelBufferCreateWithBytes") {
1089      // FIXES: <rdar://problem/7283567>
1090      // Eventually this can be improved by recognizing that the pixel
1091      // buffer passed to CVPixelBufferCreateWithBytes is released via
1092      // a callback and doing full IPA to make sure this is done correctly.
1093      // FIXME: This function has an out parameter that returns an
1094      // allocated object.
1095      ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1096      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1097    } else if (FName == "CGBitmapContextCreateWithData") {
1098      // FIXES: <rdar://problem/7358899>
1099      // Eventually this can be improved by recognizing that 'releaseInfo'
1100      // passed to CGBitmapContextCreateWithData is released via
1101      // a callback and doing full IPA to make sure this is done correctly.
1102      ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1103      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1104                               DoNothing, DoNothing);
1105    } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1106      // FIXES: <rdar://problem/7283567>
1107      // Eventually this can be improved by recognizing that the pixel
1108      // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1109      // via a callback and doing full IPA to make sure this is done
1110      // correctly.
1111      ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1112      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1113    } else if (FName == "dispatch_set_context") {
1114      // <rdar://problem/11059275> - The analyzer currently doesn't have
1115      // a good way to reason about the finalizer function for libdispatch.
1116      // If we pass a context object that is memory managed, stop tracking it.
1117      // FIXME: this hack should possibly go away once we can handle
1118      // libdispatch finalizers.
1119      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1120      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1121    } else if (FName.startswith("NSLog")) {
1122      S = getDoNothingSummary();
1123    } else if (FName.startswith("NS") &&
1124                (FName.find("Insert") != StringRef::npos)) {
1125      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1126      // be deallocated by NSMapRemove. (radar://11152419)
1127      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1128      ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1129      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1130    }
1131
1132    // Did we get a summary?
1133    if (S)
1134      break;
1135
1136    if (RetTy->isPointerType()) {
1137      if (FD->getAttr<CFAuditedTransferAttr>()) {
1138        S = getCFCreateGetRuleSummary(FD);
1139        break;
1140      }
1141
1142      // For CoreFoundation ('CF') types.
1143      if (cocoa::isRefType(RetTy, "CF", FName)) {
1144        if (isRetain(FD, FName))
1145          S = getUnarySummary(FT, cfretain);
1146        else if (isMakeCollectable(FD, FName))
1147          S = getUnarySummary(FT, cfmakecollectable);
1148        else
1149          S = getCFCreateGetRuleSummary(FD);
1150
1151        break;
1152      }
1153
1154      // For CoreGraphics ('CG') types.
1155      if (cocoa::isRefType(RetTy, "CG", FName)) {
1156        if (isRetain(FD, FName))
1157          S = getUnarySummary(FT, cfretain);
1158        else
1159          S = getCFCreateGetRuleSummary(FD);
1160
1161        break;
1162      }
1163
1164      // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1165      if (cocoa::isRefType(RetTy, "DADisk") ||
1166          cocoa::isRefType(RetTy, "DADissenter") ||
1167          cocoa::isRefType(RetTy, "DASessionRef")) {
1168        S = getCFCreateGetRuleSummary(FD);
1169        break;
1170      }
1171
1172      break;
1173    }
1174
1175    // Check for release functions, the only kind of functions that we care
1176    // about that don't return a pointer type.
1177    if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1178      // Test for 'CGCF'.
1179      FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1180
1181      if (isRelease(FD, FName))
1182        S = getUnarySummary(FT, cfrelease);
1183      else {
1184        assert (ScratchArgs.isEmpty());
1185        // Remaining CoreFoundation and CoreGraphics functions.
1186        // We use to assume that they all strictly followed the ownership idiom
1187        // and that ownership cannot be transferred.  While this is technically
1188        // correct, many methods allow a tracked object to escape.  For example:
1189        //
1190        //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1191        //   CFDictionaryAddValue(y, key, x);
1192        //   CFRelease(x);
1193        //   ... it is okay to use 'x' since 'y' has a reference to it
1194        //
1195        // We handle this and similar cases with the follow heuristic.  If the
1196        // function name contains "InsertValue", "SetValue", "AddValue",
1197        // "AppendValue", or "SetAttribute", then we assume that arguments may
1198        // "escape."  This means that something else holds on to the object,
1199        // allowing it be used even after its local retain count drops to 0.
1200        ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1201                       StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1202                       StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1203                       StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1204                       StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1205                      ? MayEscape : DoNothing;
1206
1207        S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1208      }
1209    }
1210  }
1211  while (0);
1212
1213  // If we got all the way here without any luck, use a default summary.
1214  if (!S)
1215    S = getDefaultSummary();
1216
1217  // Annotations override defaults.
1218  if (AllowAnnotations)
1219    updateSummaryFromAnnotations(S, FD);
1220
1221  FuncSummaries[FD] = S;
1222  return S;
1223}
1224
1225const RetainSummary *
1226RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1227  if (coreFoundation::followsCreateRule(FD))
1228    return getCFSummaryCreateRule(FD);
1229
1230  return getCFSummaryGetRule(FD);
1231}
1232
1233const RetainSummary *
1234RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1235                                      UnaryFuncKind func) {
1236
1237  // Sanity check that this is *really* a unary function.  This can
1238  // happen if people do weird things.
1239  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1240  if (!FTP || FTP->getNumArgs() != 1)
1241    return getPersistentStopSummary();
1242
1243  assert (ScratchArgs.isEmpty());
1244
1245  ArgEffect Effect;
1246  switch (func) {
1247    case cfretain: Effect = IncRef; break;
1248    case cfrelease: Effect = DecRef; break;
1249    case cfmakecollectable: Effect = MakeCollectable; break;
1250  }
1251
1252  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1253  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1254}
1255
1256const RetainSummary *
1257RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1258  assert (ScratchArgs.isEmpty());
1259
1260  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1261}
1262
1263const RetainSummary *
1264RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1265  assert (ScratchArgs.isEmpty());
1266  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1267                              DoNothing, DoNothing);
1268}
1269
1270//===----------------------------------------------------------------------===//
1271// Summary creation for Selectors.
1272//===----------------------------------------------------------------------===//
1273
1274void
1275RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1276                                                   const FunctionDecl *FD) {
1277  if (!FD)
1278    return;
1279
1280  assert(Summ && "Must have a summary to add annotations to.");
1281  RetainSummaryTemplate Template(Summ, *this);
1282
1283  // Effects on the parameters.
1284  unsigned parm_idx = 0;
1285  for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1286         pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1287    const ParmVarDecl *pd = *pi;
1288    if (pd->getAttr<NSConsumedAttr>()) {
1289      if (!GCEnabled) {
1290        Template->addArg(AF, parm_idx, DecRef);
1291      }
1292    } else if (pd->getAttr<CFConsumedAttr>()) {
1293      Template->addArg(AF, parm_idx, DecRef);
1294    }
1295  }
1296
1297  QualType RetTy = FD->getResultType();
1298
1299  // Determine if there is a special return effect for this method.
1300  if (cocoa::isCocoaObjectRef(RetTy)) {
1301    if (FD->getAttr<NSReturnsRetainedAttr>()) {
1302      Template->setRetEffect(ObjCAllocRetE);
1303    }
1304    else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1305      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1306    }
1307    else if (FD->getAttr<NSReturnsNotRetainedAttr>() ||
1308             FD->getAttr<NSReturnsAutoreleasedAttr>()) {
1309      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1310    }
1311    else if (FD->getAttr<CFReturnsNotRetainedAttr>())
1312      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1313    }
1314    else if (RetTy->getAs<PointerType>()) {
1315    if (FD->getAttr<CFReturnsRetainedAttr>()) {
1316      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1317    }
1318    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1319      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1320    }
1321  }
1322}
1323
1324void
1325RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1326                                                   const ObjCMethodDecl *MD) {
1327  if (!MD)
1328    return;
1329
1330  assert(Summ && "Must have a valid summary to add annotations to");
1331  RetainSummaryTemplate Template(Summ, *this);
1332  bool isTrackedLoc = false;
1333
1334  // Effects on the receiver.
1335  if (MD->getAttr<NSConsumesSelfAttr>()) {
1336    if (!GCEnabled)
1337      Template->setReceiverEffect(DecRefMsg);
1338  }
1339
1340  // Effects on the parameters.
1341  unsigned parm_idx = 0;
1342  for (ObjCMethodDecl::param_const_iterator
1343         pi=MD->param_begin(), pe=MD->param_end();
1344       pi != pe; ++pi, ++parm_idx) {
1345    const ParmVarDecl *pd = *pi;
1346    if (pd->getAttr<NSConsumedAttr>()) {
1347      if (!GCEnabled)
1348        Template->addArg(AF, parm_idx, DecRef);
1349    }
1350    else if(pd->getAttr<CFConsumedAttr>()) {
1351      Template->addArg(AF, parm_idx, DecRef);
1352    }
1353  }
1354
1355  // Determine if there is a special return effect for this method.
1356  if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1357    if (MD->getAttr<NSReturnsRetainedAttr>()) {
1358      Template->setRetEffect(ObjCAllocRetE);
1359      return;
1360    }
1361    if (MD->getAttr<NSReturnsNotRetainedAttr>() ||
1362        MD->getAttr<NSReturnsAutoreleasedAttr>()) {
1363      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1364      return;
1365    }
1366
1367    isTrackedLoc = true;
1368  } else {
1369    isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1370  }
1371
1372  if (isTrackedLoc) {
1373    if (MD->getAttr<CFReturnsRetainedAttr>())
1374      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1375    else if (MD->getAttr<CFReturnsNotRetainedAttr>())
1376      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1377  }
1378}
1379
1380const RetainSummary *
1381RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1382                                               Selector S, QualType RetTy) {
1383  // Any special effects?
1384  ArgEffect ReceiverEff = DoNothing;
1385  RetEffect ResultEff = RetEffect::MakeNoRet();
1386
1387  // Check the method family, and apply any default annotations.
1388  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1389    case OMF_None:
1390    case OMF_performSelector:
1391      // Assume all Objective-C methods follow Cocoa Memory Management rules.
1392      // FIXME: Does the non-threaded performSelector family really belong here?
1393      // The selector could be, say, @selector(copy).
1394      if (cocoa::isCocoaObjectRef(RetTy))
1395        ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1396      else if (coreFoundation::isCFObjectRef(RetTy)) {
1397        // ObjCMethodDecl currently doesn't consider CF objects as valid return
1398        // values for alloc, new, copy, or mutableCopy, so we have to
1399        // double-check with the selector. This is ugly, but there aren't that
1400        // many Objective-C methods that return CF objects, right?
1401        if (MD) {
1402          switch (S.getMethodFamily()) {
1403          case OMF_alloc:
1404          case OMF_new:
1405          case OMF_copy:
1406          case OMF_mutableCopy:
1407            ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1408            break;
1409          default:
1410            ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1411            break;
1412          }
1413        } else {
1414          ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1415        }
1416      }
1417      break;
1418    case OMF_init:
1419      ResultEff = ObjCInitRetE;
1420      ReceiverEff = DecRefMsg;
1421      break;
1422    case OMF_alloc:
1423    case OMF_new:
1424    case OMF_copy:
1425    case OMF_mutableCopy:
1426      if (cocoa::isCocoaObjectRef(RetTy))
1427        ResultEff = ObjCAllocRetE;
1428      else if (coreFoundation::isCFObjectRef(RetTy))
1429        ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1430      break;
1431    case OMF_autorelease:
1432      ReceiverEff = Autorelease;
1433      break;
1434    case OMF_retain:
1435      ReceiverEff = IncRefMsg;
1436      break;
1437    case OMF_release:
1438      ReceiverEff = DecRefMsg;
1439      break;
1440    case OMF_dealloc:
1441      ReceiverEff = Dealloc;
1442      break;
1443    case OMF_self:
1444      // -self is handled specially by the ExprEngine to propagate the receiver.
1445      break;
1446    case OMF_retainCount:
1447    case OMF_finalize:
1448      // These methods don't return objects.
1449      break;
1450  }
1451
1452  // If one of the arguments in the selector has the keyword 'delegate' we
1453  // should stop tracking the reference count for the receiver.  This is
1454  // because the reference count is quite possibly handled by a delegate
1455  // method.
1456  if (S.isKeywordSelector()) {
1457    for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1458      StringRef Slot = S.getNameForSlot(i);
1459      if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1460        if (ResultEff == ObjCInitRetE)
1461          ResultEff = RetEffect::MakeNoRetHard();
1462        else
1463          ReceiverEff = StopTrackingHard;
1464      }
1465    }
1466  }
1467
1468  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1469      ResultEff.getKind() == RetEffect::NoRet)
1470    return getDefaultSummary();
1471
1472  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1473}
1474
1475const RetainSummary *
1476RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1477                                               ProgramStateRef State) {
1478  const ObjCInterfaceDecl *ReceiverClass = 0;
1479
1480  // We do better tracking of the type of the object than the core ExprEngine.
1481  // See if we have its type in our private state.
1482  // FIXME: Eventually replace the use of state->get<RefBindings> with
1483  // a generic API for reasoning about the Objective-C types of symbolic
1484  // objects.
1485  SVal ReceiverV = Msg.getReceiverSVal();
1486  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1487    if (const RefVal *T = getRefBinding(State, Sym))
1488      if (const ObjCObjectPointerType *PT =
1489            T->getType()->getAs<ObjCObjectPointerType>())
1490        ReceiverClass = PT->getInterfaceDecl();
1491
1492  // If we don't know what kind of object this is, fall back to its static type.
1493  if (!ReceiverClass)
1494    ReceiverClass = Msg.getReceiverInterface();
1495
1496  // FIXME: The receiver could be a reference to a class, meaning that
1497  //  we should use the class method.
1498  // id x = [NSObject class];
1499  // [x performSelector:... withObject:... afterDelay:...];
1500  Selector S = Msg.getSelector();
1501  const ObjCMethodDecl *Method = Msg.getDecl();
1502  if (!Method && ReceiverClass)
1503    Method = ReceiverClass->getInstanceMethod(S);
1504
1505  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1506                          ObjCMethodSummaries);
1507}
1508
1509const RetainSummary *
1510RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1511                                       const ObjCMethodDecl *MD, QualType RetTy,
1512                                       ObjCMethodSummariesTy &CachedSummaries) {
1513
1514  // Look up a summary in our summary cache.
1515  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1516
1517  if (!Summ) {
1518    Summ = getStandardMethodSummary(MD, S, RetTy);
1519
1520    // Annotations override defaults.
1521    updateSummaryFromAnnotations(Summ, MD);
1522
1523    // Memoize the summary.
1524    CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1525  }
1526
1527  return Summ;
1528}
1529
1530void RetainSummaryManager::InitializeClassMethodSummaries() {
1531  assert(ScratchArgs.isEmpty());
1532  // Create the [NSAssertionHandler currentHander] summary.
1533  addClassMethSummary("NSAssertionHandler", "currentHandler",
1534                getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1535
1536  // Create the [NSAutoreleasePool addObject:] summary.
1537  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1538  addClassMethSummary("NSAutoreleasePool", "addObject",
1539                      getPersistentSummary(RetEffect::MakeNoRet(),
1540                                           DoNothing, Autorelease));
1541}
1542
1543void RetainSummaryManager::InitializeMethodSummaries() {
1544
1545  assert (ScratchArgs.isEmpty());
1546
1547  // Create the "init" selector.  It just acts as a pass-through for the
1548  // receiver.
1549  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1550  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1551
1552  // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1553  // claims the receiver and returns a retained object.
1554  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1555                         InitSumm);
1556
1557  // The next methods are allocators.
1558  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1559  const RetainSummary *CFAllocSumm =
1560    getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1561
1562  // Create the "retain" selector.
1563  RetEffect NoRet = RetEffect::MakeNoRet();
1564  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1565  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1566
1567  // Create the "release" selector.
1568  Summ = getPersistentSummary(NoRet, DecRefMsg);
1569  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1570
1571  // Create the -dealloc summary.
1572  Summ = getPersistentSummary(NoRet, Dealloc);
1573  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1574
1575  // Create the "autorelease" selector.
1576  Summ = getPersistentSummary(NoRet, Autorelease);
1577  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1578
1579  // For NSWindow, allocated objects are (initially) self-owned.
1580  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1581  //  self-own themselves.  However, they only do this once they are displayed.
1582  //  Thus, we need to track an NSWindow's display status.
1583  //  This is tracked in <rdar://problem/6062711>.
1584  //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1585  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1586                                                   StopTracking,
1587                                                   StopTracking);
1588
1589  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1590
1591  // For NSPanel (which subclasses NSWindow), allocated objects are not
1592  //  self-owned.
1593  // FIXME: For now we don't track NSPanels. object for the same reason
1594  //   as for NSWindow objects.
1595  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1596
1597  // Don't track allocated autorelease pools, as it is okay to prematurely
1598  // exit a method.
1599  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1600  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1601  addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1602
1603  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1604  addInstMethSummary("QCRenderer", AllocSumm,
1605                     "createSnapshotImageOfType", NULL);
1606  addInstMethSummary("QCView", AllocSumm,
1607                     "createSnapshotImageOfType", NULL);
1608
1609  // Create summaries for CIContext, 'createCGImage' and
1610  // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1611  // automatically garbage collected.
1612  addInstMethSummary("CIContext", CFAllocSumm,
1613                     "createCGImage", "fromRect", NULL);
1614  addInstMethSummary("CIContext", CFAllocSumm,
1615                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
1616  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1617           "info", NULL);
1618}
1619
1620//===----------------------------------------------------------------------===//
1621// Error reporting.
1622//===----------------------------------------------------------------------===//
1623namespace {
1624  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1625    SummaryLogTy;
1626
1627  //===-------------===//
1628  // Bug Descriptions. //
1629  //===-------------===//
1630
1631  class CFRefBug : public BugType {
1632  protected:
1633    CFRefBug(StringRef name)
1634    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
1635  public:
1636
1637    // FIXME: Eventually remove.
1638    virtual const char *getDescription() const = 0;
1639
1640    virtual bool isLeak() const { return false; }
1641  };
1642
1643  class UseAfterRelease : public CFRefBug {
1644  public:
1645    UseAfterRelease() : CFRefBug("Use-after-release") {}
1646
1647    const char *getDescription() const {
1648      return "Reference-counted object is used after it is released";
1649    }
1650  };
1651
1652  class BadRelease : public CFRefBug {
1653  public:
1654    BadRelease() : CFRefBug("Bad release") {}
1655
1656    const char *getDescription() const {
1657      return "Incorrect decrement of the reference count of an object that is "
1658             "not owned at this point by the caller";
1659    }
1660  };
1661
1662  class DeallocGC : public CFRefBug {
1663  public:
1664    DeallocGC()
1665    : CFRefBug("-dealloc called while using garbage collection") {}
1666
1667    const char *getDescription() const {
1668      return "-dealloc called while using garbage collection";
1669    }
1670  };
1671
1672  class DeallocNotOwned : public CFRefBug {
1673  public:
1674    DeallocNotOwned()
1675    : CFRefBug("-dealloc sent to non-exclusively owned object") {}
1676
1677    const char *getDescription() const {
1678      return "-dealloc sent to object that may be referenced elsewhere";
1679    }
1680  };
1681
1682  class OverAutorelease : public CFRefBug {
1683  public:
1684    OverAutorelease()
1685    : CFRefBug("Object sent -autorelease too many times") {}
1686
1687    const char *getDescription() const {
1688      return "Object sent -autorelease too many times";
1689    }
1690  };
1691
1692  class ReturnedNotOwnedForOwned : public CFRefBug {
1693  public:
1694    ReturnedNotOwnedForOwned()
1695    : CFRefBug("Method should return an owned object") {}
1696
1697    const char *getDescription() const {
1698      return "Object with a +0 retain count returned to caller where a +1 "
1699             "(owning) retain count is expected";
1700    }
1701  };
1702
1703  class Leak : public CFRefBug {
1704  public:
1705    Leak(StringRef name)
1706    : CFRefBug(name) {
1707      // Leaks should not be reported if they are post-dominated by a sink.
1708      setSuppressOnSink(true);
1709    }
1710
1711    const char *getDescription() const { return ""; }
1712
1713    bool isLeak() const { return true; }
1714  };
1715
1716  //===---------===//
1717  // Bug Reports.  //
1718  //===---------===//
1719
1720  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1721  protected:
1722    SymbolRef Sym;
1723    const SummaryLogTy &SummaryLog;
1724    bool GCEnabled;
1725
1726  public:
1727    CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1728       : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1729
1730    virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1731      static int x = 0;
1732      ID.AddPointer(&x);
1733      ID.AddPointer(Sym);
1734    }
1735
1736    virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1737                                           const ExplodedNode *PrevN,
1738                                           BugReporterContext &BRC,
1739                                           BugReport &BR);
1740
1741    virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1742                                            const ExplodedNode *N,
1743                                            BugReport &BR);
1744  };
1745
1746  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1747  public:
1748    CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1749                           const SummaryLogTy &log)
1750       : CFRefReportVisitor(sym, GCEnabled, log) {}
1751
1752    PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1753                                    const ExplodedNode *N,
1754                                    BugReport &BR);
1755
1756    virtual BugReporterVisitor *clone() const {
1757      // The curiously-recurring template pattern only works for one level of
1758      // subclassing. Rather than make a new template base for
1759      // CFRefReportVisitor, we simply override clone() to do the right thing.
1760      // This could be trouble someday if BugReporterVisitorImpl is ever
1761      // used for something else besides a convenient implementation of clone().
1762      return new CFRefLeakReportVisitor(*this);
1763    }
1764  };
1765
1766  class CFRefReport : public BugReport {
1767    void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1768
1769  public:
1770    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1771                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1772                bool registerVisitor = true)
1773      : BugReport(D, D.getDescription(), n) {
1774      if (registerVisitor)
1775        addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1776      addGCModeDescription(LOpts, GCEnabled);
1777    }
1778
1779    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1780                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1781                StringRef endText)
1782      : BugReport(D, D.getDescription(), endText, n) {
1783      addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1784      addGCModeDescription(LOpts, GCEnabled);
1785    }
1786
1787    virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
1788      const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1789      if (!BugTy.isLeak())
1790        return BugReport::getRanges();
1791      else
1792        return std::make_pair(ranges_iterator(), ranges_iterator());
1793    }
1794  };
1795
1796  class CFRefLeakReport : public CFRefReport {
1797    const MemRegion* AllocBinding;
1798
1799  public:
1800    CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1801                    const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1802                    CheckerContext &Ctx);
1803
1804    PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1805      assert(Location.isValid());
1806      return Location;
1807    }
1808  };
1809} // end anonymous namespace
1810
1811void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1812                                       bool GCEnabled) {
1813  const char *GCModeDescription = 0;
1814
1815  switch (LOpts.getGC()) {
1816  case LangOptions::GCOnly:
1817    assert(GCEnabled);
1818    GCModeDescription = "Code is compiled to only use garbage collection";
1819    break;
1820
1821  case LangOptions::NonGC:
1822    assert(!GCEnabled);
1823    GCModeDescription = "Code is compiled to use reference counts";
1824    break;
1825
1826  case LangOptions::HybridGC:
1827    if (GCEnabled) {
1828      GCModeDescription = "Code is compiled to use either garbage collection "
1829                          "(GC) or reference counts (non-GC).  The bug occurs "
1830                          "with GC enabled";
1831      break;
1832    } else {
1833      GCModeDescription = "Code is compiled to use either garbage collection "
1834                          "(GC) or reference counts (non-GC).  The bug occurs "
1835                          "in non-GC mode";
1836      break;
1837    }
1838  }
1839
1840  assert(GCModeDescription && "invalid/unknown GC mode");
1841  addExtraText(GCModeDescription);
1842}
1843
1844// FIXME: This should be a method on SmallVector.
1845static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
1846                            ArgEffect X) {
1847  for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1848       I!=E; ++I)
1849    if (*I == X) return true;
1850
1851  return false;
1852}
1853
1854static bool isNumericLiteralExpression(const Expr *E) {
1855  // FIXME: This set of cases was copied from SemaExprObjC.
1856  return isa<IntegerLiteral>(E) ||
1857         isa<CharacterLiteral>(E) ||
1858         isa<FloatingLiteral>(E) ||
1859         isa<ObjCBoolLiteralExpr>(E) ||
1860         isa<CXXBoolLiteralExpr>(E);
1861}
1862
1863PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1864                                                   const ExplodedNode *PrevN,
1865                                                   BugReporterContext &BRC,
1866                                                   BugReport &BR) {
1867  // FIXME: We will eventually need to handle non-statement-based events
1868  // (__attribute__((cleanup))).
1869  if (!isa<StmtPoint>(N->getLocation()))
1870    return NULL;
1871
1872  // Check if the type state has changed.
1873  ProgramStateRef PrevSt = PrevN->getState();
1874  ProgramStateRef CurrSt = N->getState();
1875  const LocationContext *LCtx = N->getLocationContext();
1876
1877  const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1878  if (!CurrT) return NULL;
1879
1880  const RefVal &CurrV = *CurrT;
1881  const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1882
1883  // Create a string buffer to constain all the useful things we want
1884  // to tell the user.
1885  std::string sbuf;
1886  llvm::raw_string_ostream os(sbuf);
1887
1888  // This is the allocation site since the previous node had no bindings
1889  // for this symbol.
1890  if (!PrevT) {
1891    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1892
1893    if (isa<ObjCArrayLiteral>(S)) {
1894      os << "NSArray literal is an object with a +0 retain count";
1895    }
1896    else if (isa<ObjCDictionaryLiteral>(S)) {
1897      os << "NSDictionary literal is an object with a +0 retain count";
1898    }
1899    else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1900      if (isNumericLiteralExpression(BL->getSubExpr()))
1901        os << "NSNumber literal is an object with a +0 retain count";
1902      else {
1903        const ObjCInterfaceDecl *BoxClass = 0;
1904        if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1905          BoxClass = Method->getClassInterface();
1906
1907        // We should always be able to find the boxing class interface,
1908        // but consider this future-proofing.
1909        if (BoxClass)
1910          os << *BoxClass << " b";
1911        else
1912          os << "B";
1913
1914        os << "oxed expression produces an object with a +0 retain count";
1915      }
1916    }
1917    else {
1918      if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1919        // Get the name of the callee (if it is available).
1920        SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1921        if (const FunctionDecl *FD = X.getAsFunctionDecl())
1922          os << "Call to function '" << *FD << '\'';
1923        else
1924          os << "function call";
1925      }
1926      else {
1927        assert(isa<ObjCMessageExpr>(S));
1928        CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1929        CallEventRef<ObjCMethodCall> Call
1930          = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1931
1932        switch (Call->getMessageKind()) {
1933        case OCM_Message:
1934          os << "Method";
1935          break;
1936        case OCM_PropertyAccess:
1937          os << "Property";
1938          break;
1939        case OCM_Subscript:
1940          os << "Subscript";
1941          break;
1942        }
1943      }
1944
1945      if (CurrV.getObjKind() == RetEffect::CF) {
1946        os << " returns a Core Foundation object with a ";
1947      }
1948      else {
1949        assert (CurrV.getObjKind() == RetEffect::ObjC);
1950        os << " returns an Objective-C object with a ";
1951      }
1952
1953      if (CurrV.isOwned()) {
1954        os << "+1 retain count";
1955
1956        if (GCEnabled) {
1957          assert(CurrV.getObjKind() == RetEffect::CF);
1958          os << ".  "
1959          "Core Foundation objects are not automatically garbage collected.";
1960        }
1961      }
1962      else {
1963        assert (CurrV.isNotOwned());
1964        os << "+0 retain count";
1965      }
1966    }
1967
1968    PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1969                                  N->getLocationContext());
1970    return new PathDiagnosticEventPiece(Pos, os.str());
1971  }
1972
1973  // Gather up the effects that were performed on the object at this
1974  // program point
1975  SmallVector<ArgEffect, 2> AEffects;
1976
1977  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1978  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
1979    // We only have summaries attached to nodes after evaluating CallExpr and
1980    // ObjCMessageExprs.
1981    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1982
1983    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1984      // Iterate through the parameter expressions and see if the symbol
1985      // was ever passed as an argument.
1986      unsigned i = 0;
1987
1988      for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
1989           AI!=AE; ++AI, ++i) {
1990
1991        // Retrieve the value of the argument.  Is it the symbol
1992        // we are interested in?
1993        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
1994          continue;
1995
1996        // We have an argument.  Get the effect!
1997        AEffects.push_back(Summ->getArg(i));
1998      }
1999    }
2000    else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2001      if (const Expr *receiver = ME->getInstanceReceiver())
2002        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2003              .getAsLocSymbol() == Sym) {
2004          // The symbol we are tracking is the receiver.
2005          AEffects.push_back(Summ->getReceiverEffect());
2006        }
2007    }
2008  }
2009
2010  do {
2011    // Get the previous type state.
2012    RefVal PrevV = *PrevT;
2013
2014    // Specially handle -dealloc.
2015    if (!GCEnabled && contains(AEffects, Dealloc)) {
2016      // Determine if the object's reference count was pushed to zero.
2017      assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2018      // We may not have transitioned to 'release' if we hit an error.
2019      // This case is handled elsewhere.
2020      if (CurrV.getKind() == RefVal::Released) {
2021        assert(CurrV.getCombinedCounts() == 0);
2022        os << "Object released by directly sending the '-dealloc' message";
2023        break;
2024      }
2025    }
2026
2027    // Specially handle CFMakeCollectable and friends.
2028    if (contains(AEffects, MakeCollectable)) {
2029      // Get the name of the function.
2030      const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2031      SVal X =
2032        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2033      const FunctionDecl *FD = X.getAsFunctionDecl();
2034
2035      if (GCEnabled) {
2036        // Determine if the object's reference count was pushed to zero.
2037        assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2038
2039        os << "In GC mode a call to '" << *FD
2040        <<  "' decrements an object's retain count and registers the "
2041        "object with the garbage collector. ";
2042
2043        if (CurrV.getKind() == RefVal::Released) {
2044          assert(CurrV.getCount() == 0);
2045          os << "Since it now has a 0 retain count the object can be "
2046          "automatically collected by the garbage collector.";
2047        }
2048        else
2049          os << "An object must have a 0 retain count to be garbage collected. "
2050          "After this call its retain count is +" << CurrV.getCount()
2051          << '.';
2052      }
2053      else
2054        os << "When GC is not enabled a call to '" << *FD
2055        << "' has no effect on its argument.";
2056
2057      // Nothing more to say.
2058      break;
2059    }
2060
2061    // Determine if the typestate has changed.
2062    if (!(PrevV == CurrV))
2063      switch (CurrV.getKind()) {
2064        case RefVal::Owned:
2065        case RefVal::NotOwned:
2066
2067          if (PrevV.getCount() == CurrV.getCount()) {
2068            // Did an autorelease message get sent?
2069            if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2070              return 0;
2071
2072            assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2073            os << "Object sent -autorelease message";
2074            break;
2075          }
2076
2077          if (PrevV.getCount() > CurrV.getCount())
2078            os << "Reference count decremented.";
2079          else
2080            os << "Reference count incremented.";
2081
2082          if (unsigned Count = CurrV.getCount())
2083            os << " The object now has a +" << Count << " retain count.";
2084
2085          if (PrevV.getKind() == RefVal::Released) {
2086            assert(GCEnabled && CurrV.getCount() > 0);
2087            os << " The object is not eligible for garbage collection until "
2088                  "the retain count reaches 0 again.";
2089          }
2090
2091          break;
2092
2093        case RefVal::Released:
2094          os << "Object released.";
2095          break;
2096
2097        case RefVal::ReturnedOwned:
2098          // Autoreleases can be applied after marking a node ReturnedOwned.
2099          if (CurrV.getAutoreleaseCount())
2100            return NULL;
2101
2102          os << "Object returned to caller as an owning reference (single "
2103                "retain count transferred to caller)";
2104          break;
2105
2106        case RefVal::ReturnedNotOwned:
2107          os << "Object returned to caller with a +0 retain count";
2108          break;
2109
2110        default:
2111          return NULL;
2112      }
2113
2114    // Emit any remaining diagnostics for the argument effects (if any).
2115    for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2116         E=AEffects.end(); I != E; ++I) {
2117
2118      // A bunch of things have alternate behavior under GC.
2119      if (GCEnabled)
2120        switch (*I) {
2121          default: break;
2122          case Autorelease:
2123            os << "In GC mode an 'autorelease' has no effect.";
2124            continue;
2125          case IncRefMsg:
2126            os << "In GC mode the 'retain' message has no effect.";
2127            continue;
2128          case DecRefMsg:
2129            os << "In GC mode the 'release' message has no effect.";
2130            continue;
2131        }
2132    }
2133  } while (0);
2134
2135  if (os.str().empty())
2136    return 0; // We have nothing to say!
2137
2138  const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2139  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2140                                N->getLocationContext());
2141  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2142
2143  // Add the range by scanning the children of the statement for any bindings
2144  // to Sym.
2145  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2146       I!=E; ++I)
2147    if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2148      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2149        P->addRange(Exp->getSourceRange());
2150        break;
2151      }
2152
2153  return P;
2154}
2155
2156// Find the first node in the current function context that referred to the
2157// tracked symbol and the memory location that value was stored to. Note, the
2158// value is only reported if the allocation occurred in the same function as
2159// the leak.
2160static std::pair<const ExplodedNode*,const MemRegion*>
2161GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2162                  SymbolRef Sym) {
2163  const ExplodedNode *Last = N;
2164  const MemRegion* FirstBinding = 0;
2165  const LocationContext *LeakContext = N->getLocationContext();
2166
2167  while (N) {
2168    ProgramStateRef St = N->getState();
2169
2170    if (!getRefBinding(St, Sym))
2171      break;
2172
2173    StoreManager::FindUniqueBinding FB(Sym);
2174    StateMgr.iterBindings(St, FB);
2175    if (FB) FirstBinding = FB.getRegion();
2176
2177    // Allocation node, is the last node in the current context in which the
2178    // symbol was tracked.
2179    if (N->getLocationContext() == LeakContext)
2180      Last = N;
2181
2182    N = N->pred_empty() ? NULL : *(N->pred_begin());
2183  }
2184
2185  // If allocation happened in a function different from the leak node context,
2186  // do not report the binding.
2187  assert(N && "Could not find allocation node");
2188  if (N->getLocationContext() != LeakContext) {
2189    FirstBinding = 0;
2190  }
2191
2192  return std::make_pair(Last, FirstBinding);
2193}
2194
2195PathDiagnosticPiece*
2196CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2197                               const ExplodedNode *EndN,
2198                               BugReport &BR) {
2199  BR.markInteresting(Sym);
2200  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2201}
2202
2203PathDiagnosticPiece*
2204CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2205                                   const ExplodedNode *EndN,
2206                                   BugReport &BR) {
2207
2208  // Tell the BugReporterContext to report cases when the tracked symbol is
2209  // assigned to different variables, etc.
2210  BR.markInteresting(Sym);
2211
2212  // We are reporting a leak.  Walk up the graph to get to the first node where
2213  // the symbol appeared, and also get the first VarDecl that tracked object
2214  // is stored to.
2215  const ExplodedNode *AllocNode = 0;
2216  const MemRegion* FirstBinding = 0;
2217
2218  llvm::tie(AllocNode, FirstBinding) =
2219    GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2220
2221  SourceManager& SM = BRC.getSourceManager();
2222
2223  // Compute an actual location for the leak.  Sometimes a leak doesn't
2224  // occur at an actual statement (e.g., transition between blocks; end
2225  // of function) so we need to walk the graph and compute a real location.
2226  const ExplodedNode *LeakN = EndN;
2227  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2228
2229  std::string sbuf;
2230  llvm::raw_string_ostream os(sbuf);
2231
2232  os << "Object leaked: ";
2233
2234  if (FirstBinding) {
2235    os << "object allocated and stored into '"
2236       << FirstBinding->getString() << '\'';
2237  }
2238  else
2239    os << "allocated object";
2240
2241  // Get the retain count.
2242  const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2243  assert(RV);
2244
2245  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2246    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2247    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2248    // to the caller for NS objects.
2249    const Decl *D = &EndN->getCodeDecl();
2250
2251    os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2252                                  : " is returned from a function ");
2253
2254    if (D->getAttr<CFReturnsNotRetainedAttr>())
2255      os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2256    else if (D->getAttr<NSReturnsNotRetainedAttr>())
2257      os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2258    else {
2259      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2260        os << "whose name ('" << MD->getSelector().getAsString()
2261           << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2262              "  This violates the naming convention rules"
2263              " given in the Memory Management Guide for Cocoa";
2264      }
2265      else {
2266        const FunctionDecl *FD = cast<FunctionDecl>(D);
2267        os << "whose name ('" << *FD
2268           << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2269              " convention rules given in the Memory Management Guide for Core"
2270              " Foundation";
2271      }
2272    }
2273  }
2274  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2275    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2276    os << " and returned from method '" << MD.getSelector().getAsString()
2277       << "' is potentially leaked when using garbage collection.  Callers "
2278          "of this method do not expect a returned object with a +1 retain "
2279          "count since they expect the object to be managed by the garbage "
2280          "collector";
2281  }
2282  else
2283    os << " is not referenced later in this execution path and has a retain "
2284          "count of +" << RV->getCount();
2285
2286  return new PathDiagnosticEventPiece(L, os.str());
2287}
2288
2289CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2290                                 bool GCEnabled, const SummaryLogTy &Log,
2291                                 ExplodedNode *n, SymbolRef sym,
2292                                 CheckerContext &Ctx)
2293: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2294
2295  // Most bug reports are cached at the location where they occurred.
2296  // With leaks, we want to unique them by the location where they were
2297  // allocated, and only report a single path.  To do this, we need to find
2298  // the allocation site of a piece of tracked memory, which we do via a
2299  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2300  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2301  // that all ancestor nodes that represent the allocation site have the
2302  // same SourceLocation.
2303  const ExplodedNode *AllocNode = 0;
2304
2305  const SourceManager& SMgr = Ctx.getSourceManager();
2306
2307  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2308    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2309
2310  // Get the SourceLocation for the allocation site.
2311  // FIXME: This will crash the analyzer if an allocation comes from an
2312  // implicit call. (Currently there are no such allocations in Cocoa, though.)
2313  const Stmt *AllocStmt;
2314  ProgramPoint P = AllocNode->getLocation();
2315  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2316    AllocStmt = Exit->getCalleeContext()->getCallSite();
2317  else
2318    AllocStmt = cast<PostStmt>(P).getStmt();
2319  assert(AllocStmt && "All allocations must come from explicit calls");
2320  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2321                                                  n->getLocationContext());
2322  // Fill in the description of the bug.
2323  Description.clear();
2324  llvm::raw_string_ostream os(Description);
2325  os << "Potential leak ";
2326  if (GCEnabled)
2327    os << "(when using garbage collection) ";
2328  os << "of an object";
2329
2330  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2331  if (AllocBinding)
2332    os << " stored into '" << AllocBinding->getString() << '\'';
2333
2334  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2335}
2336
2337//===----------------------------------------------------------------------===//
2338// Main checker logic.
2339//===----------------------------------------------------------------------===//
2340
2341namespace {
2342class RetainCountChecker
2343  : public Checker< check::Bind,
2344                    check::DeadSymbols,
2345                    check::EndAnalysis,
2346                    check::EndFunction,
2347                    check::PostStmt<BlockExpr>,
2348                    check::PostStmt<CastExpr>,
2349                    check::PostStmt<ObjCArrayLiteral>,
2350                    check::PostStmt<ObjCDictionaryLiteral>,
2351                    check::PostStmt<ObjCBoxedExpr>,
2352                    check::PostCall,
2353                    check::PreStmt<ReturnStmt>,
2354                    check::RegionChanges,
2355                    eval::Assume,
2356                    eval::Call > {
2357  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2358  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2359  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2360  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2361  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2362
2363  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2364
2365  // This map is only used to ensure proper deletion of any allocated tags.
2366  mutable SymbolTagMap DeadSymbolTags;
2367
2368  mutable OwningPtr<RetainSummaryManager> Summaries;
2369  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2370  mutable SummaryLogTy SummaryLog;
2371  mutable bool ShouldResetSummaryLog;
2372
2373public:
2374  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2375
2376  virtual ~RetainCountChecker() {
2377    DeleteContainerSeconds(DeadSymbolTags);
2378  }
2379
2380  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2381                        ExprEngine &Eng) const {
2382    // FIXME: This is a hack to make sure the summary log gets cleared between
2383    // analyses of different code bodies.
2384    //
2385    // Why is this necessary? Because a checker's lifetime is tied to a
2386    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2387    // Once in a blue moon, a new ExplodedNode will have the same address as an
2388    // old one with an associated summary, and the bug report visitor gets very
2389    // confused. (To make things worse, the summary lifetime is currently also
2390    // tied to a code body, so we get a crash instead of incorrect results.)
2391    //
2392    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2393    // changes, things will start going wrong again. Really the lifetime of this
2394    // log needs to be tied to either the specific nodes in it or the entire
2395    // ExplodedGraph, not to a specific part of the code being analyzed.
2396    //
2397    // (Also, having stateful local data means that the same checker can't be
2398    // used from multiple threads, but a lot of checkers have incorrect
2399    // assumptions about that anyway. So that wasn't a priority at the time of
2400    // this fix.)
2401    //
2402    // This happens at the end of analysis, but bug reports are emitted /after/
2403    // this point. So we can't just clear the summary log now. Instead, we mark
2404    // that the next time we access the summary log, it should be cleared.
2405
2406    // If we never reset the summary log during /this/ code body analysis,
2407    // there were no new summaries. There might still have been summaries from
2408    // the /last/ analysis, so clear them out to make sure the bug report
2409    // visitors don't get confused.
2410    if (ShouldResetSummaryLog)
2411      SummaryLog.clear();
2412
2413    ShouldResetSummaryLog = !SummaryLog.empty();
2414  }
2415
2416  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2417                                     bool GCEnabled) const {
2418    if (GCEnabled) {
2419      if (!leakWithinFunctionGC)
2420        leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2421                                             "garbage collection"));
2422      return leakWithinFunctionGC.get();
2423    } else {
2424      if (!leakWithinFunction) {
2425        if (LOpts.getGC() == LangOptions::HybridGC) {
2426          leakWithinFunction.reset(new Leak("Leak of object when not using "
2427                                            "garbage collection (GC) in "
2428                                            "dual GC/non-GC code"));
2429        } else {
2430          leakWithinFunction.reset(new Leak("Leak"));
2431        }
2432      }
2433      return leakWithinFunction.get();
2434    }
2435  }
2436
2437  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2438    if (GCEnabled) {
2439      if (!leakAtReturnGC)
2440        leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2441                                      "garbage collection"));
2442      return leakAtReturnGC.get();
2443    } else {
2444      if (!leakAtReturn) {
2445        if (LOpts.getGC() == LangOptions::HybridGC) {
2446          leakAtReturn.reset(new Leak("Leak of returned object when not using "
2447                                      "garbage collection (GC) in dual "
2448                                      "GC/non-GC code"));
2449        } else {
2450          leakAtReturn.reset(new Leak("Leak of returned object"));
2451        }
2452      }
2453      return leakAtReturn.get();
2454    }
2455  }
2456
2457  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2458                                          bool GCEnabled) const {
2459    // FIXME: We don't support ARC being turned on and off during one analysis.
2460    // (nor, for that matter, do we support changing ASTContexts)
2461    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2462    if (GCEnabled) {
2463      if (!SummariesGC)
2464        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2465      else
2466        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2467      return *SummariesGC;
2468    } else {
2469      if (!Summaries)
2470        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2471      else
2472        assert(Summaries->isARCEnabled() == ARCEnabled);
2473      return *Summaries;
2474    }
2475  }
2476
2477  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2478    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2479  }
2480
2481  void printState(raw_ostream &Out, ProgramStateRef State,
2482                  const char *NL, const char *Sep) const;
2483
2484  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2485  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2486  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2487
2488  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2489  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2490  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2491
2492  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2493
2494  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2495                    CheckerContext &C) const;
2496
2497  void processSummaryOfInlined(const RetainSummary &Summ,
2498                               const CallEvent &Call,
2499                               CheckerContext &C) const;
2500
2501  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2502
2503  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2504                                 bool Assumption) const;
2505
2506  ProgramStateRef
2507  checkRegionChanges(ProgramStateRef state,
2508                     const InvalidatedSymbols *invalidated,
2509                     ArrayRef<const MemRegion *> ExplicitRegions,
2510                     ArrayRef<const MemRegion *> Regions,
2511                     const CallEvent *Call) const;
2512
2513  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2514    return true;
2515  }
2516
2517  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2518  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2519                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2520                                SymbolRef Sym, ProgramStateRef state) const;
2521
2522  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2523  void checkEndFunction(CheckerContext &C) const;
2524
2525  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2526                               RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2527                               CheckerContext &C) const;
2528
2529  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2530                           RefVal::Kind ErrorKind, SymbolRef Sym,
2531                           CheckerContext &C) const;
2532
2533  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2534
2535  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2536
2537  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2538                                    SymbolRef sid, RefVal V,
2539                                    SmallVectorImpl<SymbolRef> &Leaked) const;
2540
2541  ProgramStateRef
2542  handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2543                          const ProgramPointTag *Tag, CheckerContext &Ctx,
2544                          SymbolRef Sym, RefVal V) const;
2545
2546  ExplodedNode *processLeaks(ProgramStateRef state,
2547                             SmallVectorImpl<SymbolRef> &Leaked,
2548                             CheckerContext &Ctx,
2549                             ExplodedNode *Pred = 0) const;
2550};
2551} // end anonymous namespace
2552
2553namespace {
2554class StopTrackingCallback : public SymbolVisitor {
2555  ProgramStateRef state;
2556public:
2557  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2558  ProgramStateRef getState() const { return state; }
2559
2560  bool VisitSymbol(SymbolRef sym) {
2561    state = state->remove<RefBindings>(sym);
2562    return true;
2563  }
2564};
2565} // end anonymous namespace
2566
2567//===----------------------------------------------------------------------===//
2568// Handle statements that may have an effect on refcounts.
2569//===----------------------------------------------------------------------===//
2570
2571void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2572                                       CheckerContext &C) const {
2573
2574  // Scan the BlockDecRefExprs for any object the retain count checker
2575  // may be tracking.
2576  if (!BE->getBlockDecl()->hasCaptures())
2577    return;
2578
2579  ProgramStateRef state = C.getState();
2580  const BlockDataRegion *R =
2581    cast<BlockDataRegion>(state->getSVal(BE,
2582                                         C.getLocationContext()).getAsRegion());
2583
2584  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2585                                            E = R->referenced_vars_end();
2586
2587  if (I == E)
2588    return;
2589
2590  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2591  // via captured variables, even though captured variables result in a copy
2592  // and in implicit increment/decrement of a retain count.
2593  SmallVector<const MemRegion*, 10> Regions;
2594  const LocationContext *LC = C.getLocationContext();
2595  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2596
2597  for ( ; I != E; ++I) {
2598    const VarRegion *VR = I.getCapturedRegion();
2599    if (VR->getSuperRegion() == R) {
2600      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2601    }
2602    Regions.push_back(VR);
2603  }
2604
2605  state =
2606    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2607                                    Regions.data() + Regions.size()).getState();
2608  C.addTransition(state);
2609}
2610
2611void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2612                                       CheckerContext &C) const {
2613  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2614  if (!BE)
2615    return;
2616
2617  ArgEffect AE = IncRef;
2618
2619  switch (BE->getBridgeKind()) {
2620    case clang::OBC_Bridge:
2621      // Do nothing.
2622      return;
2623    case clang::OBC_BridgeRetained:
2624      AE = IncRef;
2625      break;
2626    case clang::OBC_BridgeTransfer:
2627      AE = DecRefBridgedTransfered;
2628      break;
2629  }
2630
2631  ProgramStateRef state = C.getState();
2632  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2633  if (!Sym)
2634    return;
2635  const RefVal* T = getRefBinding(state, Sym);
2636  if (!T)
2637    return;
2638
2639  RefVal::Kind hasErr = (RefVal::Kind) 0;
2640  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2641
2642  if (hasErr) {
2643    // FIXME: If we get an error during a bridge cast, should we report it?
2644    // Should we assert that there is no error?
2645    return;
2646  }
2647
2648  C.addTransition(state);
2649}
2650
2651void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2652                                             const Expr *Ex) const {
2653  ProgramStateRef state = C.getState();
2654  const ExplodedNode *pred = C.getPredecessor();
2655  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2656       it != et ; ++it) {
2657    const Stmt *child = *it;
2658    SVal V = state->getSVal(child, pred->getLocationContext());
2659    if (SymbolRef sym = V.getAsSymbol())
2660      if (const RefVal* T = getRefBinding(state, sym)) {
2661        RefVal::Kind hasErr = (RefVal::Kind) 0;
2662        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2663        if (hasErr) {
2664          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2665          return;
2666        }
2667      }
2668  }
2669
2670  // Return the object as autoreleased.
2671  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2672  if (SymbolRef sym =
2673        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2674    QualType ResultTy = Ex->getType();
2675    state = setRefBinding(state, sym,
2676                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2677  }
2678
2679  C.addTransition(state);
2680}
2681
2682void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2683                                       CheckerContext &C) const {
2684  // Apply the 'MayEscape' to all values.
2685  processObjCLiterals(C, AL);
2686}
2687
2688void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2689                                       CheckerContext &C) const {
2690  // Apply the 'MayEscape' to all keys and values.
2691  processObjCLiterals(C, DL);
2692}
2693
2694void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2695                                       CheckerContext &C) const {
2696  const ExplodedNode *Pred = C.getPredecessor();
2697  const LocationContext *LCtx = Pred->getLocationContext();
2698  ProgramStateRef State = Pred->getState();
2699
2700  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2701    QualType ResultTy = Ex->getType();
2702    State = setRefBinding(State, Sym,
2703                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2704  }
2705
2706  C.addTransition(State);
2707}
2708
2709void RetainCountChecker::checkPostCall(const CallEvent &Call,
2710                                       CheckerContext &C) const {
2711  RetainSummaryManager &Summaries = getSummaryManager(C);
2712  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2713
2714  if (C.wasInlined) {
2715    processSummaryOfInlined(*Summ, Call, C);
2716    return;
2717  }
2718  checkSummary(*Summ, Call, C);
2719}
2720
2721/// GetReturnType - Used to get the return type of a message expression or
2722///  function call with the intention of affixing that type to a tracked symbol.
2723///  While the return type can be queried directly from RetEx, when
2724///  invoking class methods we augment to the return type to be that of
2725///  a pointer to the class (as opposed it just being id).
2726// FIXME: We may be able to do this with related result types instead.
2727// This function is probably overestimating.
2728static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2729  QualType RetTy = RetE->getType();
2730  // If RetE is not a message expression just return its type.
2731  // If RetE is a message expression, return its types if it is something
2732  /// more specific than id.
2733  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2734    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2735      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2736          PT->isObjCClassType()) {
2737        // At this point we know the return type of the message expression is
2738        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2739        // is a call to a class method whose type we can resolve.  In such
2740        // cases, promote the return type to XXX* (where XXX is the class).
2741        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2742        return !D ? RetTy :
2743                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2744      }
2745
2746  return RetTy;
2747}
2748
2749// We don't always get the exact modeling of the function with regards to the
2750// retain count checker even when the function is inlined. For example, we need
2751// to stop tracking the symbols which were marked with StopTrackingHard.
2752void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2753                                                 const CallEvent &CallOrMsg,
2754                                                 CheckerContext &C) const {
2755  ProgramStateRef state = C.getState();
2756
2757  // Evaluate the effect of the arguments.
2758  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2759    if (Summ.getArg(idx) == StopTrackingHard) {
2760      SVal V = CallOrMsg.getArgSVal(idx);
2761      if (SymbolRef Sym = V.getAsLocSymbol()) {
2762        state = removeRefBinding(state, Sym);
2763      }
2764    }
2765  }
2766
2767  // Evaluate the effect on the message receiver.
2768  const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2769  if (MsgInvocation) {
2770    if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2771      if (Summ.getReceiverEffect() == StopTrackingHard) {
2772        state = removeRefBinding(state, Sym);
2773      }
2774    }
2775  }
2776
2777  // Consult the summary for the return value.
2778  RetEffect RE = Summ.getRetEffect();
2779  if (RE.getKind() == RetEffect::NoRetHard) {
2780    SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2781    if (Sym)
2782      state = removeRefBinding(state, Sym);
2783  }
2784
2785  C.addTransition(state);
2786}
2787
2788void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2789                                      const CallEvent &CallOrMsg,
2790                                      CheckerContext &C) const {
2791  ProgramStateRef state = C.getState();
2792
2793  // Evaluate the effect of the arguments.
2794  RefVal::Kind hasErr = (RefVal::Kind) 0;
2795  SourceRange ErrorRange;
2796  SymbolRef ErrorSym = 0;
2797
2798  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2799    SVal V = CallOrMsg.getArgSVal(idx);
2800
2801    if (SymbolRef Sym = V.getAsLocSymbol()) {
2802      if (const RefVal *T = getRefBinding(state, Sym)) {
2803        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2804        if (hasErr) {
2805          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2806          ErrorSym = Sym;
2807          break;
2808        }
2809      }
2810    }
2811  }
2812
2813  // Evaluate the effect on the message receiver.
2814  bool ReceiverIsTracked = false;
2815  if (!hasErr) {
2816    const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2817    if (MsgInvocation) {
2818      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2819        if (const RefVal *T = getRefBinding(state, Sym)) {
2820          ReceiverIsTracked = true;
2821          state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2822                                 hasErr, C);
2823          if (hasErr) {
2824            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2825            ErrorSym = Sym;
2826          }
2827        }
2828      }
2829    }
2830  }
2831
2832  // Process any errors.
2833  if (hasErr) {
2834    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2835    return;
2836  }
2837
2838  // Consult the summary for the return value.
2839  RetEffect RE = Summ.getRetEffect();
2840
2841  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2842    if (ReceiverIsTracked)
2843      RE = getSummaryManager(C).getObjAllocRetEffect();
2844    else
2845      RE = RetEffect::MakeNoRet();
2846  }
2847
2848  switch (RE.getKind()) {
2849    default:
2850      llvm_unreachable("Unhandled RetEffect.");
2851
2852    case RetEffect::NoRet:
2853    case RetEffect::NoRetHard:
2854      // No work necessary.
2855      break;
2856
2857    case RetEffect::OwnedAllocatedSymbol:
2858    case RetEffect::OwnedSymbol: {
2859      SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2860      if (!Sym)
2861        break;
2862
2863      // Use the result type from the CallEvent as it automatically adjusts
2864      // for methods/functions that return references.
2865      QualType ResultTy = CallOrMsg.getResultType();
2866      state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2867                                                          ResultTy));
2868
2869      // FIXME: Add a flag to the checker where allocations are assumed to
2870      // *not* fail.
2871      break;
2872    }
2873
2874    case RetEffect::GCNotOwnedSymbol:
2875    case RetEffect::ARCNotOwnedSymbol:
2876    case RetEffect::NotOwnedSymbol: {
2877      const Expr *Ex = CallOrMsg.getOriginExpr();
2878      SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2879      if (!Sym)
2880        break;
2881      assert(Ex);
2882      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2883      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2884      state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2885                                                             ResultTy));
2886      break;
2887    }
2888  }
2889
2890  // This check is actually necessary; otherwise the statement builder thinks
2891  // we've hit a previously-found path.
2892  // Normally addTransition takes care of this, but we want the node pointer.
2893  ExplodedNode *NewNode;
2894  if (state == C.getState()) {
2895    NewNode = C.getPredecessor();
2896  } else {
2897    NewNode = C.addTransition(state);
2898  }
2899
2900  // Annotate the node with summary we used.
2901  if (NewNode) {
2902    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2903    if (ShouldResetSummaryLog) {
2904      SummaryLog.clear();
2905      ShouldResetSummaryLog = false;
2906    }
2907    SummaryLog[NewNode] = &Summ;
2908  }
2909}
2910
2911
2912ProgramStateRef
2913RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2914                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2915                                 CheckerContext &C) const {
2916  // In GC mode [... release] and [... retain] do nothing.
2917  // In ARC mode they shouldn't exist at all, but we just ignore them.
2918  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2919  if (!IgnoreRetainMsg)
2920    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2921
2922  switch (E) {
2923  default:
2924    break;
2925  case IncRefMsg:
2926    E = IgnoreRetainMsg ? DoNothing : IncRef;
2927    break;
2928  case DecRefMsg:
2929    E = IgnoreRetainMsg ? DoNothing : DecRef;
2930    break;
2931  case DecRefMsgAndStopTrackingHard:
2932    E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
2933    break;
2934  case MakeCollectable:
2935    E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2936    break;
2937  }
2938
2939  // Handle all use-after-releases.
2940  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2941    V = V ^ RefVal::ErrorUseAfterRelease;
2942    hasErr = V.getKind();
2943    return setRefBinding(state, sym, V);
2944  }
2945
2946  switch (E) {
2947    case DecRefMsg:
2948    case IncRefMsg:
2949    case MakeCollectable:
2950    case DecRefMsgAndStopTrackingHard:
2951      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2952
2953    case Dealloc:
2954      // Any use of -dealloc in GC is *bad*.
2955      if (C.isObjCGCEnabled()) {
2956        V = V ^ RefVal::ErrorDeallocGC;
2957        hasErr = V.getKind();
2958        break;
2959      }
2960
2961      switch (V.getKind()) {
2962        default:
2963          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2964        case RefVal::Owned:
2965          // The object immediately transitions to the released state.
2966          V = V ^ RefVal::Released;
2967          V.clearCounts();
2968          return setRefBinding(state, sym, V);
2969        case RefVal::NotOwned:
2970          V = V ^ RefVal::ErrorDeallocNotOwned;
2971          hasErr = V.getKind();
2972          break;
2973      }
2974      break;
2975
2976    case MayEscape:
2977      if (V.getKind() == RefVal::Owned) {
2978        V = V ^ RefVal::NotOwned;
2979        break;
2980      }
2981
2982      // Fall-through.
2983
2984    case DoNothing:
2985      return state;
2986
2987    case Autorelease:
2988      if (C.isObjCGCEnabled())
2989        return state;
2990      // Update the autorelease counts.
2991      V = V.autorelease();
2992      break;
2993
2994    case StopTracking:
2995    case StopTrackingHard:
2996      return removeRefBinding(state, sym);
2997
2998    case IncRef:
2999      switch (V.getKind()) {
3000        default:
3001          llvm_unreachable("Invalid RefVal state for a retain.");
3002        case RefVal::Owned:
3003        case RefVal::NotOwned:
3004          V = V + 1;
3005          break;
3006        case RefVal::Released:
3007          // Non-GC cases are handled above.
3008          assert(C.isObjCGCEnabled());
3009          V = (V ^ RefVal::Owned) + 1;
3010          break;
3011      }
3012      break;
3013
3014    case DecRef:
3015    case DecRefBridgedTransfered:
3016    case DecRefAndStopTrackingHard:
3017      switch (V.getKind()) {
3018        default:
3019          // case 'RefVal::Released' handled above.
3020          llvm_unreachable("Invalid RefVal state for a release.");
3021
3022        case RefVal::Owned:
3023          assert(V.getCount() > 0);
3024          if (V.getCount() == 1)
3025            V = V ^ (E == DecRefBridgedTransfered ?
3026                      RefVal::NotOwned : RefVal::Released);
3027          else if (E == DecRefAndStopTrackingHard)
3028            return removeRefBinding(state, sym);
3029
3030          V = V - 1;
3031          break;
3032
3033        case RefVal::NotOwned:
3034          if (V.getCount() > 0) {
3035            if (E == DecRefAndStopTrackingHard)
3036              return removeRefBinding(state, sym);
3037            V = V - 1;
3038          } else {
3039            V = V ^ RefVal::ErrorReleaseNotOwned;
3040            hasErr = V.getKind();
3041          }
3042          break;
3043
3044        case RefVal::Released:
3045          // Non-GC cases are handled above.
3046          assert(C.isObjCGCEnabled());
3047          V = V ^ RefVal::ErrorUseAfterRelease;
3048          hasErr = V.getKind();
3049          break;
3050      }
3051      break;
3052  }
3053  return setRefBinding(state, sym, V);
3054}
3055
3056void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3057                                             SourceRange ErrorRange,
3058                                             RefVal::Kind ErrorKind,
3059                                             SymbolRef Sym,
3060                                             CheckerContext &C) const {
3061  ExplodedNode *N = C.generateSink(St);
3062  if (!N)
3063    return;
3064
3065  CFRefBug *BT;
3066  switch (ErrorKind) {
3067    default:
3068      llvm_unreachable("Unhandled error.");
3069    case RefVal::ErrorUseAfterRelease:
3070      if (!useAfterRelease)
3071        useAfterRelease.reset(new UseAfterRelease());
3072      BT = &*useAfterRelease;
3073      break;
3074    case RefVal::ErrorReleaseNotOwned:
3075      if (!releaseNotOwned)
3076        releaseNotOwned.reset(new BadRelease());
3077      BT = &*releaseNotOwned;
3078      break;
3079    case RefVal::ErrorDeallocGC:
3080      if (!deallocGC)
3081        deallocGC.reset(new DeallocGC());
3082      BT = &*deallocGC;
3083      break;
3084    case RefVal::ErrorDeallocNotOwned:
3085      if (!deallocNotOwned)
3086        deallocNotOwned.reset(new DeallocNotOwned());
3087      BT = &*deallocNotOwned;
3088      break;
3089  }
3090
3091  assert(BT);
3092  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3093                                        C.isObjCGCEnabled(), SummaryLog,
3094                                        N, Sym);
3095  report->addRange(ErrorRange);
3096  C.emitReport(report);
3097}
3098
3099//===----------------------------------------------------------------------===//
3100// Handle the return values of retain-count-related functions.
3101//===----------------------------------------------------------------------===//
3102
3103bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3104  // Get the callee. We're only interested in simple C functions.
3105  ProgramStateRef state = C.getState();
3106  const FunctionDecl *FD = C.getCalleeDecl(CE);
3107  if (!FD)
3108    return false;
3109
3110  IdentifierInfo *II = FD->getIdentifier();
3111  if (!II)
3112    return false;
3113
3114  // For now, we're only handling the functions that return aliases of their
3115  // arguments: CFRetain and CFMakeCollectable (and their families).
3116  // Eventually we should add other functions we can model entirely,
3117  // such as CFRelease, which don't invalidate their arguments or globals.
3118  if (CE->getNumArgs() != 1)
3119    return false;
3120
3121  // Get the name of the function.
3122  StringRef FName = II->getName();
3123  FName = FName.substr(FName.find_first_not_of('_'));
3124
3125  // See if it's one of the specific functions we know how to eval.
3126  bool canEval = false;
3127
3128  QualType ResultTy = CE->getCallReturnType();
3129  if (ResultTy->isObjCIdType()) {
3130    // Handle: id NSMakeCollectable(CFTypeRef)
3131    canEval = II->isStr("NSMakeCollectable");
3132  } else if (ResultTy->isPointerType()) {
3133    // Handle: (CF|CG)Retain
3134    //         CFMakeCollectable
3135    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3136    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3137        cocoa::isRefType(ResultTy, "CG", FName)) {
3138      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3139    }
3140  }
3141
3142  if (!canEval)
3143    return false;
3144
3145  // Bind the return value.
3146  const LocationContext *LCtx = C.getLocationContext();
3147  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3148  if (RetVal.isUnknown()) {
3149    // If the receiver is unknown, conjure a return value.
3150    SValBuilder &SVB = C.getSValBuilder();
3151    RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
3152  }
3153  state = state->BindExpr(CE, LCtx, RetVal, false);
3154
3155  // FIXME: This should not be necessary, but otherwise the argument seems to be
3156  // considered alive during the next statement.
3157  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3158    // Save the refcount status of the argument.
3159    SymbolRef Sym = RetVal.getAsLocSymbol();
3160    const RefVal *Binding = 0;
3161    if (Sym)
3162      Binding = getRefBinding(state, Sym);
3163
3164    // Invalidate the argument region.
3165    state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
3166                                     /*CausesPointerEscape*/ false);
3167
3168    // Restore the refcount status of the argument.
3169    if (Binding)
3170      state = setRefBinding(state, Sym, *Binding);
3171  }
3172
3173  C.addTransition(state);
3174  return true;
3175}
3176
3177//===----------------------------------------------------------------------===//
3178// Handle return statements.
3179//===----------------------------------------------------------------------===//
3180
3181void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3182                                      CheckerContext &C) const {
3183
3184  // Only adjust the reference count if this is the top-level call frame,
3185  // and not the result of inlining.  In the future, we should do
3186  // better checking even for inlined calls, and see if they match
3187  // with their expected semantics (e.g., the method should return a retained
3188  // object, etc.).
3189  if (!C.inTopFrame())
3190    return;
3191
3192  const Expr *RetE = S->getRetValue();
3193  if (!RetE)
3194    return;
3195
3196  ProgramStateRef state = C.getState();
3197  SymbolRef Sym =
3198    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3199  if (!Sym)
3200    return;
3201
3202  // Get the reference count binding (if any).
3203  const RefVal *T = getRefBinding(state, Sym);
3204  if (!T)
3205    return;
3206
3207  // Change the reference count.
3208  RefVal X = *T;
3209
3210  switch (X.getKind()) {
3211    case RefVal::Owned: {
3212      unsigned cnt = X.getCount();
3213      assert(cnt > 0);
3214      X.setCount(cnt - 1);
3215      X = X ^ RefVal::ReturnedOwned;
3216      break;
3217    }
3218
3219    case RefVal::NotOwned: {
3220      unsigned cnt = X.getCount();
3221      if (cnt) {
3222        X.setCount(cnt - 1);
3223        X = X ^ RefVal::ReturnedOwned;
3224      }
3225      else {
3226        X = X ^ RefVal::ReturnedNotOwned;
3227      }
3228      break;
3229    }
3230
3231    default:
3232      return;
3233  }
3234
3235  // Update the binding.
3236  state = setRefBinding(state, Sym, X);
3237  ExplodedNode *Pred = C.addTransition(state);
3238
3239  // At this point we have updated the state properly.
3240  // Everything after this is merely checking to see if the return value has
3241  // been over- or under-retained.
3242
3243  // Did we cache out?
3244  if (!Pred)
3245    return;
3246
3247  // Update the autorelease counts.
3248  static SimpleProgramPointTag
3249         AutoreleaseTag("RetainCountChecker : Autorelease");
3250  state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
3251
3252  // Did we cache out?
3253  if (!state)
3254    return;
3255
3256  // Get the updated binding.
3257  T = getRefBinding(state, Sym);
3258  assert(T);
3259  X = *T;
3260
3261  // Consult the summary of the enclosing method.
3262  RetainSummaryManager &Summaries = getSummaryManager(C);
3263  const Decl *CD = &Pred->getCodeDecl();
3264  RetEffect RE = RetEffect::MakeNoRet();
3265
3266  // FIXME: What is the convention for blocks? Is there one?
3267  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3268    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3269    RE = Summ->getRetEffect();
3270  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3271    if (!isa<CXXMethodDecl>(FD)) {
3272      const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3273      RE = Summ->getRetEffect();
3274    }
3275  }
3276
3277  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3278}
3279
3280void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3281                                                  CheckerContext &C,
3282                                                  ExplodedNode *Pred,
3283                                                  RetEffect RE, RefVal X,
3284                                                  SymbolRef Sym,
3285                                              ProgramStateRef state) const {
3286  // Any leaks or other errors?
3287  if (X.isReturnedOwned() && X.getCount() == 0) {
3288    if (RE.getKind() != RetEffect::NoRet) {
3289      bool hasError = false;
3290      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3291        // Things are more complicated with garbage collection.  If the
3292        // returned object is suppose to be an Objective-C object, we have
3293        // a leak (as the caller expects a GC'ed object) because no
3294        // method should return ownership unless it returns a CF object.
3295        hasError = true;
3296        X = X ^ RefVal::ErrorGCLeakReturned;
3297      }
3298      else if (!RE.isOwned()) {
3299        // Either we are using GC and the returned object is a CF type
3300        // or we aren't using GC.  In either case, we expect that the
3301        // enclosing method is expected to return ownership.
3302        hasError = true;
3303        X = X ^ RefVal::ErrorLeakReturned;
3304      }
3305
3306      if (hasError) {
3307        // Generate an error node.
3308        state = setRefBinding(state, Sym, X);
3309
3310        static SimpleProgramPointTag
3311               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3312        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3313        if (N) {
3314          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3315          bool GCEnabled = C.isObjCGCEnabled();
3316          CFRefReport *report =
3317            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3318                                LOpts, GCEnabled, SummaryLog,
3319                                N, Sym, C);
3320          C.emitReport(report);
3321        }
3322      }
3323    }
3324  } else if (X.isReturnedNotOwned()) {
3325    if (RE.isOwned()) {
3326      // Trying to return a not owned object to a caller expecting an
3327      // owned object.
3328      state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3329
3330      static SimpleProgramPointTag
3331             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3332      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3333      if (N) {
3334        if (!returnNotOwnedForOwned)
3335          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3336
3337        CFRefReport *report =
3338            new CFRefReport(*returnNotOwnedForOwned,
3339                            C.getASTContext().getLangOpts(),
3340                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3341        C.emitReport(report);
3342      }
3343    }
3344  }
3345}
3346
3347//===----------------------------------------------------------------------===//
3348// Check various ways a symbol can be invalidated.
3349//===----------------------------------------------------------------------===//
3350
3351void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3352                                   CheckerContext &C) const {
3353  // Are we storing to something that causes the value to "escape"?
3354  bool escapes = true;
3355
3356  // A value escapes in three possible cases (this may change):
3357  //
3358  // (1) we are binding to something that is not a memory region.
3359  // (2) we are binding to a memregion that does not have stack storage
3360  // (3) we are binding to a memregion with stack storage that the store
3361  //     does not understand.
3362  ProgramStateRef state = C.getState();
3363
3364  if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
3365    escapes = !regionLoc->getRegion()->hasStackStorage();
3366
3367    if (!escapes) {
3368      // To test (3), generate a new state with the binding added.  If it is
3369      // the same state, then it escapes (since the store cannot represent
3370      // the binding).
3371      // Do this only if we know that the store is not supposed to generate the
3372      // same state.
3373      SVal StoredVal = state->getSVal(regionLoc->getRegion());
3374      if (StoredVal != val)
3375        escapes = (state == (state->bindLoc(*regionLoc, val)));
3376    }
3377    if (!escapes) {
3378      // Case 4: We do not currently model what happens when a symbol is
3379      // assigned to a struct field, so be conservative here and let the symbol
3380      // go. TODO: This could definitely be improved upon.
3381      escapes = !isa<VarRegion>(regionLoc->getRegion());
3382    }
3383  }
3384
3385  // If our store can represent the binding and we aren't storing to something
3386  // that doesn't have local storage then just return and have the simulation
3387  // state continue as is.
3388  if (!escapes)
3389      return;
3390
3391  // Otherwise, find all symbols referenced by 'val' that we are tracking
3392  // and stop tracking them.
3393  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3394  C.addTransition(state);
3395}
3396
3397ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3398                                                   SVal Cond,
3399                                                   bool Assumption) const {
3400
3401  // FIXME: We may add to the interface of evalAssume the list of symbols
3402  //  whose assumptions have changed.  For now we just iterate through the
3403  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3404  //  too bad since the number of symbols we will track in practice are
3405  //  probably small and evalAssume is only called at branches and a few
3406  //  other places.
3407  RefBindingsTy B = state->get<RefBindings>();
3408
3409  if (B.isEmpty())
3410    return state;
3411
3412  bool changed = false;
3413  RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3414
3415  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3416    // Check if the symbol is null stop tracking the symbol.
3417    ConstraintManager &CMgr = state->getConstraintManager();
3418    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3419    if (AllocFailed.isConstrainedTrue()) {
3420      changed = true;
3421      B = RefBFactory.remove(B, I.getKey());
3422    }
3423  }
3424
3425  if (changed)
3426    state = state->set<RefBindings>(B);
3427
3428  return state;
3429}
3430
3431ProgramStateRef
3432RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3433                                    const InvalidatedSymbols *invalidated,
3434                                    ArrayRef<const MemRegion *> ExplicitRegions,
3435                                    ArrayRef<const MemRegion *> Regions,
3436                                    const CallEvent *Call) const {
3437  if (!invalidated)
3438    return state;
3439
3440  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3441  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3442       E = ExplicitRegions.end(); I != E; ++I) {
3443    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3444      WhitelistedSymbols.insert(SR->getSymbol());
3445  }
3446
3447  for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
3448       E = invalidated->end(); I!=E; ++I) {
3449    SymbolRef sym = *I;
3450    if (WhitelistedSymbols.count(sym))
3451      continue;
3452    // Remove any existing reference-count binding.
3453    state = removeRefBinding(state, sym);
3454  }
3455  return state;
3456}
3457
3458//===----------------------------------------------------------------------===//
3459// Handle dead symbols and end-of-path.
3460//===----------------------------------------------------------------------===//
3461
3462ProgramStateRef
3463RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3464                                            ExplodedNode *Pred,
3465                                            const ProgramPointTag *Tag,
3466                                            CheckerContext &Ctx,
3467                                            SymbolRef Sym, RefVal V) const {
3468  unsigned ACnt = V.getAutoreleaseCount();
3469
3470  // No autorelease counts?  Nothing to be done.
3471  if (!ACnt)
3472    return state;
3473
3474  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3475  unsigned Cnt = V.getCount();
3476
3477  // FIXME: Handle sending 'autorelease' to already released object.
3478
3479  if (V.getKind() == RefVal::ReturnedOwned)
3480    ++Cnt;
3481
3482  if (ACnt <= Cnt) {
3483    if (ACnt == Cnt) {
3484      V.clearCounts();
3485      if (V.getKind() == RefVal::ReturnedOwned)
3486        V = V ^ RefVal::ReturnedNotOwned;
3487      else
3488        V = V ^ RefVal::NotOwned;
3489    } else {
3490      V.setCount(V.getCount() - ACnt);
3491      V.setAutoreleaseCount(0);
3492    }
3493    return setRefBinding(state, Sym, V);
3494  }
3495
3496  // Woah!  More autorelease counts then retain counts left.
3497  // Emit hard error.
3498  V = V ^ RefVal::ErrorOverAutorelease;
3499  state = setRefBinding(state, Sym, V);
3500
3501  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3502  if (N) {
3503    SmallString<128> sbuf;
3504    llvm::raw_svector_ostream os(sbuf);
3505    os << "Object over-autoreleased: object was sent -autorelease ";
3506    if (V.getAutoreleaseCount() > 1)
3507      os << V.getAutoreleaseCount() << " times ";
3508    os << "but the object has a +" << V.getCount() << " retain count";
3509
3510    if (!overAutorelease)
3511      overAutorelease.reset(new OverAutorelease());
3512
3513    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3514    CFRefReport *report =
3515      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3516                      SummaryLog, N, Sym, os.str());
3517    Ctx.emitReport(report);
3518  }
3519
3520  return 0;
3521}
3522
3523ProgramStateRef
3524RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3525                                      SymbolRef sid, RefVal V,
3526                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3527  bool hasLeak = false;
3528  if (V.isOwned())
3529    hasLeak = true;
3530  else if (V.isNotOwned() || V.isReturnedOwned())
3531    hasLeak = (V.getCount() > 0);
3532
3533  if (!hasLeak)
3534    return removeRefBinding(state, sid);
3535
3536  Leaked.push_back(sid);
3537  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3538}
3539
3540ExplodedNode *
3541RetainCountChecker::processLeaks(ProgramStateRef state,
3542                                 SmallVectorImpl<SymbolRef> &Leaked,
3543                                 CheckerContext &Ctx,
3544                                 ExplodedNode *Pred) const {
3545  // Generate an intermediate node representing the leak point.
3546  ExplodedNode *N = Ctx.addTransition(state, Pred);
3547
3548  if (N) {
3549    for (SmallVectorImpl<SymbolRef>::iterator
3550         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3551
3552      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3553      bool GCEnabled = Ctx.isObjCGCEnabled();
3554      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3555                          : getLeakAtReturnBug(LOpts, GCEnabled);
3556      assert(BT && "BugType not initialized.");
3557
3558      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3559                                                    SummaryLog, N, *I, Ctx);
3560      Ctx.emitReport(report);
3561    }
3562  }
3563
3564  return N;
3565}
3566
3567void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
3568  ProgramStateRef state = Ctx.getState();
3569  RefBindingsTy B = state->get<RefBindings>();
3570  ExplodedNode *Pred = Ctx.getPredecessor();
3571
3572  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3573    state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3574                                    I->first, I->second);
3575    if (!state)
3576      return;
3577  }
3578
3579  // If the current LocationContext has a parent, don't check for leaks.
3580  // We will do that later.
3581  // FIXME: we should instead check for imbalances of the retain/releases,
3582  // and suggest annotations.
3583  if (Ctx.getLocationContext()->getParent())
3584    return;
3585
3586  B = state->get<RefBindings>();
3587  SmallVector<SymbolRef, 10> Leaked;
3588
3589  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
3590    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3591
3592  processLeaks(state, Leaked, Ctx, Pred);
3593}
3594
3595const ProgramPointTag *
3596RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3597  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3598  if (!tag) {
3599    SmallString<64> buf;
3600    llvm::raw_svector_ostream out(buf);
3601    out << "RetainCountChecker : Dead Symbol : ";
3602    sym->dumpToStream(out);
3603    tag = new SimpleProgramPointTag(out.str());
3604  }
3605  return tag;
3606}
3607
3608void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3609                                          CheckerContext &C) const {
3610  ExplodedNode *Pred = C.getPredecessor();
3611
3612  ProgramStateRef state = C.getState();
3613  RefBindingsTy B = state->get<RefBindings>();
3614  SmallVector<SymbolRef, 10> Leaked;
3615
3616  // Update counts from autorelease pools
3617  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3618       E = SymReaper.dead_end(); I != E; ++I) {
3619    SymbolRef Sym = *I;
3620    if (const RefVal *T = B.lookup(Sym)){
3621      // Use the symbol as the tag.
3622      // FIXME: This might not be as unique as we would like.
3623      const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3624      state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
3625      if (!state)
3626        return;
3627
3628      // Fetch the new reference count from the state, and use it to handle
3629      // this symbol.
3630      state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
3631    }
3632  }
3633
3634  if (Leaked.empty()) {
3635    C.addTransition(state);
3636    return;
3637  }
3638
3639  Pred = processLeaks(state, Leaked, C, Pred);
3640
3641  // Did we cache out?
3642  if (!Pred)
3643    return;
3644
3645  // Now generate a new node that nukes the old bindings.
3646  // The only bindings left at this point are the leaked symbols.
3647  RefBindingsTy::Factory &F = state->get_context<RefBindings>();
3648  B = state->get<RefBindings>();
3649
3650  for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3651                                            E = Leaked.end();
3652       I != E; ++I)
3653    B = F.remove(B, *I);
3654
3655  state = state->set<RefBindings>(B);
3656  C.addTransition(state, Pred);
3657}
3658
3659void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3660                                    const char *NL, const char *Sep) const {
3661
3662  RefBindingsTy B = State->get<RefBindings>();
3663
3664  if (!B.isEmpty())
3665    Out << Sep << NL;
3666
3667  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3668    Out << I->first << " : ";
3669    I->second.print(Out);
3670    Out << NL;
3671  }
3672}
3673
3674//===----------------------------------------------------------------------===//
3675// Checker registration.
3676//===----------------------------------------------------------------------===//
3677
3678void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3679  Mgr.registerChecker<RetainCountChecker>();
3680}
3681
3682