RetainCountChecker.cpp revision 537dd3a8c87765245aad792a3356852a87380a30
19720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
29720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//
39720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//                     The LLVM Compiler Infrastructure
49720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//
59720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// This file is distributed under the University of Illinois Open Source
69720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// License. See LICENSE.TXT for details.
79720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//
89720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
99720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//
109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//  This file defines the methods for RetainCountChecker, which implements
119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//
139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "ClangSACheckers.h"
169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/AST/DeclObjC.h"
179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/AST/DeclCXX.h"
189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/Basic/LangOptions.h"
199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/Basic/SourceManager.h"
209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/AST/ParentMap.h"
229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/Checker.h"
239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/CheckerManager.h"
249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/DenseMap.h"
319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/FoldingSet.h"
329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/ImmutableList.h"
339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/ImmutableMap.h"
349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/SmallString.h"
359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/STLExtras.h"
369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include "llvm/ADT/StringExtras.h"
379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#include <cstdarg>
389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockusing namespace clang;
409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockusing namespace ento;
419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockusing llvm::StrInStrNoCase;
429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace {
449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block/// Wrapper around different kinds of node builder, so that helper functions
459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block/// can have a common interface.
469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass GenericNodeBuilderRefCount {
479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  CheckerContext *C;
489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const ProgramPointTag *tag;
499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  GenericNodeBuilderRefCount(CheckerContext &c,
519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                             const ProgramPointTag *t = 0)
529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  : C(&c), tag(t){}
539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                         bool MarkAsSink = false) {
569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return C->addTransition(state, Pred, tag, MarkAsSink);
579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end anonymous namespace
609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Primitives used for constructing summaries for function/method calls.
639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
65a721beb6d7372334152406a36e8db016650a9691Tareq A. Siraj/// ArgEffect is used to summarize a function/method call's effect on a
66a721beb6d7372334152406a36e8db016650a9691Tareq A. Siraj/// particular argument.
67a721beb6d7372334152406a36e8db016650a9691Tareq A. Sirajenum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
68a721beb6d7372334152406a36e8db016650a9691Tareq A. Siraj                 DecRefBridgedTransfered,
69a721beb6d7372334152406a36e8db016650a9691Tareq A. Siraj                 IncRefMsg, IncRef, MakeCollectable, MayEscape,
70a721beb6d7372334152406a36e8db016650a9691Tareq A. Siraj                 NewAutoreleasePool, SelfOwn, StopTracking };
719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace llvm {
739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktemplate <> struct FoldingSetTrait<ArgEffect> {
749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstatic inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ID.AddInteger((unsigned) X);
769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end llvm namespace
799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block/// ArgEffects summarizes the effects of a function/method call on all of
819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block/// its arguments.
829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktypedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
84e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scottnamespace {
859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block///  RetEffect is used to summarize a function/method call's behavior with
879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block///  respect to its return value.
889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass RetEffect {
899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block              NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block              OwnedWhenTrackedReceiver };
939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  enum ObjKind { CF, ObjC, AnyObj };
959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockprivate:
979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Kind K;
989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjKind O;
999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
1019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
1039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Kind getKind() const { return K; }
1049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjKind getObjKind() const { return O; }
1069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isOwned() const {
1089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
1099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block           K == OwnedWhenTrackedReceiver;
1109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool operator==(const RetEffect &Other) const {
1139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return K == Other.K && O == Other.O;
1149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeOwnedWhenTrackedReceiver() {
1179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(OwnedWhenTrackedReceiver, ObjC);
1189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
1219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
1229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeNotOwned(ObjKind o) {
1249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(NotOwnedSymbol, o);
1259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeGCNotOwned() {
1279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(GCNotOwnedSymbol, ObjC);
1289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeARCNotOwned() {
1309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(ARCNotOwnedSymbol, ObjC);
1319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RetEffect MakeNoRet() {
1339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RetEffect(NoRet);
1349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void Profile(llvm::FoldingSetNodeID& ID) const {
1379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.AddInteger((unsigned) K);
1389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.AddInteger((unsigned) O);
1399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
1419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
1439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Reference-counting logic (typestate + counts).
1449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
1459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass RefVal {
1479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
148e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  enum Kind {
149e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    Owned = 0, // Owning reference.
150e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    NotOwned,  // Reference is not owned by still valid (not freed).
151e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    Released,  // Object has been released.
152e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ReturnedOwned, // Returned object passes ownership to caller.
153e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ReturnedNotOwned, // Return object does not pass ownership to caller.
154e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ERROR_START,
155e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ErrorDeallocNotOwned, // -dealloc called on non-owned object.
156e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ErrorDeallocGC, // Calling -dealloc with GC enabled.
157e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    ErrorUseAfterRelease, // Object used after released.
1589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorReleaseNotOwned, // Release of an object that was not owned.
1599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ERROR_LEAK_START,
1609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorLeak,  // A memory leak due to excessive reference counts.
1619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorLeakReturned, // A memory leak due to the returning method not having
1629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                       // the correct naming conventions.
1639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorGCLeakReturned,
1649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorOverAutorelease,
1659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ErrorReturnedNotOwned
1669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  };
1679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockprivate:
1699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Kind kind;
1709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect::ObjKind okind;
17189f07d6a92dab765c534266a640933ebd2f6d9e4Chris Dearman  unsigned Cnt;
1729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  unsigned ACnt;
1739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  QualType T;
1749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
1779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
1799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Kind getKind() const { return kind; }
1809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect::ObjKind getObjKind() const { return okind; }
1829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  unsigned getCount() const { return Cnt; }
1849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  unsigned getAutoreleaseCount() const { return ACnt; }
1859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  unsigned getCombinedCounts() const { return Cnt + ACnt; }
1869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void clearCounts() { Cnt = 0; ACnt = 0; }
1879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void setCount(unsigned i) { Cnt = i; }
1889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void setAutoreleaseCount(unsigned i) { ACnt = i; }
1899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  QualType getType() const { return T; }
1919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isOwned() const {
1939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getKind() == Owned;
1949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isNotOwned() const {
1979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getKind() == NotOwned;
1989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
1999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isReturnedOwned() const {
2019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getKind() == ReturnedOwned;
2029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isReturnedNotOwned() const {
2059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getKind() == ReturnedNotOwned;
2069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
2099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                          unsigned Count = 1) {
2109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RefVal(Owned, o, Count, 0, t);
211e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  }
212e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
2139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
2149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                             unsigned Count = 0) {
2159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RefVal(NotOwned, o, Count, 0, t);
2169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // Comparison, profiling, and pretty-printing.
2199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool operator==(const RefVal& X) const {
2219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
2229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
223e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
224e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  RefVal operator-(size_t i) const {
225e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    return RefVal(getKind(), getObjKind(), getCount() - i,
2269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                  getAutoreleaseCount(), getType());
2279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RefVal operator+(size_t i) const {
2309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RefVal(getKind(), getObjKind(), getCount() + i,
2319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                  getAutoreleaseCount(), getType());
2329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RefVal operator^(Kind k) const {
2359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
2369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                  getType());
2379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RefVal autorelease() const {
2409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
2419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                  getType());
2429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void Profile(llvm::FoldingSetNodeID& ID) const {
2459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.AddInteger((unsigned) kind);
2469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.AddInteger(Cnt);
2479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.AddInteger(ACnt);
2489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.Add(T);
2499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
2509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void print(raw_ostream &Out) const;
2529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
2539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockvoid RefVal::print(raw_ostream &Out) const {
255e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  if (!T.isNull())
2569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Out << "Tracked " << T.getAsString() << '/';
2579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  switch (getKind()) {
2599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    default: llvm_unreachable("Invalid RefVal kind");
2609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case Owned: {
2619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Owned";
2629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      unsigned cnt = getCount();
2639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cnt) Out << " (+ " << cnt << ")";
2649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
266e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
2679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case NotOwned: {
2689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "NotOwned";
2699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      unsigned cnt = getCount();
2709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cnt) Out << " (+ " << cnt << ")";
2719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
2739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ReturnedOwned: {
2759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "ReturnedOwned";
2769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      unsigned cnt = getCount();
2779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cnt) Out << " (+ " << cnt << ")";
2789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
2809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ReturnedNotOwned: {
2829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "ReturnedNotOwned";
2839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      unsigned cnt = getCount();
2849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cnt) Out << " (+ " << cnt << ")";
2859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
2879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case Released:
2899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Released";
2909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorDeallocGC:
2939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "-dealloc (GC)";
2949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
2969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorDeallocNotOwned:
297e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      Out << "-dealloc (not-owned)";
2989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
2999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorLeak:
3019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Leaked";
3029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorLeakReturned:
3059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Leaked (Bad naming)";
3069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorGCLeakReturned:
3099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Leaked (GC-ed at return)";
3109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorUseAfterRelease:
3139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Use-After-Release [ERROR]";
3149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case ErrorReleaseNotOwned:
3179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Release of Not-Owned [ERROR]";
3189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case RefVal::ErrorOverAutorelease:
3219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Over autoreleased";
3229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    case RefVal::ErrorReturnedNotOwned:
3259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Out << "Non-owned object returned instead of owned";
3269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
3279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
3289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  if (ACnt) {
3309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Out << " [ARC +" << ACnt << ']';
3319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
3329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
3339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} //end anonymous namespace
3349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
3369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// RefBindings - State used to track object reference counts.
3379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
3389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktypedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
3409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace clang {
3429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace ento {
3439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktemplate<>
3449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstruct ProgramStateTrait<RefBindings>
345e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  : public ProgramStatePartialTrait<RefBindings> {
346e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  static void *GDMIndex() {
347e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    static int RefBIndex = 0;
348e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    return &RefBIndex;
349e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  }
350e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott};
351e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott}
3529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
3539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
3559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Function/Method behavior summaries.
3569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
3579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace {
3599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass RetainSummary {
3609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Args - a map of (index, ArgEffect) pairs, where index
3619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  specifies the argument (starting from 0).  This can be sparsely
3629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
3639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffects Args;
3649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// DefaultArgEffect - The default ArgEffect to apply to arguments that
3669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  do not have an entry in Args.
3679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffect DefaultArgEffect;
3689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Receiver - If this summary applies to an Objective-C message expression,
3709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  this is the effect applied to the state of the receiver.
3719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffect Receiver;
3729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Ret - The effect on the return value.  Used to indicate if the
3749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  function/method call returns a new tracked symbol.
3759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect Ret;
3769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
3789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
3799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                ArgEffect ReceiverEff)
3809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
3819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// getArg - Return the argument effect on the argument specified by
3839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  idx (starting from 0).
3849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffect getArg(unsigned idx) const {
385e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    if (const ArgEffect *AE = Args.lookup(idx))
386e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      return *AE;
3879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return DefaultArgEffect;
3899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
3909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
3929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Args = af.add(Args, idx, e);
3939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
3949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
3959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// setDefaultArgEffect - Set the default argument effect.
3969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void setDefaultArgEffect(ArgEffect E) {
3979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    DefaultArgEffect = E;
3989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
3999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// getRetEffect - Returns the effect on the return value of the call.
4019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect getRetEffect() const { return Ret; }
4029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// setRetEffect - Set the effect of the return value of the call.
4049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void setRetEffect(RetEffect E) { Ret = E; }
4059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Sets the effect on the receiver of the message.
4089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void setReceiverEffect(ArgEffect e) { Receiver = e; }
4099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// getReceiverEffect - Returns the effect on the receiver of the call.
4119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
4129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffect getReceiverEffect() const { return Receiver; }
4139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Test if two retain summaries are identical. Note that merely equivalent
4159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// summaries are not necessarily identical (for example, if an explicit
4169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// argument effect matches the default effect).
4179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool operator==(const RetainSummary &Other) const {
4189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
4199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block           Receiver == Other.Receiver && Ret == Other.Ret;
4209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Profile this summary for inclusion in a FoldingSet.
4239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void Profile(llvm::FoldingSetNodeID& ID) const {
4249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.Add(Args);
4259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.Add(DefaultArgEffect);
4269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.Add(Receiver);
4279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ID.Add(Ret);
428e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  }
4299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// A retain summary is simple if it has no ArgEffects other than the default.
4319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isSimple() const {
4329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return Args.isEmpty();
4339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
4359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end anonymous namespace
4369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
4389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Data structures for constructing summaries.
4399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
4409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace {
4429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass ObjCSummaryKey {
4439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  IdentifierInfo* II;
4449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Selector S;
4459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
4469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCSummaryKey(IdentifierInfo* ii, Selector s)
4479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    : II(ii), S(s) {}
4489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
4509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    : II(d ? d->getIdentifier() : 0), S(s) {}
4519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
4539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    : II(d ? d->getIdentifier() : ii), S(s) {}
4549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCSummaryKey(Selector s)
4569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    : II(0), S(s) {}
4579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  IdentifierInfo *getIdentifier() const { return II; }
4599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Selector getSelector() const { return S; }
4609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
4619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
4629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace llvm {
4649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktemplate <> struct DenseMapInfo<ObjCSummaryKey> {
4659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static inline ObjCSummaryKey getEmptyKey() {
4669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
4679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                          DenseMapInfo<Selector>::getEmptyKey());
4689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static inline ObjCSummaryKey getTombstoneKey() {
4719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
4729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                          DenseMapInfo<Selector>::getTombstoneKey());
4739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static unsigned getHashValue(const ObjCSummaryKey &V) {
4769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
4779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block            & 0x88888888)
4789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
4799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block            & 0x55555555);
4809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
483e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
4849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                                  RHS.getIdentifier()) &&
4859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block           DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
4869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                           RHS.getSelector());
4879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
4889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
4909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocktemplate <>
4919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstruct isPodLike<ObjCSummaryKey> { static const bool value = true; };
4929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end llvm namespace
4939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
4949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace {
4959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass ObjCSummaryCache {
4969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
4979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  MapTy M;
4989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
4999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCSummaryCache() {}
5009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
5029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                Selector S) {
5039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Lookup the method using the decl for the class @interface.  If we
5049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // have no decl, lookup using the class name.
5059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return D ? find(D, S) : find(ClsName, S);
506e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  }
5079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
5099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Do a lookup with the (D,S) pair.  If we find a match return
5109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // the iterator.
5119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCSummaryKey K(D, S);
5129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    MapTy::iterator I = M.find(K);
5139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (I != M.end() || !D)
5159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      return I->second;
5169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Walk the super chain.  If we find a hit with a parent, we'll end
5189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // up returning that summary.  We actually allow that key (null,S), as
5199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // we cache summaries for the null ObjCInterfaceDecl* to allow us to
5209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // generate initial summaries without having to worry about NSObject
521e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // being declared.
522e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // FIXME: We may change this at some point.
523e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
524e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
525e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        break;
526e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
527e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      if (!C)
528e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        return NULL;
529e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    }
530e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
531e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // Cache the summary with original key to make the next lookup faster
532e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // and return the iterator.
533e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    const RetainSummary *Summ = I->second;
534e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    M[K] = Summ;
535e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    return Summ;
536e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  }
5379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *find(IdentifierInfo* II, Selector S) {
539e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // FIXME: Class method lookup.  Right now we dont' have a good way
540e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // of going between IdentifierInfo* and the class hierarchy.
5419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
5429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (I == M.end())
5449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      I = M.find(ObjCSummaryKey(S));
5459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return I == M.end() ? NULL : I->second;
5479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
5489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *& operator[](ObjCSummaryKey K) {
5509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return M[K];
5519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
5529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *& operator[](Selector S) {
554e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    return M[ ObjCSummaryKey(S) ];
5559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
556e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott};
5579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end anonymous namespace
5589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
5609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Data structures for managing collections of summaries.
5619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
5629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blocknamespace {
5649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockclass RetainSummaryManager {
5659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
5679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //  Typedefs.
5689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
5699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
5719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          FuncSummariesTy;
5729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  typedef ObjCSummaryCache ObjCMethodSummariesTy;
5749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
5769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
5789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //  Data.
5799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
5809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Ctx - The ASTContext object for the analyzed ASTs.
5829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ASTContext &Ctx;
5839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
5859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const bool GCEnabled;
5869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// Records whether or not the analyzed code runs in ARC mode.
5889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const bool ARCEnabled;
5899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// FuncSummaries - A map from FunctionDecls to summaries.
5919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  FuncSummariesTy FuncSummaries;
5929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
5949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  to summaries.
5959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCMethodSummariesTy ObjCClassMethodSummaries;
5969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
5979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// ObjCMethodSummaries - A map from selectors to summaries.
5989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ObjCMethodSummariesTy ObjCMethodSummaries;
5999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
6019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  and all other data used by the checker.
6029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  llvm::BumpPtrAllocator BPAlloc;
6039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// AF - A factory for ArgEffects objects.
6059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffects::Factory AF;
6069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// ScratchArgs - A holding buffer for construct ArgEffects.
6089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffects ScratchArgs;
6099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// ObjCAllocRetE - Default return effect for methods returning Objective-C
6119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  objects.
6129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect ObjCAllocRetE;
613e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
614e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  /// ObjCInitRetE - Default return effect for init methods returning
615e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  ///   Objective-C objects.
616e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  RetEffect ObjCInitRetE;
617e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
618e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  /// SimpleSummaries - Used for uniquing summaries that don't have special
6199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// effects.
6209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
6219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
6239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //  Methods.
6249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  //==-----------------------------------------------------------------==//
6259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// getArgEffects - Returns a persistent ArgEffects object based on the
6279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  data in ScratchArgs.
6289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffects getArgEffects();
6299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
6319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
6339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
6349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getUnarySummary(const FunctionType* FT,
6369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                       UnaryFuncKind func);
6379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
638e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
6399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
640e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
6419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
6439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getPersistentSummary(RetEffect RetEff,
6459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                            ArgEffect ReceiverEff = DoNothing,
6469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                            ArgEffect DefaultEff = MayEscape) {
6479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
6489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getPersistentSummary(Summ);
6499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getDefaultSummary() {
6529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getPersistentSummary(RetEffect::MakeNoRet(),
6539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                DoNothing, MayEscape);
6549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getPersistentStopSummary() {
6579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getPersistentSummary(RetEffect::MakeNoRet(),
6589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                StopTracking, StopTracking);
6599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void InitializeClassMethodSummaries();
6629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void InitializeMethodSummaries();
6639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockprivate:
6649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
6659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCClassMethodSummaries[S] = Summ;
6669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
6699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCMethodSummaries[S] = Summ;
6709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addClassMethSummary(const char* Cls, const char* name,
6739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                           const RetainSummary *Summ, bool isNullary = true) {
6749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
6759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Selector S = isNullary ? GetNullarySelector(name, Ctx)
6769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                           : GetUnarySelector(name, Ctx);
6779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
6789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addInstMethSummary(const char* Cls, const char* nullaryName,
6819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                          const RetainSummary *Summ) {
6829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
6839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Selector S = GetNullarySelector(nullaryName, Ctx);
6849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
6859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  Selector generateSelector(va_list argp) {
6889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    SmallVector<IdentifierInfo*, 10> II;
6899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    while (const char* s = va_arg(argp, const char*))
6919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      II.push_back(&Ctx.Idents.get(s));
6929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return Ctx.Selectors.getSelector(II.size(), &II[0]);
6949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
6959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
6969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
6979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                        const RetainSummary * Summ, va_list argp) {
6989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Selector S = generateSelector(argp);
6999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
7009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
7039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_list argp;
7049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_start(argp, Summ);
7059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
7069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_end(argp);
7079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
7109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_list argp;
7119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_start(argp, Summ);
7129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
7139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_end(argp);
7149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
7179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_list argp;
7189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_start(argp, Summ);
7199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
7209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    va_end(argp);
7219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
7249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
7269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block   : Ctx(ctx),
7279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block     GCEnabled(gcenabled),
7289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block     ARCEnabled(usesARC),
7299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block     AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
7309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block     ObjCAllocRetE(gcenabled
7319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                    ? RetEffect::MakeGCNotOwned()
7329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                    : (usesARC ? RetEffect::MakeARCNotOwned()
7339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                               : RetEffect::MakeOwned(RetEffect::ObjC, true))),
7349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block     ObjCInitRetE(gcenabled
7359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                    ? RetEffect::MakeGCNotOwned()
7369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                    : (usesARC ? RetEffect::MakeARCNotOwned()
7379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                               : RetEffect::MakeOwnedWhenTrackedReceiver())) {
7389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    InitializeClassMethodSummaries();
7399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    InitializeMethodSummaries();
7409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getSummary(const FunctionDecl *FD);
7439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName,
7459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                        const ObjCInterfaceDecl *ID,
7469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                        const ObjCMethodDecl *MD,
7479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                        QualType RetTy,
7489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                        ObjCMethodSummariesTy &CachedSummaries);
7499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
7519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                                ProgramStateRef state,
7529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                                const LocationContext *LC);
7539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
7559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                                const ObjCInterfaceDecl *ID) {
7569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
7579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                            msg.getType(Ctx), ObjCMethodSummaries);
7589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
7619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    const ObjCInterfaceDecl *Class = 0;
7629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (!msg.isInstanceMessage())
7639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      Class = msg.getReceiverInterface();
7649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
7669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                            Class, msg.getMethodDecl(), msg.getType(Ctx),
7679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                            ObjCClassMethodSummaries);
7689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  /// getMethodSummary - This version of getMethodSummary is used to query
7719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ///  the summary for the current method being analyzed.
7729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
7739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // FIXME: Eventually this should be unneeded.
7749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    const ObjCInterfaceDecl *ID = MD->getClassInterface();
7759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Selector S = MD->getSelector();
7769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    IdentifierInfo *ClsName = ID->getIdentifier();
7779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    QualType ResultTy = MD->getResultType();
7789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    ObjCMethodSummariesTy *CachedSummaries;
7809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (MD->isInstanceMethod())
7819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      CachedSummaries = &ObjCMethodSummaries;
7829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    else
7839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      CachedSummaries = &ObjCClassMethodSummaries;
7849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries);
7869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
7879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
7899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                              Selector S, QualType RetTy);
7909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
7929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                    const ObjCMethodDecl *MD);
7939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
7959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                                    const FunctionDecl *FD);
7969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isGCEnabled() const { return GCEnabled; }
7989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
7999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isARCEnabled() const { return ARCEnabled; }
8009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
8029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
8039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
8059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// summaries. If a function or method looks like it has a default summary, but
806e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott// it has annotations, the annotations are added to the stack-based template
807e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott// and then copied into managed memory.
808e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scottclass RetainSummaryTemplate {
809e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  RetainSummaryManager &Manager;
810e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  const RetainSummary *&RealSummary;
811e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott  RetainSummary ScratchSummary;
8129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  bool Accessed;
8139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockpublic:
8149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base,
8159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                        RetainSummaryManager &mgr)
8169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
8179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Accessed(false) {}
8189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ~RetainSummaryTemplate() {
8209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (Accessed)
8219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      RealSummary = Manager.getPersistentSummary(ScratchSummary);
8229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
8239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummary &operator*() {
8259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Accessed = true;
8269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return ScratchSummary;
8279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
8289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummary *operator->() {
8309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    Accessed = true;
8319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return &ScratchSummary;
8329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
8339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block};
8349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block} // end anonymous namespace
8369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
837e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott//===----------------------------------------------------------------------===//
8389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Implementation of checker data structures.
8399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
840e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
8419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve BlockArgEffects RetainSummaryManager::getArgEffects() {
8429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ArgEffects AE = ScratchArgs;
8439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  ScratchArgs = AF.getEmptyMap();
8449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  return AE;
8459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
8469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockconst RetainSummary *
8489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve BlockRetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
8499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // Unique "simple" summaries -- those without ArgEffects.
8509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  if (OldSumm.isSimple()) {
8519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    llvm::FoldingSetNodeID ID;
8529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    OldSumm.Profile(ID);
8539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    void *Pos;
8559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
8569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (!N) {
8589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
8599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      new (N) CachedSummaryNode(OldSumm);
8609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      SimpleSummaries.InsertNode(N, Pos);
8619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
8629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return &N->getValue();
8649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  }
8659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
8679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  new (Summ) RetainSummary(OldSumm);
8689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  return Summ;
8699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
8709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
8729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block// Summary creation for functions (largely uses of Core Foundation).
8739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block//===----------------------------------------------------------------------===//
8749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstatic bool isRetain(const FunctionDecl *FD, StringRef FName) {
8769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  return FName.endswith("Retain");
8779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
8789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstatic bool isRelease(const FunctionDecl *FD, StringRef FName) {
8809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  return FName.endswith("Release");
8819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
8829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockstatic bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
8849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // FIXME: Remove FunctionDecl parameter.
8859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // FIXME: Is it really okay if MakeCollectable isn't a suffix?
8869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  return FName.find("MakeCollectable") != StringRef::npos;
8879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block}
8889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Blockconst RetainSummary * RetainSummaryManager::getSummary(const FunctionDecl *FD) {
8909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // Look up a summary in our cache of FunctionDecls -> Summaries.
8919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
8929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  if (I != FuncSummaries.end())
8939720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    return I->second;
8949720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  // No summary?  Generate one.
8969720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  const RetainSummary *S = 0;
8979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
8989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block  do {
8999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // We generate "stop" summaries for implicitly defined functions.
9009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (FD->isImplicit()) {
9019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentStopSummary();
9029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
9039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
9049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // For C++ methods, generate an implicit "stop" summary as well.  We
9059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // can relax this once we have a clear policy for C++ methods and
9069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // ownership attributes.
9079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (isa<CXXMethodDecl>(FD)) {
9089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentStopSummary();
9099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
9109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
9119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
9129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
9139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // function's type.
9149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    const FunctionType* FT = FD->getType()->getAs<FunctionType>();
9159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    const IdentifierInfo *II = FD->getIdentifier();
9169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (!II)
9179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
9189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
9199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    StringRef FName = II->getName();
9209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
9219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Strip away preceding '_'.  Doing this here will effect all the checks
9229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // down below.
923e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    FName = FName.substr(FName.find_first_not_of('_'));
924e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
925e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // Inspect the result type.
926e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    QualType RetTy = FT->getResultType();
927e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
928e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // FIXME: This should all be refactored into a chain of "summary lookup"
9299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    //  filters.
9309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    assert(ScratchArgs.isEmpty());
9319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
9329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (FName == "pthread_create" || FName == "pthread_setspecific") {
9339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
9349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // This will be addressed better with IPA.
9359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentStopSummary();
9369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "NSMakeCollectable") {
937e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      // Handle: id NSMakeCollectable(CFTypeRef)
9389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = (RetTy->isObjCIdType())
9399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          ? getUnarySummary(FT, cfmakecollectable)
9409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          : getPersistentStopSummary();
9419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "IOBSDNameMatching" ||
9429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IOServiceMatching" ||
9439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IOServiceNameMatching" ||
9449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IORegistryEntrySearchCFProperty" ||
9459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IORegistryEntryIDMatching" ||
9469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IOOpenFirmwarePathMatching") {
9479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Part of <rdar://problem/6961230>. (IOKit)
9489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // This should be addressed using a API table.
9499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
9509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                               DoNothing, DoNothing);
9519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "IOServiceGetMatchingService" ||
9529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IOServiceGetMatchingServices") {
9539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // FIXES: <rdar://problem/6326900>
9549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // This should be addressed using a API table.  This strcmp is also
9559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // a little gross, but there is no need to super optimize here.
9569720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
9579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
9589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "IOServiceAddNotification" ||
9599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block               FName == "IOServiceAddMatchingNotification") {
9609720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Part of <rdar://problem/6961230>. (IOKit)
9619720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // This should be addressed using a API table.
9629720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
9639720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
9649720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "CVPixelBufferCreateWithBytes") {
9659720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // FIXES: <rdar://problem/7283567>
9669720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Eventually this can be improved by recognizing that the pixel
9679720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // buffer passed to CVPixelBufferCreateWithBytes is released via
9689720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // a callback and doing full IPA to make sure this is done correctly.
9699720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // FIXME: This function has an out parameter that returns an
9709720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // allocated object.
9719720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
9729720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
9739720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "CGBitmapContextCreateWithData") {
9749720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // FIXES: <rdar://problem/7358899>
9759720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Eventually this can be improved by recognizing that 'releaseInfo'
9769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // passed to CGBitmapContextCreateWithData is released via
9779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // a callback and doing full IPA to make sure this is done correctly.
9789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
9799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
9809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                               DoNothing, DoNothing);
9819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
9829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // FIXES: <rdar://problem/7283567>
9839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Eventually this can be improved by recognizing that the pixel
9849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
9859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // via a callback and doing full IPA to make sure this is done
9869720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // correctly.
9879720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
9889720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
9899720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName == "dispatch_set_context") {
9909720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // <rdar://problem/11059275> - The analyzer currently doesn't have
9919720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // a good way to reason about the finalizer function for libdispatch.
9929720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // If we pass a context object that is memory managed, stop tracking it.
993e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      // FIXME: this hack should possibly go away once we can handle
994e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      // libdispatch finalizers.
9959720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
996e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
9979720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    } else if (FName.startswith("NS") &&
9989720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                (FName.find("Insert") != StringRef::npos)) {
9999720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
10009720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // be deallocated by NSMapRemove. (radar://11152419)
10019720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
10029720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
10039720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
10049720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
10059720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10069720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Did we get a summary?
10079720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (S)
10089720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
10099720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10109720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Enable this code once the semantics of NSDeallocateObject are resolved
10119720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // for GC.  <rdar://problem/6619988>
10129720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#if 0
10139720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // Handle: NSDeallocateObject(id anObject);
10149720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // This method does allow 'nil' (although we don't check it now).
10159720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (strcmp(FName, "NSDeallocateObject") == 0) {
10169720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      return RetTy == Ctx.VoidTy
10179720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
10189720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        : getPersistentStopSummary();
10199720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
10209720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block#endif
10219720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10229720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (RetTy->isPointerType()) {
10239720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // For CoreFoundation ('CF') types.
10249720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cocoa::isRefType(RetTy, "CF", FName)) {
10259720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        if (isRetain(FD, FName))
10269720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          S = getUnarySummary(FT, cfretain);
10279720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        else if (isMakeCollectable(FD, FName))
10289720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          S = getUnarySummary(FT, cfmakecollectable);
10299720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        else
10309720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          S = getCFCreateGetRuleSummary(FD);
10319720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10329720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        break;
10339720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      }
10349720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10359720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // For CoreGraphics ('CG') types.
10369720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cocoa::isRefType(RetTy, "CG", FName)) {
10379720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        if (isRetain(FD, FName))
10389720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          S = getUnarySummary(FT, cfretain);
10399720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        else
10409720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          S = getCFCreateGetRuleSummary(FD);
10419720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10429720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        break;
10439720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      }
10449720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10459720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // For the Disk Arbitration API (DiskArbitration/DADisk.h)
10469720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      if (cocoa::isRefType(RetTy, "DADisk") ||
10479720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          cocoa::isRefType(RetTy, "DADissenter") ||
10489720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block          cocoa::isRefType(RetTy, "DASessionRef")) {
10499720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        S = getCFCreateGetRuleSummary(FD);
10509720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        break;
10519720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      }
10529720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
10539720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      break;
10549720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    }
10559720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block
1056e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott    // Check for release functions, the only kind of functions that we care
10579720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    // about that don't return a pointer type.
10589720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block    if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
10599720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block      // Test for 'CGCF'.
1060e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1061e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott
1062e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      if (isRelease(FD, FName))
1063e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        S = getUnarySummary(FT, cfrelease);
1064e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott      else {
1065e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        assert (ScratchArgs.isEmpty());
1066e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        // Remaining CoreFoundation and CoreGraphics functions.
1067e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        // We use to assume that they all strictly followed the ownership idiom
1068e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        // and that ownership cannot be transferred.  While this is technically
1069e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        // correct, many methods allow a tracked object to escape.  For example:
1070e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //
1071e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1072e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //   CFDictionaryAddValue(y, key, x);
1073e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //   CFRelease(x);
1074e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //   ... it is okay to use 'x' since 'y' has a reference to it
1075e46c9386c4f79aa40185f79a19fc5b2a7ef528b3Patrick Scott        //
10769720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        // We handle this and similar cases with the follow heuristic.  If the
10779720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        // function name contains "InsertValue", "SetValue", "AddValue",
10789720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        // "AppendValue", or "SetAttribute", then we assume that arguments may
10799720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        // "escape."  This means that something else holds on to the object,
10809720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        // allowing it be used even after its local retain count drops to 0.
10819720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block        ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
10829720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                       StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
10839720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                       StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
10849720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                       StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
10859720d5f59b9c1f5d1b9ecbc9173dbcb71bd557beSteve Block                       StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1086                      ? MayEscape : DoNothing;
1087
1088        S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1089      }
1090    }
1091  }
1092  while (0);
1093
1094  // Annotations override defaults.
1095  updateSummaryFromAnnotations(S, FD);
1096
1097  FuncSummaries[FD] = S;
1098  return S;
1099}
1100
1101const RetainSummary *
1102RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1103  if (coreFoundation::followsCreateRule(FD))
1104    return getCFSummaryCreateRule(FD);
1105
1106  return getCFSummaryGetRule(FD);
1107}
1108
1109const RetainSummary *
1110RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1111                                      UnaryFuncKind func) {
1112
1113  // Sanity check that this is *really* a unary function.  This can
1114  // happen if people do weird things.
1115  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1116  if (!FTP || FTP->getNumArgs() != 1)
1117    return getPersistentStopSummary();
1118
1119  assert (ScratchArgs.isEmpty());
1120
1121  ArgEffect Effect;
1122  switch (func) {
1123    case cfretain: Effect = IncRef; break;
1124    case cfrelease: Effect = DecRef; break;
1125    case cfmakecollectable: Effect = MakeCollectable; break;
1126  }
1127
1128  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1129  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1130}
1131
1132const RetainSummary *
1133RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1134  assert (ScratchArgs.isEmpty());
1135
1136  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1137}
1138
1139const RetainSummary *
1140RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1141  assert (ScratchArgs.isEmpty());
1142  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1143                              DoNothing, DoNothing);
1144}
1145
1146//===----------------------------------------------------------------------===//
1147// Summary creation for Selectors.
1148//===----------------------------------------------------------------------===//
1149
1150void
1151RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1152                                                   const FunctionDecl *FD) {
1153  if (!FD)
1154    return;
1155
1156  RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
1157
1158  // Effects on the parameters.
1159  unsigned parm_idx = 0;
1160  for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1161         pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1162    const ParmVarDecl *pd = *pi;
1163    if (pd->getAttr<NSConsumedAttr>()) {
1164      if (!GCEnabled) {
1165        Template->addArg(AF, parm_idx, DecRef);
1166      }
1167    } else if (pd->getAttr<CFConsumedAttr>()) {
1168      Template->addArg(AF, parm_idx, DecRef);
1169    }
1170  }
1171
1172  QualType RetTy = FD->getResultType();
1173
1174  // Determine if there is a special return effect for this method.
1175  if (cocoa::isCocoaObjectRef(RetTy)) {
1176    if (FD->getAttr<NSReturnsRetainedAttr>()) {
1177      Template->setRetEffect(ObjCAllocRetE);
1178    }
1179    else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1180      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1181    }
1182    else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
1183      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1184    }
1185    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1186      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1187    }
1188  } else if (RetTy->getAs<PointerType>()) {
1189    if (FD->getAttr<CFReturnsRetainedAttr>()) {
1190      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1191    }
1192    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1193      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1194    }
1195  }
1196}
1197
1198void
1199RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1200                                                   const ObjCMethodDecl *MD) {
1201  if (!MD)
1202    return;
1203
1204  RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
1205  bool isTrackedLoc = false;
1206
1207  // Effects on the receiver.
1208  if (MD->getAttr<NSConsumesSelfAttr>()) {
1209    if (!GCEnabled)
1210      Template->setReceiverEffect(DecRefMsg);
1211  }
1212
1213  // Effects on the parameters.
1214  unsigned parm_idx = 0;
1215  for (ObjCMethodDecl::param_const_iterator
1216         pi=MD->param_begin(), pe=MD->param_end();
1217       pi != pe; ++pi, ++parm_idx) {
1218    const ParmVarDecl *pd = *pi;
1219    if (pd->getAttr<NSConsumedAttr>()) {
1220      if (!GCEnabled)
1221        Template->addArg(AF, parm_idx, DecRef);
1222    }
1223    else if(pd->getAttr<CFConsumedAttr>()) {
1224      Template->addArg(AF, parm_idx, DecRef);
1225    }
1226  }
1227
1228  // Determine if there is a special return effect for this method.
1229  if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1230    if (MD->getAttr<NSReturnsRetainedAttr>()) {
1231      Template->setRetEffect(ObjCAllocRetE);
1232      return;
1233    }
1234    if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
1235      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1236      return;
1237    }
1238
1239    isTrackedLoc = true;
1240  } else {
1241    isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1242  }
1243
1244  if (isTrackedLoc) {
1245    if (MD->getAttr<CFReturnsRetainedAttr>())
1246      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1247    else if (MD->getAttr<CFReturnsNotRetainedAttr>())
1248      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1249  }
1250}
1251
1252const RetainSummary *
1253RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1254                                               Selector S, QualType RetTy) {
1255
1256  if (MD) {
1257    // Scan the method decl for 'void*' arguments.  These should be treated
1258    // as 'StopTracking' because they are often used with delegates.
1259    // Delegates are a frequent form of false positives with the retain
1260    // count checker.
1261    unsigned i = 0;
1262    for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
1263         E = MD->param_end(); I != E; ++I, ++i)
1264      if (const ParmVarDecl *PD = *I) {
1265        QualType Ty = Ctx.getCanonicalType(PD->getType());
1266        if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
1267          ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
1268      }
1269  }
1270
1271  // Any special effects?
1272  ArgEffect ReceiverEff = DoNothing;
1273  RetEffect ResultEff = RetEffect::MakeNoRet();
1274
1275  // Check the method family, and apply any default annotations.
1276  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1277    case OMF_None:
1278    case OMF_performSelector:
1279      // Assume all Objective-C methods follow Cocoa Memory Management rules.
1280      // FIXME: Does the non-threaded performSelector family really belong here?
1281      // The selector could be, say, @selector(copy).
1282      if (cocoa::isCocoaObjectRef(RetTy))
1283        ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1284      else if (coreFoundation::isCFObjectRef(RetTy)) {
1285        // ObjCMethodDecl currently doesn't consider CF objects as valid return
1286        // values for alloc, new, copy, or mutableCopy, so we have to
1287        // double-check with the selector. This is ugly, but there aren't that
1288        // many Objective-C methods that return CF objects, right?
1289        if (MD) {
1290          switch (S.getMethodFamily()) {
1291          case OMF_alloc:
1292          case OMF_new:
1293          case OMF_copy:
1294          case OMF_mutableCopy:
1295            ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1296            break;
1297          default:
1298            ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1299            break;
1300          }
1301        } else {
1302          ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1303        }
1304      }
1305      break;
1306    case OMF_init:
1307      ResultEff = ObjCInitRetE;
1308      ReceiverEff = DecRefMsg;
1309      break;
1310    case OMF_alloc:
1311    case OMF_new:
1312    case OMF_copy:
1313    case OMF_mutableCopy:
1314      if (cocoa::isCocoaObjectRef(RetTy))
1315        ResultEff = ObjCAllocRetE;
1316      else if (coreFoundation::isCFObjectRef(RetTy))
1317        ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1318      break;
1319    case OMF_autorelease:
1320      ReceiverEff = Autorelease;
1321      break;
1322    case OMF_retain:
1323      ReceiverEff = IncRefMsg;
1324      break;
1325    case OMF_release:
1326      ReceiverEff = DecRefMsg;
1327      break;
1328    case OMF_dealloc:
1329      ReceiverEff = Dealloc;
1330      break;
1331    case OMF_self:
1332      // -self is handled specially by the ExprEngine to propagate the receiver.
1333      break;
1334    case OMF_retainCount:
1335    case OMF_finalize:
1336      // These methods don't return objects.
1337      break;
1338  }
1339
1340  // If one of the arguments in the selector has the keyword 'delegate' we
1341  // should stop tracking the reference count for the receiver.  This is
1342  // because the reference count is quite possibly handled by a delegate
1343  // method.
1344  if (S.isKeywordSelector()) {
1345    const std::string &str = S.getAsString();
1346    assert(!str.empty());
1347    if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1348      ReceiverEff = StopTracking;
1349  }
1350
1351  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1352      ResultEff.getKind() == RetEffect::NoRet)
1353    return getDefaultSummary();
1354
1355  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1356}
1357
1358const RetainSummary *
1359RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
1360                                               ProgramStateRef state,
1361                                               const LocationContext *LC) {
1362
1363  // We need the type-information of the tracked receiver object
1364  // Retrieve it from the state.
1365  const Expr *Receiver = msg.getInstanceReceiver();
1366  const ObjCInterfaceDecl *ID = 0;
1367
1368  // FIXME: Is this really working as expected?  There are cases where
1369  //  we just use the 'ID' from the message expression.
1370  SVal receiverV;
1371
1372  if (Receiver) {
1373    receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
1374
1375    // FIXME: Eventually replace the use of state->get<RefBindings> with
1376    // a generic API for reasoning about the Objective-C types of symbolic
1377    // objects.
1378    if (SymbolRef Sym = receiverV.getAsLocSymbol())
1379      if (const RefVal *T = state->get<RefBindings>(Sym))
1380        if (const ObjCObjectPointerType* PT =
1381            T->getType()->getAs<ObjCObjectPointerType>())
1382          ID = PT->getInterfaceDecl();
1383
1384    // FIXME: this is a hack.  This may or may not be the actual method
1385    //  that is called.
1386    if (!ID) {
1387      if (const ObjCObjectPointerType *PT =
1388          Receiver->getType()->getAs<ObjCObjectPointerType>())
1389        ID = PT->getInterfaceDecl();
1390    }
1391  } else {
1392    // FIXME: Hack for 'super'.
1393    ID = msg.getReceiverInterface();
1394  }
1395
1396  // FIXME: The receiver could be a reference to a class, meaning that
1397  //  we should use the class method.
1398  return getInstanceMethodSummary(msg, ID);
1399}
1400
1401const RetainSummary *
1402RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
1403                                       const ObjCInterfaceDecl *ID,
1404                                       const ObjCMethodDecl *MD, QualType RetTy,
1405                                       ObjCMethodSummariesTy &CachedSummaries) {
1406
1407  // Look up a summary in our summary cache.
1408  const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S);
1409
1410  if (!Summ) {
1411    Summ = getStandardMethodSummary(MD, S, RetTy);
1412
1413    // Annotations override defaults.
1414    updateSummaryFromAnnotations(Summ, MD);
1415
1416    // Memoize the summary.
1417    CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1418  }
1419
1420  return Summ;
1421}
1422
1423void RetainSummaryManager::InitializeClassMethodSummaries() {
1424  assert(ScratchArgs.isEmpty());
1425  // Create the [NSAssertionHandler currentHander] summary.
1426  addClassMethSummary("NSAssertionHandler", "currentHandler",
1427                getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1428
1429  // Create the [NSAutoreleasePool addObject:] summary.
1430  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1431  addClassMethSummary("NSAutoreleasePool", "addObject",
1432                      getPersistentSummary(RetEffect::MakeNoRet(),
1433                                           DoNothing, Autorelease));
1434
1435  // Create the summaries for [NSObject performSelector...].  We treat
1436  // these as 'stop tracking' for the arguments because they are often
1437  // used for delegates that can release the object.  When we have better
1438  // inter-procedural analysis we can potentially do something better.  This
1439  // workaround is to remove false positives.
1440  const RetainSummary *Summ =
1441    getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1442  IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1443  addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1444                    "afterDelay", NULL);
1445  addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1446                    "afterDelay", "inModes", NULL);
1447  addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1448                    "withObject", "waitUntilDone", NULL);
1449  addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1450                    "withObject", "waitUntilDone", "modes", NULL);
1451  addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1452                    "withObject", "waitUntilDone", NULL);
1453  addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1454                    "withObject", "waitUntilDone", "modes", NULL);
1455  addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1456                    "withObject", NULL);
1457}
1458
1459void RetainSummaryManager::InitializeMethodSummaries() {
1460
1461  assert (ScratchArgs.isEmpty());
1462
1463  // Create the "init" selector.  It just acts as a pass-through for the
1464  // receiver.
1465  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1466  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1467
1468  // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1469  // claims the receiver and returns a retained object.
1470  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1471                         InitSumm);
1472
1473  // The next methods are allocators.
1474  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1475  const RetainSummary *CFAllocSumm =
1476    getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1477
1478  // Create the "retain" selector.
1479  RetEffect NoRet = RetEffect::MakeNoRet();
1480  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1481  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1482
1483  // Create the "release" selector.
1484  Summ = getPersistentSummary(NoRet, DecRefMsg);
1485  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1486
1487  // Create the "drain" selector.
1488  Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
1489  addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
1490
1491  // Create the -dealloc summary.
1492  Summ = getPersistentSummary(NoRet, Dealloc);
1493  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1494
1495  // Create the "autorelease" selector.
1496  Summ = getPersistentSummary(NoRet, Autorelease);
1497  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1498
1499  // Specially handle NSAutoreleasePool.
1500  addInstMethSummary("NSAutoreleasePool", "init",
1501                     getPersistentSummary(NoRet, NewAutoreleasePool));
1502
1503  // For NSWindow, allocated objects are (initially) self-owned.
1504  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1505  //  self-own themselves.  However, they only do this once they are displayed.
1506  //  Thus, we need to track an NSWindow's display status.
1507  //  This is tracked in <rdar://problem/6062711>.
1508  //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1509  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1510                                                   StopTracking,
1511                                                   StopTracking);
1512
1513  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1514
1515#if 0
1516  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1517                     "styleMask", "backing", "defer", NULL);
1518
1519  addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
1520                     "styleMask", "backing", "defer", "screen", NULL);
1521#endif
1522
1523  // For NSPanel (which subclasses NSWindow), allocated objects are not
1524  //  self-owned.
1525  // FIXME: For now we don't track NSPanels. object for the same reason
1526  //   as for NSWindow objects.
1527  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1528
1529#if 0
1530  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1531                     "styleMask", "backing", "defer", NULL);
1532
1533  addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
1534                     "styleMask", "backing", "defer", "screen", NULL);
1535#endif
1536
1537  // Don't track allocated autorelease pools yet, as it is okay to prematurely
1538  // exit a method.
1539  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1540  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1541
1542  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1543  addInstMethSummary("QCRenderer", AllocSumm,
1544                     "createSnapshotImageOfType", NULL);
1545  addInstMethSummary("QCView", AllocSumm,
1546                     "createSnapshotImageOfType", NULL);
1547
1548  // Create summaries for CIContext, 'createCGImage' and
1549  // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1550  // automatically garbage collected.
1551  addInstMethSummary("CIContext", CFAllocSumm,
1552                     "createCGImage", "fromRect", NULL);
1553  addInstMethSummary("CIContext", CFAllocSumm,
1554                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
1555  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1556           "info", NULL);
1557}
1558
1559//===----------------------------------------------------------------------===//
1560// AutoreleaseBindings - State used to track objects in autorelease pools.
1561//===----------------------------------------------------------------------===//
1562
1563typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1564typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1565typedef llvm::ImmutableList<SymbolRef> ARStack;
1566
1567static int AutoRCIndex = 0;
1568static int AutoRBIndex = 0;
1569
1570namespace { class AutoreleasePoolContents {}; }
1571namespace { class AutoreleaseStack {}; }
1572
1573namespace clang {
1574namespace ento {
1575template<> struct ProgramStateTrait<AutoreleaseStack>
1576  : public ProgramStatePartialTrait<ARStack> {
1577  static inline void *GDMIndex() { return &AutoRBIndex; }
1578};
1579
1580template<> struct ProgramStateTrait<AutoreleasePoolContents>
1581  : public ProgramStatePartialTrait<ARPoolContents> {
1582  static inline void *GDMIndex() { return &AutoRCIndex; }
1583};
1584} // end GR namespace
1585} // end clang namespace
1586
1587static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
1588  ARStack stack = state->get<AutoreleaseStack>();
1589  return stack.isEmpty() ? SymbolRef() : stack.getHead();
1590}
1591
1592static ProgramStateRef
1593SendAutorelease(ProgramStateRef state,
1594                ARCounts::Factory &F,
1595                SymbolRef sym) {
1596  SymbolRef pool = GetCurrentAutoreleasePool(state);
1597  const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
1598  ARCounts newCnts(0);
1599
1600  if (cnts) {
1601    const unsigned *cnt = (*cnts).lookup(sym);
1602    newCnts = F.add(*cnts, sym, cnt ? *cnt  + 1 : 1);
1603  }
1604  else
1605    newCnts = F.add(F.getEmptyMap(), sym, 1);
1606
1607  return state->set<AutoreleasePoolContents>(pool, newCnts);
1608}
1609
1610//===----------------------------------------------------------------------===//
1611// Error reporting.
1612//===----------------------------------------------------------------------===//
1613namespace {
1614  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1615    SummaryLogTy;
1616
1617  //===-------------===//
1618  // Bug Descriptions. //
1619  //===-------------===//
1620
1621  class CFRefBug : public BugType {
1622  protected:
1623    CFRefBug(StringRef name)
1624    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
1625  public:
1626
1627    // FIXME: Eventually remove.
1628    virtual const char *getDescription() const = 0;
1629
1630    virtual bool isLeak() const { return false; }
1631  };
1632
1633  class UseAfterRelease : public CFRefBug {
1634  public:
1635    UseAfterRelease() : CFRefBug("Use-after-release") {}
1636
1637    const char *getDescription() const {
1638      return "Reference-counted object is used after it is released";
1639    }
1640  };
1641
1642  class BadRelease : public CFRefBug {
1643  public:
1644    BadRelease() : CFRefBug("Bad release") {}
1645
1646    const char *getDescription() const {
1647      return "Incorrect decrement of the reference count of an object that is "
1648             "not owned at this point by the caller";
1649    }
1650  };
1651
1652  class DeallocGC : public CFRefBug {
1653  public:
1654    DeallocGC()
1655    : CFRefBug("-dealloc called while using garbage collection") {}
1656
1657    const char *getDescription() const {
1658      return "-dealloc called while using garbage collection";
1659    }
1660  };
1661
1662  class DeallocNotOwned : public CFRefBug {
1663  public:
1664    DeallocNotOwned()
1665    : CFRefBug("-dealloc sent to non-exclusively owned object") {}
1666
1667    const char *getDescription() const {
1668      return "-dealloc sent to object that may be referenced elsewhere";
1669    }
1670  };
1671
1672  class OverAutorelease : public CFRefBug {
1673  public:
1674    OverAutorelease()
1675    : CFRefBug("Object sent -autorelease too many times") {}
1676
1677    const char *getDescription() const {
1678      return "Object sent -autorelease too many times";
1679    }
1680  };
1681
1682  class ReturnedNotOwnedForOwned : public CFRefBug {
1683  public:
1684    ReturnedNotOwnedForOwned()
1685    : CFRefBug("Method should return an owned object") {}
1686
1687    const char *getDescription() const {
1688      return "Object with a +0 retain count returned to caller where a +1 "
1689             "(owning) retain count is expected";
1690    }
1691  };
1692
1693  class Leak : public CFRefBug {
1694    const bool isReturn;
1695  protected:
1696    Leak(StringRef name, bool isRet)
1697    : CFRefBug(name), isReturn(isRet) {
1698      // Leaks should not be reported if they are post-dominated by a sink.
1699      setSuppressOnSink(true);
1700    }
1701  public:
1702
1703    const char *getDescription() const { return ""; }
1704
1705    bool isLeak() const { return true; }
1706  };
1707
1708  class LeakAtReturn : public Leak {
1709  public:
1710    LeakAtReturn(StringRef name)
1711    : Leak(name, true) {}
1712  };
1713
1714  class LeakWithinFunction : public Leak {
1715  public:
1716    LeakWithinFunction(StringRef name)
1717    : Leak(name, false) {}
1718  };
1719
1720  //===---------===//
1721  // Bug Reports.  //
1722  //===---------===//
1723
1724  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1725  protected:
1726    SymbolRef Sym;
1727    const SummaryLogTy &SummaryLog;
1728    bool GCEnabled;
1729
1730  public:
1731    CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1732       : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1733
1734    virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1735      static int x = 0;
1736      ID.AddPointer(&x);
1737      ID.AddPointer(Sym);
1738    }
1739
1740    virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1741                                           const ExplodedNode *PrevN,
1742                                           BugReporterContext &BRC,
1743                                           BugReport &BR);
1744
1745    virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1746                                            const ExplodedNode *N,
1747                                            BugReport &BR);
1748  };
1749
1750  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1751  public:
1752    CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1753                           const SummaryLogTy &log)
1754       : CFRefReportVisitor(sym, GCEnabled, log) {}
1755
1756    PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1757                                    const ExplodedNode *N,
1758                                    BugReport &BR);
1759
1760    virtual BugReporterVisitor *clone() const {
1761      // The curiously-recurring template pattern only works for one level of
1762      // subclassing. Rather than make a new template base for
1763      // CFRefReportVisitor, we simply override clone() to do the right thing.
1764      // This could be trouble someday if BugReporterVisitorImpl is ever
1765      // used for something else besides a convenient implementation of clone().
1766      return new CFRefLeakReportVisitor(*this);
1767    }
1768  };
1769
1770  class CFRefReport : public BugReport {
1771    void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1772
1773  public:
1774    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1775                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1776                bool registerVisitor = true)
1777      : BugReport(D, D.getDescription(), n) {
1778      if (registerVisitor)
1779        addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1780      addGCModeDescription(LOpts, GCEnabled);
1781    }
1782
1783    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1784                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1785                StringRef endText)
1786      : BugReport(D, D.getDescription(), endText, n) {
1787      addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1788      addGCModeDescription(LOpts, GCEnabled);
1789    }
1790
1791    virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
1792      const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1793      if (!BugTy.isLeak())
1794        return BugReport::getRanges();
1795      else
1796        return std::make_pair(ranges_iterator(), ranges_iterator());
1797    }
1798  };
1799
1800  class CFRefLeakReport : public CFRefReport {
1801    const MemRegion* AllocBinding;
1802
1803  public:
1804    CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1805                    const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1806                    CheckerContext &Ctx);
1807
1808    PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1809      assert(Location.isValid());
1810      return Location;
1811    }
1812  };
1813} // end anonymous namespace
1814
1815void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1816                                       bool GCEnabled) {
1817  const char *GCModeDescription = 0;
1818
1819  switch (LOpts.getGC()) {
1820  case LangOptions::GCOnly:
1821    assert(GCEnabled);
1822    GCModeDescription = "Code is compiled to only use garbage collection";
1823    break;
1824
1825  case LangOptions::NonGC:
1826    assert(!GCEnabled);
1827    GCModeDescription = "Code is compiled to use reference counts";
1828    break;
1829
1830  case LangOptions::HybridGC:
1831    if (GCEnabled) {
1832      GCModeDescription = "Code is compiled to use either garbage collection "
1833                          "(GC) or reference counts (non-GC).  The bug occurs "
1834                          "with GC enabled";
1835      break;
1836    } else {
1837      GCModeDescription = "Code is compiled to use either garbage collection "
1838                          "(GC) or reference counts (non-GC).  The bug occurs "
1839                          "in non-GC mode";
1840      break;
1841    }
1842  }
1843
1844  assert(GCModeDescription && "invalid/unknown GC mode");
1845  addExtraText(GCModeDescription);
1846}
1847
1848// FIXME: This should be a method on SmallVector.
1849static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
1850                            ArgEffect X) {
1851  for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1852       I!=E; ++I)
1853    if (*I == X) return true;
1854
1855  return false;
1856}
1857
1858static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1859  unsigned maxDepth = 4;
1860  while (S && maxDepth) {
1861    if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1862      if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1863        return true;
1864      return false;
1865    }
1866    S = PM.getParent(S);
1867    --maxDepth;
1868  }
1869  return false;
1870}
1871
1872PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1873                                                   const ExplodedNode *PrevN,
1874                                                   BugReporterContext &BRC,
1875                                                   BugReport &BR) {
1876
1877  if (!isa<StmtPoint>(N->getLocation()))
1878    return NULL;
1879
1880  // Check if the type state has changed.
1881  ProgramStateRef PrevSt = PrevN->getState();
1882  ProgramStateRef CurrSt = N->getState();
1883  const LocationContext *LCtx = N->getLocationContext();
1884
1885  const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
1886  if (!CurrT) return NULL;
1887
1888  const RefVal &CurrV = *CurrT;
1889  const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
1890
1891  // Create a string buffer to constain all the useful things we want
1892  // to tell the user.
1893  std::string sbuf;
1894  llvm::raw_string_ostream os(sbuf);
1895
1896  // This is the allocation site since the previous node had no bindings
1897  // for this symbol.
1898  if (!PrevT) {
1899    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1900
1901    if (isa<ObjCArrayLiteral>(S)) {
1902      os << "NSArray literal is an object with a +0 retain count";
1903    }
1904    else if (isa<ObjCDictionaryLiteral>(S)) {
1905      os << "NSDictionary literal is an object with a +0 retain count";
1906    }
1907    else {
1908      if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1909        // Get the name of the callee (if it is available).
1910        SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1911        if (const FunctionDecl *FD = X.getAsFunctionDecl())
1912          os << "Call to function '" << *FD << '\'';
1913        else
1914          os << "function call";
1915      }
1916      else {
1917        assert(isa<ObjCMessageExpr>(S));
1918        // The message expression may have between written directly or as
1919        // a property access.  Lazily determine which case we are looking at.
1920        os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1921      }
1922
1923      if (CurrV.getObjKind() == RetEffect::CF) {
1924        os << " returns a Core Foundation object with a ";
1925      }
1926      else {
1927        assert (CurrV.getObjKind() == RetEffect::ObjC);
1928        os << " returns an Objective-C object with a ";
1929      }
1930
1931      if (CurrV.isOwned()) {
1932        os << "+1 retain count";
1933
1934        if (GCEnabled) {
1935          assert(CurrV.getObjKind() == RetEffect::CF);
1936          os << ".  "
1937          "Core Foundation objects are not automatically garbage collected.";
1938        }
1939      }
1940      else {
1941        assert (CurrV.isNotOwned());
1942        os << "+0 retain count";
1943      }
1944    }
1945
1946    PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1947                                  N->getLocationContext());
1948    return new PathDiagnosticEventPiece(Pos, os.str());
1949  }
1950
1951  // Gather up the effects that were performed on the object at this
1952  // program point
1953  SmallVector<ArgEffect, 2> AEffects;
1954
1955  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1956  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
1957    // We only have summaries attached to nodes after evaluating CallExpr and
1958    // ObjCMessageExprs.
1959    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1960
1961    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1962      // Iterate through the parameter expressions and see if the symbol
1963      // was ever passed as an argument.
1964      unsigned i = 0;
1965
1966      for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
1967           AI!=AE; ++AI, ++i) {
1968
1969        // Retrieve the value of the argument.  Is it the symbol
1970        // we are interested in?
1971        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
1972          continue;
1973
1974        // We have an argument.  Get the effect!
1975        AEffects.push_back(Summ->getArg(i));
1976      }
1977    }
1978    else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1979      if (const Expr *receiver = ME->getInstanceReceiver())
1980        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1981              .getAsLocSymbol() == Sym) {
1982          // The symbol we are tracking is the receiver.
1983          AEffects.push_back(Summ->getReceiverEffect());
1984        }
1985    }
1986  }
1987
1988  do {
1989    // Get the previous type state.
1990    RefVal PrevV = *PrevT;
1991
1992    // Specially handle -dealloc.
1993    if (!GCEnabled && contains(AEffects, Dealloc)) {
1994      // Determine if the object's reference count was pushed to zero.
1995      assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1996      // We may not have transitioned to 'release' if we hit an error.
1997      // This case is handled elsewhere.
1998      if (CurrV.getKind() == RefVal::Released) {
1999        assert(CurrV.getCombinedCounts() == 0);
2000        os << "Object released by directly sending the '-dealloc' message";
2001        break;
2002      }
2003    }
2004
2005    // Specially handle CFMakeCollectable and friends.
2006    if (contains(AEffects, MakeCollectable)) {
2007      // Get the name of the function.
2008      const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2009      SVal X =
2010        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2011      const FunctionDecl *FD = X.getAsFunctionDecl();
2012
2013      if (GCEnabled) {
2014        // Determine if the object's reference count was pushed to zero.
2015        assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2016
2017        os << "In GC mode a call to '" << *FD
2018        <<  "' decrements an object's retain count and registers the "
2019        "object with the garbage collector. ";
2020
2021        if (CurrV.getKind() == RefVal::Released) {
2022          assert(CurrV.getCount() == 0);
2023          os << "Since it now has a 0 retain count the object can be "
2024          "automatically collected by the garbage collector.";
2025        }
2026        else
2027          os << "An object must have a 0 retain count to be garbage collected. "
2028          "After this call its retain count is +" << CurrV.getCount()
2029          << '.';
2030      }
2031      else
2032        os << "When GC is not enabled a call to '" << *FD
2033        << "' has no effect on its argument.";
2034
2035      // Nothing more to say.
2036      break;
2037    }
2038
2039    // Determine if the typestate has changed.
2040    if (!(PrevV == CurrV))
2041      switch (CurrV.getKind()) {
2042        case RefVal::Owned:
2043        case RefVal::NotOwned:
2044
2045          if (PrevV.getCount() == CurrV.getCount()) {
2046            // Did an autorelease message get sent?
2047            if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2048              return 0;
2049
2050            assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2051            os << "Object sent -autorelease message";
2052            break;
2053          }
2054
2055          if (PrevV.getCount() > CurrV.getCount())
2056            os << "Reference count decremented.";
2057          else
2058            os << "Reference count incremented.";
2059
2060          if (unsigned Count = CurrV.getCount())
2061            os << " The object now has a +" << Count << " retain count.";
2062
2063          if (PrevV.getKind() == RefVal::Released) {
2064            assert(GCEnabled && CurrV.getCount() > 0);
2065            os << " The object is not eligible for garbage collection until "
2066                  "the retain count reaches 0 again.";
2067          }
2068
2069          break;
2070
2071        case RefVal::Released:
2072          os << "Object released.";
2073          break;
2074
2075        case RefVal::ReturnedOwned:
2076          // Autoreleases can be applied after marking a node ReturnedOwned.
2077          if (CurrV.getAutoreleaseCount())
2078            return NULL;
2079
2080          os << "Object returned to caller as an owning reference (single "
2081                "retain count transferred to caller)";
2082          break;
2083
2084        case RefVal::ReturnedNotOwned:
2085          os << "Object returned to caller with a +0 retain count";
2086          break;
2087
2088        default:
2089          return NULL;
2090      }
2091
2092    // Emit any remaining diagnostics for the argument effects (if any).
2093    for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2094         E=AEffects.end(); I != E; ++I) {
2095
2096      // A bunch of things have alternate behavior under GC.
2097      if (GCEnabled)
2098        switch (*I) {
2099          default: break;
2100          case Autorelease:
2101            os << "In GC mode an 'autorelease' has no effect.";
2102            continue;
2103          case IncRefMsg:
2104            os << "In GC mode the 'retain' message has no effect.";
2105            continue;
2106          case DecRefMsg:
2107            os << "In GC mode the 'release' message has no effect.";
2108            continue;
2109        }
2110    }
2111  } while (0);
2112
2113  if (os.str().empty())
2114    return 0; // We have nothing to say!
2115
2116  const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2117  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2118                                N->getLocationContext());
2119  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2120
2121  // Add the range by scanning the children of the statement for any bindings
2122  // to Sym.
2123  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2124       I!=E; ++I)
2125    if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2126      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2127        P->addRange(Exp->getSourceRange());
2128        break;
2129      }
2130
2131  return P;
2132}
2133
2134// Find the first node in the current function context that referred to the
2135// tracked symbol and the memory location that value was stored to. Note, the
2136// value is only reported if the allocation occurred in the same function as
2137// the leak.
2138static std::pair<const ExplodedNode*,const MemRegion*>
2139GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2140                  SymbolRef Sym) {
2141  const ExplodedNode *Last = N;
2142  const MemRegion* FirstBinding = 0;
2143  const LocationContext *LeakContext = N->getLocationContext();
2144
2145  while (N) {
2146    ProgramStateRef St = N->getState();
2147    RefBindings B = St->get<RefBindings>();
2148
2149    if (!B.lookup(Sym))
2150      break;
2151
2152    StoreManager::FindUniqueBinding FB(Sym);
2153    StateMgr.iterBindings(St, FB);
2154    if (FB) FirstBinding = FB.getRegion();
2155
2156    // Allocation node, is the last node in the current context in which the
2157    // symbol was tracked.
2158    if (N->getLocationContext() == LeakContext)
2159      Last = N;
2160
2161    N = N->pred_empty() ? NULL : *(N->pred_begin());
2162  }
2163
2164  // If allocation happened in a function different from the leak node context,
2165  // do not report the binding.
2166  if (N->getLocationContext() != LeakContext) {
2167    FirstBinding = 0;
2168  }
2169
2170  return std::make_pair(Last, FirstBinding);
2171}
2172
2173PathDiagnosticPiece*
2174CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2175                               const ExplodedNode *EndN,
2176                               BugReport &BR) {
2177  BR.markInteresting(Sym);
2178  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2179}
2180
2181PathDiagnosticPiece*
2182CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2183                                   const ExplodedNode *EndN,
2184                                   BugReport &BR) {
2185
2186  // Tell the BugReporterContext to report cases when the tracked symbol is
2187  // assigned to different variables, etc.
2188  BR.markInteresting(Sym);
2189
2190  // We are reporting a leak.  Walk up the graph to get to the first node where
2191  // the symbol appeared, and also get the first VarDecl that tracked object
2192  // is stored to.
2193  const ExplodedNode *AllocNode = 0;
2194  const MemRegion* FirstBinding = 0;
2195
2196  llvm::tie(AllocNode, FirstBinding) =
2197    GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2198
2199  SourceManager& SM = BRC.getSourceManager();
2200
2201  // Compute an actual location for the leak.  Sometimes a leak doesn't
2202  // occur at an actual statement (e.g., transition between blocks; end
2203  // of function) so we need to walk the graph and compute a real location.
2204  const ExplodedNode *LeakN = EndN;
2205  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2206
2207  std::string sbuf;
2208  llvm::raw_string_ostream os(sbuf);
2209
2210  os << "Object leaked: ";
2211
2212  if (FirstBinding) {
2213    os << "object allocated and stored into '"
2214       << FirstBinding->getString() << '\'';
2215  }
2216  else
2217    os << "allocated object";
2218
2219  // Get the retain count.
2220  const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2221
2222  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2223    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2224    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2225    // to the caller for NS objects.
2226    const Decl *D = &EndN->getCodeDecl();
2227    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2228      os << " is returned from a method whose name ('"
2229         << MD->getSelector().getAsString()
2230         << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2231            "  This violates the naming convention rules"
2232            " given in the Memory Management Guide for Cocoa";
2233    }
2234    else {
2235      const FunctionDecl *FD = cast<FunctionDecl>(D);
2236      os << " is returned from a function whose name ('"
2237         << *FD
2238         << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2239            " convention rules given in the Memory Management Guide for Core"
2240            " Foundation";
2241    }
2242  }
2243  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2244    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2245    os << " and returned from method '" << MD.getSelector().getAsString()
2246       << "' is potentially leaked when using garbage collection.  Callers "
2247          "of this method do not expect a returned object with a +1 retain "
2248          "count since they expect the object to be managed by the garbage "
2249          "collector";
2250  }
2251  else
2252    os << " is not referenced later in this execution path and has a retain "
2253          "count of +" << RV->getCount();
2254
2255  return new PathDiagnosticEventPiece(L, os.str());
2256}
2257
2258CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2259                                 bool GCEnabled, const SummaryLogTy &Log,
2260                                 ExplodedNode *n, SymbolRef sym,
2261                                 CheckerContext &Ctx)
2262: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2263
2264  // Most bug reports are cached at the location where they occurred.
2265  // With leaks, we want to unique them by the location where they were
2266  // allocated, and only report a single path.  To do this, we need to find
2267  // the allocation site of a piece of tracked memory, which we do via a
2268  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2269  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2270  // that all ancestor nodes that represent the allocation site have the
2271  // same SourceLocation.
2272  const ExplodedNode *AllocNode = 0;
2273
2274  const SourceManager& SMgr = Ctx.getSourceManager();
2275
2276  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2277    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2278
2279  // Get the SourceLocation for the allocation site.
2280  ProgramPoint P = AllocNode->getLocation();
2281  const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2282  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2283                                                  n->getLocationContext());
2284  // Fill in the description of the bug.
2285  Description.clear();
2286  llvm::raw_string_ostream os(Description);
2287  os << "Potential leak ";
2288  if (GCEnabled)
2289    os << "(when using garbage collection) ";
2290  os << "of an object";
2291
2292  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2293  if (AllocBinding)
2294    os << " stored into '" << AllocBinding->getString() << '\'';
2295
2296  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2297}
2298
2299//===----------------------------------------------------------------------===//
2300// Main checker logic.
2301//===----------------------------------------------------------------------===//
2302
2303namespace {
2304class RetainCountChecker
2305  : public Checker< check::Bind,
2306                    check::DeadSymbols,
2307                    check::EndAnalysis,
2308                    check::EndPath,
2309                    check::PostStmt<BlockExpr>,
2310                    check::PostStmt<CastExpr>,
2311                    check::PostStmt<CallExpr>,
2312                    check::PostStmt<CXXConstructExpr>,
2313                    check::PostStmt<ObjCArrayLiteral>,
2314                    check::PostStmt<ObjCDictionaryLiteral>,
2315                    check::PostObjCMessage,
2316                    check::PreStmt<ReturnStmt>,
2317                    check::RegionChanges,
2318                    eval::Assume,
2319                    eval::Call > {
2320  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2321  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2322  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2323  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2324  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2325
2326  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2327
2328  // This map is only used to ensure proper deletion of any allocated tags.
2329  mutable SymbolTagMap DeadSymbolTags;
2330
2331  mutable OwningPtr<RetainSummaryManager> Summaries;
2332  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2333
2334  mutable ARCounts::Factory ARCountFactory;
2335
2336  mutable SummaryLogTy SummaryLog;
2337  mutable bool ShouldResetSummaryLog;
2338
2339public:
2340  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2341
2342  virtual ~RetainCountChecker() {
2343    DeleteContainerSeconds(DeadSymbolTags);
2344  }
2345
2346  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2347                        ExprEngine &Eng) const {
2348    // FIXME: This is a hack to make sure the summary log gets cleared between
2349    // analyses of different code bodies.
2350    //
2351    // Why is this necessary? Because a checker's lifetime is tied to a
2352    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2353    // Once in a blue moon, a new ExplodedNode will have the same address as an
2354    // old one with an associated summary, and the bug report visitor gets very
2355    // confused. (To make things worse, the summary lifetime is currently also
2356    // tied to a code body, so we get a crash instead of incorrect results.)
2357    //
2358    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2359    // changes, things will start going wrong again. Really the lifetime of this
2360    // log needs to be tied to either the specific nodes in it or the entire
2361    // ExplodedGraph, not to a specific part of the code being analyzed.
2362    //
2363    // (Also, having stateful local data means that the same checker can't be
2364    // used from multiple threads, but a lot of checkers have incorrect
2365    // assumptions about that anyway. So that wasn't a priority at the time of
2366    // this fix.)
2367    //
2368    // This happens at the end of analysis, but bug reports are emitted /after/
2369    // this point. So we can't just clear the summary log now. Instead, we mark
2370    // that the next time we access the summary log, it should be cleared.
2371
2372    // If we never reset the summary log during /this/ code body analysis,
2373    // there were no new summaries. There might still have been summaries from
2374    // the /last/ analysis, so clear them out to make sure the bug report
2375    // visitors don't get confused.
2376    if (ShouldResetSummaryLog)
2377      SummaryLog.clear();
2378
2379    ShouldResetSummaryLog = !SummaryLog.empty();
2380  }
2381
2382  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2383                                     bool GCEnabled) const {
2384    if (GCEnabled) {
2385      if (!leakWithinFunctionGC)
2386        leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when "
2387                                                          "using garbage "
2388                                                          "collection"));
2389      return leakWithinFunctionGC.get();
2390    } else {
2391      if (!leakWithinFunction) {
2392        if (LOpts.getGC() == LangOptions::HybridGC) {
2393          leakWithinFunction.reset(new LeakWithinFunction("Leak of object when "
2394                                                          "not using garbage "
2395                                                          "collection (GC) in "
2396                                                          "dual GC/non-GC "
2397                                                          "code"));
2398        } else {
2399          leakWithinFunction.reset(new LeakWithinFunction("Leak"));
2400        }
2401      }
2402      return leakWithinFunction.get();
2403    }
2404  }
2405
2406  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2407    if (GCEnabled) {
2408      if (!leakAtReturnGC)
2409        leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when "
2410                                              "using garbage collection"));
2411      return leakAtReturnGC.get();
2412    } else {
2413      if (!leakAtReturn) {
2414        if (LOpts.getGC() == LangOptions::HybridGC) {
2415          leakAtReturn.reset(new LeakAtReturn("Leak of returned object when "
2416                                              "not using garbage collection "
2417                                              "(GC) in dual GC/non-GC code"));
2418        } else {
2419          leakAtReturn.reset(new LeakAtReturn("Leak of returned object"));
2420        }
2421      }
2422      return leakAtReturn.get();
2423    }
2424  }
2425
2426  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2427                                          bool GCEnabled) const {
2428    // FIXME: We don't support ARC being turned on and off during one analysis.
2429    // (nor, for that matter, do we support changing ASTContexts)
2430    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2431    if (GCEnabled) {
2432      if (!SummariesGC)
2433        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2434      else
2435        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2436      return *SummariesGC;
2437    } else {
2438      if (!Summaries)
2439        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2440      else
2441        assert(Summaries->isARCEnabled() == ARCEnabled);
2442      return *Summaries;
2443    }
2444  }
2445
2446  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2447    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2448  }
2449
2450  void printState(raw_ostream &Out, ProgramStateRef State,
2451                  const char *NL, const char *Sep) const;
2452
2453  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2454  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2455  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2456
2457  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
2458  void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
2459  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2460  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2461  void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
2462
2463  void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
2464                    CheckerContext &C) const;
2465
2466  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2467
2468  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2469                                 bool Assumption) const;
2470
2471  ProgramStateRef
2472  checkRegionChanges(ProgramStateRef state,
2473                     const StoreManager::InvalidatedSymbols *invalidated,
2474                     ArrayRef<const MemRegion *> ExplicitRegions,
2475                     ArrayRef<const MemRegion *> Regions,
2476                     const CallOrObjCMessage *Call) const;
2477
2478  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2479    return true;
2480  }
2481
2482  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2483  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2484                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2485                                SymbolRef Sym, ProgramStateRef state) const;
2486
2487  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2488  void checkEndPath(CheckerContext &C) const;
2489
2490  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2491                                   RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2492                                   CheckerContext &C) const;
2493
2494  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2495                           RefVal::Kind ErrorKind, SymbolRef Sym,
2496                           CheckerContext &C) const;
2497
2498  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2499
2500  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2501
2502  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2503                                        SymbolRef sid, RefVal V,
2504                                      SmallVectorImpl<SymbolRef> &Leaked) const;
2505
2506  std::pair<ExplodedNode *, ProgramStateRef >
2507  handleAutoreleaseCounts(ProgramStateRef state,
2508                          GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
2509                          CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
2510
2511  ExplodedNode *processLeaks(ProgramStateRef state,
2512                             SmallVectorImpl<SymbolRef> &Leaked,
2513                             GenericNodeBuilderRefCount &Builder,
2514                             CheckerContext &Ctx,
2515                             ExplodedNode *Pred = 0) const;
2516};
2517} // end anonymous namespace
2518
2519namespace {
2520class StopTrackingCallback : public SymbolVisitor {
2521  ProgramStateRef state;
2522public:
2523  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2524  ProgramStateRef getState() const { return state; }
2525
2526  bool VisitSymbol(SymbolRef sym) {
2527    state = state->remove<RefBindings>(sym);
2528    return true;
2529  }
2530};
2531} // end anonymous namespace
2532
2533//===----------------------------------------------------------------------===//
2534// Handle statements that may have an effect on refcounts.
2535//===----------------------------------------------------------------------===//
2536
2537void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2538                                       CheckerContext &C) const {
2539
2540  // Scan the BlockDecRefExprs for any object the retain count checker
2541  // may be tracking.
2542  if (!BE->getBlockDecl()->hasCaptures())
2543    return;
2544
2545  ProgramStateRef state = C.getState();
2546  const BlockDataRegion *R =
2547    cast<BlockDataRegion>(state->getSVal(BE,
2548                                         C.getLocationContext()).getAsRegion());
2549
2550  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2551                                            E = R->referenced_vars_end();
2552
2553  if (I == E)
2554    return;
2555
2556  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2557  // via captured variables, even though captured variables result in a copy
2558  // and in implicit increment/decrement of a retain count.
2559  SmallVector<const MemRegion*, 10> Regions;
2560  const LocationContext *LC = C.getLocationContext();
2561  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2562
2563  for ( ; I != E; ++I) {
2564    const VarRegion *VR = *I;
2565    if (VR->getSuperRegion() == R) {
2566      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2567    }
2568    Regions.push_back(VR);
2569  }
2570
2571  state =
2572    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2573                                    Regions.data() + Regions.size()).getState();
2574  C.addTransition(state);
2575}
2576
2577void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2578                                       CheckerContext &C) const {
2579  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2580  if (!BE)
2581    return;
2582
2583  ArgEffect AE = IncRef;
2584
2585  switch (BE->getBridgeKind()) {
2586    case clang::OBC_Bridge:
2587      // Do nothing.
2588      return;
2589    case clang::OBC_BridgeRetained:
2590      AE = IncRef;
2591      break;
2592    case clang::OBC_BridgeTransfer:
2593      AE = DecRefBridgedTransfered;
2594      break;
2595  }
2596
2597  ProgramStateRef state = C.getState();
2598  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2599  if (!Sym)
2600    return;
2601  const RefVal* T = state->get<RefBindings>(Sym);
2602  if (!T)
2603    return;
2604
2605  RefVal::Kind hasErr = (RefVal::Kind) 0;
2606  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2607
2608  if (hasErr) {
2609    // FIXME: If we get an error during a bridge cast, should we report it?
2610    // Should we assert that there is no error?
2611    return;
2612  }
2613
2614  C.addTransition(state);
2615}
2616
2617void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2618                                       CheckerContext &C) const {
2619  if (C.wasInlined)
2620    return;
2621
2622  // Get the callee.
2623  ProgramStateRef state = C.getState();
2624  const Expr *Callee = CE->getCallee();
2625  SVal L = state->getSVal(Callee, C.getLocationContext());
2626
2627  RetainSummaryManager &Summaries = getSummaryManager(C);
2628  const RetainSummary *Summ = 0;
2629
2630  // FIXME: Better support for blocks.  For now we stop tracking anything
2631  // that is passed to blocks.
2632  // FIXME: Need to handle variables that are "captured" by the block.
2633  if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2634    Summ = Summaries.getPersistentStopSummary();
2635  } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
2636    Summ = Summaries.getSummary(FD);
2637  } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
2638    if (const CXXMethodDecl *MD = me->getMethodDecl())
2639      Summ = Summaries.getSummary(MD);
2640  }
2641
2642  if (!Summ)
2643    Summ = Summaries.getDefaultSummary();
2644
2645  checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
2646}
2647
2648void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2649                                       CheckerContext &C) const {
2650  const CXXConstructorDecl *Ctor = CE->getConstructor();
2651  if (!Ctor)
2652    return;
2653
2654  RetainSummaryManager &Summaries = getSummaryManager(C);
2655  const RetainSummary *Summ = Summaries.getSummary(Ctor);
2656
2657  // If we didn't get a summary, this constructor doesn't affect retain counts.
2658  if (!Summ)
2659    return;
2660
2661  ProgramStateRef state = C.getState();
2662  checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
2663}
2664
2665void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2666                                             const Expr *Ex) const {
2667  ProgramStateRef state = C.getState();
2668  const ExplodedNode *pred = C.getPredecessor();
2669  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2670       it != et ; ++it) {
2671    const Stmt *child = *it;
2672    SVal V = state->getSVal(child, pred->getLocationContext());
2673    if (SymbolRef sym = V.getAsSymbol())
2674      if (const RefVal* T = state->get<RefBindings>(sym)) {
2675        RefVal::Kind hasErr = (RefVal::Kind) 0;
2676        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2677        if (hasErr) {
2678          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2679          return;
2680        }
2681      }
2682  }
2683
2684  // Return the object as autoreleased.
2685  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2686  if (SymbolRef sym =
2687        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2688    QualType ResultTy = Ex->getType();
2689    state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2690                                                              ResultTy));
2691  }
2692
2693  C.addTransition(state);
2694}
2695
2696void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2697                                       CheckerContext &C) const {
2698  // Apply the 'MayEscape' to all values.
2699  processObjCLiterals(C, AL);
2700}
2701
2702void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2703                                       CheckerContext &C) const {
2704  // Apply the 'MayEscape' to all keys and values.
2705  processObjCLiterals(C, DL);
2706}
2707
2708void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2709                                              CheckerContext &C) const {
2710  ProgramStateRef state = C.getState();
2711
2712  RetainSummaryManager &Summaries = getSummaryManager(C);
2713
2714  const RetainSummary *Summ;
2715  if (Msg.isInstanceMessage()) {
2716    const LocationContext *LC = C.getLocationContext();
2717    Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2718  } else {
2719    Summ = Summaries.getClassMethodSummary(Msg);
2720  }
2721
2722  // If we didn't get a summary, this message doesn't affect retain counts.
2723  if (!Summ)
2724    return;
2725
2726  checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
2727}
2728
2729/// GetReturnType - Used to get the return type of a message expression or
2730///  function call with the intention of affixing that type to a tracked symbol.
2731///  While the the return type can be queried directly from RetEx, when
2732///  invoking class methods we augment to the return type to be that of
2733///  a pointer to the class (as opposed it just being id).
2734// FIXME: We may be able to do this with related result types instead.
2735// This function is probably overestimating.
2736static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2737  QualType RetTy = RetE->getType();
2738  // If RetE is not a message expression just return its type.
2739  // If RetE is a message expression, return its types if it is something
2740  /// more specific than id.
2741  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2742    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2743      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2744          PT->isObjCClassType()) {
2745        // At this point we know the return type of the message expression is
2746        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2747        // is a call to a class method whose type we can resolve.  In such
2748        // cases, promote the return type to XXX* (where XXX is the class).
2749        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2750        return !D ? RetTy :
2751                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2752      }
2753
2754  return RetTy;
2755}
2756
2757void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2758                                      const CallOrObjCMessage &CallOrMsg,
2759                                      CheckerContext &C) const {
2760  ProgramStateRef state = C.getState();
2761
2762  // Evaluate the effect of the arguments.
2763  RefVal::Kind hasErr = (RefVal::Kind) 0;
2764  SourceRange ErrorRange;
2765  SymbolRef ErrorSym = 0;
2766
2767  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2768    SVal V = CallOrMsg.getArgSVal(idx);
2769
2770    if (SymbolRef Sym = V.getAsLocSymbol()) {
2771      if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
2772        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2773        if (hasErr) {
2774          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2775          ErrorSym = Sym;
2776          break;
2777        }
2778      }
2779    }
2780  }
2781
2782  // Evaluate the effect on the message receiver.
2783  bool ReceiverIsTracked = false;
2784  if (!hasErr && CallOrMsg.isObjCMessage()) {
2785    const LocationContext *LC = C.getLocationContext();
2786    SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2787    if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
2788      if (const RefVal *T = state->get<RefBindings>(Sym)) {
2789        ReceiverIsTracked = true;
2790        state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2791                             hasErr, C);
2792        if (hasErr) {
2793          ErrorRange = CallOrMsg.getReceiverSourceRange();
2794          ErrorSym = Sym;
2795        }
2796      }
2797    }
2798  }
2799
2800  // Process any errors.
2801  if (hasErr) {
2802    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2803    return;
2804  }
2805
2806  // Consult the summary for the return value.
2807  RetEffect RE = Summ.getRetEffect();
2808
2809  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2810    if (ReceiverIsTracked)
2811      RE = getSummaryManager(C).getObjAllocRetEffect();
2812    else
2813      RE = RetEffect::MakeNoRet();
2814  }
2815
2816  switch (RE.getKind()) {
2817    default:
2818      llvm_unreachable("Unhandled RetEffect.");
2819
2820    case RetEffect::NoRet:
2821      // No work necessary.
2822      break;
2823
2824    case RetEffect::OwnedAllocatedSymbol:
2825    case RetEffect::OwnedSymbol: {
2826      SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2827                                     C.getLocationContext()).getAsSymbol();
2828      if (!Sym)
2829        break;
2830
2831      // Use the result type from callOrMsg as it automatically adjusts
2832      // for methods/functions that return references.
2833      QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2834      state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2835                                                             ResultTy));
2836
2837      // FIXME: Add a flag to the checker where allocations are assumed to
2838      // *not* fail. (The code below is out-of-date, though.)
2839#if 0
2840      if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2841        bool isFeasible;
2842        state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2843        assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2844      }
2845#endif
2846
2847      break;
2848    }
2849
2850    case RetEffect::GCNotOwnedSymbol:
2851    case RetEffect::ARCNotOwnedSymbol:
2852    case RetEffect::NotOwnedSymbol: {
2853      const Expr *Ex = CallOrMsg.getOriginExpr();
2854      SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
2855      if (!Sym)
2856        break;
2857
2858      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2859      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2860      state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2861                                                                ResultTy));
2862      break;
2863    }
2864  }
2865
2866  // This check is actually necessary; otherwise the statement builder thinks
2867  // we've hit a previously-found path.
2868  // Normally addTransition takes care of this, but we want the node pointer.
2869  ExplodedNode *NewNode;
2870  if (state == C.getState()) {
2871    NewNode = C.getPredecessor();
2872  } else {
2873    NewNode = C.addTransition(state);
2874  }
2875
2876  // Annotate the node with summary we used.
2877  if (NewNode) {
2878    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2879    if (ShouldResetSummaryLog) {
2880      SummaryLog.clear();
2881      ShouldResetSummaryLog = false;
2882    }
2883    SummaryLog[NewNode] = &Summ;
2884  }
2885}
2886
2887
2888ProgramStateRef
2889RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2890                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2891                                 CheckerContext &C) const {
2892  // In GC mode [... release] and [... retain] do nothing.
2893  // In ARC mode they shouldn't exist at all, but we just ignore them.
2894  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2895  if (!IgnoreRetainMsg)
2896    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2897
2898  switch (E) {
2899    default: break;
2900    case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2901    case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2902    case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2903    case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2904                                                      NewAutoreleasePool; break;
2905  }
2906
2907  // Handle all use-after-releases.
2908  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2909    V = V ^ RefVal::ErrorUseAfterRelease;
2910    hasErr = V.getKind();
2911    return state->set<RefBindings>(sym, V);
2912  }
2913
2914  switch (E) {
2915    case DecRefMsg:
2916    case IncRefMsg:
2917    case MakeCollectable:
2918      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2919
2920    case Dealloc:
2921      // Any use of -dealloc in GC is *bad*.
2922      if (C.isObjCGCEnabled()) {
2923        V = V ^ RefVal::ErrorDeallocGC;
2924        hasErr = V.getKind();
2925        break;
2926      }
2927
2928      switch (V.getKind()) {
2929        default:
2930          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2931        case RefVal::Owned:
2932          // The object immediately transitions to the released state.
2933          V = V ^ RefVal::Released;
2934          V.clearCounts();
2935          return state->set<RefBindings>(sym, V);
2936        case RefVal::NotOwned:
2937          V = V ^ RefVal::ErrorDeallocNotOwned;
2938          hasErr = V.getKind();
2939          break;
2940      }
2941      break;
2942
2943    case NewAutoreleasePool:
2944      assert(!C.isObjCGCEnabled());
2945      return state->add<AutoreleaseStack>(sym);
2946
2947    case MayEscape:
2948      if (V.getKind() == RefVal::Owned) {
2949        V = V ^ RefVal::NotOwned;
2950        break;
2951      }
2952
2953      // Fall-through.
2954
2955    case DoNothing:
2956      return state;
2957
2958    case Autorelease:
2959      if (C.isObjCGCEnabled())
2960        return state;
2961
2962      // Update the autorelease counts.
2963      state = SendAutorelease(state, ARCountFactory, sym);
2964      V = V.autorelease();
2965      break;
2966
2967    case StopTracking:
2968      return state->remove<RefBindings>(sym);
2969
2970    case IncRef:
2971      switch (V.getKind()) {
2972        default:
2973          llvm_unreachable("Invalid RefVal state for a retain.");
2974        case RefVal::Owned:
2975        case RefVal::NotOwned:
2976          V = V + 1;
2977          break;
2978        case RefVal::Released:
2979          // Non-GC cases are handled above.
2980          assert(C.isObjCGCEnabled());
2981          V = (V ^ RefVal::Owned) + 1;
2982          break;
2983      }
2984      break;
2985
2986    case SelfOwn:
2987      V = V ^ RefVal::NotOwned;
2988      // Fall-through.
2989    case DecRef:
2990    case DecRefBridgedTransfered:
2991      switch (V.getKind()) {
2992        default:
2993          // case 'RefVal::Released' handled above.
2994          llvm_unreachable("Invalid RefVal state for a release.");
2995
2996        case RefVal::Owned:
2997          assert(V.getCount() > 0);
2998          if (V.getCount() == 1)
2999            V = V ^ (E == DecRefBridgedTransfered ?
3000                      RefVal::NotOwned : RefVal::Released);
3001          V = V - 1;
3002          break;
3003
3004        case RefVal::NotOwned:
3005          if (V.getCount() > 0)
3006            V = V - 1;
3007          else {
3008            V = V ^ RefVal::ErrorReleaseNotOwned;
3009            hasErr = V.getKind();
3010          }
3011          break;
3012
3013        case RefVal::Released:
3014          // Non-GC cases are handled above.
3015          assert(C.isObjCGCEnabled());
3016          V = V ^ RefVal::ErrorUseAfterRelease;
3017          hasErr = V.getKind();
3018          break;
3019      }
3020      break;
3021  }
3022  return state->set<RefBindings>(sym, V);
3023}
3024
3025void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3026                                             SourceRange ErrorRange,
3027                                             RefVal::Kind ErrorKind,
3028                                             SymbolRef Sym,
3029                                             CheckerContext &C) const {
3030  ExplodedNode *N = C.generateSink(St);
3031  if (!N)
3032    return;
3033
3034  CFRefBug *BT;
3035  switch (ErrorKind) {
3036    default:
3037      llvm_unreachable("Unhandled error.");
3038    case RefVal::ErrorUseAfterRelease:
3039      if (!useAfterRelease)
3040        useAfterRelease.reset(new UseAfterRelease());
3041      BT = &*useAfterRelease;
3042      break;
3043    case RefVal::ErrorReleaseNotOwned:
3044      if (!releaseNotOwned)
3045        releaseNotOwned.reset(new BadRelease());
3046      BT = &*releaseNotOwned;
3047      break;
3048    case RefVal::ErrorDeallocGC:
3049      if (!deallocGC)
3050        deallocGC.reset(new DeallocGC());
3051      BT = &*deallocGC;
3052      break;
3053    case RefVal::ErrorDeallocNotOwned:
3054      if (!deallocNotOwned)
3055        deallocNotOwned.reset(new DeallocNotOwned());
3056      BT = &*deallocNotOwned;
3057      break;
3058  }
3059
3060  assert(BT);
3061  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3062                                        C.isObjCGCEnabled(), SummaryLog,
3063                                        N, Sym);
3064  report->addRange(ErrorRange);
3065  C.EmitReport(report);
3066}
3067
3068//===----------------------------------------------------------------------===//
3069// Handle the return values of retain-count-related functions.
3070//===----------------------------------------------------------------------===//
3071
3072bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3073  // Get the callee. We're only interested in simple C functions.
3074  ProgramStateRef state = C.getState();
3075  const FunctionDecl *FD = C.getCalleeDecl(CE);
3076  if (!FD)
3077    return false;
3078
3079  IdentifierInfo *II = FD->getIdentifier();
3080  if (!II)
3081    return false;
3082
3083  // For now, we're only handling the functions that return aliases of their
3084  // arguments: CFRetain and CFMakeCollectable (and their families).
3085  // Eventually we should add other functions we can model entirely,
3086  // such as CFRelease, which don't invalidate their arguments or globals.
3087  if (CE->getNumArgs() != 1)
3088    return false;
3089
3090  // Get the name of the function.
3091  StringRef FName = II->getName();
3092  FName = FName.substr(FName.find_first_not_of('_'));
3093
3094  // See if it's one of the specific functions we know how to eval.
3095  bool canEval = false;
3096
3097  QualType ResultTy = CE->getCallReturnType();
3098  if (ResultTy->isObjCIdType()) {
3099    // Handle: id NSMakeCollectable(CFTypeRef)
3100    canEval = II->isStr("NSMakeCollectable");
3101  } else if (ResultTy->isPointerType()) {
3102    // Handle: (CF|CG)Retain
3103    //         CFMakeCollectable
3104    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3105    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3106        cocoa::isRefType(ResultTy, "CG", FName)) {
3107      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3108    }
3109  }
3110
3111  if (!canEval)
3112    return false;
3113
3114  // Bind the return value.
3115  const LocationContext *LCtx = C.getLocationContext();
3116  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3117  if (RetVal.isUnknown()) {
3118    // If the receiver is unknown, conjure a return value.
3119    SValBuilder &SVB = C.getSValBuilder();
3120    unsigned Count = C.getCurrentBlockCount();
3121    SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
3122  }
3123  state = state->BindExpr(CE, LCtx, RetVal, false);
3124
3125  // FIXME: This should not be necessary, but otherwise the argument seems to be
3126  // considered alive during the next statement.
3127  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3128    // Save the refcount status of the argument.
3129    SymbolRef Sym = RetVal.getAsLocSymbol();
3130    RefBindings::data_type *Binding = 0;
3131    if (Sym)
3132      Binding = state->get<RefBindings>(Sym);
3133
3134    // Invalidate the argument region.
3135    unsigned Count = C.getCurrentBlockCount();
3136    state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
3137
3138    // Restore the refcount status of the argument.
3139    if (Binding)
3140      state = state->set<RefBindings>(Sym, *Binding);
3141  }
3142
3143  C.addTransition(state);
3144  return true;
3145}
3146
3147//===----------------------------------------------------------------------===//
3148// Handle return statements.
3149//===----------------------------------------------------------------------===//
3150
3151// Return true if the current LocationContext has no caller context.
3152static bool inTopFrame(CheckerContext &C) {
3153  const LocationContext *LC = C.getLocationContext();
3154  return LC->getParent() == 0;
3155}
3156
3157void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3158                                      CheckerContext &C) const {
3159
3160  // Only adjust the reference count if this is the top-level call frame,
3161  // and not the result of inlining.  In the future, we should do
3162  // better checking even for inlined calls, and see if they match
3163  // with their expected semantics (e.g., the method should return a retained
3164  // object, etc.).
3165  if (!inTopFrame(C))
3166    return;
3167
3168  const Expr *RetE = S->getRetValue();
3169  if (!RetE)
3170    return;
3171
3172  ProgramStateRef state = C.getState();
3173  SymbolRef Sym =
3174    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3175  if (!Sym)
3176    return;
3177
3178  // Get the reference count binding (if any).
3179  const RefVal *T = state->get<RefBindings>(Sym);
3180  if (!T)
3181    return;
3182
3183  // Change the reference count.
3184  RefVal X = *T;
3185
3186  switch (X.getKind()) {
3187    case RefVal::Owned: {
3188      unsigned cnt = X.getCount();
3189      assert(cnt > 0);
3190      X.setCount(cnt - 1);
3191      X = X ^ RefVal::ReturnedOwned;
3192      break;
3193    }
3194
3195    case RefVal::NotOwned: {
3196      unsigned cnt = X.getCount();
3197      if (cnt) {
3198        X.setCount(cnt - 1);
3199        X = X ^ RefVal::ReturnedOwned;
3200      }
3201      else {
3202        X = X ^ RefVal::ReturnedNotOwned;
3203      }
3204      break;
3205    }
3206
3207    default:
3208      return;
3209  }
3210
3211  // Update the binding.
3212  state = state->set<RefBindings>(Sym, X);
3213  ExplodedNode *Pred = C.addTransition(state);
3214
3215  // At this point we have updated the state properly.
3216  // Everything after this is merely checking to see if the return value has
3217  // been over- or under-retained.
3218
3219  // Did we cache out?
3220  if (!Pred)
3221    return;
3222
3223  // Update the autorelease counts.
3224  static SimpleProgramPointTag
3225         AutoreleaseTag("RetainCountChecker : Autorelease");
3226  GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
3227  llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
3228
3229  // Did we cache out?
3230  if (!Pred)
3231    return;
3232
3233  // Get the updated binding.
3234  T = state->get<RefBindings>(Sym);
3235  assert(T);
3236  X = *T;
3237
3238  // Consult the summary of the enclosing method.
3239  RetainSummaryManager &Summaries = getSummaryManager(C);
3240  const Decl *CD = &Pred->getCodeDecl();
3241
3242  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3243    // Unlike regular functions, /all/ ObjC methods are assumed to always
3244    // follow Cocoa retain-count conventions, not just those with special
3245    // names or attributes.
3246    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3247    RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3248    checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3249  }
3250
3251  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3252    if (!isa<CXXMethodDecl>(FD))
3253      if (const RetainSummary *Summ = Summaries.getSummary(FD))
3254        checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3255                                 Sym, state);
3256  }
3257}
3258
3259void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3260                                                  CheckerContext &C,
3261                                                  ExplodedNode *Pred,
3262                                                  RetEffect RE, RefVal X,
3263                                                  SymbolRef Sym,
3264                                              ProgramStateRef state) const {
3265  // Any leaks or other errors?
3266  if (X.isReturnedOwned() && X.getCount() == 0) {
3267    if (RE.getKind() != RetEffect::NoRet) {
3268      bool hasError = false;
3269      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3270        // Things are more complicated with garbage collection.  If the
3271        // returned object is suppose to be an Objective-C object, we have
3272        // a leak (as the caller expects a GC'ed object) because no
3273        // method should return ownership unless it returns a CF object.
3274        hasError = true;
3275        X = X ^ RefVal::ErrorGCLeakReturned;
3276      }
3277      else if (!RE.isOwned()) {
3278        // Either we are using GC and the returned object is a CF type
3279        // or we aren't using GC.  In either case, we expect that the
3280        // enclosing method is expected to return ownership.
3281        hasError = true;
3282        X = X ^ RefVal::ErrorLeakReturned;
3283      }
3284
3285      if (hasError) {
3286        // Generate an error node.
3287        state = state->set<RefBindings>(Sym, X);
3288
3289        static SimpleProgramPointTag
3290               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3291        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3292        if (N) {
3293          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3294          bool GCEnabled = C.isObjCGCEnabled();
3295          CFRefReport *report =
3296            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3297                                LOpts, GCEnabled, SummaryLog,
3298                                N, Sym, C);
3299          C.EmitReport(report);
3300        }
3301      }
3302    }
3303  } else if (X.isReturnedNotOwned()) {
3304    if (RE.isOwned()) {
3305      // Trying to return a not owned object to a caller expecting an
3306      // owned object.
3307      state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3308
3309      static SimpleProgramPointTag
3310             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3311      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3312      if (N) {
3313        if (!returnNotOwnedForOwned)
3314          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3315
3316        CFRefReport *report =
3317            new CFRefReport(*returnNotOwnedForOwned,
3318                            C.getASTContext().getLangOpts(),
3319                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3320        C.EmitReport(report);
3321      }
3322    }
3323  }
3324}
3325
3326//===----------------------------------------------------------------------===//
3327// Check various ways a symbol can be invalidated.
3328//===----------------------------------------------------------------------===//
3329
3330void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3331                                   CheckerContext &C) const {
3332  // Are we storing to something that causes the value to "escape"?
3333  bool escapes = true;
3334
3335  // A value escapes in three possible cases (this may change):
3336  //
3337  // (1) we are binding to something that is not a memory region.
3338  // (2) we are binding to a memregion that does not have stack storage
3339  // (3) we are binding to a memregion with stack storage that the store
3340  //     does not understand.
3341  ProgramStateRef state = C.getState();
3342
3343  if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3344    escapes = !regionLoc->getRegion()->hasStackStorage();
3345
3346    if (!escapes) {
3347      // To test (3), generate a new state with the binding added.  If it is
3348      // the same state, then it escapes (since the store cannot represent
3349      // the binding).
3350      escapes = (state == (state->bindLoc(*regionLoc, val)));
3351    }
3352    if (!escapes) {
3353      // Case 4: We do not currently model what happens when a symbol is
3354      // assigned to a struct field, so be conservative here and let the symbol
3355      // go. TODO: This could definitely be improved upon.
3356      escapes = !isa<VarRegion>(regionLoc->getRegion());
3357    }
3358  }
3359
3360  // If our store can represent the binding and we aren't storing to something
3361  // that doesn't have local storage then just return and have the simulation
3362  // state continue as is.
3363  if (!escapes)
3364      return;
3365
3366  // Otherwise, find all symbols referenced by 'val' that we are tracking
3367  // and stop tracking them.
3368  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3369  C.addTransition(state);
3370}
3371
3372ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3373                                                   SVal Cond,
3374                                                   bool Assumption) const {
3375
3376  // FIXME: We may add to the interface of evalAssume the list of symbols
3377  //  whose assumptions have changed.  For now we just iterate through the
3378  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3379  //  too bad since the number of symbols we will track in practice are
3380  //  probably small and evalAssume is only called at branches and a few
3381  //  other places.
3382  RefBindings B = state->get<RefBindings>();
3383
3384  if (B.isEmpty())
3385    return state;
3386
3387  bool changed = false;
3388  RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3389
3390  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3391    // Check if the symbol is null (or equal to any constant).
3392    // If this is the case, stop tracking the symbol.
3393    if (state->getSymVal(I.getKey())) {
3394      changed = true;
3395      B = RefBFactory.remove(B, I.getKey());
3396    }
3397  }
3398
3399  if (changed)
3400    state = state->set<RefBindings>(B);
3401
3402  return state;
3403}
3404
3405ProgramStateRef
3406RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3407                            const StoreManager::InvalidatedSymbols *invalidated,
3408                                    ArrayRef<const MemRegion *> ExplicitRegions,
3409                                    ArrayRef<const MemRegion *> Regions,
3410                                    const CallOrObjCMessage *Call) const {
3411  if (!invalidated)
3412    return state;
3413
3414  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3415  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3416       E = ExplicitRegions.end(); I != E; ++I) {
3417    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3418      WhitelistedSymbols.insert(SR->getSymbol());
3419  }
3420
3421  for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3422       E = invalidated->end(); I!=E; ++I) {
3423    SymbolRef sym = *I;
3424    if (WhitelistedSymbols.count(sym))
3425      continue;
3426    // Remove any existing reference-count binding.
3427    state = state->remove<RefBindings>(sym);
3428  }
3429  return state;
3430}
3431
3432//===----------------------------------------------------------------------===//
3433// Handle dead symbols and end-of-path.
3434//===----------------------------------------------------------------------===//
3435
3436std::pair<ExplodedNode *, ProgramStateRef >
3437RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3438                                            GenericNodeBuilderRefCount Bd,
3439                                            ExplodedNode *Pred,
3440                                            CheckerContext &Ctx,
3441                                            SymbolRef Sym, RefVal V) const {
3442  unsigned ACnt = V.getAutoreleaseCount();
3443
3444  // No autorelease counts?  Nothing to be done.
3445  if (!ACnt)
3446    return std::make_pair(Pred, state);
3447
3448  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3449  unsigned Cnt = V.getCount();
3450
3451  // FIXME: Handle sending 'autorelease' to already released object.
3452
3453  if (V.getKind() == RefVal::ReturnedOwned)
3454    ++Cnt;
3455
3456  if (ACnt <= Cnt) {
3457    if (ACnt == Cnt) {
3458      V.clearCounts();
3459      if (V.getKind() == RefVal::ReturnedOwned)
3460        V = V ^ RefVal::ReturnedNotOwned;
3461      else
3462        V = V ^ RefVal::NotOwned;
3463    } else {
3464      V.setCount(Cnt - ACnt);
3465      V.setAutoreleaseCount(0);
3466    }
3467    state = state->set<RefBindings>(Sym, V);
3468    ExplodedNode *N = Bd.MakeNode(state, Pred);
3469    if (N == 0)
3470      state = 0;
3471    return std::make_pair(N, state);
3472  }
3473
3474  // Woah!  More autorelease counts then retain counts left.
3475  // Emit hard error.
3476  V = V ^ RefVal::ErrorOverAutorelease;
3477  state = state->set<RefBindings>(Sym, V);
3478
3479  if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
3480    SmallString<128> sbuf;
3481    llvm::raw_svector_ostream os(sbuf);
3482    os << "Object over-autoreleased: object was sent -autorelease ";
3483    if (V.getAutoreleaseCount() > 1)
3484      os << V.getAutoreleaseCount() << " times ";
3485    os << "but the object has a +" << V.getCount() << " retain count";
3486
3487    if (!overAutorelease)
3488      overAutorelease.reset(new OverAutorelease());
3489
3490    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3491    CFRefReport *report =
3492      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3493                      SummaryLog, N, Sym, os.str());
3494    Ctx.EmitReport(report);
3495  }
3496
3497  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
3498}
3499
3500ProgramStateRef
3501RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3502                                      SymbolRef sid, RefVal V,
3503                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3504  bool hasLeak = false;
3505  if (V.isOwned())
3506    hasLeak = true;
3507  else if (V.isNotOwned() || V.isReturnedOwned())
3508    hasLeak = (V.getCount() > 0);
3509
3510  if (!hasLeak)
3511    return state->remove<RefBindings>(sid);
3512
3513  Leaked.push_back(sid);
3514  return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3515}
3516
3517ExplodedNode *
3518RetainCountChecker::processLeaks(ProgramStateRef state,
3519                                 SmallVectorImpl<SymbolRef> &Leaked,
3520                                 GenericNodeBuilderRefCount &Builder,
3521                                 CheckerContext &Ctx,
3522                                 ExplodedNode *Pred) const {
3523  if (Leaked.empty())
3524    return Pred;
3525
3526  // Generate an intermediate node representing the leak point.
3527  ExplodedNode *N = Builder.MakeNode(state, Pred);
3528
3529  if (N) {
3530    for (SmallVectorImpl<SymbolRef>::iterator
3531         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3532
3533      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3534      bool GCEnabled = Ctx.isObjCGCEnabled();
3535      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3536                          : getLeakAtReturnBug(LOpts, GCEnabled);
3537      assert(BT && "BugType not initialized.");
3538
3539      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3540                                                    SummaryLog, N, *I, Ctx);
3541      Ctx.EmitReport(report);
3542    }
3543  }
3544
3545  return N;
3546}
3547
3548void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
3549  ProgramStateRef state = Ctx.getState();
3550  GenericNodeBuilderRefCount Bd(Ctx);
3551  RefBindings B = state->get<RefBindings>();
3552  ExplodedNode *Pred = Ctx.getPredecessor();
3553
3554  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3555    llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
3556                                                     I->first, I->second);
3557    if (!state)
3558      return;
3559  }
3560
3561  // If the current LocationContext has a parent, don't check for leaks.
3562  // We will do that later.
3563  // FIXME: we should instead check for imblances of the retain/releases,
3564  // and suggest annotations.
3565  if (Ctx.getLocationContext()->getParent())
3566    return;
3567
3568  B = state->get<RefBindings>();
3569  SmallVector<SymbolRef, 10> Leaked;
3570
3571  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3572    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3573
3574  processLeaks(state, Leaked, Bd, Ctx, Pred);
3575}
3576
3577const ProgramPointTag *
3578RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3579  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3580  if (!tag) {
3581    SmallString<64> buf;
3582    llvm::raw_svector_ostream out(buf);
3583    out << "RetainCountChecker : Dead Symbol : ";
3584    sym->dumpToStream(out);
3585    tag = new SimpleProgramPointTag(out.str());
3586  }
3587  return tag;
3588}
3589
3590void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3591                                          CheckerContext &C) const {
3592  ExplodedNode *Pred = C.getPredecessor();
3593
3594  ProgramStateRef state = C.getState();
3595  RefBindings B = state->get<RefBindings>();
3596
3597  // Update counts from autorelease pools
3598  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3599       E = SymReaper.dead_end(); I != E; ++I) {
3600    SymbolRef Sym = *I;
3601    if (const RefVal *T = B.lookup(Sym)){
3602      // Use the symbol as the tag.
3603      // FIXME: This might not be as unique as we would like.
3604      GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
3605      llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
3606                                                       Sym, *T);
3607      if (!state)
3608        return;
3609    }
3610  }
3611
3612  B = state->get<RefBindings>();
3613  SmallVector<SymbolRef, 10> Leaked;
3614
3615  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3616       E = SymReaper.dead_end(); I != E; ++I) {
3617    if (const RefVal *T = B.lookup(*I))
3618      state = handleSymbolDeath(state, *I, *T, Leaked);
3619  }
3620
3621  {
3622    GenericNodeBuilderRefCount Bd(C, this);
3623    Pred = processLeaks(state, Leaked, Bd, C, Pred);
3624  }
3625
3626  // Did we cache out?
3627  if (!Pred)
3628    return;
3629
3630  // Now generate a new node that nukes the old bindings.
3631  RefBindings::Factory &F = state->get_context<RefBindings>();
3632
3633  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3634       E = SymReaper.dead_end(); I != E; ++I)
3635    B = F.remove(B, *I);
3636
3637  state = state->set<RefBindings>(B);
3638  C.addTransition(state, Pred);
3639}
3640
3641//===----------------------------------------------------------------------===//
3642// Debug printing of refcount bindings and autorelease pools.
3643//===----------------------------------------------------------------------===//
3644
3645static void PrintPool(raw_ostream &Out, SymbolRef Sym,
3646                      ProgramStateRef State) {
3647  Out << ' ';
3648  if (Sym)
3649    Sym->dumpToStream(Out);
3650  else
3651    Out << "<pool>";
3652  Out << ":{";
3653
3654  // Get the contents of the pool.
3655  if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3656    for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3657      Out << '(' << I.getKey() << ',' << I.getData() << ')';
3658
3659  Out << '}';
3660}
3661
3662static bool UsesAutorelease(ProgramStateRef state) {
3663  // A state uses autorelease if it allocated an autorelease pool or if it has
3664  // objects in the caller's autorelease pool.
3665  return !state->get<AutoreleaseStack>().isEmpty() ||
3666          state->get<AutoreleasePoolContents>(SymbolRef());
3667}
3668
3669void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3670                                    const char *NL, const char *Sep) const {
3671
3672  RefBindings B = State->get<RefBindings>();
3673
3674  if (!B.isEmpty())
3675    Out << Sep << NL;
3676
3677  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3678    Out << I->first << " : ";
3679    I->second.print(Out);
3680    Out << NL;
3681  }
3682
3683  // Print the autorelease stack.
3684  if (UsesAutorelease(State)) {
3685    Out << Sep << NL << "AR pool stack:";
3686    ARStack Stack = State->get<AutoreleaseStack>();
3687
3688    PrintPool(Out, SymbolRef(), State);  // Print the caller's pool.
3689    for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3690      PrintPool(Out, *I, State);
3691
3692    Out << NL;
3693  }
3694}
3695
3696//===----------------------------------------------------------------------===//
3697// Checker registration.
3698//===----------------------------------------------------------------------===//
3699
3700void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3701  Mgr.registerChecker<RetainCountChecker>();
3702}
3703
3704