r339079 - [analyzer] Add ASTContext to CheckerManager

2018-08-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Aug  6 16:09:07 2018
New Revision: 339079

URL: http://llvm.org/viewvc/llvm-project?rev=339079&view=rev
Log:
[analyzer] Add ASTContext to CheckerManager

Some checkers require ASTContext. Having it in the constructor saves a
lot of boilerplate of having to pass it around.

Differential Revision: https://reviews.llvm.org/D50111

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/CheckerManager.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h
cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/CheckerManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/CheckerManager.h?rev=339079&r1=339078&r2=339079&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/CheckerManager.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/CheckerManager.h Mon Aug  6 
16:09:07 2018
@@ -115,13 +115,14 @@ enum class ObjCMessageVisitKind {
 };
 
 class CheckerManager {
+  ASTContext &Context;
   const LangOptions LangOpts;
   AnalyzerOptions &AOptions;
   CheckName CurrentCheckName;
 
 public:
-  CheckerManager(const LangOptions &langOpts, AnalyzerOptions &AOptions)
-  : LangOpts(langOpts), AOptions(AOptions) {}
+  CheckerManager(ASTContext &Context, AnalyzerOptions &AOptions)
+  : Context(Context), LangOpts(Context.getLangOpts()), AOptions(AOptions) 
{}
 
   ~CheckerManager();
 
@@ -134,6 +135,7 @@ public:
 
   const LangOptions &getLangOpts() const { return LangOpts; }
   AnalyzerOptions &getAnalyzerOptions() { return AOptions; }
+  ASTContext &getASTContext() { return Context; }
 
   using CheckerRef = CheckerBase *;
   using CheckerTag = const void *;

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h?rev=339079&r1=339078&r2=339079&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h 
Mon Aug  6 16:09:07 2018
@@ -46,14 +46,12 @@ class AnalysisManager : public BugReport
 public:
   AnalyzerOptions &options;
 
-  AnalysisManager(ASTContext &ctx,DiagnosticsEngine &diags,
-  const LangOptions &lang,
+  AnalysisManager(ASTContext &ctx, DiagnosticsEngine &diags,
   const PathDiagnosticConsumers &Consumers,
   StoreManagerCreator storemgr,
   ConstraintManagerCreator constraintmgr,
-  CheckerManager *checkerMgr,
-  AnalyzerOptions &Options,
-  CodeInjector* injector = nullptr);
+  CheckerManager *checkerMgr, AnalyzerOptions &Options,
+  CodeInjector *injector = nullptr);
 
   ~AnalysisManager() override;
 

Modified: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h?rev=339079&r1=339078&r2=339079&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h Mon 
Aug  6 16:09:07 2018
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_STATICANALYZER_FRONTEND_CHECKERREGISTRATION_H
 #define LLVM_CLANG_STATICANALYZER_FRONTEND_CHECKERREGISTRATION_H
 
+#include "clang/AST/ASTContext.h"
 #include "clang/Basic/LLVM.h"
 #include 
 #include 
@@ -25,7 +26,8 @@ namespace ento {
   class CheckerRegistry;
 
   std::unique_ptr createCheckerManager(
-  AnalyzerOptions &opts, const LangOptions &langOpts,
+  ASTContext &context,
+  AnalyzerOptions &opts,
   ArrayRef plugins,
   ArrayRef> checkerRegistrationFns,
   DiagnosticsEngine &diags);

Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp?rev=339079&r1=339078&r2=339079&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp Mon Aug  6 16:09:07 
2018
@@ -14,28 +14,28 @@ using namespace ento;
 
 void AnalysisManager::anchor() { }
 
-AnalysisManager::AnalysisManager(
-ASTContext &ASTCtx, DiagnosticsEngine &diags, const LangOptions &lang,
-

r339183 - [analyzer] [tests] Do not be verbose by default when updating reference results.

2018-08-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Aug  7 14:14:35 2018
New Revision: 339183

URL: http://llvm.org/viewvc/llvm-project?rev=339183&view=rev
Log:
[analyzer] [tests] Do not be verbose by default when updating reference results.

Modified:
cfe/trunk/utils/analyzer/SATestUpdateDiffs.py

Modified: cfe/trunk/utils/analyzer/SATestUpdateDiffs.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestUpdateDiffs.py?rev=339183&r1=339182&r2=339183&view=diff
==
--- cfe/trunk/utils/analyzer/SATestUpdateDiffs.py (original)
+++ cfe/trunk/utils/analyzer/SATestUpdateDiffs.py Tue Aug  7 14:14:35 2018
@@ -10,7 +10,7 @@ from subprocess import check_call
 import os
 import sys
 
-Verbose = 1
+Verbose = 0
 
 
 def runCmd(Command, **kwargs):


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339369 - [analyzer] Fix the bug in UninitializedObjectChecker caused by not handling block pointers

2018-08-09 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Aug  9 12:03:12 2018
New Revision: 339369

URL: http://llvm.org/viewvc/llvm-project?rev=339369&view=rev
Log:
[analyzer] Fix the bug in UninitializedObjectChecker caused by not handling 
block pointers

Differential Revision: https://reviews.llvm.org/D50523

Added:
cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp?rev=339369&r1=339368&r2=339369&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp Thu 
Aug  9 12:03:12 2018
@@ -417,7 +417,7 @@ bool FindUninitializedFields::isNonUnion
   continue;
 }
 
-if (T->isPointerType() || T->isReferenceType()) {
+if (T->isPointerType() || T->isReferenceType() || T->isBlockPointerType()) 
{
   if (isPointerOrReferenceUninit(FR, LocalChain))
 ContainsUninitField = true;
   continue;
@@ -478,7 +478,8 @@ bool FindUninitializedFields::isPointerO
 const FieldRegion *FR, FieldChainInfo LocalChain) {
 
   assert((FR->getDecl()->getType()->isPointerType() ||
-  FR->getDecl()->getType()->isReferenceType()) &&
+  FR->getDecl()->getType()->isReferenceType() ||
+  FR->getDecl()->getType()->isBlockPointerType()) &&
  "This method only checks pointer/reference objects!");
 
   SVal V = State->getSVal(FR);

Added: cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm?rev=339369&view=auto
==
--- cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm (added)
+++ cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm Thu Aug  9 12:03:12 
2018
@@ -0,0 +1,22 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.cplusplus.UninitializedObject -std=c++11 -fblocks 
-verify %s
+
+typedef void (^myBlock) ();
+
+struct StructWithBlock {
+  int a;
+  myBlock z; // expected-note{{uninitialized field 'this->z'}}
+
+  StructWithBlock() : a(0), z(^{}) {}
+
+  // Miss initialization of field `z`.
+  StructWithBlock(int pA) : a(pA) {} // expected-warning{{1 uninitialized 
field at the end of the constructor call}}
+
+};
+
+void warnOnUninitializedBlock() {
+  StructWithBlock a(10);
+}
+
+void noWarningWhenInitialized() {
+  StructWithBlock a;
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339459 - Invalidate static locals when escaping lambdas

2018-08-10 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 10 11:28:04 2018
New Revision: 339459

URL: http://llvm.org/viewvc/llvm-project?rev=339459&view=rev
Log:
Invalidate static locals when escaping lambdas

Lambdas can affect static locals even without an explicit capture.

rdar://39537031

Differential Revision: https://reviews.llvm.org/D50368

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
cfe/trunk/test/Analysis/lambdas.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=339459&r1=339458&r2=339459&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Aug 10 11:28:04 2018
@@ -17,6 +17,7 @@
 
 #include "clang/AST/Attr.h"
 #include "clang/AST/CharUnits.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/Analyses/LiveVariables.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Basic/TargetInfo.h"
@@ -1033,6 +1034,32 @@ void invalidateRegionsWorker::VisitClust
   B = B.remove(baseR);
   }
 
+  if (const auto *TO = dyn_cast(baseR)) {
+if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) {
+
+  // Lambdas can affect all static local variables without explicitly
+  // capturing those.
+  // We invalidate all static locals referenced inside the lambda body.
+  if (RD->isLambda() && RD->getLambdaCallOperator()->getBody()) {
+using namespace ast_matchers;
+
+const char *DeclBind = "DeclBind";
+StatementMatcher RefToStatic = stmt(hasDescendant(declRefExpr(
+  to(varDecl(hasStaticStorageDuration()).bind(DeclBind);
+auto Matches =
+match(RefToStatic, *RD->getLambdaCallOperator()->getBody(),
+  RD->getASTContext());
+
+for (BoundNodes &Match : Matches) {
+  auto *VD = Match.getNodeAs(DeclBind);
+  const VarRegion *ToInvalidate =
+  RM.getRegionManager().getVarRegion(VD, LCtx);
+  AddToWorkList(ToInvalidate);
+}
+  }
+}
+  }
+
   // BlockDataRegion?  If so, invalidate captured variables that are passed
   // by reference.
   if (const BlockDataRegion *BR = dyn_cast(baseR)) {

Modified: cfe/trunk/test/Analysis/lambdas.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/lambdas.cpp?rev=339459&r1=339458&r2=339459&view=diff
==
--- cfe/trunk/test/Analysis/lambdas.cpp (original)
+++ cfe/trunk/test/Analysis/lambdas.cpp Fri Aug 10 11:28:04 2018
@@ -1,10 +1,26 @@
 // RUN: %clang_analyze_cc1 -std=c++11 
-analyzer-checker=core,deadcode,debug.ExprInspection -analyzer-config 
inline-lambdas=true -verify %s
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core -analyzer-config 
inline-lambdas=false -DNO_INLINING=1 -verify %s
 // RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,debug.DumpCFG 
-analyzer-config inline-lambdas=true %s > %t 2>&1
 // RUN: FileCheck --input-file=%t %s
 
 void clang_analyzer_warnIfReached();
 void clang_analyzer_eval(int);
 
+#ifdef NO_INLINING
+
+// expected-no-diagnostics
+
+int& invalidate_static_on_unknown_lambda() {
+  static int* z;
+  auto f = [] {
+z = nullptr;
+  }; // should invalidate "z" when inlining is disabled.
+  f();
+  return *z; // no-warning
+}
+
+#else
+
 struct X { X(const X&); };
 void f(X x) { (void) [x]{}; }
 
@@ -348,6 +364,18 @@ void testCapturedConstExprFloat() {
   lambda();
 }
 
+void escape(void*);
+
+int& invalidate_static_on_unknown_lambda() {
+  static int* z;
+  auto lambda = [] {
+static float zz;
+z = new int(120);
+  };
+  escape(&lambda);
+  return *z; // no-warning
+}
+
 
 static int b = 0;
 
@@ -365,6 +393,8 @@ int f() {
   return 0;
 }
 
+#endif
+
 // CHECK: [B2 (ENTRY)]
 // CHECK:   Succs (1): B1
 // CHECK: [B1]


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339476 - [analyzer] Fix tracking expressions through negation operator

2018-08-10 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 10 14:42:19 2018
New Revision: 339476

URL: http://llvm.org/viewvc/llvm-project?rev=339476&view=rev
Log:
[analyzer] Fix tracking expressions through negation operator

Differential Revision: https://reviews.llvm.org/D50537

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=339476&r1=339475&r2=339476&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Fri Aug 10 
14:42:19 2018
@@ -1560,6 +1560,10 @@ static const Expr *peelOffOuterExpr(cons
 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
   return peelOffOuterExpr(SubEx, N);
 
+  if (auto *UO = dyn_cast(Ex))
+if (UO->getOpcode() == UO_LNot)
+  return peelOffOuterExpr(UO->getSubExpr(), N);
+
   return Ex;
 }
 

Modified: cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp?rev=339476&r1=339475&r2=339476&view=diff
==
--- cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp (original)
+++ cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp Fri Aug 10 
14:42:19 2018
@@ -357,3 +357,18 @@ int forceElementRegionApperence() {
   return ((HasFieldB*)&a)->x; // expected-warning{{Undefined or garbage value 
returned to caller}}
   // expected-note@-1{{Undefined or garbage value 
returned to caller}}
 }
+
+
+
+struct HasForgottenField {
+  int x;
+  HasForgottenField() {} // expected-note{{Returning without writing to 
'this->x'}}
+};
+
+// Test that tracking across exclamation mark works.
+bool tracksThroughExclamationMark() {
+  HasForgottenField a; // expected-note{{Calling default constructor for 
'HasForgottenField'}}
+   // expected-note@-1{{Returning from default constructor 
for 'HasForgottenField'}}
+  return !a.x; // expected-warning{{Undefined or garbage value returned to 
caller}}
+   // expected-note@-1{{Undefined or garbage value returned to 
caller}}
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339482 - [analyzer] Record nullability implications on getting items from NSDictionary

2018-08-10 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 10 15:27:04 2018
New Revision: 339482

URL: http://llvm.org/viewvc/llvm-project?rev=339482&view=rev
Log:
[analyzer] Record nullability implications on getting items from NSDictionary

If we get an item from a dictionary, we know that the item is non-null
if and only if the key is non-null.

This patch is a rather hacky way to record this implication, because
some logic needs to be duplicated from the solver.
And yet, it's pretty simple, performant, and works.

Other possible approaches:

 - Record the implication, in future rely on Z3 to pick it up.
 - Generalize the current code and move it to the constraint manager.

rdar://34990742

Differential Revision: https://reviews.llvm.org/D50124

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
cfe/trunk/test/Analysis/Inputs/system-header-simulator-for-nullability.h
cfe/trunk/test/Analysis/trustnonnullchecker_test.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp?rev=339482&r1=339481&r2=339482&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/TrustNonnullChecker.cpp Fri Aug 10 
15:27:04 2018
@@ -1,4 +1,4 @@
-//== TrustNonnullChecker.cpp - Checker for trusting annotations -*- C++ 
-*--==//
+//== TrustNonnullChecker.cpp - API nullability modeling -*- C++ 
-*--==//
 //
 // The LLVM Compiler Infrastructure
 //
@@ -7,12 +7,20 @@
 //
 
//===--===//
 //
-// This checker adds an assumption that methods annotated with _Nonnull
+// This checker adds nullability-related assumptions:
+//
+// 1. Methods annotated with _Nonnull
 // which come from system headers actually return a non-null pointer.
 //
+// 2. NSDictionary key is non-null after the keyword subscript operation
+// on read if and only if the resulting expression is non-null.
+//
+// 3. NSMutableDictionary index is non-null after a write operation.
+//
 
//===--===//
 
 #include "ClangSACheckers.h"
+#include "SelectorExtras.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
@@ -22,10 +30,129 @@
 using namespace clang;
 using namespace ento;
 
+/// Records implications between symbols.
+/// The semantics is:
+///(antecedent != 0) => (consequent != 0)
+/// These implications are then read during the evaluation of the assumption,
+/// and the appropriate antecedents are applied.
+REGISTER_MAP_WITH_PROGRAMSTATE(NonNullImplicationMap, SymbolRef, SymbolRef)
+
+/// The semantics is:
+///(antecedent == 0) => (consequent == 0)
+REGISTER_MAP_WITH_PROGRAMSTATE(NullImplicationMap, SymbolRef, SymbolRef)
+
 namespace {
 
-class TrustNonnullChecker : public Checker {
+class TrustNonnullChecker : public Checker {
+  // Do not try to iterate over symbols with higher complexity.
+  static unsigned constexpr ComplexityThreshold = 10;
+  Selector ObjectForKeyedSubscriptSel;
+  Selector ObjectForKeySel;
+  Selector SetObjectForKeyedSubscriptSel;
+  Selector SetObjectForKeySel;
+
+public:
+  TrustNonnullChecker(ASTContext &Ctx)
+  : ObjectForKeyedSubscriptSel(
+getKeywordSelector(Ctx, "objectForKeyedSubscript")),
+ObjectForKeySel(getKeywordSelector(Ctx, "objectForKey")),
+SetObjectForKeyedSubscriptSel(
+getKeywordSelector(Ctx, "setObject", "forKeyedSubscript")),
+SetObjectForKeySel(getKeywordSelector(Ctx, "setObject", "forKey")) {}
+
+  ProgramStateRef evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+const SymbolRef CondS = Cond.getAsSymbol();
+if (!CondS || CondS->computeComplexity() > ComplexityThreshold)
+  return State;
+
+for (auto B=CondS->symbol_begin(), E=CondS->symbol_end(); B != E; ++B) {
+  const SymbolRef Antecedent = *B;
+  State = addImplication(Antecedent, State, true);
+  State = addImplication(Antecedent, State, false);
+}
+
+return State;
+  }
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
+// Only trust annotations for system headers for non-protocols.
+if (!Call.isInSystemHeader())
+  return;
+
+ProgramStateRef State = C.getState();
+
+if (isNonNullPtr(Call, C))
+  if (auto L = Call.getReturnValue().getAs())
+State = State->assume(*L, /*Assumption=*/true);
+
+C.addTransition(State);
+  }
+
+  void checkPostObjCMessage(const ObjCMethodCall &Msg,
+CheckerContext &C) const {
+const ObjCInterfaceDecl *ID = Msg.getRe

r339493 - [analyzer] Fix keyboard navigation for .msgNote events

2018-08-10 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 10 18:47:41 2018
New Revision: 339493

URL: http://llvm.org/viewvc/llvm-project?rev=339493&view=rev
Log:
[analyzer] Fix keyboard navigation for .msgNote events

Does not go to msgNote's.

Differential Revision: https://reviews.llvm.org/D50595

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=339493&r1=339492&r2=339493&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Fri Aug 10 18:47:41 
2018
@@ -997,7 +997,8 @@ var numToId = function(num) {
 };
 
 var navigateTo = function(up) {
-  var numItems = document.querySelectorAll(".line > .msg").length;
+  var numItems = document.querySelectorAll(
+  ".line > .msgEvent, .line > .msgControl").length;
   var currentSelected = findNum();
   var newSelected = move(currentSelected, up, numItems);
   var newEl = numToId(newSelected, numItems);


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339629 - [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-13 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Aug 13 16:12:43 2018
New Revision: 339629

URL: http://llvm.org/viewvc/llvm-project?rev=339629&view=rev
Log:
[analyzer] [NFC] Introduce separate targets for testing the analyzer: 
check-clang-analyzer and check-clang-analyzer-z3

Current testing setup for analyzer tests with Z3 is rather inconvenient:

There's no way to run the analyzer tests separately (I use
LIT_FILTER=Analysis ninja check-clang, but a direct target is nicer).

When Clang is built with Z3 support, there's no way to *not* run tests
with Z3 solver, and this is often desired, as tests with Z3 solver take
a very long time.

This patch introduces two extra targets:

 - check-clang-analyzer
 - check-clang-analyzer-z3

which solve those problems.

Differential Revision: https://reviews.llvm.org/D50594

Modified:
cfe/trunk/test/Analysis/analyzer_test.py
cfe/trunk/test/Analysis/lit.local.cfg
cfe/trunk/test/CMakeLists.txt
cfe/trunk/test/lit.site.cfg.py.in

Modified: cfe/trunk/test/Analysis/analyzer_test.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer_test.py?rev=339629&r1=339628&r2=339629&view=diff
==
--- cfe/trunk/test/Analysis/analyzer_test.py (original)
+++ cfe/trunk/test/Analysis/analyzer_test.py Mon Aug 13 16:12:43 2018
@@ -4,6 +4,10 @@ import lit.TestRunner
 # Custom format class for static analyzer tests
 class AnalyzerTest(lit.formats.ShTest):
 
+def __init__(self, execute_external, use_z3_solver=False):
+super(AnalyzerTest, self).__init__(execute_external)
+self.use_z3_solver = use_z3_solver
+
 def execute(self, test, litConfig):
 results = []
 
@@ -19,7 +23,8 @@ class AnalyzerTest(lit.formats.ShTest):
 return results[-1]
 
 # If z3 backend available, add an additional run line for it
-if test.config.clang_staticanalyzer_z3 == '1':
+if self.use_z3_solver == '1':
+assert(test.config.clang_staticanalyzer_z3 == '1')
 results.append(self.executeWithAnalyzeSubstitution(
 saved_test, litConfig, '-analyzer-constraints=z3 
-DANALYZER_CM_Z3'))
 

Modified: cfe/trunk/test/Analysis/lit.local.cfg
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/lit.local.cfg?rev=339629&r1=339628&r2=339629&view=diff
==
--- cfe/trunk/test/Analysis/lit.local.cfg (original)
+++ cfe/trunk/test/Analysis/lit.local.cfg Mon Aug 13 16:12:43 2018
@@ -7,7 +7,7 @@ import site
 site.addsitedir(os.path.dirname(__file__))
 import analyzer_test
 config.test_format = analyzer_test.AnalyzerTest(
-config.test_format.execute_external)
+config.test_format.execute_external, config.use_z3_solver)
 
 if not config.root.clang_staticanalyzer:
 config.unsupported = True

Modified: cfe/trunk/test/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CMakeLists.txt?rev=339629&r1=339628&r2=339629&view=diff
==
--- cfe/trunk/test/CMakeLists.txt (original)
+++ cfe/trunk/test/CMakeLists.txt Mon Aug 13 16:12:43 2018
@@ -88,8 +88,15 @@ endif ()
 
 set(CLANG_TEST_PARAMS
   clang_site_config=${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
+  USE_Z3_SOLVER=0
   )
 
+set(ANALYZER_TEST_PARAMS
+  USE_Z3_SOLVER=0)
+
+set(ANALYZER_TEST_PARAMS_Z3
+  USE_Z3_SOLVER=1)
+
 if( NOT CLANG_BUILT_STANDALONE )
   list(APPEND CLANG_TEST_DEPS
 llvm-config
@@ -126,6 +133,24 @@ add_lit_testsuite(check-clang "Running t
   )
 set_target_properties(check-clang PROPERTIES FOLDER "Clang tests")
 
+if (CLANG_ENABLE_STATIC_ANALYZER)
+  add_lit_testsuite(check-clang-analyzer "Running the Clang analyzer tests"
+${CMAKE_CURRENT_BINARY_DIR}/Analysis
+PARAMS ${ANALYZER_TEST_PARAMS}
+DEPENDS ${CLANG_TEST_DEPS})
+  set_target_properties(check-clang-analyzer PROPERTIES FOLDER "Clang tests")
+
+
+  if (CLANG_ANALYZER_WITH_Z3)
+add_lit_testsuite(check-clang-analyzer-z3 "Running the Clang analyzer 
tests, using Z3 as a solver"
+  ${CMAKE_CURRENT_BINARY_DIR}/Analysis
+  PARAMS ${ANALYZER_TEST_PARAMS_Z3}
+  DEPENDS ${CLANG_TEST_DEPS})
+set_target_properties(check-clang-analyzer-z3 PROPERTIES FOLDER "Clang 
tests")
+  endif()
+
+endif()
+
 add_lit_testsuites(CLANG ${CMAKE_CURRENT_SOURCE_DIR}
   PARAMS ${CLANG_TEST_PARAMS}
   DEPENDS ${CLANG_TEST_DEPS}

Modified: cfe/trunk/test/lit.site.cfg.py.in
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/lit.site.cfg.py.in?rev=339629&r1=339628&r2=339629&view=diff
==
--- cfe/trunk/test/lit.site.cfg.py.in (original)
+++ cfe/trunk/test/lit.site.cfg.py.in Mon Aug 13 16:12:43 2018
@@ -26,6 +26,7 @@ config.enable_shared = @ENABLE_SHARED@
 config.enable_backtrace = @ENABLE_BACKTRACES@
 config.host_arch = "@HOST_ARCH@"
 config.python_ex

r339631 - [analyzer] Fix UninitializedObjectChecker to not crash on uninitialized "id" fields

2018-08-13 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Aug 13 16:32:15 2018
New Revision: 339631

URL: http://llvm.org/viewvc/llvm-project?rev=339631&view=rev
Log:
[analyzer] Fix UninitializedObjectChecker to not crash on uninitialized "id" 
fields

Differential Revision: https://reviews.llvm.org/D50673

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp?rev=339631&r1=339630&r2=339631&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObjectChecker.cpp
 Mon Aug 13 16:32:15 2018
@@ -265,7 +265,7 @@ bool FindUninitializedFields::isNonUnion
   continue;
 }
 
-if (T->isPointerType() || T->isReferenceType() || T->isBlockPointerType()) 
{
+if (T->isAnyPointerType() || T->isReferenceType() || 
T->isBlockPointerType()) {
   if (isPointerOrReferenceUninit(FR, LocalChain))
 ContainsUninitField = true;
   continue;

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp?rev=339631&r1=339630&r2=339631&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedPointee.cpp
 Mon Aug 13 16:32:15 2018
@@ -78,7 +78,7 @@ static bool isVoidPointer(QualType T);
 bool FindUninitializedFields::isPointerOrReferenceUninit(
 const FieldRegion *FR, FieldChainInfo LocalChain) {
 
-  assert((FR->getDecl()->getType()->isPointerType() ||
+  assert((FR->getDecl()->getType()->isAnyPointerType() ||
   FR->getDecl()->getType()->isReferenceType() ||
   FR->getDecl()->getType()->isBlockPointerType()) &&
  "This method only checks pointer/reference objects!");

Modified: cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm?rev=339631&r1=339630&r2=339631&view=diff
==
--- cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm (original)
+++ cfe/trunk/test/Analysis/objcpp-uninitialized-object.mm Mon Aug 13 16:32:15 
2018
@@ -20,3 +20,13 @@ void warnOnUninitializedBlock() {
 void noWarningWhenInitialized() {
   StructWithBlock a;
 }
+
+struct StructWithId {
+  int a;
+  id z; // expected-note{{uninitialized pointer 'this->z'}}
+  StructWithId() : a(0) {} // expected-warning{{1 uninitialized field at the 
end of the constructor call}}
+};
+
+void warnOnUninitializedId() {
+  StructWithId s;
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D50594: [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-14 Thread George Karpenkov via cfe-commits
Yes, investigating. Will rollback if not fixed in a few hours.

> On Aug 14, 2018, at 3:17 AM, Yvan Roux via Phabricator 
>  wrote:
> 
> yroux added a comment.
> 
> Notice that the affected bots run two times the test cases where one 
> execution passes and one fails, as you can see in (search 
> Analysis/plist-macros.cpp for instance):
> 
> http://lab.llvm.org:8011/builders/clang-cmake-armv8-full/builds/5450/steps/ninja%20check%201/logs/stdio
> 
> and I think it is due to llvm-lit being invoked with "--param USE_Z3_SOLVER=0 
> --param USE_Z3_SOLVER=0"
> 
> 
> Repository:
>  rC Clang
> 
> https://reviews.llvm.org/D50594
> 
> 
> 

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339709 - [analyzer] Fix bots by removing new check-clang-analyzer commands from CHECK-ALL

2018-08-14 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Aug 14 11:55:34 2018
New Revision: 339709

URL: http://llvm.org/viewvc/llvm-project?rev=339709&view=rev
Log:
[analyzer] Fix bots by removing new check-clang-analyzer commands from CHECK-ALL

Modified:
cfe/trunk/test/CMakeLists.txt

Modified: cfe/trunk/test/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CMakeLists.txt?rev=339709&r1=339708&r2=339709&view=diff
==
--- cfe/trunk/test/CMakeLists.txt (original)
+++ cfe/trunk/test/CMakeLists.txt Tue Aug 14 11:55:34 2018
@@ -134,6 +134,9 @@ add_lit_testsuite(check-clang "Running t
 set_target_properties(check-clang PROPERTIES FOLDER "Clang tests")
 
 if (CLANG_ENABLE_STATIC_ANALYZER)
+  # check-all would launch those tests via check-clang.
+  set(EXCLUDE_FROM_ALL ON)
+
   add_lit_testsuite(check-clang-analyzer "Running the Clang analyzer tests"
 ${CMAKE_CURRENT_BINARY_DIR}/Analysis
 PARAMS ${ANALYZER_TEST_PARAMS}
@@ -149,6 +152,7 @@ if (CLANG_ENABLE_STATIC_ANALYZER)
 set_target_properties(check-clang-analyzer-z3 PROPERTIES FOLDER "Clang 
tests")
   endif()
 
+  set(EXCLUDE_FROM_ALL OFF)
 endif()
 
 add_lit_testsuites(CLANG ${CMAKE_CURRENT_SOURCE_DIR}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D50594: [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-14 Thread George Karpenkov via cfe-commits
Should be fixed.

> On Aug 14, 2018, at 10:32 AM, George Karpenkov via cfe-commits 
>  wrote:
> 
> Yes, investigating. Will rollback if not fixed in a few hours.
> 
>> On Aug 14, 2018, at 3:17 AM, Yvan Roux via Phabricator 
>>  wrote:
>> 
>> yroux added a comment.
>> 
>> Notice that the affected bots run two times the test cases where one 
>> execution passes and one fails, as you can see in (search 
>> Analysis/plist-macros.cpp for instance):
>> 
>> http://lab.llvm.org:8011/builders/clang-cmake-armv8-full/builds/5450/steps/ninja%20check%201/logs/stdio
>> 
>> and I think it is due to llvm-lit being invoked with "--param 
>> USE_Z3_SOLVER=0 --param USE_Z3_SOLVER=0"
>> 
>> 
>> Repository:
>> rC Clang
>> 
>> https://reviews.llvm.org/D50594
>> 
>> 
>> 
> 
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D50594: [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-14 Thread George Karpenkov via cfe-commits
Should be fixed now.

> On Aug 14, 2018, at 1:10 AM, Thomas Preud'homme via Phabricator 
>  wrote:
> 
> thopre added a comment.
> 
> Hi George,
> 
> This commit seems to be causing some testsuite regression on Armv8 (both 
> Aarch64 and ARM) architectures:
> http://lab.llvm.org:8011/builders/clang-cmake-armv8-full/builds/5450
> http://lab.llvm.org:8011/builders/clang-cmake-armv8-quick/builds/5625
> 
> Best regards,
> 
> Thomas
> 
> 
> Repository:
>  rC Clang
> 
> https://reviews.llvm.org/D50594
> 
> 
> 

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r339629 - [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-14 Thread George Karpenkov via cfe-commits
Hi, this should have been fixed by https://reviews.llvm.org/rC339709 
<https://reviews.llvm.org/rC339709>

> On Aug 14, 2018, at 12:16 PM, Galina Kistanova  wrote:
> 
> Hello George,
> 
> This commit broke few of our builders:
> 
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/34845
>  
> <http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/34845>
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast/builds/19056
>  
> <http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast/builds/19056>
> 
> http://lab.llvm.org:8011/builders/clang-lld-x86_64-2stage 
> <http://lab.llvm.org:8011/builders/clang-lld-x86_64-2stage>
> http://lab.llvm.org:8011/builders/clang-with-lto-ubuntu 
> <http://lab.llvm.org:8011/builders/clang-with-lto-ubuntu>
> etc...
> 
> ...
> Failing Tests (11):
> Clang :: Analysis/auto-obj-dtors-cfg-output.cpp
> Clang :: Analysis/blocks.mm <http://blocks.mm/>
> Clang :: Analysis/cfg-rich-constructors.cpp
> Clang :: Analysis/cfg-rich-constructors.mm 
> <http://cfg-rich-constructors.mm/>
> Clang :: Analysis/conditional-path-notes.c
> Clang :: Analysis/diagnostics/plist-multi-file.c
> Clang :: Analysis/html-diags.c
> Clang :: Analysis/plist-html-macros.c
> Clang :: Analysis/plist-html-macros.c
> Clang :: Analysis/retain-release-path-notes-gc.m
> Clang :: Analysis/temp-obj-dtors-cfg-output.cpp
> 
> Please have a look ASAP?
> 
> Thanks
> 
> Galina
> 
> 
> On Mon, Aug 13, 2018 at 4:12 PM, George Karpenkov via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
> Author: george.karpenkov
> Date: Mon Aug 13 16:12:43 2018
> New Revision: 339629
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=339629&view=rev 
> <http://llvm.org/viewvc/llvm-project?rev=339629&view=rev>
> Log:
> [analyzer] [NFC] Introduce separate targets for testing the analyzer: 
> check-clang-analyzer and check-clang-analyzer-z3
> 
> Current testing setup for analyzer tests with Z3 is rather inconvenient:
> 
> There's no way to run the analyzer tests separately (I use
> LIT_FILTER=Analysis ninja check-clang, but a direct target is nicer).
> 
> When Clang is built with Z3 support, there's no way to *not* run tests
> with Z3 solver, and this is often desired, as tests with Z3 solver take
> a very long time.
> 
> This patch introduces two extra targets:
> 
>  - check-clang-analyzer
>  - check-clang-analyzer-z3
> 
> which solve those problems.
> 
> Differential Revision: https://reviews.llvm.org/D50594 
> <https://reviews.llvm.org/D50594>
> 
> Modified:
> cfe/trunk/test/Analysis/analyzer_test.py
> cfe/trunk/test/Analysis/lit.local.cfg
> cfe/trunk/test/CMakeLists.txt
> cfe/trunk/test/lit.site.cfg.py.in <http://lit.site.cfg.py.in/>
> 
> Modified: cfe/trunk/test/Analysis/analyzer_test.py
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer_test.py?rev=339629&r1=339628&r2=339629&view=diff
>  
> <http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer_test.py?rev=339629&r1=339628&r2=339629&view=diff>
> ==
> --- cfe/trunk/test/Analysis/analyzer_test.py (original)
> +++ cfe/trunk/test/Analysis/analyzer_test.py Mon Aug 13 16:12:43 2018
> @@ -4,6 +4,10 @@ import lit.TestRunner
>  # Custom format class for static analyzer tests
>  class AnalyzerTest(lit.formats.ShTest):
> 
> +def __init__(self, execute_external, use_z3_solver=False):
> +super(AnalyzerTest, self).__init__(execute_external)
> +self.use_z3_solver = use_z3_solver
> +
>  def execute(self, test, litConfig):
>  results = []
> 
> @@ -19,7 +23,8 @@ class AnalyzerTest(lit.formats.ShTest):
>  return results[-1]
> 
>  # If z3 backend available, add an additional run line for it
> -if test.config.clang_staticanalyzer_z3 == '1':
> +if self.use_z3_solver == '1':
> +assert(test.config.clang_staticanalyzer_z3 == '1')
>  results.append(self.executeWithAnalyzeSubstitution(
>  saved_test, litConfig, '-analyzer-constraints=z3 
> -DANALYZER_CM_Z3'))
> 
> 
> Modified: cfe/trunk/test/Analysis/lit.local.cfg
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/lit.local.cfg?rev=339629&r1=339628&r2=339629&view=diff
>  
> <http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analy

Re: r339629 - [analyzer] [NFC] Introduce separate targets for testing the analyzer: check-clang-analyzer and check-clang-analyzer-z3

2018-08-14 Thread George Karpenkov via cfe-commits


> On Aug 14, 2018, at 2:17 PM, Reid Kleckner  wrote:
> 
> After this, check-clang no longer worked, it emitted a fatal error because 
> USE_Z3_SOLVER was not in lit_config.params. I worked around it in r339728, 
> but you might want to double check it.

Hm that’s strange, it works for me, and the buildbots are quiet this time.
Sorry for the trouble.
Your change seems safe in either case.

> 
> On Mon, Aug 13, 2018 at 4:13 PM George Karpenkov via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
> Author: george.karpenkov
> Date: Mon Aug 13 16:12:43 2018
> New Revision: 339629
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=339629&view=rev 
> <http://llvm.org/viewvc/llvm-project?rev=339629&view=rev>
> Log:
> [analyzer] [NFC] Introduce separate targets for testing the analyzer: 
> check-clang-analyzer and check-clang-analyzer-z3
> 
> Current testing setup for analyzer tests with Z3 is rather inconvenient:
> 
> There's no way to run the analyzer tests separately (I use
> LIT_FILTER=Analysis ninja check-clang, but a direct target is nicer).
> 
> When Clang is built with Z3 support, there's no way to *not* run tests
> with Z3 solver, and this is often desired, as tests with Z3 solver take
> a very long time.
> 
> This patch introduces two extra targets:
> 
>  - check-clang-analyzer
>  - check-clang-analyzer-z3
> 
> which solve those problems.
> 
> Differential Revision: https://reviews.llvm.org/D50594 
> <https://reviews.llvm.org/D50594>
> 
> Modified:
> cfe/trunk/test/Analysis/analyzer_test.py
> cfe/trunk/test/Analysis/lit.local.cfg
> cfe/trunk/test/CMakeLists.txt
> cfe/trunk/test/lit.site.cfg.py.in <http://lit.site.cfg.py.in/>
> 
> Modified: cfe/trunk/test/Analysis/analyzer_test.py
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer_test.py?rev=339629&r1=339628&r2=339629&view=diff
>  
> <http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer_test.py?rev=339629&r1=339628&r2=339629&view=diff>
> ==
> --- cfe/trunk/test/Analysis/analyzer_test.py (original)
> +++ cfe/trunk/test/Analysis/analyzer_test.py Mon Aug 13 16:12:43 2018
> @@ -4,6 +4,10 @@ import lit.TestRunner
>  # Custom format class for static analyzer tests
>  class AnalyzerTest(lit.formats.ShTest):
> 
> +def __init__(self, execute_external, use_z3_solver=False):
> +super(AnalyzerTest, self).__init__(execute_external)
> +self.use_z3_solver = use_z3_solver
> +
>  def execute(self, test, litConfig):
>  results = []
> 
> @@ -19,7 +23,8 @@ class AnalyzerTest(lit.formats.ShTest):
>  return results[-1]
> 
>  # If z3 backend available, add an additional run line for it
> -if test.config.clang_staticanalyzer_z3 == '1':
> +if self.use_z3_solver == '1':
> +assert(test.config.clang_staticanalyzer_z3 == '1')
>  results.append(self.executeWithAnalyzeSubstitution(
>  saved_test, litConfig, '-analyzer-constraints=z3 
> -DANALYZER_CM_Z3'))
> 
> 
> Modified: cfe/trunk/test/Analysis/lit.local.cfg
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/lit.local.cfg?rev=339629&r1=339628&r2=339629&view=diff
>  
> <http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/lit.local.cfg?rev=339629&r1=339628&r2=339629&view=diff>
> ==
> --- cfe/trunk/test/Analysis/lit.local.cfg (original)
> +++ cfe/trunk/test/Analysis/lit.local.cfg Mon Aug 13 16:12:43 2018
> @@ -7,7 +7,7 @@ import site
>  site.addsitedir(os.path.dirname(__file__))
>  import analyzer_test
>  config.test_format = analyzer_test.AnalyzerTest(
> -config.test_format.execute_external)
> +config.test_format.execute_external, config.use_z3_solver)
> 
>  if not config.root.clang_staticanalyzer:
>  config.unsupported = True
> 
> Modified: cfe/trunk/test/CMakeLists.txt
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CMakeLists.txt?rev=339629&r1=339628&r2=339629&view=diff
>  
> <http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CMakeLists.txt?rev=339629&r1=339628&r2=339629&view=diff>
> ==
> --- cfe/trunk/test/CMakeLists.txt (original)
> +++ cfe/trunk/test/CMakeLists.txt Mon Aug 13 16:12:43 2018
> @@ -88,8 +88,15 @@ endif ()
> 
>  set(CLANG_TEST_PARAMS
>clang_site_config=${CMAKE_CURRENT_BINA

r340093 - [analyzer] [NFC] Split up summary generation in RetainCountChecker in two methods

2018-08-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 17 14:41:37 2018
New Revision: 340093

URL: http://llvm.org/viewvc/llvm-project?rev=340093&view=rev
Log:
[analyzer] [NFC] Split up summary generation in RetainCountChecker in two 
methods

Differential Revision: https://reviews.llvm.org/D50830

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.h

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp?rev=340093&r1=340092&r2=340093&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 Fri Aug 17 14:41:37 2018
@@ -58,228 +58,215 @@ RetainSummaryManager::getPersistentSumma
 }
 
 const RetainSummary *
-RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
-  // If we don't know what function we're calling, use our default summary.
-  if (!FD)
-return getDefaultSummary();
-
-  // Look up a summary in our cache of FunctionDecls -> Summaries.
-  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
-  if (I != FuncSummaries.end())
-return I->second;
+RetainSummaryManager::generateSummary(const FunctionDecl *FD,
+  bool &AllowAnnotations) {
+  // We generate "stop" summaries for implicitly defined functions.
+  if (FD->isImplicit()) {
+return getPersistentStopSummary();
+  }
 
-  // No summary?  Generate one.
-  const RetainSummary *S = nullptr;
-  bool AllowAnnotations = true;
+  // [PR 3337] Use 'getAs' to strip away any typedefs on the
+  // function's type.
+  const FunctionType *FT = FD->getType()->getAs();
+  const IdentifierInfo *II = FD->getIdentifier();
+  if (!II)
+return getDefaultSummary();
 
-  do {
-// We generate "stop" summaries for implicitly defined functions.
-if (FD->isImplicit()) {
-  S = getPersistentStopSummary();
-  break;
-}
+  StringRef FName = II->getName();
 
-// [PR 3337] Use 'getAs' to strip away any typedefs on the
-// function's type.
-const FunctionType* FT = FD->getType()->getAs();
-const IdentifierInfo *II = FD->getIdentifier();
-if (!II)
-  break;
-
-StringRef FName = II->getName();
-
-// Strip away preceding '_'.  Doing this here will effect all the checks
-// down below.
-FName = FName.substr(FName.find_first_not_of('_'));
-
-// Inspect the result type.
-QualType RetTy = FT->getReturnType();
-std::string RetTyName = RetTy.getAsString();
-
-// FIXME: This should all be refactored into a chain of "summary lookup"
-//  filters.
-assert(ScratchArgs.isEmpty());
-
-if (FName == "pthread_create" || FName == "pthread_setspecific") {
-  // Part of:  and .
-  // This will be addressed better with IPA.
-  S = getPersistentStopSummary();
-} else if (FName == "CFPlugInInstanceCreate") {
-  S = getPersistentSummary(RetEffect::MakeNoRet());
-} else if (FName == "IORegistryEntrySearchCFProperty"
-|| (RetTyName == "CFMutableDictionaryRef" && (
-   FName == "IOBSDNameMatching" ||
-   FName == "IOServiceMatching" ||
+  // Strip away preceding '_'.  Doing this here will effect all the checks
+  // down below.
+  FName = FName.substr(FName.find_first_not_of('_'));
+
+  // Inspect the result type.
+  QualType RetTy = FT->getReturnType();
+  std::string RetTyName = RetTy.getAsString();
+
+  // FIXME: This should all be refactored into a chain of "summary lookup"
+  //  filters.
+  assert(ScratchArgs.isEmpty());
+
+  if (FName == "pthread_create" || FName == "pthread_setspecific") {
+// Part of:  and .
+// This will be addressed better with IPA.
+return getPersistentStopSummary();
+  } else if (FName == "CFPlugInInstanceCreate") {
+return getPersistentSummary(RetEffect::MakeNoRet());
+  } else if (FName == "IORegistryEntrySearchCFProperty" ||
+ (RetTyName == "CFMutableDictionaryRef" &&
+  (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
FName == "IOServiceNameMatching" ||
FName == "IORegistryEntryIDMatching" ||
-   FName == "IOOpenFirmwarePathMatching"
-))) {
-  // Part of . (IOKit)
-  // This should be addressed using a API table.
-  S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),
-   DoNothing, DoNothing);
-} else if (FName == "IOServiceGetMatchingService" ||
-   FName == "IOServiceGetMatchingServices") {
-  // FIXES: 
-  // This should be addressed using a API table.  This strcmp is also
-  // a little gross, 

r340094 - [analyzer] [NFC] Move canEval function from RetainCountChecker to RetainCountSummaries

2018-08-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 17 14:42:05 2018
New Revision: 340094

URL: http://llvm.org/viewvc/llvm-project?rev=340094&view=rev
Log:
[analyzer] [NFC] Move canEval function from RetainCountChecker to 
RetainCountSummaries

Differential Revision: https://reviews.llvm.org/D50863

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.h

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=340094&r1=340093&r2=340094&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Fri Aug 17 14:42:05 2018
@@ -754,45 +754,15 @@ bool RetainCountChecker::evalCall(const
   if (!FD)
 return false;
 
-  IdentifierInfo *II = FD->getIdentifier();
-  if (!II)
-return false;
-
-  // For now, we're only handling the functions that return aliases of their
-  // arguments: CFRetain (and its families).
-  // Eventually we should add other functions we can model entirely,
-  // such as CFRelease, which don't invalidate their arguments or globals.
-  if (CE->getNumArgs() != 1)
-return false;
-
-  // Get the name of the function.
-  StringRef FName = II->getName();
-  FName = FName.substr(FName.find_first_not_of('_'));
+  RetainSummaryManager &SmrMgr = getSummaryManager(C);
+  QualType ResultTy = CE->getCallReturnType(C.getASTContext());
 
-  // See if it's one of the specific functions we know how to eval.
-  bool canEval = false;
   // See if the function has 'rc_ownership_trusted_implementation'
   // annotate attribute. If it does, we will not inline it.
   bool hasTrustedImplementationAnnotation = false;
 
-  QualType ResultTy = CE->getCallReturnType(C.getASTContext());
-  if (ResultTy->isPointerType()) {
-// Handle: (CF|CG|CV)Retain
-// CFAutorelease
-// It's okay to be a little sloppy here.
-if (cocoa::isRefType(ResultTy, "CF", FName) ||
-cocoa::isRefType(ResultTy, "CG", FName) ||
-cocoa::isRefType(ResultTy, "CV", FName)) {
-  canEval = RetainSummary::isRetain(FD, FName) ||
-RetainSummary::isAutorelease(FD, FName);
-} else {
-  if (FD->getDefinition()) {
-canEval = RetainSummary::isTrustedReferenceCountImplementation(
-FD->getDefinition());
-hasTrustedImplementationAnnotation = canEval;
-  }
-}
-  }
+  // See if it's one of the specific functions we know how to eval.
+  bool canEval = SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
 
   if (!canEval)
 return false;
@@ -1273,16 +1243,15 @@ void RetainCountChecker::checkBeginFunct
   if (!Ctx.inTopFrame())
 return;
 
+  RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
   const LocationContext *LCtx = Ctx.getLocationContext();
   const FunctionDecl *FD = dyn_cast(LCtx->getDecl());
 
-  if (!FD || RetainSummary::isTrustedReferenceCountImplementation(FD))
+  if (!FD || SmrMgr.isTrustedReferenceCountImplementation(FD))
 return;
 
   ProgramStateRef state = Ctx.getState();
-
-  const RetainSummary *FunctionSummary =
-  getSummaryManager(Ctx).getFunctionSummary(FD);
+  const RetainSummary *FunctionSummary = SmrMgr.getFunctionSummary(FD);
   ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
 
   for (unsigned idx = 0, e = FD->getNumParams(); idx != e; ++idx) {

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp?rev=340094&r1=340093&r2=340094&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 Fri Aug 17 14:42:05 2018
@@ -57,6 +57,27 @@ RetainSummaryManager::getPersistentSumma
   return Summ;
 }
 
+static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
+  for (const auto *Ann : D->specific_attrs()) {
+if (Ann->getAnnotation() == rcAnnotation)
+  return true;
+  }
+  return false;
+}
+
+static bool isRetain(const FunctionDecl *FD, StringRef FName) {
+  return FName.startswith_lower("retain") || FName.endswith_lower("retain");
+}
+
+static bool isRelease(const FunctionDecl *FD, StringRef FName) {
+  return FName.startswith_lower("release") || FName.endswith_lower("release");
+}
+
+static bool isAutorelease(const FunctionDecl *FD, Str

r340096 - [analyzer] [NFC] Move ObjCRetainCount to include/Analysis

2018-08-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 17 14:42:32 2018
New Revision: 340096

URL: http://llvm.org/viewvc/llvm-project?rev=340096&view=rev
Log:
[analyzer] [NFC] Move ObjCRetainCount to include/Analysis

Differential Revision: https://reviews.llvm.org/D50869

Added:
cfe/trunk/include/clang/Analysis/ObjCRetainCount.h
Removed:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
Modified:
cfe/trunk/lib/ARCMigrate/ObjCMT.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.h

Added: cfe/trunk/include/clang/Analysis/ObjCRetainCount.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/ObjCRetainCount.h?rev=340096&view=auto
==
--- cfe/trunk/include/clang/Analysis/ObjCRetainCount.h (added)
+++ cfe/trunk/include/clang/Analysis/ObjCRetainCount.h Fri Aug 17 14:42:32 2018
@@ -0,0 +1,228 @@
+//==-- ObjCRetainCount.h - Retain count summaries for Cocoa ---*- C++ 
-*--//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+//  This file defines the core data structures for retain count "summaries"
+//  for Objective-C and Core Foundation APIs.  These summaries are used
+//  by the static analyzer to summarize the retain/release effects of
+//  function and method calls.  This drives a path-sensitive typestate
+//  analysis in the static analyzer, but can also potentially be used by
+//  other clients.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_OBJCRETAINCOUNT_H
+#define LLVM_CLANG_STATICANALYZER_CHECKERS_OBJCRETAINCOUNT_H
+
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+
+namespace clang {
+class FunctionDecl;
+class ObjCMethodDecl;
+
+namespace ento { namespace objc_retain {
+
+/// An ArgEffect summarizes the retain count behavior on an argument or 
receiver
+/// to a function or method.
+enum ArgEffect {
+  /// There is no effect.
+  DoNothing,
+
+  /// The argument is treated as if an -autorelease message had been sent to
+  /// the referenced object.
+  Autorelease,
+
+  /// The argument is treated as if an -dealloc message had been sent to
+  /// the referenced object.
+  Dealloc,
+
+  /// The argument has its reference count decreased by 1.  This is as
+  /// if CFRelease has been called on the argument.
+  DecRef,
+
+  /// The argument has its reference count decreased by 1.  This is as
+  /// if a -release message has been sent to the argument.  This differs
+  /// in behavior from DecRef when GC is enabled.
+  DecRefMsg,
+
+  /// The argument has its reference count decreased by 1 to model
+  /// a transferred bridge cast under ARC.
+  DecRefBridgedTransferred,
+
+  /// The argument has its reference count increased by 1.  This is as
+  /// if a -retain message has been sent to the argument.  This differs
+  /// in behavior from IncRef when GC is enabled.
+  IncRefMsg,
+
+  /// The argument has its reference count increased by 1.  This is as
+  /// if CFRetain has been called on the argument.
+  IncRef,
+
+  /// The argument is a pointer to a retain-counted object; on exit, the new
+  /// value of the pointer is a +0 value or NULL.
+  UnretainedOutParameter,
+
+  /// The argument is a pointer to a retain-counted object; on exit, the new
+  /// value of the pointer is a +1 value or NULL.
+  RetainedOutParameter,
+
+  /// The argument is treated as potentially escaping, meaning that
+  /// even when its reference count hits 0 it should be treated as still
+  /// possibly being alive as someone else *may* be holding onto the object.
+  MayEscape,
+
+  /// All typestate tracking of the object ceases.  This is usually employed
+  /// when the effect of the call is completely unknown.
+  StopTracking,
+
+  /// All typestate tracking of the object ceases.  Unlike StopTracking,
+  /// this is also enforced when the method body is inlined.
+  ///
+  /// In some cases, we obtain a better summary for this checker
+  /// by looking at the call site than by inlining the function.
+  /// Signifies that we should stop tracking the symbol even if
+  /// the function is inlined.
+  StopTrackingHard,
+
+  /// Performs the combined functionality of DecRef and StopTrackingHard.
+  ///
+  /// The models the effect that the called function decrements the reference
+  /// count of the argument and all typestate tracking on that argument
+  /// should cease.
+  DecRefAndStopTrackingHard,
+
+  /// Performs the combined functionality of DecRefMsg and StopTrackingHard.
+  ///
+  /// The models the effect that the called function decrements the r

r340098 - [analyzer] [NFC] Minor refactoring of ISL-specific code in RetainCountChecker

2018-08-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 17 14:43:27 2018
New Revision: 340098

URL: http://llvm.org/viewvc/llvm-project?rev=340098&view=rev
Log:
[analyzer] [NFC] Minor refactoring of ISL-specific code in RetainCountChecker

Differential Revision: https://reviews.llvm.org/D50879

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=340098&r1=340097&r2=340098&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Fri Aug 17 14:43:27 2018
@@ -765,9 +765,7 @@ bool RetainCountChecker::evalCall(const
   bool hasTrustedImplementationAnnotation = false;
 
   // See if it's one of the specific functions we know how to eval.
-  bool canEval = SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
-
-  if (!canEval)
+  if (!SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation))
 return false;
 
   // Bind the return value.
@@ -1235,11 +1233,8 @@ RetainCountChecker::processLeaks(Program
   return N;
 }
 
-static bool isGeneralizedObjectRef(QualType Ty) {
-  if (Ty.getAsString().substr(0, 4) == "isl_")
-return true;
-  else
-return false;
+static bool isISLObjectRef(QualType Ty) {
+  return StringRef(Ty.getAsString()).startswith("isl_");
 }
 
 void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
@@ -1263,9 +1258,9 @@ void RetainCountChecker::checkBeginFunct
 
 QualType Ty = Param->getType();
 const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
-if (AE && *AE == DecRef && isGeneralizedObjectRef(Ty)) {
+if (AE && *AE == DecRef && isISLObjectRef(Ty)) {
   state = setRefBinding(state, Sym, 
RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
-} else if (isGeneralizedObjectRef(Ty)) {
+} else if (isISLObjectRef(Ty)) {
   state = setRefBinding(
   state, Sym,
   RefVal::makeNotOwned(RetEffect::ObjKind::Generalized, Ty));

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp?rev=340098&r1=340097&r2=340098&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountSummaries.cpp
 Fri Aug 17 14:43:27 2018
@@ -482,10 +482,10 @@ bool RetainSummaryManager::canEval(const
   return isRetain(FD, FName) || isAutorelease(FD, FName) ||
  isMakeCollectable(FName);
 
-if (FD->getDefinition()) {
-  bool out = isTrustedReferenceCountImplementation(FD->getDefinition());
-  hasTrustedImplementationAnnotation = out;
-  return out;
+const FunctionDecl* FDD = FD->getDefinition();
+if (FDD && isTrustedReferenceCountImplementation(FDD)) {
+  hasTrustedImplementationAnnotation = true;
+  return true;
 }
   }
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340110 - Quickfix for failing tests.

2018-08-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Aug 17 16:54:00 2018
New Revision: 340110

URL: http://llvm.org/viewvc/llvm-project?rev=340110&view=rev
Log:
Quickfix for failing tests.

Modified:
cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result

Modified: cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result?rev=340110&r1=340109&r2=340110&view=diff
==
--- cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result (original)
+++ cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result Fri Aug 17 16:54:00 
2018
@@ -299,11 +299,11 @@ extern DADissenterRef DADissenterCreate(
 @protocol QCCompositionRenderer - (NSDictionary*) attributes;
 @end   @interface QCRenderer : NSObject  {
 }
-- (id) createSnapshotImageOfType:(NSString*)type;
+- (id) createSnapshotImageOfType:(NSString*)type NS_RETURNS_RETAINED;
 @end  extern NSString* const QCViewDidStartRenderingNotification;
 @interface QCView : NSView  {
 }
-- (id) createSnapshotImageOfType:(NSString*)type;
+- (id) createSnapshotImageOfType:(NSString*)type NS_RETURNS_RETAINED;
 @endenum {
 ICEXIFOrientation1 = 1, ICEXIFOrientation2 = 2, ICEXIFOrientation3 = 
3, ICEXIFOrientation4 = 4, ICEXIFOrientation5 = 5, 
ICEXIFOrientation6 = 6, ICEXIFOrientation7 = 7, ICEXIFOrientation8 = 8, 
};
 @class ICDevice;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340377 - [analyzer] [NFC] Extract a method for creating RefVal from RetEffect in RetainCountChecker

2018-08-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Aug 21 18:16:49 2018
New Revision: 340377

URL: http://llvm.org/viewvc/llvm-project?rev=340377&view=rev
Log:
[analyzer] [NFC] Extract a method for creating RefVal from RetEffect in 
RetainCountChecker

Differential Revision: https://reviews.llvm.org/D51071

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=340377&r1=340376&r2=340377&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Tue Aug 21 18:16:49 2018
@@ -379,6 +379,17 @@ static QualType GetReturnType(const Expr
   return RetTy;
 }
 
+static Optional refValFromRetEffect(RetEffect RE,
+QualType ResultTy) {
+  if (RE.isOwned()) {
+return RefVal::makeOwned(RE.getObjKind(), ResultTy);
+  } else if (RE.notOwned()) {
+return RefVal::makeNotOwned(RE.getObjKind(), ResultTy);
+  }
+
+  return None;
+}
+
 // We don't always get the exact modeling of the function with regards to the
 // retain count checker even when the function is inlined. For example, we need
 // to stop tracking the symbols which were marked with StopTrackingHard.
@@ -515,43 +526,15 @@ void RetainCountChecker::checkSummary(co
   RE = RetEffect::MakeNoRet();
   }
 
-  switch (RE.getKind()) {
-default:
-  llvm_unreachable("Unhandled RetEffect.");
-
-case RetEffect::NoRet:
-case RetEffect::NoRetHard:
-  // No work necessary.
-  break;
-
-case RetEffect::OwnedSymbol: {
-  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
-  if (!Sym)
-break;
-
-  // Use the result type from the CallEvent as it automatically adjusts
-  // for methods/functions that return references.
-  QualType ResultTy = CallOrMsg.getResultType();
-  state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
-  ResultTy));
-
-  // FIXME: Add a flag to the checker where allocations are assumed to
-  // *not* fail.
-  break;
-}
-
-case RetEffect::NotOwnedSymbol: {
+  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
+QualType ResultTy = CallOrMsg.getResultType();
+if (RE.notOwned()) {
   const Expr *Ex = CallOrMsg.getOriginExpr();
-  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
-  if (!Sym)
-break;
   assert(Ex);
-  // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
-  QualType ResultTy = GetReturnType(Ex, C.getASTContext());
-  state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
- ResultTy));
-  break;
+  ResultTy = GetReturnType(Ex, C.getASTContext());
 }
+if (Optional updatedRefVal = refValFromRetEffect(RE, ResultTy))
+  state = setRefBinding(state, Sym, *updatedRefVal);
   }
 
   // This check is actually necessary; otherwise the statement builder thinks


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340378 - [analyzer] [NFC] Fix minor formatting issues in RetainCountChecker

2018-08-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Aug 21 18:17:09 2018
New Revision: 340378

URL: http://llvm.org/viewvc/llvm-project?rev=340378&view=rev
Log:
[analyzer] [NFC] Fix minor formatting issues in RetainCountChecker

Differential Revision: https://reviews.llvm.org/D51072

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=340378&r1=340377&r2=340378&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Tue Aug 21 18:17:09 2018
@@ -409,8 +409,7 @@ void RetainCountChecker::processSummaryO
   }
 
   // Evaluate the effect on the message receiver.
-  const ObjCMethodCall *MsgInvocation = dyn_cast(&CallOrMsg);
-  if (MsgInvocation) {
+  if (const auto *MsgInvocation = dyn_cast(&CallOrMsg)) {
 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
   if (Summ.getReceiverEffect() == StopTrackingHard) {
 state = removeRefBinding(state, Sym);
@@ -987,7 +986,7 @@ void RetainCountChecker::checkBind(SVal
   // does not understand.
   ProgramStateRef state = C.getState();
 
-  if (Optional regionLoc = loc.getAs()) {
+  if (auto regionLoc = loc.getAs()) {
 escapes = !regionLoc->getRegion()->hasStackStorage();
 
 if (!escapes) {
@@ -1011,7 +1010,7 @@ void RetainCountChecker::checkBind(SVal
   // If we are storing the value into an auto function scope variable annotated
   // with (__attribute__((cleanup))), stop tracking the value to avoid leak
   // false positives.
-  if (const VarRegion *LVR = dyn_cast_or_null(loc.getAsRegion())) {
+  if (const auto *LVR = dyn_cast_or_null(loc.getAsRegion())) {
 const VarDecl *VD = LVR->getDecl();
 if (VD->hasAttr()) {
   escapes = true;
@@ -1031,8 +1030,8 @@ void RetainCountChecker::checkBind(SVal
 }
 
 ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
-   SVal Cond,
-   bool Assumption) const {
+   SVal Cond,
+   bool Assumption) const {
   // FIXME: We may add to the interface of evalAssume the list of symbols
   //  whose assumptions have changed.  For now we just iterate through the
   //  bindings and check if any of the tracked symbols are NULL.  This isn't
@@ -1253,7 +1252,8 @@ void RetainCountChecker::checkBeginFunct
 QualType Ty = Param->getType();
 const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
 if (AE && *AE == DecRef && isISLObjectRef(Ty)) {
-  state = setRefBinding(state, Sym, 
RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
+  state = setRefBinding(
+  state, Sym, RefVal::makeOwned(RetEffect::ObjKind::Generalized, Ty));
 } else if (isISLObjectRef(Ty)) {
   state = setRefBinding(
   state, Sym,

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h?rev=340378&r1=340377&r2=340378&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h 
Tue Aug 21 18:17:09 2018
@@ -218,7 +218,6 @@ public:
   }
 
   // Comparison, profiling, and pretty-printing.
-
   bool hasSameState(const RefVal &X) const {
 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
getIvarAccessHistory() == X.getIvarAccessHistory();

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp?rev=340378&r1=340377&r2=340378&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 Tue Aug 21 18:17:09 2018
@@ -457,8 +457,7 @@ CFRefLeakReportVisitor::getEndPath(BugRe
 "  This violates the naming convention rules"
 " given in the Memory Management Guide for Cocoa";

r340473 - [analyzer] [NFC] Minor refactoring of BugReporterVisitors

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 16:16:44 2018
New Revision: 340473

URL: http://llvm.org/viewvc/llvm-project?rev=340473&view=rev
Log:
[analyzer] [NFC] Minor refactoring of BugReporterVisitors

Differential Revision: https://reviews.llvm.org/D51130

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=340473&r1=340472&r2=340473&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Wed Aug 22 
16:16:44 2018
@@ -759,10 +759,14 @@ class ReturnVisitor : public BugReporter
 
   bool EnableNullFPSuppression;
   bool ShouldInvalidate = true;
+  AnalyzerOptions& Options;
 
 public:
-  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
-  : StackFrame(Frame), EnableNullFPSuppression(Suppressed) {}
+  ReturnVisitor(const StackFrameContext *Frame,
+bool Suppressed,
+AnalyzerOptions &Options)
+  : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
+Options(Options) {}
 
   static void *getTag() {
 static int Tag = 0;
@@ -790,10 +794,10 @@ public:
 
 // First, find when we processed the statement.
 do {
-  if (Optional CEE = Node->getLocationAs())
+  if (auto CEE = Node->getLocationAs())
 if (CEE->getCalleeContext()->getCallSite() == S)
   break;
-  if (Optional SP = Node->getLocationAs())
+  if (auto SP = Node->getLocationAs())
 if (SP->getStmt() == S)
   break;
 
@@ -834,13 +838,8 @@ public:
 
 BR.markInteresting(CalleeContext);
 BR.addVisitor(llvm::make_unique(CalleeContext,
-   EnableNullFPSuppression));
-  }
-
-  /// Returns true if any counter-suppression heuristics are enabled for
-  /// ReturnVisitor.
-  static bool hasCounterSuppression(AnalyzerOptions &Options) {
-return Options.shouldAvoidSuppressingNullArgumentPaths();
+   EnableNullFPSuppression,
+   Options));
   }
 
   std::shared_ptr
@@ -909,8 +908,8 @@ public:
   // If we have counter-suppression enabled, make sure we keep visiting
   // future nodes. We want to emit a path note as well, in case
   // the report is resurrected as valid later on.
-  AnalyzerOptions &Options = BRC.getAnalyzerOptions();
-  if (EnableNullFPSuppression && hasCounterSuppression(Options))
+  if (EnableNullFPSuppression &&
+  Options.shouldAvoidSuppressingNullArgumentPaths())
 Mode = MaybeUnsuppress;
 
   if (RetE->getType()->isObjCObjectPointerType())
@@ -947,8 +946,7 @@ public:
   visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
BugReporterContext &BRC, BugReport &BR) {
 #ifndef NDEBUG
-AnalyzerOptions &Options = BRC.getAnalyzerOptions();
-assert(hasCounterSuppression(Options));
+assert(Options.shouldAvoidSuppressingNullArgumentPaths());
 #endif
 
 // Are we at the entry node for this call?


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340474 - [analyzer] Track the problematic subexpression in UndefResultChecker

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 16:17:02 2018
New Revision: 340474

URL: http://llvm.org/viewvc/llvm-project?rev=340474&view=rev
Log:
[analyzer] Track the problematic subexpression in UndefResultChecker

This is tested in a subsequent commit, which allows tracking those values.

Differential Revision: https://reviews.llvm.org/D51139

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp?rev=340474&r1=340473&r2=340474&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp Wed Aug 22 
16:17:02 2018
@@ -122,6 +122,7 @@ void UndefResultChecker::checkPostStmt(c
<< ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
   : "right")
<< " shift is undefined because the right operand is negative";
+Ex = B->getRHS();
   } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
   B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
  isShiftOverflow(B, C)) {
@@ -130,6 +131,7 @@ void UndefResultChecker::checkPostStmt(c
<< ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
   : "right")
<< " shift is undefined due to shifting by ";
+Ex = B->getRHS();
 
 SValBuilder &SB = C.getSValBuilder();
 const llvm::APSInt *I =
@@ -147,6 +149,7 @@ void UndefResultChecker::checkPostStmt(c
  C.isNegative(B->getLHS())) {
 OS << "The result of the left shift is undefined because the left "
   "operand is negative";
+Ex = B->getLHS();
   } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
  isLeftShiftResultUnrepresentable(B, C)) {
 ProgramStateRef State = C.getState();
@@ -160,6 +163,7 @@ void UndefResultChecker::checkPostStmt(c
<< "\', which is unrepresentable in the unsigned version of "
<< "the return type \'" << B->getLHS()->getType().getAsString()
<< "\'";
+Ex = B->getLHS();
   } else {
 OS << "The result of the '"
<< BinaryOperator::getOpcodeStr(B->getOpcode())


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340475 - [analyzer] Track non-zero values in ReturnVisitor

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 16:17:25 2018
New Revision: 340475

URL: http://llvm.org/viewvc/llvm-project?rev=340475&view=rev
Log:
[analyzer] Track non-zero values in ReturnVisitor

Tracking those can help to provide much better diagnostics in many cases.

In general, most of the visitor machinery should be refactored to allow
tracking the origin of arbitrary values.

rdar://36039765

Differential Revision: https://reviews.llvm.org/D51131

Added:
cfe/trunk/test/Analysis/diagnostics/track_subexpressions.cpp
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/uninit-const.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=340475&r1=340474&r2=340475&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Wed Aug 22 
16:17:25 2018
@@ -887,15 +887,6 @@ public:
 
 RetE = RetE->IgnoreParenCasts();
 
-// If we can't prove the return value is 0, just mark it interesting, and
-// make sure to track it into any further inner functions.
-if (!State->isNull(V).isConstrainedTrue()) {
-  BR.markInteresting(V);
-  ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
-   EnableNullFPSuppression);
-  return nullptr;
-}
-
 // If we're returning 0, we should track where that 0 came from.
 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
EnableNullFPSuppression);
@@ -904,20 +895,33 @@ public:
 SmallString<64> Msg;
 llvm::raw_svector_ostream Out(Msg);
 
-if (V.getAs()) {
-  // If we have counter-suppression enabled, make sure we keep visiting
-  // future nodes. We want to emit a path note as well, in case
-  // the report is resurrected as valid later on.
-  if (EnableNullFPSuppression &&
-  Options.shouldAvoidSuppressingNullArgumentPaths())
-Mode = MaybeUnsuppress;
+if (State->isNull(V).isConstrainedTrue()) {
+  if (V.getAs()) {
+
+// If we have counter-suppression enabled, make sure we keep visiting
+// future nodes. We want to emit a path note as well, in case
+// the report is resurrected as valid later on.
+if (EnableNullFPSuppression &&
+Options.shouldAvoidSuppressingNullArgumentPaths())
+  Mode = MaybeUnsuppress;
+
+if (RetE->getType()->isObjCObjectPointerType()) {
+  Out << "Returning nil";
+} else {
+  Out << "Returning null pointer";
+}
+  } else {
+Out << "Returning zero";
+  }
 
-  if (RetE->getType()->isObjCObjectPointerType())
-Out << "Returning nil";
-  else
-Out << "Returning null pointer";
 } else {
-  Out << "Returning zero";
+  if (auto CI = V.getAs()) {
+Out << "Returning the value " << CI->getValue();
+  } else if (V.getAs()) {
+Out << "Returning pointer";
+  } else {
+Out << "Returning value";
+  }
 }
 
 if (LValue) {
@@ -1262,10 +1266,9 @@ FindLastStoreBRVisitor::VisitNode(const
 InitE = InitE->IgnoreParenCasts();
   bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
  EnableNullFPSuppression);
-} else {
-  ReturnVisitor::addVisitorIfNecessary(StoreSite, 
InitE->IgnoreParenCasts(),
-   BR, EnableNullFPSuppression);
 }
+ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
+ BR, EnableNullFPSuppression);
   }
 
   // Okay, we've found the binding. Emit an appropriate message.

Added: cfe/trunk/test/Analysis/diagnostics/track_subexpressions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/diagnostics/track_subexpressions.cpp?rev=340475&view=auto
==
--- cfe/trunk/test/Analysis/diagnostics/track_subexpressions.cpp (added)
+++ cfe/trunk/test/Analysis/diagnostics/track_subexpressions.cpp Wed Aug 22 
16:17:25 2018
@@ -0,0 +1,19 @@
+// RUN: %clang_analyze_cc1 -x c++ -analyzer-checker=core -analyzer-output=text 
-verify %s
+
+typedef unsigned char uint8_t;
+
+#define UINT8_MAX 255
+#define TCP_MAXWIN 65535
+
+uint8_t get_uint8_max() {
+  uint8_t rcvscale = UINT8_MAX; // expected-note{{'rcvscale' initialized to 
255}}
+  return rcvscale; // expected-note{{Returning the value 255 (loaded from 
'rcvscale')}}
+}
+
+void shift_by_undefined_value() {
+  uint8_t shift_amount = get_uint8_max(); // expected-note{{'shift_amount' 
initialized to 255}}
+// expected-note@-1{{Calling 'get_uint8_max'}}

r340479 - [NFC] Add tags file to .gitignore

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 16:23:17 2018
New Revision: 340479

URL: http://llvm.org/viewvc/llvm-project?rev=340479&view=rev
Log:
[NFC] Add tags file to .gitignore

Differential Revision: https://reviews.llvm.org/D50109

Modified:
cfe/trunk/.gitignore

Modified: cfe/trunk/.gitignore
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/.gitignore?rev=340479&r1=340478&r2=340479&view=diff
==
--- cfe/trunk/.gitignore (original)
+++ cfe/trunk/.gitignore Wed Aug 22 16:23:17 2018
@@ -24,6 +24,7 @@
 
#==#
 cscope.files
 cscope.out
+/tags
 
 
#==#
 # Directories to ignore (do not add trailing '/'s, they skip symlinks).


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340500 - Revert "[CStringSyntaxChecker] Reduces space around error message for strlcat."

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 17:02:12 2018
New Revision: 340500

URL: http://llvm.org/viewvc/llvm-project?rev=340500&view=rev
Log:
Revert "[CStringSyntaxChecker] Reduces space around error message for strlcat."

This reverts commit 6b43b80320722da41ca6ef7a3b57cc300fb83094.

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
cfe/trunk/test/Analysis/cstring-syntax.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp?rev=340500&r1=340499&r2=340500&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp Wed Aug 22 
17:02:12 2018
@@ -273,7 +273,7 @@ void WalkAST::VisitCallExpr(CallExpr *CE
   if (!LenName.empty())
 os << "'" << LenName << "'";
   else
-os << "";
+os << "  ";
   if (!DstName.empty())
 os << " - strlen(" << DstName << ")";
   else

Modified: cfe/trunk/test/Analysis/cstring-syntax.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cstring-syntax.c?rev=340500&r1=340499&r2=340500&view=diff
==
--- cfe/trunk/test/Analysis/cstring-syntax.c (original)
+++ cfe/trunk/test/Analysis/cstring-syntax.c Wed Aug 22 17:02:12 2018
@@ -42,7 +42,7 @@ void testStrlcat(const char *src) {
   strlcpy(dest, "a", sizeof("a") - 1);
   strlcat(dest, "", (sizeof("") - 1) - sizeof(dest) - 1);
   strlcpy(dest, "012345678", sizeof(dest));
-  strlcat(dest, "910", sizeof(dest)); // expected-warning {{The third argument 
allows to potentially copy more bytes than it should. Replace with the value 
 - strlen(dest) - 1 or lower}}
+  strlcat(dest, "910", sizeof(dest)); // expected-warning {{The third argument 
allows to potentially copy more bytes than it should. Replace with the value  
  - strlen(dest) - 1 or lower}}
   strlcpy(dest, "0123456789", sizeof(dest));
   strlcat(dest, "0123456789", badlen); // expected-warning {{The third 
argument allows to potentially copy more bytes than it should. Replace with the 
value 'badlen' - strlen(dest) - 1 or lower}}
   strlcat(dest, "0123456789", badlen - strlen(dest) - 1);


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340501 - Revert "[CStringSyntaxChecker] Check strlcat sizeof check"

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 17:02:35 2018
New Revision: 340501

URL: http://llvm.org/viewvc/llvm-project?rev=340501&view=rev
Log:
Revert "[CStringSyntaxChecker] Check strlcat sizeof check"

This reverts commit 3073790e87378fea9a68fb052185fec9596ef135.

The check is not correct, strlact(dest, "mystr", sizeof(dest)) is fine.

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
cfe/trunk/test/Analysis/cstring-syntax.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp?rev=340501&r1=340500&r2=340501&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp Wed Aug 22 
17:02:35 2018
@@ -90,16 +90,7 @@ class WalkAST: public StmtVisitorgetNumArgs() != 3)
 return false;
-  const FunctionDecl *FD = CE->getDirectCallee();
-  bool Append = CheckerContext::isCLibraryFunction(FD, "strlcat");
   const Expr *DstArg = CE->getArg(0);
   const Expr *LenArg = CE->getArg(2);
 
   const auto *DstArgDecl = 
dyn_cast(DstArg->IgnoreParenImpCasts());
   const auto *LenArgDecl = 
dyn_cast(LenArg->IgnoreParenLValueCasts());
   uint64_t DstOff = 0;
-  // - sizeof(dst)
-  // strlcat appends at most size - strlen(dst) - 1
-  if (Append && isSizeof(LenArg, DstArg))
-return true;
   // - size_t dstlen = sizeof(dst)
   if (LenArgDecl) {
 const auto *LenArgVal = dyn_cast(LenArgDecl->getDecl());
@@ -196,10 +181,7 @@ bool WalkAST::containsBadStrlcpyStrlcatP
   if (const auto *Buffer = 
dyn_cast(DstArgDecl->getType())) {
 ASTContext &C = BR.getContext();
 uint64_t BufferLen = C.getTypeSize(Buffer) / 8;
-auto RemainingBufferLen = BufferLen - DstOff;
-if (Append)
-  RemainingBufferLen -= 1;
-if (RemainingBufferLen < ILRawVal)
+if ((BufferLen - DstOff) < ILRawVal)
   return true;
   }
 }
@@ -238,7 +220,7 @@ void WalkAST::VisitCallExpr(CallExpr *CE
  LenArg->getSourceRange());
 }
   } else if (CheckerContext::isCLibraryFunction(FD, "strlcpy")) {
-if (containsBadStrlcpyStrlcatPattern(CE)) {
+if (containsBadStrlcpyPattern(CE)) {
   const Expr *DstArg = CE->getArg(0);
   const Expr *LenArg = CE->getArg(2);
   PathDiagnosticLocation Loc =
@@ -254,34 +236,6 @@ void WalkAST::VisitCallExpr(CallExpr *CE
 
   BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
  "C String API", os.str(), Loc,
- LenArg->getSourceRange());
-}
-  } else if (CheckerContext::isCLibraryFunction(FD, "strlcat")) {
-if (containsBadStrlcpyStrlcatPattern(CE)) {
-  const Expr *DstArg = CE->getArg(0);
-  const Expr *LenArg = CE->getArg(2);
-  PathDiagnosticLocation Loc =
-PathDiagnosticLocation::createBegin(LenArg, BR.getSourceManager(), AC);
-
-  StringRef DstName = getPrintableName(DstArg);
-  StringRef LenName = getPrintableName(LenArg);
-
-  SmallString<256> S;
-  llvm::raw_svector_ostream os(S);
-  os << "The third argument allows to potentially copy more bytes than it 
should. ";
-  os << "Replace with the value ";
-  if (!LenName.empty())
-os << "'" << LenName << "'";
-  else
-os << "  ";
-  if (!DstName.empty())
-os << " - strlen(" << DstName << ")";
-  else
-os << " - strlen()";
-  os << " - 1 or lower";
-
-  BR.EmitBasicReport(FD, Checker, "Anti-pattern in the argument",
- "C String API", os.str(), Loc,
  LenArg->getSourceRange());
 }
   }

Modified: cfe/trunk/test/Analysis/cstring-syntax.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cstring-syntax.c?rev=340501&r1=340500&r2=340501&view=diff
==
--- cfe/trunk/test/Analysis/cstring-syntax.c (original)
+++ cfe/trunk/test/Analysis/cstring-syntax.c Wed Aug 22 17:02:35 2018
@@ -7,7 +7,6 @@ typedef __SIZE_TYPE__ size_t;
 char  *strncat(char *, const char *, size_t);
 size_t strlen (const char *s);
 size_t strlcpy(char *, const char *, size_t);
-size_t strlcat(char *, const char *, size_t);
 
 void testStrncat(const char *src) {
   char dest[10];
@@ -34,19 +33,3 @@ void testStrlcpy(const char *src) {
   strlcpy(dest + 5, src, 5);
   strlcpy(dest + 5, src, 10); // expected-warning {{The third argument is 
larger than the size of the input buffer.}}
 }
-
-void testStrlcat(const char *src) {
-  char dest[10];
-  size_t badlen = 10;
-  size_t ulen;
-  strlcpy(dest, "a", sizeof("a") - 1);
-  strlcat(dest, "", (sizeof("") - 1) - sizeof(dest) - 1);
-  strlcpy(dest, "012345678", sizeof(dest));
-  strlcat(dest, "910", sizeof(dest)); // e

r340502 - [analyzer] Preliminary version of retain count checking for OSObjects

2018-08-22 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 22 17:26:59 2018
New Revision: 340502

URL: http://llvm.org/viewvc/llvm-project?rev=340502&view=rev
Log:
[analyzer] Preliminary version of retain count checking for OSObjects

Has quite a lot of false positives, disabled behind the flag.

Differential Revision: https://reviews.llvm.org/D50880

Added:
cfe/trunk/test/Analysis/osobject-retain-release.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h?rev=340502&r1=340501&r2=340502&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h Wed Aug 
22 17:26:59 2018
@@ -154,7 +154,10 @@ public:
 /// Indicates that the tracked object could be a CF or Objective-C object.
 AnyObj,
 /// Indicates that the tracked object is a generalized object.
-Generalized
+Generalized,
+
+/// A descendant of OSObject.
+OS
   };
 
 private:
@@ -318,14 +321,21 @@ class RetainSummary {
   ///  this is the effect applied to the state of the receiver.
   ArgEffect Receiver;
 
+  /// Effect on "this" pointer - applicable only to C++ method calls.
+  ArgEffect This;
+
   /// Ret - The effect on the return value.  Used to indicate if the
   ///  function/method call returns a new tracked symbol.
   RetEffect Ret;
 
 public:
-  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
-ArgEffect ReceiverEff)
-: Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
+  RetainSummary(ArgEffects A,
+RetEffect R,
+ArgEffect defaultEff,
+ArgEffect ReceiverEff,
+ArgEffect ThisEff)
+: Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff),
+  This(ThisEff), Ret(R) {}
 
   /// getArg - Return the argument effect on the argument specified by
   ///  idx (starting from 0).
@@ -359,12 +369,20 @@ public:
   ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
   ArgEffect getReceiverEffect() const { return Receiver; }
 
+  ArgEffect getThisEffect() const { return This; }
+
+  bool isNoop() const {
+return Ret == RetEffect::MakeNoRet() && Receiver == DoNothing
+  && DefaultArgEffect == MayEscape && This == DoNothing
+  && Args.isEmpty();
+  }
+
   /// Test if two retain summaries are identical. Note that merely equivalent
   /// summaries are not necessarily identical (for example, if an explicit
   /// argument effect matches the default effect).
   bool operator==(const RetainSummary &Other) const {
 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
-   Receiver == Other.Receiver && Ret == Other.Ret;
+   Receiver == Other.Receiver && This == Other.This && Ret == 
Other.Ret;
   }
 
   /// Profile this summary for inclusion in a FoldingSet.
@@ -372,6 +390,7 @@ public:
 ID.Add(Args);
 ID.Add(DefaultArgEffect);
 ID.Add(Receiver);
+ID.Add(This);
 ID.Add(Ret);
   }
 
@@ -460,6 +479,9 @@ class RetainSummaryManager {
   /// Records whether or not the analyzed code runs in ARC mode.
   const bool ARCEnabled;
 
+  /// Track sublcasses of OSObject
+  const bool TrackOSObjects;
+
   /// FuncSummaries - A map from FunctionDecls to summaries.
   FuncSummariesTy FuncSummaries;
 
@@ -496,6 +518,19 @@ class RetainSummaryManager {
   ///  data in ScratchArgs.
   ArgEffects getArgEffects();
 
+  /// Create an OS object at +1.
+  const RetainSummary *getOSSummaryCreateRule(const FunctionDecl *FD);
+
+  /// Get an OS object at +0.
+  const RetainSummary *getOSSummaryGetRule(const FunctionDecl *FD);
+
+  /// Increment the reference count on OS object.
+  const RetainSummary *getOSSummaryRetainRule(const FunctionDecl *FD);
+
+  /// Decrement the reference count on OS object.
+  const RetainSummary *getOSSummaryReleaseRule(const FunctionDecl *FD);
+
+
   enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
 
   const RetainSummary *getUnarySummary(const FunctionType* FT,
@@ -509,8 +544,10 @@ class RetainSummaryManager {
 
   const RetainSummary *getPersistentSummary(RetEffect RetEff,
 ArgEffect ReceiverEff = DoNothing,
-ArgEffect DefaultEff = MayEscape) {
-RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, 

r332135 - [analyzer] Fix the filename for the exploration_order test.

2018-05-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri May 11 13:38:39 2018
New Revision: 332135

URL: http://llvm.org/viewvc/llvm-project?rev=332135&view=rev
Log:
[analyzer] Fix the filename for the exploration_order test.

Ensures that the test is being run.

Added:
cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cpp
  - copied, changed from r331483, 
cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc
Removed:
cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc

Removed: cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc?rev=332134&view=auto
==
--- cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc (original)
+++ cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc (removed)
@@ -1,40 +0,0 @@
-// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first -analyzer-output=text -verify %s | 
FileCheck %s
-// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first_queue -analyzer-output=text -verify %s | 
FileCheck %s
-
-extern int coin();
-
-int foo() {
-int *x = 0; // expected-note {{'x' initialized to a null pointer value}}
-while (coin()) { // expected-note{{Loop condition is true}}
-if (coin())  // expected-note {{Taking true branch}}
-return *x; // expected-warning{{Dereference of null pointer 
(loaded from variable 'x')}}
-   // expected-note@-1{{Dereference of null pointer 
(loaded from variable 'x')}}
-}
-return 0;
-}
-
-void bar() {
-while(coin()) // expected-note{{Loop condition is true}}
-if (coin()) // expected-note {{Assuming the condition is true}}
-foo(); // expected-note{{Calling 'foo'}}
-}
-
-int foo2() {
-int *x = 0; // expected-note {{'x' initialized to a null pointer value}}
-while (coin()) { // expected-note{{Loop condition is true}}
-if (coin())  // expected-note {{Taking false branch}}
-return false;
-else
-return *x; // expected-warning{{Dereference of null pointer 
(loaded from variable 'x')}}
-   // expected-note@-1{{Dereference of null pointer 
(loaded from variable 'x')}}
-}
-return 0;
-}
-
-void bar2() {
-while(coin()) // expected-note{{Loop condition is true}}
-if (coin()) // expected-note {{Assuming the condition is false}}
-  return false;
-else
-foo(); // expected-note{{Calling 'foo'}}
-}

Copied: cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cpp (from 
r331483, cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc)
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cpp?p2=cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cpp&p1=cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc&r1=331483&r2=332135&rev=332135&view=diff
==
--- cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cc (original)
+++ cfe/trunk/test/Analysis/exploration_order/prefer_unexplored.cpp Fri May 11 
13:38:39 2018
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first -analyzer-output=text -verify %s | 
FileCheck %s
-// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first_queue -analyzer-output=text -verify %s | 
FileCheck %s
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first -analyzer-output=text -verify %s
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core -analyzer-config 
exploration_strategy=unexplored_first_queue -analyzer-output=text -verify %s
 
 extern int coin();
 
@@ -7,6 +7,7 @@ int foo() {
 int *x = 0; // expected-note {{'x' initialized to a null pointer value}}
 while (coin()) { // expected-note{{Loop condition is true}}
 if (coin())  // expected-note {{Taking true branch}}
+ // expected-note@-1 {{Assuming the condition is true}}
 return *x; // expected-warning{{Dereference of null pointer 
(loaded from variable 'x')}}
// expected-note@-1{{Dereference of null pointer 
(loaded from variable 'x')}}
 }
@@ -14,15 +15,16 @@ int foo() {
 }
 
 void bar() {
-while(coin()) // expected-note{{Loop condition is true}}
-if (coin()) // expected-note {{Assuming the condition is true}}
-foo(); // expected-note{{Calling 'foo'}}
+while(coin())
+if (coin())
+foo();
 }
 
 int foo2() {
 int *x = 0; // expected-note {{'x' initialized to a null pointer value}}
 while (coin()) { // expected-note{{Loop c

r332136 - [analyzer] Ignore the nullability quantifiers for autoreleasewritechecker

2018-05-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri May 11 13:39:19 2018
New Revision: 332136

URL: http://llvm.org/viewvc/llvm-project?rev=332136&view=rev
Log:
[analyzer] Ignore the nullability quantifiers for autoreleasewritechecker

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp?rev=332136&r1=332135&r2=332136&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp Fri 
May 11 13:39:19 2018
@@ -160,8 +160,8 @@ void ObjCAutoreleaseWriteChecker::checkA
   ));
 
   auto DoublePointerParamM =
-  parmVarDecl(hasType(pointerType(
-  pointee(hasCanonicalType(objcObjectPointerType())
+  parmVarDecl(hasType(hasCanonicalType(pointerType(
+  pointee(hasCanonicalType(objcObjectPointerType()))
   .bind(ParamBind);
 
   auto HasParamAndWritesAsyncM = allOf(

Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=332136&r1=332135&r2=332136&view=diff
==
--- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
+++ cfe/trunk/test/Analysis/autoreleasewritechecker_test.m Fri May 11 13:39:19 
2018
@@ -204,4 +204,11 @@ BOOL writeToErrorWithIterator(NSError *_
 }];
   return 0;
 }
+
+void writeToErrorWithIteratorNonnull(NSError *__autoreleasing* _Nonnull error, 
NSDictionary *a) {
+  [a enumerateKeysAndObjectsUsingBlock:^{
+ *error = [NSError errorWithDomain:1]; // expected-warning{{Write to 
autoreleasing out parameter}}
+  }];
+}
 #endif
+


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332288 - Remove the fixit for the diagnostics regarding capturing autoreleasing variables in a block

2018-05-14 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon May 14 13:29:16 2018
New Revision: 332288

URL: http://llvm.org/viewvc/llvm-project?rev=332288&view=rev
Log:
Remove the fixit for the diagnostics regarding capturing autoreleasing 
variables in a block

The fixit is actively harmful, as it encourages developers to ignore the
warning and to write unsafe code.
It is almost impossible to write safe code while capturing autoreleasing
variables in the block, as in order to check that the block is never
called in the autoreleasing pool the developer has to check the
transitive closure of all potential callers of the block.

Differential Revision: https://reviews.llvm.org/D46778

Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/test/SemaObjC/arc.m

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=332288&r1=332287&r2=332288&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Mon May 14 13:29:16 
2018
@@ -5435,8 +5435,6 @@ def warn_block_capture_autoreleasing : W
   "block captures an autoreleasing out-parameter, which may result in "
   "use-after-free bugs">,
   InGroup;
-def note_declare_parameter_autoreleasing : Note<
-  "declare the parameter __autoreleasing explicitly to suppress this warning">;
 def note_declare_parameter_strong : Note<
   "declare the parameter __strong or capture a __block __strong variable to "
   "keep values alive across autorelease pools">;

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=332288&r1=332287&r2=332288&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Mon May 14 13:29:16 2018
@@ -14579,30 +14579,6 @@ static bool captureInBlock(BlockScopeInf
   if (BuildAndDiagnose) {
 SourceLocation VarLoc = Var->getLocation();
 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
-{
-  auto AddAutoreleaseNote =
-  S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
-  // Provide a fix-it for the '__autoreleasing' keyword at the
-  // appropriate location in the variable's type.
-  if (const auto *TSI = Var->getTypeSourceInfo()) {
-PointerTypeLoc PTL =
-TSI->getTypeLoc().getAsAdjusted();
-if (PTL) {
-  SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
-  Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
-   S.getLangOpts());
-  if (Loc.isValid()) {
-StringRef CharAtLoc = Lexer::getSourceText(
-CharSourceRange::getCharRange(Loc, 
Loc.getLocWithOffset(1)),
-S.getSourceManager(), S.getLangOpts());
-AddAutoreleaseNote << FixItHint::CreateInsertion(
-Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
- ? " __autoreleasing "
- : " __autoreleasing");
-  }
-}
-  }
-}
 S.Diag(VarLoc, diag::note_declare_parameter_strong);
   }
 }

Modified: cfe/trunk/test/SemaObjC/arc.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/arc.m?rev=332288&r1=332287&r2=332288&view=diff
==
--- cfe/trunk/test/SemaObjC/arc.m (original)
+++ cfe/trunk/test/SemaObjC/arc.m Mon May 14 13:29:16 2018
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin11 -fobjc-runtime-has-weak 
-fsyntax-only -fobjc-arc -fblocks -verify -Wno-objc-root-class %s
-// RUN: not %clang_cc1 -triple x86_64-apple-darwin11 -fobjc-runtime-has-weak 
-fsyntax-only -fobjc-arc -fblocks -Wno-objc-root-class 
-fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -triple x86_64-apple-darwin11 -fobjc-runtime-has-weak 
-fsyntax-only -fobjc-arc -fblocks -Wno-objc-root-class 
-fdiagnostics-parseable-fixits %s 2>&1
 
 typedef unsigned long NSUInteger;
 typedef const void * CFTypeRef;
@@ -811,23 +811,17 @@ int garf() {
 }
 
 void block_capture_autoreleasing(A * __autoreleasing *a,
- A **b, // expected-note {{declare the 
parameter __autoreleasing explicitly to suppress this warning}} expected-note 
{{declare the parameter __strong or capture a __block __strong variable to keep 
values alive across autorelease pools}}
- A * _Nullable *c, // expected-note {{declare 
the parameter __autoreleasing explicitly to suppress this warning}} 
expected-note {{declare 

r332300 - [analyzer] Extend the ObjCAutoreleaseWriteChecker to warn on captures as well

2018-05-14 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon May 14 14:39:54 2018
New Revision: 332300

URL: http://llvm.org/viewvc/llvm-project?rev=332300&view=rev
Log:
[analyzer] Extend the ObjCAutoreleaseWriteChecker to warn on captures as well

A common pattern is that the code in the block does not write into the
variable explicitly, but instead passes it to a helper function which
performs the write.

Differential Revision: https://reviews.llvm.org/D46772

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp?rev=332300&r1=332299&r2=332300&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp Mon 
May 14 14:39:54 2018
@@ -8,7 +8,7 @@
 
//===--===//
 //
 // This file defines ObjCAutoreleaseWriteChecker which warns against writes
-// into autoreleased out parameters which are likely to cause crashes.
+// into autoreleased out parameters which cause crashes.
 // An example of a problematic write is a write to {@code error} in the example
 // below:
 //
@@ -21,8 +21,9 @@
 // return false;
 // }
 //
-// Such code is very likely to crash due to the other queue autorelease pool
-// begin able to free the error object.
+// Such code will crash on read from `*error` due to the autorelease pool
+// in `enumerateObjectsUsingBlock` implementation freeing the error object
+// on exit from the function.
 //
 
//===--===//
 
@@ -41,8 +42,9 @@ using namespace ast_matchers;
 namespace {
 
 const char *ProblematicWriteBind = "problematicwrite";
+const char *CapturedBind = "capturedbind";
 const char *ParamBind = "parambind";
-const char *MethodBind = "methodbind";
+const char *IsMethodBind = "ismethodbind";
 
 class ObjCAutoreleaseWriteChecker : public Checker {
 public:
@@ -110,67 +112,87 @@ static void emitDiagnostics(BoundNodes &
   AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
 
   const auto *PVD = Match.getNodeAs(ParamBind);
-  assert(PVD);
   QualType Ty = PVD->getType();
   if (Ty->getPointeeType().getObjCLifetime() != Qualifiers::OCL_Autoreleasing)
 return;
-  const auto *SW = Match.getNodeAs(ProblematicWriteBind);
-  bool IsMethod = Match.getNodeAs(MethodBind) != nullptr;
+  const char *WarningMsg = "Write to";
+  const auto *MarkedStmt = Match.getNodeAs(ProblematicWriteBind);
+
+  // Prefer to warn on write, but if not available, warn on capture.
+  if (!MarkedStmt) {
+MarkedStmt = Match.getNodeAs(CapturedBind);
+assert(MarkedStmt);
+WarningMsg = "Capture of";
+  }
+
+  SourceRange Range = MarkedStmt->getSourceRange();
+  PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin(
+  MarkedStmt, BR.getSourceManager(), ADC);
+  bool IsMethod = Match.getNodeAs(IsMethodBind) != nullptr;
   const char *Name = IsMethod ? "method" : "function";
-  assert(SW);
   BR.EmitBasicReport(
   ADC->getDecl(), Checker,
-  /*Name=*/"Write to autoreleasing out parameter inside autorelease pool",
+  /*Name=*/(llvm::Twine(WarningMsg)
++ " autoreleasing out parameter inside autorelease 
pool").str(),
   /*Category=*/"Memory",
-  (llvm::Twine("Write to autoreleasing out parameter inside ") +
+  (llvm::Twine(WarningMsg) + " autoreleasing out parameter inside " +
"autorelease pool that may exit before " + Name + " returns; consider "
"writing first to a strong local variable declared outside of the 
block")
   .str(),
-  PathDiagnosticLocation::createBegin(SW, BR.getSourceManager(), ADC),
-  SW->getSourceRange());
+  Location,
+  Range);
 }
 
 void ObjCAutoreleaseWriteChecker::checkASTCodeBody(const Decl *D,
   AnalysisManager &AM,
   BugReporter &BR) const {
 
+  auto DoublePointerParamM =
+  parmVarDecl(hasType(hasCanonicalType(pointerType(
+  pointee(hasCanonicalType(objcObjectPointerType()))
+  .bind(ParamBind);
+
+  auto ReferencedParamM =
+  declRefExpr(to(parmVarDecl(DoublePointerParamM)));
+
   // Write into a binded object, e.g. *ParamBind = X.
   auto WritesIntoM = binaryOperator(
 hasLHS(unaryOperator(
 hasOperatorName("*"),
 hasUnaryOperand(
-  ignoringParenImpCasts(
-declRefExpr(to(parmVarDecl(equalsBoundNode(ParamBind))
+  ignoringParenImpCasts(ReferencedParamM))
 )),
 hasOperatorName("=")
   ).bind(ProblematicWriteBind);
 
+

r332422 - [analyzer] Do not crash on callback for call_once passed by value

2018-05-15 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue May 15 17:29:13 2018
New Revision: 332422

URL: http://llvm.org/viewvc/llvm-project?rev=332422&view=rev
Log:
[analyzer] Do not crash on callback for call_once passed by value

https://bugs.llvm.org/show_bug.cgi?id=37312
rdar://40270582

Differential Revision: https://reviews.llvm.org/D46913

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=332422&r1=332421&r2=332422&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Tue May 15 17:29:13 2018
@@ -254,21 +254,24 @@ static CallExpr *create_call_once_funcpt
 
   QualType Ty = Callback->getType();
   DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
-  CastKind CK;
+  Expr *SubExpr;
   if (Ty->isRValueReferenceType()) {
-CK = CK_LValueToRValue;
-  } else {
-assert(Ty->isLValueReferenceType());
-CK = CK_FunctionToPointerDecay;
+SubExpr = M.makeImplicitCast(
+Call, Ty.getNonReferenceType(), CK_LValueToRValue);
+  } else if (Ty->isLValueReferenceType() &&
+ Call->getType()->isFunctionType()) {
 Ty = C.getPointerType(Ty.getNonReferenceType());
+SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
+  } else if (Ty->isLValueReferenceType()
+ && Call->getType()->isPointerType()
+ && Call->getType()->getPointeeType()->isFunctionType()){
+SubExpr = Call;
+  } else {
+llvm_unreachable("Unexpected state");
   }
 
   return new (C)
-  CallExpr(C, M.makeImplicitCast(Call, Ty.getNonReferenceType(), CK),
-   /*args=*/CallArgs,
-   /*QualType=*/C.VoidTy,
-   /*ExprValueType=*/VK_RValue,
-   /*SourceLocation=*/SourceLocation());
+  CallExpr(C, SubExpr, CallArgs, C.VoidTy, VK_RValue, SourceLocation());
 }
 
 static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=332422&r1=332421&r2=332422&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Tue May 15 17:29:13 2018
@@ -403,3 +403,12 @@ void callback_with_implicit_cast() {
   std::once_flag flag;
   call_once(flag, callback_taking_func, callback_with_implicit_cast);
 }
+
+std::once_flag another_once_flag;
+typedef void (*my_callback_t)(int *);
+my_callback_t callback;
+int global_int;
+
+void rdar40270582() {
+  call_once(another_once_flag, callback, &global_int);
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332545 - [ASTMatchers] Introduce a blockDecl matcher for matching block declarations

2018-05-16 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed May 16 15:47:03 2018
New Revision: 332545

URL: http://llvm.org/viewvc/llvm-project?rev=332545&view=rev
Log:
[ASTMatchers] Introduce a blockDecl matcher for matching block declarations

Blocks can be matched just as well as functions or Objective-C methods.

Differential Revision: https://reviews.llvm.org/D46980

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/ASTMatchers/ASTMatchersInternal.cpp
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersTest.h
cfe/trunk/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=332545&r1=332544&r2=332545&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Wed May 16 15:47:03 2018
@@ -124,6 +124,18 @@ accessSpecDecl()
 
 
 
+MatcherDecl>blockDeclMatcherBlockDecl>...
+Matches block 
declarations.
+
+Example matches the declaration of the nameless block printing an input
+integer.
+
+  myFunc(^(int p) {
+printf("%d", p);
+  })
+
+
+
 MatcherDecl>classTemplateDeclMatcherClassTemplateDecl>...
 Matches C++ class 
template declarations.
 
@@ -4352,6 +4364,55 @@ Example matches b (matcher = binaryOpera
 
 
 
+MatcherBlockDecl>hasAnyParameterMatcherParmVarDecl>
 InnerMatcher
+Matches any 
parameter of a function or an ObjC method declaration or a
+block.
+
+Does not match the 'this' parameter of a method.
+
+Given
+  class X { void f(int x, int y, int z) {} };
+cxxMethodDecl(hasAnyParameter(hasName("y")))
+  matches f(int x, int y, int z) {}
+with hasAnyParameter(...)
+  matching int y
+
+For ObjectiveC, given
+  @interface I - (void) f:(int) y; @end
+
+the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
+matches the declaration of method f with hasParameter
+matching y.
+
+For blocks, given
+  b = ^(int y) { printf("%d", y) };
+
+the matcher blockDecl(hasAnyParameter(hasName("y")))
+matches the declaration of the block b with hasParameter
+matching y.
+
+
+
+MatcherBlockDecl>hasParameterunsigned N, MatcherParmVarDecl>
 InnerMatcher
+Matches the n'th 
parameter of a function or an ObjC method
+declaration or a block.
+
+Given
+  class X { void f(int x) {} };
+cxxMethodDecl(hasParameter(0, hasType(varDecl(
+  matches f(int x) {}
+with hasParameter(...)
+  matching int x
+
+For ObjectiveC, given
+  @interface I - (void) f:(int) y; @end
+
+the matcher objcMethodDecl(hasParameter(0, hasName("y")))
+matches the declaration of method f with hasParameter
+matching y.
+
+
+
 MatcherBlockPointerTypeLoc>pointeeLocMatcherTypeLoc>
 Narrows PointerType (and 
similar) matchers to those where the
 pointee matches a given matcher.
@@ -5336,7 +5397,8 @@ matches 'int x = 0' in
 
 
 MatcherFunctionDecl>hasAnyParameterMatcherParmVarDecl>
 InnerMatcher
-Matches any 
parameter of a function or ObjC method declaration.
+Matches any 
parameter of a function or an ObjC method declaration or a
+block.
 
 Does not match the 'this' parameter of a method.
 
@@ -5353,6 +5415,13 @@ For ObjectiveC, given
 the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
 matches the declaration of method f with hasParameter
 matching y.
+
+For blocks, given
+  b = ^(int y) { printf("%d", y) };
+
+the matcher blockDecl(hasAnyParameter(hasName("y")))
+matches the declaration of the block b with hasParameter
+matching y.
 
 
 
@@ -5393,7 +5462,7 @@ with compoundStmt()
 
 MatcherFunctionDecl>hasParameterunsigned N, MatcherParmVarDecl>
 InnerMatcher
 Matches the n'th 
parameter of a function or an ObjC method
-declaration.
+declaration or a block.
 
 Given
   class X { void f(int x) {} };
@@ -5767,7 +5836,8 @@ matches the [webView ...] message invoca
 
 
 MatcherObjCMethodDecl>hasAnyParameterMatcher

r332546 - [analyzer] Extend ObjCAutoreleaseWriteChecker to catch block declarations with autoreleasing variables

2018-05-16 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed May 16 15:47:05 2018
New Revision: 332546

URL: http://llvm.org/viewvc/llvm-project?rev=332546&view=rev
Log:
[analyzer] Extend ObjCAutoreleaseWriteChecker to catch block declarations with 
autoreleasing variables

Differential Revision: https://reviews.llvm.org/D46984

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp?rev=332546&r1=332545&r2=332546&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp Wed 
May 16 15:47:05 2018
@@ -115,14 +115,16 @@ static void emitDiagnostics(BoundNodes &
   QualType Ty = PVD->getType();
   if (Ty->getPointeeType().getObjCLifetime() != Qualifiers::OCL_Autoreleasing)
 return;
-  const char *WarningMsg = "Write to";
+  const char *ActionMsg = "Write to";
   const auto *MarkedStmt = Match.getNodeAs(ProblematicWriteBind);
+  bool IsCapture = false;
 
   // Prefer to warn on write, but if not available, warn on capture.
   if (!MarkedStmt) {
 MarkedStmt = Match.getNodeAs(CapturedBind);
 assert(MarkedStmt);
-WarningMsg = "Capture of";
+ActionMsg = "Capture of";
+IsCapture = true;
   }
 
   SourceRange Range = MarkedStmt->getSourceRange();
@@ -130,12 +132,14 @@ static void emitDiagnostics(BoundNodes &
   MarkedStmt, BR.getSourceManager(), ADC);
   bool IsMethod = Match.getNodeAs(IsMethodBind) != nullptr;
   const char *Name = IsMethod ? "method" : "function";
+
   BR.EmitBasicReport(
   ADC->getDecl(), Checker,
-  /*Name=*/(llvm::Twine(WarningMsg)
+  /*Name=*/(llvm::Twine(ActionMsg)
 + " autoreleasing out parameter inside autorelease 
pool").str(),
   /*Category=*/"Memory",
-  (llvm::Twine(WarningMsg) + " autoreleasing out parameter inside " +
+  (llvm::Twine(ActionMsg) + " autoreleasing out parameter " +
+   (IsCapture ? "'" + PVD->getName() + "'" + " " : "") + "inside " +
"autorelease pool that may exit before " + Name + " returns; consider "
"writing first to a strong local variable declared outside of the 
block")
   .str(),
@@ -153,7 +157,7 @@ void ObjCAutoreleaseWriteChecker::checkA
   .bind(ParamBind);
 
   auto ReferencedParamM =
-  declRefExpr(to(parmVarDecl(DoublePointerParamM)));
+  declRefExpr(to(parmVarDecl(DoublePointerParamM))).bind(CapturedBind);
 
   // Write into a binded object, e.g. *ParamBind = X.
   auto WritesIntoM = binaryOperator(
@@ -169,7 +173,7 @@ void ObjCAutoreleaseWriteChecker::checkA
 ignoringParenImpCasts(ReferencedParamM));
   auto CapturedInParamM = stmt(anyOf(
   callExpr(ArgumentCaptureM),
-  objcMessageExpr(ArgumentCaptureM))).bind(CapturedBind);
+  objcMessageExpr(ArgumentCaptureM)));
 
   // WritesIntoM happens inside a block passed as an argument.
   auto WritesOrCapturesInBlockM = hasAnyArgument(allOf(
@@ -192,7 +196,8 @@ void ObjCAutoreleaseWriteChecker::checkA
 
   auto MatcherM = decl(anyOf(
   objcMethodDecl(HasParamAndWritesInMarkedFuncM).bind(IsMethodBind),
-  functionDecl(HasParamAndWritesInMarkedFuncM)));
+  functionDecl(HasParamAndWritesInMarkedFuncM),
+  blockDecl(HasParamAndWritesInMarkedFuncM)));
 
   auto Matches = match(MatcherM, *D, AM.getASTContext());
   for (BoundNodes Match : Matches)

Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=332546&r1=332545&r2=332546&view=diff
==
--- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
+++ cfe/trunk/test/Analysis/autoreleasewritechecker_test.m Wed May 16 15:47:05 
2018
@@ -265,5 +265,17 @@ void multipleErrors(NSError *__autorelea
   }];
 }
 
+typedef void (^errBlock)(NSError *__autoreleasing *error);
+
+extern void expectError(errBlock);
+
+void captureAutoreleasingVarFromBlock(NSDictionary *dict) {
+  expectError(^(NSError *__autoreleasing *err) {
+[dict enumerateKeysAndObjectsUsingBlock:^{
+  writeIntoError(err); // expected-warning{{Capture of autoreleasing out 
parameter 'err'}}
+}];
+  });
+}
+
 #endif
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332544 - [analyzer] Change the warning message for GCD antipattern checker

2018-05-16 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed May 16 15:46:47 2018
New Revision: 332544

URL: http://llvm.org/viewvc/llvm-project?rev=332544&view=rev
Log:
[analyzer] Change the warning message for GCD antipattern checker

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp
cfe/trunk/test/Analysis/gcdantipatternchecker_test.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp?rev=332544&r1=332543&r2=332544&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp Wed May 16 
15:46:47 2018
@@ -187,8 +187,8 @@ static void emitDiagnostics(const BoundN
 
   std::string Diagnostics;
   llvm::raw_string_ostream OS(Diagnostics);
-  OS << "Waiting on a " << Type << " with Grand Central Dispatch creates "
- << "useless threads and is subject to priority inversion; consider "
+  OS << "Waiting on a callback using a " << Type << " creates useless threads "
+ << "and is subject to priority inversion; consider "
  << "using a synchronous API or changing the caller to be asynchronous";
 
   BR.EmitBasicReport(

Modified: cfe/trunk/test/Analysis/gcdantipatternchecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/gcdantipatternchecker_test.m?rev=332544&r1=332543&r2=332544&view=diff
==
--- cfe/trunk/test/Analysis/gcdantipatternchecker_test.m (original)
+++ cfe/trunk/test/Analysis/gcdantipatternchecker_test.m Wed May 16 15:46:47 
2018
@@ -34,7 +34,7 @@ void use_semaphor_antipattern() {
   func(^{
   dispatch_semaphore_signal(sema);
   });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
 }
 
 // It's OK to use pattern in tests.
@@ -54,14 +54,14 @@ void use_semaphor_antipattern_multiple_t
   func(^{
   dispatch_semaphore_signal(sema1);
   });
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
 
   dispatch_semaphore_t sema2 = dispatch_semaphore_create(0);
 
   func(^{
   dispatch_semaphore_signal(sema2);
   });
-  dispatch_semaphore_wait(sema2, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema2, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
 }
 
 void use_semaphor_antipattern_multiple_wait() {
@@ -71,8 +71,8 @@ void use_semaphor_antipattern_multiple_w
   dispatch_semaphore_signal(sema1);
   });
   // FIXME: multiple waits on same semaphor should not raise a warning.
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
+  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
 }
 
 void warn_incorrect_order() {
@@ -80,7 +80,7 @@ void warn_incorrect_order() {
   // if out of order.
   dispatch_semaphore_t sema = dispatch_semaphore_create(0);
 
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
callback}}
   func(^{
   dispatch_semaphore_signal(sema);
   });
@@ -92,7 +92,7 @@ void warn_w_typedef() {
   func_w_typedef(^{
   dispatch_semaphore_signal(sema);
   });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inversion}}
+  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
callback using a semaphore}}
 }
 
 void warn_nested_ast() {
@@ -107,7 +107,7 @@ void warn_nested_ast() {
  dispatch_semaphore_signal(sema);
  });
   }
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Waiting on a 
semaphore with Grand Central Dispatch creates useless threads and is subject to 
priority inver

r314571 - [Analyzer] Synthesize function body for std::call_once

2017-09-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep 29 17:03:22 2017
New Revision: 314571

URL: http://llvm.org/viewvc/llvm-project?rev=314571&view=rev
Log:
[Analyzer] Synthesize function body for std::call_once

Differential Revision: https://reviews.llvm.org/D37840

Added:
cfe/trunk/test/Analysis/call_once.cpp
Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=314571&r1=314570&r2=314571&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Fri Sep 29 17:03:22 2017
@@ -14,11 +14,18 @@
 
 #include "BodyFarm.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/CXXInheritance.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/AST/NestedNameSpecifier.h"
 #include "clang/Analysis/CodeInjector.h"
+#include "clang/Basic/OperatorKinds.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "body-farm"
 
 using namespace clang;
 
@@ -55,7 +62,9 @@ public:
   CompoundStmt *makeCompound(ArrayRef);
   
   /// Create a new DeclRefExpr for the referenced variable.
-  DeclRefExpr *makeDeclRefExpr(const VarDecl *D);
+  DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
+   bool RefersToEnclosingVariableOrCapture = false,
+   bool GetNonReferenceType = false);
   
   /// Create a new UnaryOperator representing a dereference.
   UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
@@ -66,9 +75,24 @@ public:
   /// Create an implicit cast to a builtin boolean type.
   ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
   
-  // Create an implicit cast for lvalue-to-rvaluate conversions.
+  /// Create an implicit cast for lvalue-to-rvaluate conversions.
   ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
   
+  /// Create an implicit cast for lvalue-to-rvaluate conversions.
+  ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg,
+   bool GetNonReferenceType = false);
+
+  /// Make RValue out of variable declaration, creating a temporary
+  /// DeclRefExpr in the process.
+  ImplicitCastExpr *
+  makeLvalueToRvalue(const VarDecl *Decl,
+ bool RefersToEnclosingVariableOrCapture = false,
+ bool GetNonReferenceType = false);
+
+  /// Create an implicit cast of the given type.
+  ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
+ CastKind CK = CK_LValueToRValue);
+
   /// Create an Objective-C bool literal.
   ObjCBoolLiteralExpr *makeObjCBool(bool Val);
 
@@ -78,6 +102,18 @@ public:
   /// Create a Return statement.
   ReturnStmt *makeReturn(const Expr *RetVal);
   
+  /// Create an integer literal.
+  IntegerLiteral *makeIntegerLiteral(uint64_t value);
+
+  /// Create a member expression.
+  MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
+   bool IsArrow = false,
+   ExprValueKind ValueKind = VK_LValue);
+
+  /// Returns a *first* member field of a record declaration with a given name.
+  /// \return an nullptr if no member with such a name exists.
+  NamedDecl *findMemberField(const CXXRecordDecl *RD, StringRef Name);
+
 private:
   ASTContext &C;
 };
@@ -106,16 +142,16 @@ CompoundStmt *ASTMaker::makeCompound(Arr
   return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
 }
 
-DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D) {
-  DeclRefExpr *DR =
-DeclRefExpr::Create(/* Ctx = */ C,
-/* QualifierLoc = */ NestedNameSpecifierLoc(),
-/* TemplateKWLoc = */ SourceLocation(),
-/* D = */ const_cast(D),
-/* RefersToEnclosingVariableOrCapture = */ false,
-/* NameLoc = */ SourceLocation(),
-/* T = */ D->getType(),
-/* VK = */ VK_LValue);
+DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D,
+   bool RefersToEnclosingVariableOrCapture,
+   bool GetNonReferenceType) {
+  auto Type = D->getType();
+  if (GetNonReferenceType)
+Type = Type.getNonReferenceType();
+
+  DeclRefExpr *DR = DeclRefExpr::Create(
+  C, NestedNameSpecifierLoc(), SourceLocation(), const_cast(D),
+  RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
   return DR;
 }
 
@@ -125,8 +161,38 @@ UnaryOperator *ASTMaker::makeDereference
 }
 
 ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
-  return ImplicitCastExpr::Create(C, Ty, CK_LValueToRValue,
- 

r314572 - [Analyzer] Add nullability to the list of tested checkers in SATestBuild

2017-09-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep 29 17:05:24 2017
New Revision: 314572

URL: http://llvm.org/viewvc/llvm-project?rev=314572&view=rev
Log:
[Analyzer] Add nullability to the list of tested checkers in SATestBuild

Differential Revision: https://reviews.llvm.org/D38162

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=314572&r1=314571&r2=314572&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Fri Sep 29 17:05:24 2017
@@ -178,7 +178,18 @@ PatchfileName = "changes_for_analyzer.pa
 # The list of checkers used during analyzes.
 # Currently, consists of all the non-experimental checkers, plus a few alpha
 # checkers we don't want to regress on.
-Checkers="alpha.unix.SimpleStream,alpha.security.taint,cplusplus.NewDeleteLeaks,core,cplusplus,deadcode,security,unix,osx"
+Checkers=",".join([
+"alpha.unix.SimpleStream",
+"alpha.security.taint",
+"cplusplus.NewDeleteLeaks",
+"core",
+"cplusplus",
+"deadcode",
+"security",
+"unix",
+"osx",
+"nullability"
+])
 
 Verbose = 1
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314573 - [Analyzer] Document a gotcha: for C++ -analyze-function requires parameters in function name

2017-09-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep 29 17:07:22 2017
New Revision: 314573

URL: http://llvm.org/viewvc/llvm-project?rev=314573&view=rev
Log:
[Analyzer] Document a gotcha: for C++ -analyze-function requires parameters in 
function name

Differential Revision: https://reviews.llvm.org/D37596

Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/www/analyzer/checker_dev_manual.html

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=314573&r1=314572&r2=314573&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Fri Sep 29 17:07:22 2017
@@ -70,7 +70,7 @@ def analyzer_opt_analyze_nested_blocks :
 def analyzer_display_progress : Flag<["-"], "analyzer-display-progress">,
   HelpText<"Emit verbose output about the analyzer's progress">;
 def analyze_function : Separate<["-"], "analyze-function">,
-  HelpText<"Run analysis on specific function">;
+  HelpText<"Run analysis on specific function (for C++ include parameters in 
name)">;
 def analyze_function_EQ : Joined<["-"], "analyze-function=">, 
Alias;
 def analyzer_eagerly_assume : Flag<["-"], "analyzer-eagerly-assume">,
   HelpText<"Eagerly assume the truth/falseness of some symbolic constraints">;

Modified: cfe/trunk/www/analyzer/checker_dev_manual.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/analyzer/checker_dev_manual.html?rev=314573&r1=314572&r2=314573&view=diff
==
--- cfe/trunk/www/analyzer/checker_dev_manual.html (original)
+++ cfe/trunk/www/analyzer/checker_dev_manual.html Fri Sep 29 17:07:22 2017
@@ -575,8 +575,8 @@ execute a single checker:
 processing a large file use the  -analyzer-display-progress
 option.
 
-You can analyze a particular function within the file, which is often useful
-because the problem is always in a certain function:
+To selectively analyze only the given function, use the
+-analyze-function option:
 
 $ clang -cc1 -analyze -analyzer-checker=core test.c 
-analyzer-display-progress
 ANALYZE (Syntax): test.c foo
@@ -588,6 +588,16 @@ because the problem is always in a certa
 ANALYZE (Path,  Inline_Regular): test.c foo
 
 
+Note:  a fully qualified function name has to be used when selecting
+C++ functions and methods, Objective-C methods and blocks, e.g.:
+
+
+$ clang -cc1 -analyze -analyzer-checker=core test.cc 
-analyze-function=foo(int)
+
+
+The fully qualified name can be found from the
+-analyzer-display-progress output.
+
 The bug reporter mechanism removes path diagnostics inside intermediate
 function calls that have returned by the time the bug was found and contain
 no interesting pieces. Usually it is up to the checkers to produce more


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314580 - [Analyzer] Add dummy implementation to call_once to avoid linkage warnings in tests.

2017-09-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep 29 18:15:35 2017
New Revision: 314580

URL: http://llvm.org/viewvc/llvm-project?rev=314580&view=rev
Log:
[Analyzer] Add dummy implementation to call_once to avoid linkage warnings in 
tests.

Modified:
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=314580&r1=314579&r2=314580&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Fri Sep 29 18:15:35 2017
@@ -9,7 +9,7 @@ typedef struct once_flag_s {
 } once_flag;
 
 template 
-void call_once(once_flag &o, Callable func, Args... args);
+void call_once(once_flag &o, Callable func, Args... args) {};
 } // namespace std
 
 // Check with Lambdas.
@@ -115,9 +115,9 @@ template 
 class function; // undefined
 template 
 struct function<_Rp(_ArgTypes...)> {
-  _Rp operator()(_ArgTypes...) const;
+  _Rp operator()(_ArgTypes...) const {};
   template 
-  function(_Fp);
+  function(_Fp) {};
 };
 
 // Note: currently we do not support calls to std::function,


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314692 - [Analyzer] Make testing scripts flake8 compliant

2017-10-02 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct  2 10:59:12 2017
New Revision: 314692

URL: http://llvm.org/viewvc/llvm-project?rev=314692&view=rev
Log:
[Analyzer] Make testing scripts flake8 compliant

Differential Review: https://reviews.llvm.org/D38213

Modified:
cfe/trunk/utils/analyzer/CmpRuns.py
cfe/trunk/utils/analyzer/SATestAdd.py
cfe/trunk/utils/analyzer/SATestBuild.py
cfe/trunk/utils/analyzer/SATestUpdateDiffs.py
cfe/trunk/utils/analyzer/SumTimerInfo.py
cfe/trunk/utils/analyzer/ubiviz

Modified: cfe/trunk/utils/analyzer/CmpRuns.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/CmpRuns.py?rev=314692&r1=314691&r2=314692&view=diff
==
--- cfe/trunk/utils/analyzer/CmpRuns.py (original)
+++ cfe/trunk/utils/analyzer/CmpRuns.py Mon Oct  2 10:59:12 2017
@@ -6,8 +6,8 @@ which reports have been added, removed,
 
 This is designed to support automated testing using the static analyzer, from
 two perspectives:
-  1. To monitor changes in the static analyzer's reports on real code bases, 
for
- regression testing.
+  1. To monitor changes in the static analyzer's reports on real code bases,
+ for regression testing.
 
   2. For use by end users who want to integrate regular static analyzer testing
  into a buildbot like environment.
@@ -29,6 +29,7 @@ Usage:
 import os
 import plistlib
 
+
 # Information about analysis run:
 # path - the analysis output directory
 # root - the name of the root directory, which will be disregarded when
@@ -39,6 +40,7 @@ class SingleRunInfo:
 self.root = root.rstrip("/\\")
 self.verboseLog = verboseLog
 
+
 class AnalysisDiagnostic:
 def __init__(self, data, report, htmlReport):
 self._data = data
@@ -50,7 +52,7 @@ class AnalysisDiagnostic:
 root = self._report.run.root
 fileName = self._report.files[self._loc['file']]
 if fileName.startswith(root) and len(root) > 0:
-return fileName[len(root)+1:]
+return fileName[len(root) + 1:]
 return fileName
 
 def getLine(self):
@@ -65,12 +67,12 @@ class AnalysisDiagnostic:
 def getDescription(self):
 return self._data['description']
 
-def getIssueIdentifier(self) :
+def getIssueIdentifier(self):
 id = self.getFileName() + "+"
-if 'issue_context' in self._data :
-  id += self._data['issue_context'] + "+"
-if 'issue_hash_content_of_line_in_context' in self._data :
-  id += str(self._data['issue_hash_content_of_line_in_context'])
+if 'issue_context' in self._data:
+id += self._data['issue_context'] + "+"
+if 'issue_hash_content_of_line_in_context' in self._data:
+id += str(self._data['issue_hash_content_of_line_in_context'])
 return id
 
 def getReport(self):
@@ -88,18 +90,21 @@ class AnalysisDiagnostic:
 def getRawData(self):
 return self._data
 
+
 class CmpOptions:
 def __init__(self, verboseLog=None, rootA="", rootB=""):
 self.rootA = rootA
 self.rootB = rootB
 self.verboseLog = verboseLog
 
+
 class AnalysisReport:
 def __init__(self, run, files):
 self.run = run
 self.files = files
 self.diagnostics = []
 
+
 class AnalysisRun:
 def __init__(self, info):
 self.path = info.path
@@ -120,14 +125,14 @@ class AnalysisRun:
 # reports. Assume that all reports were created using the same
 # clang version (this is always true and is more efficient).
 if 'clang_version' in data:
-if self.clang_version == None:
+if self.clang_version is None:
 self.clang_version = data.pop('clang_version')
 else:
 data.pop('clang_version')
 
 # Ignore/delete empty reports.
 if not data['files']:
-if deleteEmpty == True:
+if deleteEmpty:
 os.remove(p)
 return
 
@@ -144,8 +149,7 @@ class AnalysisRun:
 
 report = AnalysisReport(self, data.pop('files'))
 diagnostics = [AnalysisDiagnostic(d, report, h)
-   for d,h in zip(data.pop('diagnostics'),
-  htmlFiles)]
+   for d, h in zip(data.pop('diagnostics'), htmlFiles)]
 
 assert not data
 
@@ -154,15 +158,21 @@ class AnalysisRun:
 self.diagnostics.extend(diagnostics)
 
 
-# Backward compatibility API.
-def loadResults(path, opts, root = "", deleteEmpty=True):
+def loadResults(path, opts, root="", deleteEmpty=True):
+"""
+Backwards compatibility API.
+"""
 return loadResultsFromSingleRun(SingleRunInfo(path, root, opts.verboseLog),
 deleteEmpty)
 
-# Load results of the analyzes from a given output folder.
-# - info is the SingleRunInfo object
-# - deleteEmpty specifies if the empty plist files should be deleted
+

Re: [PATCH] D38444: [compiler-rt] [cmake] Create dummy gtest target for stand-alone builds

2017-10-02 Thread George Karpenkov via cfe-commits


> On Oct 2, 2017, at 12:57 PM, Michał Górny via Phabricator 
>  wrote:
> 
> mgorny added a comment.
> 
> In https://reviews.llvm.org/D38444#886138, @george.karpenkov wrote:
> 
>>> breaking stand-alone builds as a result
>> 
>> That's a strong statement. Could you clarify? We have a lot of buildbots 
>> performing standalone builds, and they are still green.
> 
> 
> I didn't know anyone actually added bots doing that. Are you sure we're 
> talking about the same meaning of 'stand-alone'? Stand-alone == out of LLVM, 
> against installed copy of LLVM.

Yes.
You are right though that bots I was referring to do not run unit tests.

> 
>  ninja -v -j16 -l0 check-all
>  ninja: error: 
> '/var/tmp/portage/sys-libs/compiler-rt-sanitizers-/work/compiler-rt-sanitizers-/lib/asan/tests/gtest',
>  needed by 'lib/asan/tests/dynamic/Asan-i386-calls-Dynamic-Test', missing and 
> no known rule to make it
> 
> It's as broken as it could be since it depends on target that does not exist.

Right, by “works” I’ve meant that “it compiles”, not that “unit tests pass”.
My understanding is that running unit tests never meant to work,
as a freshly built clang is usually needed, and in standalone mode it is not 
available.
I could be wrong though, in that case I do not know.

Does everything magically work with this dummy target?

> 
>>> and the likeliness of people mistakenly adding more unconditional 
>>> dependencies
>> 
>> That's a good point, however I'm not sure how your change would fix the 
>> problem.
>> As far as I remember targets in compiler-rt had quite a few dependencies 
>> which required checking for whether it is a standalone build.
>> 
>> In general, I'm not sure what this change would achieve, and the added 
>> complexity can always cause more bugs in the future.
> 
> My goal is to make things work again.
> 
> 
> Repository:
>  rL LLVM
> 
> https://reviews.llvm.org/D38444
> 
> 
> 

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314722 - [Analyzer] Avoid copy and modifying passed reference in BodyFarm::create_call_once

2017-10-02 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct  2 14:01:46 2017
New Revision: 314722

URL: http://llvm.org/viewvc/llvm-project?rev=314722&view=rev
Log:
[Analyzer] Avoid copy and modifying passed reference in 
BodyFarm::create_call_once

Differential Revision: https://reviews.llvm.org/D38475

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=314722&r1=314721&r2=314722&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Mon Oct  2 14:01:46 2017
@@ -257,10 +257,9 @@ NamedDecl *ASTMaker::findMemberField(con
 
 typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
 
-static CallExpr *
-create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
-  const ParmVarDecl *Callback,
-  SmallVectorImpl &CallArgs) {
+static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
+   const ParmVarDecl *Callback,
+   ArrayRef CallArgs) {
 
   return new (C) CallExpr(
   /*ASTContext=*/C,
@@ -271,10 +270,10 @@ create_call_once_funcptr_call(ASTContext
   /*SourceLocation=*/SourceLocation());
 }
 
-static CallExpr *
-create_call_once_lambda_call(ASTContext &C, ASTMaker M,
- const ParmVarDecl *Callback, QualType 
CallbackType,
- SmallVectorImpl &CallArgs) {
+static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
+  const ParmVarDecl *Callback,
+  QualType CallbackType,
+  ArrayRef CallArgs) {
 
   CXXRecordDecl *CallbackDecl = CallbackType->getAsCXXRecordDecl();
 
@@ -293,12 +292,6 @@ create_call_once_lambda_call(ASTContext
   /* T = */ callOperatorDecl->getType(),
   /* VK = */ VK_LValue);
 
-  CallArgs.insert(
-  CallArgs.begin(),
-  M.makeDeclRefExpr(Callback,
-/* RefersToEnclosingVariableOrCapture= */ true,
-/* GetNonReferenceType= */ true));
-
   return new (C)
   CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
   /*args=*/CallArgs,
@@ -335,15 +328,24 @@ static Stmt *create_call_once(ASTContext
   const ParmVarDecl *Callback = D->getParamDecl(1);
   QualType CallbackType = Callback->getType().getNonReferenceType();
 
+  bool isLambdaCall = CallbackType->getAsCXXRecordDecl() &&
+  CallbackType->getAsCXXRecordDecl()->isLambda();
+
   SmallVector CallArgs;
 
+  if (isLambdaCall)
+// Lambda requires callback itself inserted as a first parameter.
+CallArgs.push_back(
+M.makeDeclRefExpr(Callback,
+  /* RefersToEnclosingVariableOrCapture= */ true,
+  /* GetNonReferenceType= */ true));
+
   // All arguments past first two ones are passed to the callback.
   for (unsigned int i = 2; i < D->getNumParams(); i++)
 CallArgs.push_back(M.makeLvalueToRvalue(D->getParamDecl(i)));
 
   CallExpr *CallbackCall;
-  if (CallbackType->getAsCXXRecordDecl() &&
-  CallbackType->getAsCXXRecordDecl()->isLambda()) {
+  if (isLambdaCall) {
 
 CallbackCall =
 create_call_once_lambda_call(C, M, Callback, CallbackType, CallArgs);


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314820 - [Analyzer] More granular special casing in RetainCountChecker

2017-10-03 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct  3 11:12:15 2017
New Revision: 314820

URL: http://llvm.org/viewvc/llvm-project?rev=314820&view=rev
Log:
[Analyzer] More granular special casing in RetainCountChecker

Only assume that IOBSDNameMatching and friends increment a reference counter
if their return type is a CFMutableDictionaryRef.

Differential Revision: https://reviews.llvm.org/D38487

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
cfe/trunk/test/Analysis/retain-release.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp?rev=314820&r1=314819&r2=314820&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp Tue Oct  3 
11:12:15 2017
@@ -1062,6 +1062,7 @@ RetainSummaryManager::getFunctionSummary
 
 // Inspect the result type.
 QualType RetTy = FT->getReturnType();
+StringRef RetTyName = RetTy.getAsString();
 
 // FIXME: This should all be refactored into a chain of "summary lookup"
 //  filters.
@@ -1081,12 +1082,14 @@ RetainSummaryManager::getFunctionSummary
   AllowAnnotations = false;
 } else if (FName == "CFPlugInInstanceCreate") {
   S = getPersistentSummary(RetEffect::MakeNoRet());
-} else if (FName == "IOBSDNameMatching" ||
+} else if (FName == "IORegistryEntrySearchCFProperty"
+|| (RetTyName == "CFMutableDictionaryRef" && (
+   FName == "IOBSDNameMatching" ||
FName == "IOServiceMatching" ||
FName == "IOServiceNameMatching" ||
-   FName == "IORegistryEntrySearchCFProperty" ||
FName == "IORegistryEntryIDMatching" ||
-   FName == "IOOpenFirmwarePathMatching") {
+   FName == "IOOpenFirmwarePathMatching"
+))) {
   // Part of . (IOKit)
   // This should be addressed using a API table.
   S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),

Modified: cfe/trunk/test/Analysis/retain-release.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/retain-release.mm?rev=314820&r1=314819&r2=314820&view=diff
==
--- cfe/trunk/test/Analysis/retain-release.mm (original)
+++ cfe/trunk/test/Analysis/retain-release.mm Tue Oct  3 11:12:15 2017
@@ -463,3 +463,10 @@ void   radar13722286::PrepareBitmap() {
 
 // rdar://34210609
 void _() { _(); }; // no-warning
+
+// Do not assume that IOBSDNameMatching increments a reference counter,
+// unless return type is CFMutableDictionaryRef.
+void* IOBSDNameMatching();
+void rdar33832412() {
+  void* x = IOBSDNameMatching(); // no-warning
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314859 - [Analyzer] Re-apply r314820 with a fix for StringRef lifetime.

2017-10-03 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct  3 16:15:35 2017
New Revision: 314859

URL: http://llvm.org/viewvc/llvm-project?rev=314859&view=rev
Log:
[Analyzer] Re-apply r314820 with a fix for StringRef lifetime.

Fixes the test failure: temporary is now bound to std::string, tests
fully pass on Linux.

This reverts commit b36ee0924038e1d95ea74230c62d46e05f80587e.

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
cfe/trunk/test/Analysis/retain-release.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp?rev=314859&r1=314858&r2=314859&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp Tue Oct  3 
16:15:35 2017
@@ -1062,6 +1062,7 @@ RetainSummaryManager::getFunctionSummary
 
 // Inspect the result type.
 QualType RetTy = FT->getReturnType();
+std::string RetTyName = RetTy.getAsString();
 
 // FIXME: This should all be refactored into a chain of "summary lookup"
 //  filters.
@@ -1081,12 +1082,14 @@ RetainSummaryManager::getFunctionSummary
   AllowAnnotations = false;
 } else if (FName == "CFPlugInInstanceCreate") {
   S = getPersistentSummary(RetEffect::MakeNoRet());
-} else if (FName == "IOBSDNameMatching" ||
+} else if (FName == "IORegistryEntrySearchCFProperty"
+|| (RetTyName == "CFMutableDictionaryRef" && (
+   FName == "IOBSDNameMatching" ||
FName == "IOServiceMatching" ||
FName == "IOServiceNameMatching" ||
-   FName == "IORegistryEntrySearchCFProperty" ||
FName == "IORegistryEntryIDMatching" ||
-   FName == "IOOpenFirmwarePathMatching") {
+   FName == "IOOpenFirmwarePathMatching"
+))) {
   // Part of . (IOKit)
   // This should be addressed using a API table.
   S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF),

Modified: cfe/trunk/test/Analysis/retain-release.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/retain-release.mm?rev=314859&r1=314858&r2=314859&view=diff
==
--- cfe/trunk/test/Analysis/retain-release.mm (original)
+++ cfe/trunk/test/Analysis/retain-release.mm Tue Oct  3 16:15:35 2017
@@ -463,3 +463,10 @@ void   radar13722286::PrepareBitmap() {
 
 // rdar://34210609
 void _() { _(); }; // no-warning
+
+// Do not assume that IOBSDNameMatching increments a reference counter,
+// unless return type is CFMutableDictionaryRef.
+void* IOBSDNameMatching();
+void rdar33832412() {
+  void* x = IOBSDNameMatching(); // no-warning
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314960 - [Analyzer Tests] Fix misc bugs in analyzer reference results updater.

2017-10-04 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Oct  4 18:02:20 2017
New Revision: 314960

URL: http://llvm.org/viewvc/llvm-project?rev=314960&view=rev
Log:
[Analyzer Tests] Fix misc bugs in analyzer reference results updater.

Modified:
cfe/trunk/utils/analyzer/SATestUpdateDiffs.py

Modified: cfe/trunk/utils/analyzer/SATestUpdateDiffs.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestUpdateDiffs.py?rev=314960&r1=314959&r2=314960&view=diff
==
--- cfe/trunk/utils/analyzer/SATestUpdateDiffs.py (original)
+++ cfe/trunk/utils/analyzer/SATestUpdateDiffs.py Wed Oct  4 18:02:20 2017
@@ -34,8 +34,11 @@ def updateReferenceResults(ProjName, Pro
  "previously run?"
 sys.exit(-1)
 
-# Remove reference results.
-runCmd('git rm -r "%s"' % (RefResultsPath,))
+# Remove reference results: in git, and then again for a good measure
+# with rm, as git might not remove things fully if there are empty
+# directories involved.
+runCmd('git rm -r -q "%s"' % (RefResultsPath,))
+runCmd('rm -rf "%s"' % (RefResultsPath,))
 
 # Replace reference results with a freshly computed once.
 runCmd('cp -r "%s" "%s"' % (CreatedResultsPath, RefResultsPath,))
@@ -52,12 +55,21 @@ def updateReferenceResults(ProjName, Pro
 SATestBuild.cleanupReferenceResults(RefResultsPath)
 
 # Remove the created .diffs file before adding.
-runCmd('rm -f "%s/*/%s"' % (
-RefResultsPath, SATestBuild.DiffsSummaryFileName))
+removeDiffsSummaryFiles(RefResultsPath)
 
 runCmd('git add "%s"' % (RefResultsPath,))
 
 
+def removeDiffsSummaryFiles(RefResultsPath):
+"""
+Remove all auto-generated .diffs files in reference data.
+"""
+for (Dirpath, Dirnames, Filenames) in os.walk(RefResultsPath):
+if SATestBuild.DiffsSummaryFileName in Filenames:
+runCmd("rm '%s'" % os.path.join(
+Dirpath, SATestBuild.DiffsSummaryFileName))
+
+
 def main(argv):
 if len(argv) == 2 and argv[1] in ('-h', '--help'):
 print >> sys.stderr, "Update static analyzer reference results based "\


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r314992 - [Analyzer Tests] Run static analyzer integration tests until the end,

2017-10-05 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Oct  5 10:32:06 2017
New Revision: 314992

URL: http://llvm.org/viewvc/llvm-project?rev=314992&view=rev
Log:
[Analyzer Tests] Run static analyzer integration tests until the end,

Do not stop at the first failure.

Differential Revision: https://reviews.llvm.org/D38589

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=314992&r1=314991&r2=314992&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Thu Oct  5 10:32:06 2017
@@ -570,7 +570,11 @@ def runCmpResults(Dir, Strictness=0):
   0 - success if there are no crashes or analyzer failure.
   1 - success if there are no difference in the number of reported bugs.
   2 - success if all the bug reports are identical.
+
+:return success: Whether tests pass according to the Strictness
+criteria.
 """
+TestsPassed = True
 TBegin = time.time()
 
 RefDir = os.path.join(Dir, SBOutputDirReferencePrefix + SBOutputDirName)
@@ -586,8 +590,6 @@ def runCmpResults(Dir, Strictness=0):
 RefList.remove(RefLogDir)
 NewList.remove(os.path.join(NewDir, LogFolderName))
 
-if len(RefList) == 0 or len(NewList) == 0:
-return False
 assert(len(RefList) == len(NewList))
 
 # There might be more then one folder underneath - one per each scan-build
@@ -624,15 +626,15 @@ def runCmpResults(Dir, Strictness=0):
   (NumDiffs, DiffsPath,)
 if Strictness >= 2 and NumDiffs > 0:
 print "Error: Diffs found in strict mode (2)."
-sys.exit(-1)
+TestsPassed = False
 elif Strictness >= 1 and ReportsInRef != ReportsInNew:
 print "Error: The number of results are different in "\
   "strict mode (1)."
-sys.exit(-1)
+TestsPassed = False
 
 print "Diagnostic comparison complete (time: %.2f)." % (
   time.time() - TBegin)
-return (NumDiffs > 0)
+return TestsPassed
 
 
 def cleanupReferenceResults(SBOutputDir):
@@ -686,6 +688,11 @@ def updateSVN(Mode, PMapFile):
 
 
 def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Strictness=0):
+"""
+Test a given project.
+:return TestsPassed: Whether tests have passed according
+to the :param Strictness: criteria.
+"""
 print " \n\n--- Building project %s" % (ID,)
 
 TBegin = time.time()
@@ -704,11 +711,13 @@ def testProject(ID, ProjectBuildMode, Is
 
 if IsReferenceBuild:
 cleanupReferenceResults(SBOutputDir)
+TestsPassed = True
 else:
-runCmpResults(Dir, Strictness)
+TestsPassed = runCmpResults(Dir, Strictness)
 
 print "Completed tests for project %s (time: %.2f)." % \
   (ID, (time.time() - TBegin))
+return TestsPassed
 
 
 def isCommentCSVLine(Entries):
@@ -749,6 +758,7 @@ def validateProjectFile(PMapFile):
 
 
 def testAll(IsReferenceBuild=False, UpdateSVN=False, Strictness=0):
+TestsPassed = True
 with projectFileHandler() as PMapFile:
 validateProjectFile(PMapFile)
 
@@ -760,7 +770,7 @@ def testAll(IsReferenceBuild=False, Upda
 
 # Test the projects.
 for (ProjName, ProjBuildMode) in iterateOverProjects(PMapFile):
-testProject(
+TestsPassed &= testProject(
 ProjName, int(ProjBuildMode), IsReferenceBuild, Strictness)
 
 # Re-add reference results to SVN.
@@ -793,4 +803,6 @@ if __name__ == '__main__':
 IsReference = True
 UpdateSVN = True
 
-testAll(IsReference, UpdateSVN, Strictness)
+TestsPassed = testAll(IsReference, UpdateSVN, Strictness)
+if not TestsPassed:
+sys.exit(-1)


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315250 - [Analyzer] Do not segfault on unexpected call_once implementation

2017-10-09 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct  9 16:20:46 2017
New Revision: 315250

URL: http://llvm.org/viewvc/llvm-project?rev=315250&view=rev
Log:
[Analyzer] Do not segfault on unexpected call_once implementation

Fixes https://bugs.llvm.org/show_bug.cgi?id=34869

Differential Revision: https://reviews.llvm.org/D38702

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=315250&r1=315249&r2=315250&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Mon Oct  9 16:20:46 2017
@@ -327,6 +327,28 @@ static Stmt *create_call_once(ASTContext
   const ParmVarDecl *Flag = D->getParamDecl(0);
   const ParmVarDecl *Callback = D->getParamDecl(1);
   QualType CallbackType = Callback->getType().getNonReferenceType();
+  QualType FlagType = Flag->getType().getNonReferenceType();
+  CXXRecordDecl *FlagCXXDecl = FlagType->getAsCXXRecordDecl();
+  if (!FlagCXXDecl) {
+DEBUG(llvm::dbgs() << "Flag field is not a CXX record: "
+   << "unknown std::call_once implementation."
+   << "Ignoring the call.\n");
+return nullptr;
+  }
+
+  // Note: here we are assuming libc++ implementation of call_once,
+  // which has a struct with a field `__state_`.
+  // Body farming might not work for other `call_once` implementations.
+  NamedDecl *FoundDecl = M.findMemberField(FlagCXXDecl, "__state_");
+  ValueDecl *FieldDecl;
+  if (FoundDecl) {
+FieldDecl = dyn_cast(FoundDecl);
+  } else {
+DEBUG(llvm::dbgs() << "No field __state_ found on std::once_flag struct, "
+   << "unable to synthesize call_once body, ignoring "
+   << "the call.\n");
+return nullptr;
+  }
 
   bool isLambdaCall = CallbackType->getAsCXXRecordDecl() &&
   CallbackType->getAsCXXRecordDecl()->isLambda();
@@ -355,27 +377,11 @@ static Stmt *create_call_once(ASTContext
 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
   }
 
-  QualType FlagType = Flag->getType().getNonReferenceType();
   DeclRefExpr *FlagDecl =
   M.makeDeclRefExpr(Flag,
 /* RefersToEnclosingVariableOrCapture=*/true,
 /* GetNonReferenceType=*/true);
 
-  CXXRecordDecl *FlagCXXDecl = FlagType->getAsCXXRecordDecl();
-
-  // Note: here we are assuming libc++ implementation of call_once,
-  // which has a struct with a field `__state_`.
-  // Body farming might not work for other `call_once` implementations.
-  NamedDecl *FoundDecl = M.findMemberField(FlagCXXDecl, "__state_");
-  ValueDecl *FieldDecl;
-  if (FoundDecl) {
-FieldDecl = dyn_cast(FoundDecl);
-  } else {
-DEBUG(llvm::dbgs() << "No field __state_ found on std::once_flag struct, "
-   << "unable to synthesize call_once body, ignoring "
-   << "the call.\n");
-return nullptr;
-  }
 
   MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FieldDecl);
   assert(Deref->isLValue());

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=315250&r1=315249&r2=315250&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Mon Oct  9 16:20:46 2017
@@ -231,3 +231,12 @@ void test_non_std_call_once() {
   int x = call_once();
   clang_analyzer_eval(x == 5); // expected-warning{{TRUE}}
 }
+
+namespace std {
+template 
+void call_once(d, e);
+}
+void g();
+void test_no_segfault_on_different_impl() {
+  std::call_once(g, false); // no-warning
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315488 - [Analyzer] Assume that string-like const globals are non-nil.

2017-10-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Oct 11 11:39:40 2017
New Revision: 315488

URL: http://llvm.org/viewvc/llvm-project?rev=315488&view=rev
Log:
[Analyzer] Assume that string-like const globals are non-nil.

Differential Revision: https://reviews.llvm.org/D38764

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp
cfe/trunk/test/Analysis/nonnull-string-constants.mm
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=315488&r1=315487&r2=315488&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Wed Oct 11 
11:39:40 2017
@@ -132,6 +132,10 @@ def DynamicTypePropagation : Checker<"Dy
   HelpText<"Generate dynamic type information">,
   DescFile<"DynamicTypePropagation.cpp">;
 
+def NonnullStringConstantsChecker: Checker<"NonnilStringConstants">,
+  HelpText<"Assume that const string-like globals are non-null">,
+  DescFile<"NonilStringConstantsChecker.cpp">;
+
 } // end "core"
 
 let ParentPackage = CoreAlpha in {

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=315488&r1=315487&r2=315488&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Wed Oct 11 11:39:40 
2017
@@ -57,6 +57,7 @@ add_clang_library(clangStaticAnalyzerChe
   NSErrorChecker.cpp
   NoReturnFunctionChecker.cpp
   NonNullParamChecker.cpp
+  NonnullStringConstantsChecker.cpp
   NullabilityChecker.cpp
   NumberObjectConversionChecker.cpp
   ObjCAtSyncChecker.cpp

Added: cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp?rev=315488&view=auto
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp 
(added)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp Wed 
Oct 11 11:39:40 2017
@@ -0,0 +1,134 @@
+//==- NonnullStringConstantsChecker.cpp ---*- C++ 
-*--//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+//  This checker adds an assumption that constant string-like globals are
+//  non-null, as otherwise they generally do not convey any useful information.
+//  The assumption is useful, as many framework use such global const strings,
+//  and the analyzer might not be able to infer the global value if the
+//  definition is in a separate translation unit.
+//  The following types (and their typedef aliases) are considered string-like:
+//   - `char* const`
+//   - `const CFStringRef` from CoreFoundation
+//   - `NSString* const` from Foundation
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class NonnullStringConstantsChecker : public Checker {
+  mutable IdentifierInfo *NSStringII = nullptr;
+  mutable IdentifierInfo *CFStringRefII = nullptr;
+
+public:
+  NonnullStringConstantsChecker() {}
+
+  void checkLocation(SVal l, bool isLoad, const Stmt *S,
+ CheckerContext &C) const;
+
+private:
+  void initIdentifierInfo(ASTContext &Ctx) const;
+
+  bool isGlobalConstString(SVal V) const;
+
+  bool isStringlike(QualType Ty) const;
+};
+
+} // namespace
+
+/// Lazily initialize cache for required identifier informations.
+void NonnullStringConstantsChecker::initIdentifierInfo(ASTContext &Ctx) const {
+  if (NSStringII)
+return;
+
+  NSStringII = &Ctx.Idents.get("NSString");
+  CFStringRefII = &Ctx.Idents.get("CFStringRef");
+}
+
+/// Add an assumption that const string-like globals are non-null.
+void NonnullStringConstantsChecker::checkLocation(SVal location, bool isLoad,
+ const Stmt *S,
+   

r315489 - [Analyzer] Remove dead code from testing scripts

2017-10-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Oct 11 11:42:39 2017
New Revision: 315489

URL: http://llvm.org/viewvc/llvm-project?rev=315489&view=rev
Log:
[Analyzer] Remove dead code from testing scripts

Differential Revision: https://reviews.llvm.org/D38488

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=315489&r1=315488&r2=315489&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Wed Oct 11 11:42:39 2017
@@ -653,40 +653,6 @@ def cleanupReferenceResults(SBOutputDir)
 removeLogFile(SBOutputDir)
 
 
-def updateSVN(Mode, PMapFile):
-"""
-svn delete or svn add (depending on `Mode`) all folders defined in the file
-handler `PMapFile`.
-Commit the result to SVN.
-"""
-try:
-for I in iterateOverProjects(PMapFile):
-ProjName = I[0]
-Path = os.path.join(ProjName, getSBOutputDirName(True))
-
-if Mode == "delete":
-Command = "svn delete '%s'" % (Path,)
-else:
-Command = "svn add '%s'" % (Path,)
-
-if Verbose == 1:
-print "  Executing: %s" % (Command,)
-check_call(Command, shell=True)
-
-if Mode == "delete":
-CommitCommand = "svn commit -m \"[analyzer tests] Remove " \
-"reference results.\""
-else:
-CommitCommand = "svn commit -m \"[analyzer tests] Add new " \
-"reference results.\""
-if Verbose == 1:
-print "  Executing: %s" % (CommitCommand,)
-check_call(CommitCommand, shell=True)
-except:
-print "Error: SVN update failed."
-sys.exit(-1)
-
-
 def testProject(ID, ProjectBuildMode, IsReferenceBuild=False, Strictness=0):
 """
 Test a given project.
@@ -757,26 +723,16 @@ def validateProjectFile(PMapFile):
 raise Exception()
 
 
-def testAll(IsReferenceBuild=False, UpdateSVN=False, Strictness=0):
+def testAll(IsReferenceBuild=False, Strictness=0):
 TestsPassed = True
 with projectFileHandler() as PMapFile:
 validateProjectFile(PMapFile)
 
-# When we are regenerating the reference results, we might need to
-# update svn. Remove reference results from SVN.
-if UpdateSVN:
-assert(IsReferenceBuild)
-updateSVN("delete", PMapFile)
-
 # Test the projects.
 for (ProjName, ProjBuildMode) in iterateOverProjects(PMapFile):
 TestsPassed &= testProject(
 ProjName, int(ProjBuildMode), IsReferenceBuild, Strictness)
 
-# Re-add reference results to SVN.
-if UpdateSVN:
-updateSVN("add", PMapFile)
-
 
 if __name__ == '__main__':
 # Parse command line arguments.
@@ -789,20 +745,13 @@ if __name__ == '__main__':
  reference. Default is 0.')
 Parser.add_argument('-r', dest='regenerate', action='store_true',
 default=False, help='Regenerate reference output.')
-Parser.add_argument('-rs', dest='update_reference', action='store_true',
-default=False,
-help='Regenerate reference output and update svn.')
 Args = Parser.parse_args()
 
 IsReference = False
-UpdateSVN = False
 Strictness = Args.strictness
 if Args.regenerate:
 IsReference = True
-elif Args.update_reference:
-IsReference = True
-UpdateSVN = True
 
-TestsPassed = testAll(IsReference, UpdateSVN, Strictness)
+TestsPassed = testAll(IsReference, Strictness)
 if not TestsPassed:
 sys.exit(-1)


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315492 - [Analyzer] Fix introduced regression: properly check for nullable attribute.

2017-10-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Oct 11 12:13:15 2017
New Revision: 315492

URL: http://llvm.org/viewvc/llvm-project?rev=315492&view=rev
Log:
[Analyzer] Fix introduced regression: properly check for nullable attribute.

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp?rev=315492&r1=315491&r2=315492&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp Wed 
Oct 11 12:13:15 2017
@@ -122,7 +122,8 @@ bool NonnullStringConstantsChecker::isSt
 return true;
 
   if (auto *T = dyn_cast(Ty)) {
-return T->getInterfaceDecl()->getIdentifier() == NSStringII;
+return T->getInterfaceDecl() &&
+  T->getInterfaceDecl()->getIdentifier() == NSStringII;
   } else if (auto *T = dyn_cast(Ty)) {
 return T->getDecl()->getIdentifier() == CFStringRefII;
   }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315508 - [Analyzer] Support bodyfarming libstdc++ implementation of std::call_once.

2017-10-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Oct 11 13:53:01 2017
New Revision: 315508

URL: http://llvm.org/viewvc/llvm-project?rev=315508&view=rev
Log:
[Analyzer] Support bodyfarming libstdc++ implementation of std::call_once.

Differential Revision: https://reviews.llvm.org/D38810

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=315508&r1=315507&r2=315508&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Wed Oct 11 13:53:01 2017
@@ -108,7 +108,7 @@ public:
 
   /// Returns a *first* member field of a record declaration with a given name.
   /// \return an nullptr if no member with such a name exists.
-  NamedDecl *findMemberField(const CXXRecordDecl *RD, StringRef Name);
+  ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
 
 private:
   ASTContext &C;
@@ -234,7 +234,7 @@ MemberExpr *ASTMaker::makeMemberExpressi
   OK_Ordinary);
 }
 
-NamedDecl *ASTMaker::findMemberField(const CXXRecordDecl *RD, StringRef Name) {
+ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
 
   CXXBasePaths Paths(
   /* FindAmbiguities=*/false,
@@ -246,7 +246,7 @@ NamedDecl *ASTMaker::findMemberField(con
   DeclContextLookupResult Decls = RD->lookup(DeclName);
   for (NamedDecl *FoundDecl : Decls)
 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
-  return FoundDecl;
+  return cast(FoundDecl);
 
   return nullptr;
 }
@@ -328,25 +328,31 @@ static Stmt *create_call_once(ASTContext
   const ParmVarDecl *Callback = D->getParamDecl(1);
   QualType CallbackType = Callback->getType().getNonReferenceType();
   QualType FlagType = Flag->getType().getNonReferenceType();
-  CXXRecordDecl *FlagCXXDecl = FlagType->getAsCXXRecordDecl();
-  if (!FlagCXXDecl) {
-DEBUG(llvm::dbgs() << "Flag field is not a CXX record: "
-   << "unknown std::call_once implementation."
-   << "Ignoring the call.\n");
+  auto *FlagRecordDecl = 
dyn_cast_or_null(FlagType->getAsTagDecl());
+
+  if (!FlagRecordDecl) {
+DEBUG(llvm::dbgs() << "Flag field is not a record: "
+   << "unknown std::call_once implementation, "
+   << "ignoring the call.\n");
 return nullptr;
   }
 
-  // Note: here we are assuming libc++ implementation of call_once,
-  // which has a struct with a field `__state_`.
-  // Body farming might not work for other `call_once` implementations.
-  NamedDecl *FoundDecl = M.findMemberField(FlagCXXDecl, "__state_");
-  ValueDecl *FieldDecl;
-  if (FoundDecl) {
-FieldDecl = dyn_cast(FoundDecl);
-  } else {
+  // We initially assume libc++ implementation of call_once,
+  // where the once_flag struct has a field `__state_`.
+  ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
+
+  // Otherwise, try libstdc++ implementation, with a field
+  // `_M_once`
+  if (!FlagFieldDecl) {
 DEBUG(llvm::dbgs() << "No field __state_ found on std::once_flag struct, "
-   << "unable to synthesize call_once body, ignoring "
-   << "the call.\n");
+   << "assuming libstdc++ implementation\n");
+FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
+  }
+
+  if (!FlagFieldDecl) {
+DEBUG(llvm::dbgs() << "No field _M_once found on std::once flag struct: "
+   << "unknown std::call_once implementation, "
+   << "ignoring the call");
 return nullptr;
   }
 
@@ -383,7 +389,7 @@ static Stmt *create_call_once(ASTContext
 /* GetNonReferenceType=*/true);
 
 
-  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FieldDecl);
+  MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
   assert(Deref->isLValue());
   QualType DerefType = Deref->getType();
 

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=315508&r1=315507&r2=315508&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Wed Oct 11 13:53:01 2017
@@ -1,15 +1,24 @@
-// RUN: %clang_analyze_cc1 -std=c++11 -fblocks 
-analyzer-checker=core,debug.ExprInspection -w -verify %s
+// RUN: %clang_analyze_cc1 -std=c++11 -fblocks 
-analyzer-checker=core,debug.ExprInspection -verify %s
+// RUN: %clang_analyze_cc1 -std=c++11 -fblocks 
-analyzer-checker=core,debug.ExprInspection -DEMULATE_LIBSTDCPP -verify %s
 
 void clang_analyzer_eval(bool);
 
 // Faking std::std::call_once implementation.
 namespace std {
+
+#ifndef EMULATE_LIBSTDCPP
 typedef struct once_flag_s {
   unsigned long __state_ = 0;
 } 

r315655 - [Analyzer] Assume that CFBooleanRef const globals are non-null

2017-10-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Oct 12 17:51:41 2017
New Revision: 315655

URL: http://llvm.org/viewvc/llvm-project?rev=315655&view=rev
Log:
[Analyzer] Assume that CFBooleanRef const globals are non-null

Differential Revision: https://reviews.llvm.org/D38867

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp
  - copied, changed from r315652, 
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp
cfe/trunk/test/Analysis/nonnull-global-constants.mm
  - copied, changed from r315652, 
cfe/trunk/test/Analysis/nonnull-string-constants.mm
Removed:
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp
cfe/trunk/test/Analysis/nonnull-string-constants.mm
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=315655&r1=315654&r2=315655&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Thu Oct 12 
17:51:41 2017
@@ -132,7 +132,7 @@ def DynamicTypePropagation : Checker<"Dy
   HelpText<"Generate dynamic type information">,
   DescFile<"DynamicTypePropagation.cpp">;
 
-def NonnullStringConstantsChecker: Checker<"NonnilStringConstants">,
+def NonnullGlobalConstantsChecker: Checker<"NonnilStringConstants">,
   HelpText<"Assume that const string-like globals are non-null">,
   DescFile<"NonilStringConstantsChecker.cpp">;
 

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=315655&r1=315654&r2=315655&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Thu Oct 12 17:51:41 
2017
@@ -57,7 +57,7 @@ add_clang_library(clangStaticAnalyzerChe
   NSErrorChecker.cpp
   NoReturnFunctionChecker.cpp
   NonNullParamChecker.cpp
-  NonnullStringConstantsChecker.cpp
+  NonnullGlobalConstantsChecker.cpp
   NullabilityChecker.cpp
   NumberObjectConversionChecker.cpp
   ObjCAtSyncChecker.cpp

Copied: cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp 
(from r315652, 
cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp?p2=cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp&p1=cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp&r1=315652&r2=315655&rev=315655&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullStringConstantsChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/NonnullGlobalConstantsChecker.cpp Thu 
Oct 12 17:51:41 2017
@@ -1,4 +1,4 @@
-//==- NonnullStringConstantsChecker.cpp ---*- C++ 
-*--//
+//==- NonnullGlobalConstantsChecker.cpp ---*- C++ 
-*--//
 //
 // The LLVM Compiler Infrastructure
 //
@@ -7,15 +7,17 @@
 //
 
//===--===//
 //
-//  This checker adds an assumption that constant string-like globals are
+//  This checker adds an assumption that constant globals of certain types* are
 //  non-null, as otherwise they generally do not convey any useful information.
-//  The assumption is useful, as many framework use such global const strings,
+//  The assumption is useful, as many framework use e. g. global const strings,
 //  and the analyzer might not be able to infer the global value if the
 //  definition is in a separate translation unit.
-//  The following types (and their typedef aliases) are considered string-like:
+//  The following types (and their typedef aliases) are considered to be
+//  non-null:
 //   - `char* const`
 //   - `const CFStringRef` from CoreFoundation
 //   - `NSString* const` from Foundation
+//   - `CFBooleanRef` from Foundation
 //
 
//===--===//
 
@@ -31,12 +33,13 @@ using namespace ento;
 
 namespace {
 
-class NonnullStringConstantsChecker : public Checker {
+class NonnullGlobalConstantsChecker : public Checker {
   mutable IdentifierInfo *NSStringII = nullptr;
   mutable IdentifierInfo *CFStringRefII = nullptr;
+  mutable IdentifierInfo *CFBooleanRefII = nullptr;
 
 public:
-  NonnullStringConstantsChecker() {}
+  NonnullGlobalConstantsChecker() {}
 
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
   

r315771 - Allow building libFuzzer in two-stage compiler-rt build

2017-10-13 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Oct 13 15:03:09 2017
New Revision: 315771

URL: http://llvm.org/viewvc/llvm-project?rev=315771&view=rev
Log:
Allow building libFuzzer in two-stage compiler-rt build

When LLVM_BUILD_EXTERNAL_COMPILER_RT option is set to true,
all of projects in compiler-rt are built with a freshly-built compiler using
a recursive CMake invocation.
(e.g. that's how compiler-rt is used in Swift)

Just now I have noticed that libFuzzer binaries were missing in such a case,
and ninja fuzzer returned "no such target", while ninja asan worked just fine.

To my surprise, the list of allowed targets was actually hardcoded in Clang!
While the current setup is clearly suboptimal, for the lack of a better fix
I'm just adding `fuzzer` to a list of `compiler-rt` targets.

Differential Revision: https://reviews.llvm.org/D38904

Modified:
cfe/trunk/runtime/CMakeLists.txt

Modified: cfe/trunk/runtime/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/runtime/CMakeLists.txt?rev=315771&r1=315770&r2=315771&view=diff
==
--- cfe/trunk/runtime/CMakeLists.txt (original)
+++ cfe/trunk/runtime/CMakeLists.txt Fri Oct 13 15:03:09 2017
@@ -109,7 +109,7 @@ if(LLVM_BUILD_EXTERNAL_COMPILER_RT AND E
 USES_TERMINAL)
 
   # Add top-level targets that build specific compiler-rt runtimes.
-  set(COMPILER_RT_RUNTIMES asan builtins dfsan lsan msan profile tsan ubsan 
ubsan-minimal)
+  set(COMPILER_RT_RUNTIMES fuzzer asan builtins dfsan lsan msan profile tsan 
ubsan ubsan-minimal)
   foreach(runtime ${COMPILER_RT_RUNTIMES})
 get_ext_project_build_command(build_runtime_cmd ${runtime})
 add_custom_target(${runtime}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r315776 - Allow building libFuzzer tests in two-stage compiler-rt build.

2017-10-13 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Oct 13 16:50:53 2017
New Revision: 315776

URL: http://llvm.org/viewvc/llvm-project?rev=315776&view=rev
Log:
Allow building libFuzzer tests in two-stage compiler-rt build.

Modified:
cfe/trunk/runtime/CMakeLists.txt

Modified: cfe/trunk/runtime/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/runtime/CMakeLists.txt?rev=315776&r1=315775&r2=315776&view=diff
==
--- cfe/trunk/runtime/CMakeLists.txt (original)
+++ cfe/trunk/runtime/CMakeLists.txt Fri Oct 13 16:50:53 2017
@@ -125,7 +125,7 @@ if(LLVM_BUILD_EXTERNAL_COMPILER_RT AND E
   FileCheck count not llvm-nm llvm-objdump llvm-symbolizer)
 
 # Add top-level targets for various compiler-rt test suites.
-set(COMPILER_RT_TEST_SUITES check-asan check-asan-dynamic check-dfsan
+set(COMPILER_RT_TEST_SUITES check-fuzzer check-asan check-asan-dynamic 
check-dfsan
   check-lsan check-msan check-sanitizer check-tsan check-ubsan 
check-ubsan-minimal
   check-profile check-cfi check-cfi-and-supported check-safestack)
 foreach(test_suite ${COMPILER_RT_TEST_SUITES})


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316041 - [Analyzer] Always use non-reference types when creating expressions in BodyFarm.

2017-10-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 17 15:28:18 2017
New Revision: 316041

URL: http://llvm.org/viewvc/llvm-project?rev=316041&view=rev
Log:
[Analyzer] Always use non-reference types when creating expressions in BodyFarm.

Remove an option to use a reference type (on by default!) since a
non-reference type is always needed for creating expressions, functions
with multiple boolean parameters are very hard to use, and in general it
was just a booby trap for further crashes.
Furthermore, generalize call_once test case to fix some of the crashes mentioned
https://bugs.llvm.org/show_bug.cgi?id=34869
Also removes std::call_once crash.

Differential Revision: https://reviews.llvm.org/D39015

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=316041&r1=316040&r2=316041&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Tue Oct 17 15:28:18 2017
@@ -63,8 +63,7 @@ public:
   
   /// Create a new DeclRefExpr for the referenced variable.
   DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
-   bool RefersToEnclosingVariableOrCapture = false,
-   bool GetNonReferenceType = false);
+   bool RefersToEnclosingVariableOrCapture = 
false);
   
   /// Create a new UnaryOperator representing a dereference.
   UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
@@ -82,8 +81,7 @@ public:
   /// DeclRefExpr in the process.
   ImplicitCastExpr *
   makeLvalueToRvalue(const VarDecl *Decl,
- bool RefersToEnclosingVariableOrCapture = false,
- bool GetNonReferenceType = false);
+ bool RefersToEnclosingVariableOrCapture = false);
 
   /// Create an implicit cast of the given type.
   ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
@@ -138,12 +136,10 @@ CompoundStmt *ASTMaker::makeCompound(Arr
   return new (C) CompoundStmt(C, Stmts, SourceLocation(), SourceLocation());
 }
 
-DeclRefExpr *ASTMaker::makeDeclRefExpr(const VarDecl *D,
-   bool RefersToEnclosingVariableOrCapture,
-   bool GetNonReferenceType) {
-  auto Type = D->getType();
-  if (GetNonReferenceType)
-Type = Type.getNonReferenceType();
+DeclRefExpr *ASTMaker::makeDeclRefExpr(
+const VarDecl *D,
+bool RefersToEnclosingVariableOrCapture) {
+  QualType Type = D->getType().getNonReferenceType();
 
   DeclRefExpr *DR = DeclRefExpr::Create(
   C, NestedNameSpecifierLoc(), SourceLocation(), const_cast(D),
@@ -162,14 +158,10 @@ ImplicitCastExpr *ASTMaker::makeLvalueTo
 
 ImplicitCastExpr *
 ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
- bool RefersToEnclosingVariableOrCapture,
- bool GetNonReferenceType) {
-  auto Type = Arg->getType();
-  if (GetNonReferenceType)
-Type = Type.getNonReferenceType();
+ bool RefersToEnclosingVariableOrCapture) {
+  QualType Type = Arg->getType().getNonReferenceType();
   return makeLvalueToRvalue(makeDeclRefExpr(Arg,
-RefersToEnclosingVariableOrCapture,
-GetNonReferenceType),
+
RefersToEnclosingVariableOrCapture),
 Type);
 }
 
@@ -365,12 +357,13 @@ static Stmt *create_call_once(ASTContext
 // Lambda requires callback itself inserted as a first parameter.
 CallArgs.push_back(
 M.makeDeclRefExpr(Callback,
-  /* RefersToEnclosingVariableOrCapture= */ true,
-  /* GetNonReferenceType= */ true));
+  /* RefersToEnclosingVariableOrCapture= */ true));
 
   // All arguments past first two ones are passed to the callback.
   for (unsigned int i = 2; i < D->getNumParams(); i++)
-CallArgs.push_back(M.makeLvalueToRvalue(D->getParamDecl(i)));
+CallArgs.push_back(
+M.makeLvalueToRvalue(D->getParamDecl(i),
+ /* RefersToEnclosingVariableOrCapture= */ false));
 
   CallExpr *CallbackCall;
   if (isLambdaCall) {
@@ -385,8 +378,7 @@ static Stmt *create_call_once(ASTContext
 
   DeclRefExpr *FlagDecl =
   M.makeDeclRefExpr(Flag,
-/* RefersToEnclosingVariableOrCapture=*/true,
-/* GetNonReferenceType=*/true);
+/* RefersToEnclosingVariableOrCapture=*/true);
 
 
   MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=316041&r1=3160

r316249 - [Analyzer] Correctly handle parameters passed by reference when bodyfarming std::call_once

2017-10-20 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Oct 20 16:29:59 2017
New Revision: 316249

URL: http://llvm.org/viewvc/llvm-project?rev=316249&view=rev
Log:
[Analyzer] Correctly handle parameters passed by reference when bodyfarming 
std::call_once

Explicitly not supporting functor objects.

Differential Revision: https://reviews.llvm.org/D39031

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=316249&r1=316248&r2=316249&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Fri Oct 20 16:29:59 2017
@@ -264,11 +264,8 @@ static CallExpr *create_call_once_funcpt
 
 static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
   const ParmVarDecl *Callback,
-  QualType CallbackType,
+  CXXRecordDecl *CallbackDecl,
   ArrayRef CallArgs) {
-
-  CXXRecordDecl *CallbackDecl = CallbackType->getAsCXXRecordDecl();
-
   assert(CallbackDecl != nullptr);
   assert(CallbackDecl->isLambda());
   FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
@@ -319,6 +316,9 @@ static Stmt *create_call_once(ASTContext
   const ParmVarDecl *Flag = D->getParamDecl(0);
   const ParmVarDecl *Callback = D->getParamDecl(1);
   QualType CallbackType = Callback->getType().getNonReferenceType();
+
+  // Nullable pointer, non-null iff function is a CXXRecordDecl.
+  CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
   QualType FlagType = Flag->getType().getNonReferenceType();
   auto *FlagRecordDecl = 
dyn_cast_or_null(FlagType->getAsTagDecl());
 
@@ -348,28 +348,58 @@ static Stmt *create_call_once(ASTContext
 return nullptr;
   }
 
-  bool isLambdaCall = CallbackType->getAsCXXRecordDecl() &&
-  CallbackType->getAsCXXRecordDecl()->isLambda();
+  bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
+  if (CallbackRecordDecl && !isLambdaCall) {
+DEBUG(llvm::dbgs() << "Not supported: synthesizing body for functors when "
+   << "body farming std::call_once, ignoring the call.");
+return nullptr;
+  }
 
   SmallVector CallArgs;
+  const FunctionProtoType *CallbackFunctionType;
+  if (isLambdaCall) {
 
-  if (isLambdaCall)
 // Lambda requires callback itself inserted as a first parameter.
 CallArgs.push_back(
 M.makeDeclRefExpr(Callback,
   /* RefersToEnclosingVariableOrCapture= */ true));
+CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
+   ->getType()
+   ->getAs();
+  } else {
+CallbackFunctionType =
+CallbackType->getPointeeType()->getAs();
+  }
 
-  // All arguments past first two ones are passed to the callback.
-  for (unsigned int i = 2; i < D->getNumParams(); i++)
-CallArgs.push_back(
-M.makeLvalueToRvalue(D->getParamDecl(i),
- /* RefersToEnclosingVariableOrCapture= */ false));
+  if (!CallbackFunctionType)
+return nullptr;
+
+  // First two arguments are used for the flag and for the callback.
+  if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
+DEBUG(llvm::dbgs() << "Number of params of the callback does not match "
+   << "the number of params passed to std::call_once, "
+   << "ignoring the call");
+return nullptr;
+  }
+
+  // All arguments past first two ones are passed to the callback,
+  // and we turn lvalues into rvalues if the argument is not passed by
+  // reference.
+  for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
+const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
+Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
+if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
+  QualType PTy = PDecl->getType().getNonReferenceType();
+  ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
+}
+CallArgs.push_back(ParamExpr);
+  }
 
   CallExpr *CallbackCall;
   if (isLambdaCall) {
 
-CallbackCall =
-create_call_once_lambda_call(C, M, Callback, CallbackType, CallArgs);
+CallbackCall = create_call_once_lambda_call(C, M, Callback,
+CallbackRecordDecl, CallArgs);
   } else {
 
 // Function pointer case.

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=316249&r1=316248&r2=316249&view=diff
==
--- cfe/trunk/test/Analysis/call_once

r316400 - [Analyzer] Do not use static storage to for implementations created in BodyFarm.cpp

2017-10-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct 23 16:59:52 2017
New Revision: 316400

URL: http://llvm.org/viewvc/llvm-project?rev=316400&view=rev
Log:
[Analyzer] Do not use static storage to for implementations created in 
BodyFarm.cpp

Differential Revision: https://reviews.llvm.org/D39208

Added:
cfe/trunk/include/clang/Analysis/BodyFarm.h
  - copied, changed from r316249, cfe/trunk/lib/Analysis/BodyFarm.h
Removed:
cfe/trunk/lib/Analysis/BodyFarm.h
Modified:
cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h
cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp

Modified: cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h?rev=316400&r1=316399&r2=316400&view=diff
==
--- cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h (original)
+++ cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h Mon Oct 23 16:59:52 
2017
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_ANALYSIS_ANALYSISDECLCONTEXT_H
 
 #include "clang/AST/Decl.h"
+#include "clang/Analysis/BodyFarm.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CodeInjector.h"
 #include "llvm/ADT/DenseMap.h"
@@ -409,6 +410,7 @@ class AnalysisDeclContextManager {
   typedef llvm::DenseMap>
   ContextMap;
 
+  ASTContext &ASTCtx;
   ContextMap Contexts;
   LocationContextManager LocContexts;
   CFG::BuildOptions cfgBuildOptions;
@@ -416,22 +418,25 @@ class AnalysisDeclContextManager {
   /// Pointer to an interface that can provide function bodies for
   /// declarations from external source.
   std::unique_ptr Injector;
-  
+
+  /// Pointer to a factory for creating and caching implementations for common
+  /// methods during the analysis.
+  BodyFarm *BdyFrm = nullptr;
+
   /// Flag to indicate whether or not bodies should be synthesized
   /// for well-known functions.
   bool SynthesizeBodies;
 
 public:
-  AnalysisDeclContextManager(bool useUnoptimizedCFG = false,
+  AnalysisDeclContextManager(ASTContext &ASTCtx, bool useUnoptimizedCFG = 
false,
  bool addImplicitDtors = false,
  bool addInitializers = false,
  bool addTemporaryDtors = false,
- bool addLifetime = false,
- bool addLoopExit = false,
+ bool addLifetime = false, bool addLoopExit = 
false,
  bool synthesizeBodies = false,
  bool addStaticInitBranches = false,
  bool addCXXNewAllocator = true,
- CodeInjector* injector = nullptr);
+ CodeInjector *injector = nullptr);
 
   ~AnalysisDeclContextManager();
 
@@ -472,6 +477,9 @@ public:
 return LocContexts.getStackFrame(getContext(D), Parent, S, Blk, Idx);
   }
 
+  /// Get and lazily create a {@code BodyFarm} instance.
+  BodyFarm *getBodyFarm();
+
   /// Discard all previously created AnalysisDeclContexts.
   void clear();
 

Copied: cfe/trunk/include/clang/Analysis/BodyFarm.h (from r316249, 
cfe/trunk/lib/Analysis/BodyFarm.h)
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/BodyFarm.h?p2=cfe/trunk/include/clang/Analysis/BodyFarm.h&p1=cfe/trunk/lib/Analysis/BodyFarm.h&r1=316249&r2=316400&rev=316400&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.h (original)
+++ cfe/trunk/include/clang/Analysis/BodyFarm.h Mon Oct 23 16:59:52 2017
@@ -28,11 +28,11 @@ class ObjCMethodDecl;
 class ObjCPropertyDecl;
 class Stmt;
 class CodeInjector;
-  
+
 class BodyFarm {
 public:
   BodyFarm(ASTContext &C, CodeInjector *injector) : C(C), Injector(injector) {}
-  
+
   /// Factory method for creating bodies for ordinary functions.
   Stmt *getBody(const FunctionDecl *D);
 
@@ -40,12 +40,12 @@ public:
   Stmt *getBody(const ObjCMethodDecl *D);
 
 private:
-  typedef llvm::DenseMap > BodyMap;
+  typedef llvm::DenseMap> BodyMap;
 
   ASTContext &C;
   BodyMap Bodies;
   CodeInjector *Injector;
 };
-}
+} // namespace clang
 
 #endif

Modified: cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp?rev=316400&r1=316399&r2=316400&view=diff
==
--- cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp (original)
+++ cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp Mon Oct 23 16:59:52 2017
@@ -13,7 +13,6 @@
 
//===--===//
 
 #include "clang/Analysis/AnalysisDeclContext.h"
-#include "BodyFarm.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "cla

r316402 - [Analyzer] Handle implicit function reference in bodyfarming std::call_once

2017-10-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct 23 17:13:18 2017
New Revision: 316402

URL: http://llvm.org/viewvc/llvm-project?rev=316402&view=rev
Log:
[Analyzer] Handle implicit function reference in bodyfarming std::call_once

Differential Revision: https://reviews.llvm.org/D39201

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=316402&r1=316401&r2=316402&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Mon Oct 23 17:13:18 2017
@@ -253,13 +253,23 @@ static CallExpr *create_call_once_funcpt
const ParmVarDecl *Callback,
ArrayRef CallArgs) {
 
-  return new (C) CallExpr(
-  /*ASTContext=*/C,
-  /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Callback),
-  /*args=*/CallArgs,
-  /*QualType=*/C.VoidTy,
-  /*ExprValueType=*/VK_RValue,
-  /*SourceLocation=*/SourceLocation());
+  QualType Ty = Callback->getType();
+  DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
+  CastKind CK;
+  if (Ty->isRValueReferenceType()) {
+CK = CK_LValueToRValue;
+  } else {
+assert(Ty->isLValueReferenceType());
+CK = CK_FunctionToPointerDecay;
+Ty = C.getPointerType(Ty.getNonReferenceType());
+  }
+
+  return new (C)
+  CallExpr(C, M.makeImplicitCast(Call, Ty.getNonReferenceType(), CK),
+   /*args=*/CallArgs,
+   /*QualType=*/C.VoidTy,
+   /*ExprValueType=*/VK_RValue,
+   /*SourceLocation=*/SourceLocation());
 }
 
 static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
@@ -366,9 +376,11 @@ static Stmt *create_call_once(ASTContext
 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
->getType()
->getAs();
-  } else {
+  } else if (!CallbackType->getPointeeType().isNull()) {
 CallbackFunctionType =
 CallbackType->getPointeeType()->getAs();
+  } else {
+CallbackFunctionType = CallbackType->getAs();
   }
 
   if (!CallbackFunctionType)

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=316402&r1=316401&r2=316402&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Mon Oct 23 17:13:18 2017
@@ -290,3 +290,16 @@ void test_mutator_noref() {
   std::call_once(flag, &fail_mutator, a);
   clang_analyzer_eval(a == 42); // expected-warning{{FALSE}}
 }
+
+// Function is implicitly treated as a function pointer
+// even when an ampersand is not explicitly set.
+void callbackn(int ¶m) {
+  param = 42;
+};
+void test_implicit_funcptr() {
+  int x = 0;
+  static std::once_flag flagn;
+
+  std::call_once(flagn, callbackn, x);
+  clang_analyzer_eval(x == 42); // expected-warning{{TRUE}}
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316403 - [Analyzer] Fix for the memory leak: fix typo in if-statement.

2017-10-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Oct 23 18:09:43 2017
New Revision: 316403

URL: http://llvm.org/viewvc/llvm-project?rev=316403&view=rev
Log:
[Analyzer] Fix for the memory leak: fix typo in if-statement.

Modified:
cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp

Modified: cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp?rev=316403&r1=316402&r2=316403&view=diff
==
--- cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp (original)
+++ cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp Mon Oct 23 18:09:43 2017
@@ -604,7 +604,7 @@ AnalysisDeclContext::~AnalysisDeclContex
 }
 
 AnalysisDeclContextManager::~AnalysisDeclContextManager() {
-  if (!BdyFrm)
+  if (BdyFrm)
 delete BdyFrm;
 }
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316522 - [Analyzer] Fix bug in testing scripts, which always marked result as failure.

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 15:24:13 2017
New Revision: 316522

URL: http://llvm.org/viewvc/llvm-project?rev=316522&view=rev
Log:
[Analyzer] Fix bug in testing scripts, which always marked result as failure.

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=316522&r1=316521&r2=316522&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Tue Oct 24 15:24:13 2017
@@ -732,6 +732,7 @@ def testAll(IsReferenceBuild=False, Stri
 for (ProjName, ProjBuildMode) in iterateOverProjects(PMapFile):
 TestsPassed &= testProject(
 ProjName, int(ProjBuildMode), IsReferenceBuild, Strictness)
+return TestsPassed
 
 
 if __name__ == '__main__':


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316535 - [Analyzer] [Tests] Minor refactor of testing infrastructure:

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 16:52:48 2017
New Revision: 316535

URL: http://llvm.org/viewvc/llvm-project?rev=316535&view=rev
Log:
[Analyzer] [Tests] Minor refactor of testing infrastructure:

Move utilities functions into a separate file to make comprehension
easier.

Added:
cfe/trunk/utils/analyzer/SATestUtils.py
Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=316535&r1=316534&r2=316535&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Tue Oct 24 16:52:48 2017
@@ -43,6 +43,7 @@ For testing additional checkers, use the
 variable. It should contain a comma separated list.
 """
 import CmpRuns
+import SATestUtils
 
 import os
 import csv
@@ -53,7 +54,7 @@ import shutil
 import time
 import plistlib
 import argparse
-from subprocess import check_call, check_output, CalledProcessError
+from subprocess import check_call, CalledProcessError
 import multiprocessing
 
 #--
@@ -61,51 +62,7 @@ import multiprocessing
 #--
 
 
-def which(command, paths=None):
-"""which(command, [paths]) - Look up the given command in the paths string
-(or the PATH environment variable, if unspecified)."""
-
-if paths is None:
-paths = os.environ.get('PATH', '')
-
-# Check for absolute match first.
-if os.path.exists(command):
-return command
-
-# Would be nice if Python had a lib function for this.
-if not paths:
-paths = os.defpath
-
-# Get suffixes to search.
-# On Cygwin, 'PATHEXT' may exist but it should not be used.
-if os.pathsep == ';':
-pathext = os.environ.get('PATHEXT', '').split(';')
-else:
-pathext = ['']
-
-# Search the paths...
-for path in paths.split(os.pathsep):
-for ext in pathext:
-p = os.path.join(path, command + ext)
-if os.path.exists(p):
-return p
-
-return None
-
-
-class flushfile(object):
-"""
-Wrapper to flush the output after every print statement.
-"""
-def __init__(self, f):
-self.f = f
-
-def write(self, x):
-self.f.write(x)
-self.f.flush()
-
-
-sys.stdout = flushfile(sys.stdout)
+sys.stdout = SATestUtils.flushfile(sys.stdout)
 
 
 def getProjectMapPath():
@@ -137,7 +94,7 @@ def getSBOutputDirName(IsReferenceBuild)
 if 'CC' in os.environ:
 Clang = os.environ['CC']
 else:
-Clang = which("clang", os.environ['PATH'])
+Clang = SATestUtils.which("clang", os.environ['PATH'])
 if not Clang:
 print "Error: cannot find 'clang' in PATH"
 sys.exit(-1)
@@ -215,7 +172,7 @@ def runCleanupScript(Dir, PBuildLogFile)
 """
 Cwd = os.path.join(Dir, PatchedSourceDirName)
 ScriptPath = os.path.join(Dir, CleanupScript)
-runScript(ScriptPath, PBuildLogFile, Cwd)
+SATestUtils.runScript(ScriptPath, PBuildLogFile, Cwd)
 
 
 def runDownloadScript(Dir, PBuildLogFile):
@@ -223,29 +180,7 @@ def runDownloadScript(Dir, PBuildLogFile
 Run the script to download the project, if it exists.
 """
 ScriptPath = os.path.join(Dir, DownloadScript)
-runScript(ScriptPath, PBuildLogFile, Dir)
-
-
-def runScript(ScriptPath, PBuildLogFile, Cwd):
-"""
-Run the provided script if it exists.
-"""
-if os.path.exists(ScriptPath):
-try:
-if Verbose == 1:
-print "  Executing: %s" % (ScriptPath,)
-check_call("chmod +x '%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
-   shell=True)
-check_call("'%s'" % ScriptPath, cwd=Cwd,
-   stderr=PBuildLogFile,
-   stdout=PBuildLogFile,
-   shell=True)
-except:
-print "Error: Running %s failed. See %s for details." % (
-  ScriptPath, PBuildLogFile.name)
-sys.exit(-1)
+SATestUtils.runScript(ScriptPath, PBuildLogFile, Dir)
 
 
 def downloadAndPatch(Dir, PBuildLogFile):
@@ -343,28 +278,6 @@ def runScanBuild(Dir, SBOutputDir, PBuil
 raise
 
 
-def hasNoExtension(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return (Ext == "")
-
-
-def isValidSingleInputFile(FileName):
-(Root, Ext) = os.path.splitext(FileName)
-return Ext in (".i", ".ii", ".c", ".cpp", ".m", "")
-
-
-def getSDKPath(SDKName):
-"""
-Get the path to the SDK for the given SDK name. Returns None if
-the path cannot be determined.
-"""
-if which("xcrun") is None:
-return None
-
-Cmd = "xcrun --sdk " + SDKName + " --show-sdk-path"
-return che

r316534 - [Analyzer] [Tests] Remove temporary fields from generated reference results.

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 16:52:46 2017
New Revision: 316534

URL: http://llvm.org/viewvc/llvm-project?rev=316534&view=rev
Log:
[Analyzer] [Tests] Remove temporary fields from generated reference results.

Pointer to HTML diagnostics is removed (as it is not stored) as well as
the version (as it would be available from the commit message).

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=316534&r1=316533&r2=316534&view=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Tue Oct 24 16:52:46 2017
@@ -493,6 +493,14 @@ def normalizeReferenceResults(Dir, SBOut
  if SourceFile.startswith(PathPrefix)
  else SourceFile for SourceFile in Data['files']]
 Data['files'] = Paths
+
+# Remove transient fields which change from run to run.
+for Diag in Data['diagnostics']:
+if 'HTMLDiagnostics_files' in Diag:
+Diag.pop('HTMLDiagnostics_files')
+if 'clang_version' in Data:
+Data.pop('clang_version')
+
 plistlib.writePlist(Data, Plist)
 
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316536 - [Analyzer] Store BodyFarm in std::unique_ptr

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 16:53:19 2017
New Revision: 316536

URL: http://llvm.org/viewvc/llvm-project?rev=316536&view=rev
Log:
[Analyzer] Store BodyFarm in std::unique_ptr

Differential Revision: https://reviews.llvm.org/D39220

Modified:
cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h
cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp

Modified: cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h?rev=316536&r1=316535&r2=316536&view=diff
==
--- cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h (original)
+++ cfe/trunk/include/clang/Analysis/AnalysisDeclContext.h Tue Oct 24 16:53:19 
2017
@@ -421,7 +421,7 @@ class AnalysisDeclContextManager {
 
   /// Pointer to a factory for creating and caching implementations for common
   /// methods during the analysis.
-  BodyFarm *BdyFrm = nullptr;
+  std::unique_ptr BdyFrm;
 
   /// Flag to indicate whether or not bodies should be synthesized
   /// for well-known functions.
@@ -438,8 +438,6 @@ public:
  bool addCXXNewAllocator = true,
  CodeInjector *injector = nullptr);
 
-  ~AnalysisDeclContextManager();
-
   AnalysisDeclContext *getContext(const Decl *D);
 
   bool getUseUnoptimizedCFG() const {

Modified: cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp?rev=316536&r1=316535&r2=316536&view=diff
==
--- cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp (original)
+++ cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp Tue Oct 24 16:53:19 2017
@@ -306,8 +306,8 @@ AnalysisDeclContext *AnalysisDeclContext
 
 BodyFarm *AnalysisDeclContextManager::getBodyFarm() {
   if (!BdyFrm)
-BdyFrm = new BodyFarm(ASTCtx, Injector.get());
-  return BdyFrm;
+BdyFrm = llvm::make_unique(ASTCtx, Injector.get());
+  return BdyFrm.get();
 }
 
 const StackFrameContext *
@@ -603,11 +603,6 @@ AnalysisDeclContext::~AnalysisDeclContex
   }
 }
 
-AnalysisDeclContextManager::~AnalysisDeclContextManager() {
-  if (BdyFrm)
-delete BdyFrm;
-}
-
 LocationContext::~LocationContext() {}
 
 LocationContextManager::~LocationContextManager() {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316538 - [Analyzer] Remove unnecessary semicolon in analyzer tests.

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 17:03:45 2017
New Revision: 316538

URL: http://llvm.org/viewvc/llvm-project?rev=316538&view=rev
Log:
[Analyzer] Remove unnecessary semicolon in analyzer tests.

Modified:
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=316538&r1=316537&r2=316538&view=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Tue Oct 24 17:03:45 2017
@@ -295,7 +295,7 @@ void test_mutator_noref() {
 // even when an ampersand is not explicitly set.
 void callbackn(int ¶m) {
   param = 42;
-};
+}
 void test_implicit_funcptr() {
   int x = 0;
   static std::once_flag flagn;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r316539 - [Analyzer] Remove spaces inside comments mentioning the parameter name,

2017-10-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Oct 24 17:03:45 2017
New Revision: 316539

URL: http://llvm.org/viewvc/llvm-project?rev=316539&view=rev
Log:
[Analyzer] Remove spaces inside comments mentioning the parameter name,

to aid clang-tidy comprehension.
Requested by @alexfh in https://reviews.llvm.org/D39015

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=316539&r1=316538&r2=316539&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Tue Oct 24 17:03:45 2017
@@ -168,10 +168,10 @@ ASTMaker::makeLvalueToRvalue(const VarDe
 ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
  CastKind CK) {
   return ImplicitCastExpr::Create(C, Ty,
-  /* CastKind= */ CK,
-  /* Expr= */ const_cast(Arg),
-  /* CXXCastPath= */ nullptr,
-  /* ExprValueKind= */ VK_RValue);
+  /* CastKind=*/ CK,
+  /* Expr=*/ const_cast(Arg),
+  /* CXXCastPath=*/ nullptr,
+  /* ExprValueKind=*/ VK_RValue);
 }
 
 Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
@@ -222,7 +222,7 @@ MemberExpr *ASTMaker::makeMemberExpressi
   C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
   SourceLocation(), MemberDecl, FoundDecl,
   DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
-  /* TemplateArgumentListInfo= */ nullptr, MemberDecl->getType(), 
ValueKind,
+  /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
   OK_Ordinary);
 }
 
@@ -231,7 +231,7 @@ ValueDecl *ASTMaker::findMemberField(con
   CXXBasePaths Paths(
   /* FindAmbiguities=*/false,
   /* RecordPaths=*/false,
-  /* DetectVirtual= */ false);
+  /* DetectVirtual=*/ false);
   const IdentifierInfo &II = C.Idents.get(Name);
   DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
 
@@ -282,14 +282,14 @@ static CallExpr *create_call_once_lambda
   assert(callOperatorDecl != nullptr);
 
   DeclRefExpr *callOperatorDeclRef =
-  DeclRefExpr::Create(/* Ctx = */ C,
-  /* QualifierLoc = */ NestedNameSpecifierLoc(),
-  /* TemplateKWLoc = */ SourceLocation(),
+  DeclRefExpr::Create(/* Ctx =*/ C,
+  /* QualifierLoc =*/ NestedNameSpecifierLoc(),
+  /* TemplateKWLoc =*/ SourceLocation(),
   const_cast(callOperatorDecl),
-  /* RefersToEnclosingVariableOrCapture= */ false,
-  /* NameLoc = */ SourceLocation(),
-  /* T = */ callOperatorDecl->getType(),
-  /* VK = */ VK_LValue);
+  /* RefersToEnclosingVariableOrCapture=*/ false,
+  /* NameLoc =*/ SourceLocation(),
+  /* T =*/ callOperatorDecl->getType(),
+  /* VK =*/ VK_LValue);
 
   return new (C)
   CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
@@ -372,7 +372,7 @@ static Stmt *create_call_once(ASTContext
 // Lambda requires callback itself inserted as a first parameter.
 CallArgs.push_back(
 M.makeDeclRefExpr(Callback,
-  /* RefersToEnclosingVariableOrCapture= */ true));
+  /* RefersToEnclosingVariableOrCapture=*/ true));
 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
->getType()
->getAs();
@@ -429,13 +429,13 @@ static Stmt *create_call_once(ASTContext
 
   // Negation predicate.
   UnaryOperator *FlagCheck = new (C) UnaryOperator(
-  /* input= */
+  /* input=*/
   M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
  CK_IntegralToBoolean),
-  /* opc= */ UO_LNot,
-  /* QualType= */ C.IntTy,
-  /* ExprValueKind= */ VK_RValue,
-  /* ExprObjectKind= */ OK_Ordinary, SourceLocation());
+  /* opc=*/ UO_LNot,
+  /* QualType=*/ C.IntTy,
+  /* ExprValueKind=*/ VK_RValue,
+  /* ExprObjectKind=*/ OK_Ordinary, SourceLocation());
 
   // Create assignment.
   BinaryOperator *FlagAssignment = M.makeAssignment(
@@ -443,11 +443,11 @@ static Stmt *create_call_once(ASTContext
 
   IfStmt *Out = new (C)
   IfStmt(C, SourceLocation(),
- /* IsConstexpr= */ false,
- /* init= */ nullptr,
- /* var= */ nullptr,
- /* cond= */ FlagCheck,
- /* then= */ M.makeCompound({Callba

r340960 - [analyzer] [NFC] Follow the convention when naming classes

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:28:13 2018
New Revision: 340960

URL: http://llvm.org/viewvc/llvm-project?rev=340960&view=rev
Log:
[analyzer] [NFC] Follow the convention when naming classes

Renames InvalidateRegionsWorker and RemoveDeadBindingsWorker

Differential Revision: https://reviews.llvm.org/D51324

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=340960&r1=340959&r2=340960&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Wed Aug 29 13:28:13 2018
@@ -309,7 +309,7 @@ public:
 
//===--===//
 
 namespace {
-class invalidateRegionsWorker;
+class InvalidateRegionsWorker;
 
 class RegionStoreManager : public StoreManager {
 public:
@@ -336,7 +336,7 @@ private:
 
   /// A helper used to populate the work list with the given set of
   /// regions.
-  void populateWorkList(invalidateRegionsWorker &W,
+  void populateWorkList(InvalidateRegionsWorker &W,
 ArrayRef Values,
 InvalidatedRegions *TopLevelRegions);
 
@@ -946,7 +946,7 @@ RegionStoreManager::removeSubRegionBindi
 }
 
 namespace {
-class invalidateRegionsWorker : public ClusterAnalysis
+class InvalidateRegionsWorker : public ClusterAnalysis
 {
   const Expr *Ex;
   unsigned Count;
@@ -956,7 +956,7 @@ class invalidateRegionsWorker : public C
   StoreManager::InvalidatedRegions *Regions;
   GlobalsFilterKind GlobalsFilter;
 public:
-  invalidateRegionsWorker(RegionStoreManager &rm,
+  InvalidateRegionsWorker(RegionStoreManager &rm,
   ProgramStateManager &stateMgr,
   RegionBindingsRef b,
   const Expr *ex, unsigned count,
@@ -965,7 +965,7 @@ public:
   RegionAndSymbolInvalidationTraits &ITraitsIn,
   StoreManager::InvalidatedRegions *r,
   GlobalsFilterKind GFK)
- : ClusterAnalysis(rm, stateMgr, b),
+ : ClusterAnalysis(rm, stateMgr, b),
Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), 
Regions(r),
GlobalsFilter(GFK) {}
 
@@ -986,14 +986,14 @@ public:
 };
 }
 
-bool invalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
+bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
   bool doNotInvalidateSuperRegion = ITraits.hasTrait(
   R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
   const MemRegion *BaseR = doNotInvalidateSuperRegion ? R : R->getBaseRegion();
   return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
 }
 
-void invalidateRegionsWorker::VisitBinding(SVal V) {
+void InvalidateRegionsWorker::VisitBinding(SVal V) {
   // A symbol?  Mark it touched by the invalidation.
   if (SymbolRef Sym = V.getAsSymbol())
 IS.insert(Sym);
@@ -1018,7 +1018,7 @@ void invalidateRegionsWorker::VisitBindi
   }
 }
 
-void invalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
+void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
const ClusterBindings *C) {
 
   bool PreserveRegionsContents =
@@ -1208,7 +1208,7 @@ void invalidateRegionsWorker::VisitClust
   B = B.addBinding(baseR, BindingKey::Direct, V);
 }
 
-bool invalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
+bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
 const MemRegion *R) {
   switch (GlobalsFilter) {
   case GFK_None:
@@ -1222,7 +1222,7 @@ bool invalidateRegionsWorker::isInitiall
   llvm_unreachable("unknown globals filter");
 }
 
-bool invalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
+bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
   if (isInitiallyIncludedGlobalRegion(Base))
 return true;
 
@@ -1256,7 +1256,7 @@ RegionStoreManager::invalidateGlobalRegi
   return B;
 }
 
-void RegionStoreManager::populateWorkList(invalidateRegionsWorker &W,
+void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W,
   ArrayRef Values,
   InvalidatedRegions *TopLevelRegions) 
{
   for (ArrayRef::iterator I = Values.begin(),
@@ -1307,7 +1307,7 @@ RegionStoreManager::invalidateRegions(St
   }
 
   RegionBindingsRef B = getRegionBindings(store);
-  invalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
+  InvalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
 Invalidated, GlobalsFilter);
 
   // Scan the bindings and generate the clusters.
@@ -2390,24 +2390,24 @@ RegionStoreManager::bindAggregate(Region
 
//===--

r340961 - [analyzer] Better retain count rules for OSObjects

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:28:33 2018
New Revision: 340961

URL: http://llvm.org/viewvc/llvm-project?rev=340961&view=rev
Log:
[analyzer] Better retain count rules for OSObjects

Differential Revision: https://reviews.llvm.org/D51184

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=340961&r1=340960&r2=340961&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Wed Aug 29 13:28:33 2018
@@ -31,6 +31,7 @@ const RefVal *getRefBinding(ProgramState
 
 ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym,
  RefVal Val) {
+  assert(Sym != nullptr);
   return State->set(Sym, Val);
 }
 
@@ -418,17 +419,19 @@ void RetainCountChecker::processSummaryO
   }
 
   // Consult the summary for the return value.
-  SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
   RetEffect RE = Summ.getRetEffect();
-  if (const auto *MCall = dyn_cast(&CallOrMsg)) {
-if (Optional updatedRefVal =
-refValFromRetEffect(RE, MCall->getResultType())) {
-  state = setRefBinding(state, Sym, *updatedRefVal);
+
+  if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
+if (const auto *MCall = dyn_cast(&CallOrMsg)) {
+  if (Optional updatedRefVal =
+  refValFromRetEffect(RE, MCall->getResultType())) {
+state = setRefBinding(state, Sym, *updatedRefVal);
+  }
 }
-  }
 
-  if (RE.getKind() == RetEffect::NoRetHard && Sym)
-state = removeRefBinding(state, Sym);
+if (RE.getKind() == RetEffect::NoRetHard)
+  state = removeRefBinding(state, Sym);
+  }
 
   C.addTransition(state);
 }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp?rev=340961&r1=340960&r2=340961&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp Wed Aug 29 
13:28:33 2018
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ParentMap.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 
 using namespace clang;
 using namespace ento;
@@ -53,29 +54,19 @@ RetainSummaryManager::getPersistentSumma
   return Summ;
 }
 
-static bool isOSObjectSubclass(QualType T);
-
-static bool isOSObjectSubclass(const CXXRecordDecl *RD) {
-  if (RD->getDeclName().getAsString() == "OSObject")
-return true;
-
-  const CXXRecordDecl *RDD = RD->getDefinition();
-  if (!RDD)
-return false;
+static bool isSubclass(const Decl *D,
+   StringRef ClassName) {
+  using namespace ast_matchers;
+  DeclarationMatcher SubclassM = cxxRecordDecl(isSameOrDerivedFrom(ClassName));
+  return !(match(SubclassM, *D, D->getASTContext()).empty());
+}
 
-  for (const CXXBaseSpecifier Spec : RDD->bases()) {
-if (isOSObjectSubclass(Spec.getType()))
-  return true;
-  }
-  return false;
+static bool isOSObjectSubclass(const Decl *D) {
+  return isSubclass(D, "OSObject");
 }
 
-/// \return Whether type represents an OSObject successor.
-static bool isOSObjectSubclass(QualType T) {
-  if (const auto *RD = T->getAsCXXRecordDecl()) {
-return isOSObjectSubclass(RD);
-  }
-  return false;
+static bool isOSIteratorSubclass(const Decl *D) {
+  return isSubclass(D, "OSIterator");
 }
 
 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
@@ -221,15 +212,22 @@ RetainSummaryManager::generateSummary(co
   }
 
   if (RetTy->isPointerType()) {
-if (TrackOSObjects && isOSObjectSubclass(RetTy->getPointeeType())) {
+
+const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
+if (TrackOSObjects && PD && isOSObjectSubclass(PD)) {
   if (const IdentifierInfo *II = FD->getIdentifier()) {
-StringRef FuncName = II->getName();
-if (FuncName.contains_lower("with")
-|| FuncName.contains_lower("create")
-|| FuncName.contains_lower("copy"))
+
+// All objects returned with functions starting with "get" are getters.
+if (II->getName().startswith("get")) {
+
+  // ...except for iterators.
+  if (isOSIteratorSubclass(PD))
+return getOSSummaryCreateRule(FD);
+  return getOSSummaryGetRule(FD);
+} else {
   return getOSSummaryCreateRule(FD);
+}
   }

r340962 - [analyzer] [NFC] Remove unused "state" argument from makeSymExprValNN

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:28:54 2018
New Revision: 340962

URL: http://llvm.org/viewvc/llvm-project?rev=340962&view=rev
Log:
[analyzer] [NFC] Remove unused "state" argument from makeSymExprValNN

Differential Revision: https://reviews.llvm.org/D51250

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h?rev=340962&r1=340961&r2=340962&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h Wed 
Aug 29 13:28:54 2018
@@ -139,8 +139,8 @@ public:
   virtual SVal simplifySVal(ProgramStateRef State, SVal Val) = 0;
 
   /// Constructs a symbolic expression for two non-location values.
-  SVal makeSymExprValNN(ProgramStateRef state, BinaryOperator::Opcode op,
-  NonLoc lhs, NonLoc rhs, QualType resultTy);
+  SVal makeSymExprValNN(BinaryOperator::Opcode op,
+NonLoc lhs, NonLoc rhs, QualType resultTy);
 
   SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
  SVal lhs, SVal rhs, QualType type);

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp?rev=340962&r1=340961&r2=340962&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp Wed Aug 29 13:28:54 2018
@@ -375,8 +375,7 @@ Optional SValBuilder::getConstantV
   }
 }
 
-SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
-   BinaryOperator::Opcode Op,
+SVal SValBuilder::makeSymExprValNN(BinaryOperator::Opcode Op,
NonLoc LHS, NonLoc RHS,
QualType ResultTy) {
   const SymExpr *symLHS = LHS.getAsSymExpr();

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=340962&r1=340961&r2=340962&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Wed Aug 29 13:28:54 
2018
@@ -534,7 +534,7 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
   while (1) {
 switch (lhs.getSubKind()) {
 default:
-  return makeSymExprValNN(state, op, lhs, rhs, resultTy);
+  return makeSymExprValNN(op, lhs, rhs, resultTy);
 case nonloc::PointerToMemberKind: {
   assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
  "Both SVals should have pointer-to-member-type");
@@ -582,7 +582,7 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
   return makeTruthVal(true, resultTy);
 default:
   // This case also handles pointer arithmetic.
-  return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
+  return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
   }
   }
 }
@@ -643,9 +643,9 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
 // 0<>a
 if (LHSValue == 0)
   return evalCastFromNonLoc(lhs, resultTy);
-return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
+return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
   default:
-return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
+return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
   }
 }
 case nonloc::SymbolValKind: {
@@ -757,7 +757,7 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
 return *V;
 
   // Give up -- this is not a symbolic expression we can handle.
-  return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
+  return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
 }
 }
   }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340964 - [analyzer] [NFC] Move class definition out of the function

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:29:39 2018
New Revision: 340964

URL: http://llvm.org/viewvc/llvm-project?rev=340964&view=rev
Log:
[analyzer] [NFC] Move class definition out of the function

Differential Revision: https://reviews.llvm.org/D51322

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp?rev=340964&r1=340963&r2=340964&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp Wed Aug 29 
13:29:39 2018
@@ -196,6 +196,45 @@ bool CallAndMessageChecker::uninitRefOrP
   return false;
 }
 
+class FindUninitializedField {
+public:
+  SmallVector FieldChain;
+
+private:
+  StoreManager &StoreMgr;
+  MemRegionManager &MrMgr;
+  Store store;
+
+public:
+  FindUninitializedField(StoreManager &storeMgr, MemRegionManager &mrMgr,
+ Store s)
+  : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
+
+  bool Find(const TypedValueRegion *R) {
+QualType T = R->getValueType();
+if (const RecordType *RT = T->getAsStructureType()) {
+  const RecordDecl *RD = RT->getDecl()->getDefinition();
+  assert(RD && "Referred record has no definition");
+  for (const auto *I : RD->fields()) {
+const FieldRegion *FR = MrMgr.getFieldRegion(I, R);
+FieldChain.push_back(I);
+T = I->getType();
+if (T->getAsStructureType()) {
+  if (Find(FR))
+return true;
+} else {
+  const SVal &V = StoreMgr.getBinding(store, loc::MemRegionVal(FR));
+  if (V.isUndef())
+return true;
+}
+FieldChain.pop_back();
+  }
+}
+
+return false;
+  }
+};
+
 bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
SVal V,
SourceRange ArgRange,
@@ -232,47 +271,7 @@ bool CallAndMessageChecker::PreVisitProc
   if (!CheckUninitFields)
 return false;
 
-  if (Optional LV =
-  V.getAs()) {
-
-class FindUninitializedField {
-public:
-  SmallVector FieldChain;
-private:
-  StoreManager &StoreMgr;
-  MemRegionManager &MrMgr;
-  Store store;
-public:
-  FindUninitializedField(StoreManager &storeMgr,
- MemRegionManager &mrMgr, Store s)
-  : StoreMgr(storeMgr), MrMgr(mrMgr), store(s) {}
-
-  bool Find(const TypedValueRegion *R) {
-QualType T = R->getValueType();
-if (const RecordType *RT = T->getAsStructureType()) {
-  const RecordDecl *RD = RT->getDecl()->getDefinition();
-  assert(RD && "Referred record has no definition");
-  for (const auto *I : RD->fields()) {
-const FieldRegion *FR = MrMgr.getFieldRegion(I, R);
-FieldChain.push_back(I);
-T = I->getType();
-if (T->getAsStructureType()) {
-  if (Find(FR))
-return true;
-}
-else {
-  const SVal &V = StoreMgr.getBinding(store, 
loc::MemRegionVal(FR));
-  if (V.isUndef())
-return true;
-}
-FieldChain.pop_back();
-  }
-}
-
-return false;
-  }
-};
-
+  if (auto LV = V.getAs()) {
 const LazyCompoundValData *D = LV->getCVData();
 FindUninitializedField F(C.getState()->getStateManager().getStoreManager(),
  C.getSValBuilder().getRegionManager(),


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340963 - [analyzer] Move analyzer-eagerly-assume to AnalyzerOptions, enable by default

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:29:17 2018
New Revision: 340963

URL: http://llvm.org/viewvc/llvm-project?rev=340963&view=rev
Log:
[analyzer] Move analyzer-eagerly-assume to AnalyzerOptions, enable by default

Differential Revision: https://reviews.llvm.org/D51251

Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/test/Analysis/MisusedMovedObject.cpp
cfe/trunk/test/Analysis/PR24184.cpp
cfe/trunk/test/Analysis/PR37855.c
cfe/trunk/test/Analysis/additive-folding-range-constraints.c
cfe/trunk/test/Analysis/additive-folding.cpp
cfe/trunk/test/Analysis/analyzer-config.c
cfe/trunk/test/Analysis/analyzer-config.cpp
cfe/trunk/test/Analysis/array-struct-region.c
cfe/trunk/test/Analysis/atomics.c
cfe/trunk/test/Analysis/blocks-no-inline.c
cfe/trunk/test/Analysis/bstring.c
cfe/trunk/test/Analysis/bstring.cpp
cfe/trunk/test/Analysis/call-invalidation.cpp
cfe/trunk/test/Analysis/casts.c
cfe/trunk/test/Analysis/conditional-operator.cpp
cfe/trunk/test/Analysis/const-method-call.cpp
cfe/trunk/test/Analysis/constant-folding.c
cfe/trunk/test/Analysis/copy-elision.cpp
cfe/trunk/test/Analysis/ctor.mm
cfe/trunk/test/Analysis/cxx-for-range.cpp
cfe/trunk/test/Analysis/dtor.cpp
cfe/trunk/test/Analysis/edges-new.mm
cfe/trunk/test/Analysis/func.c
cfe/trunk/test/Analysis/global-region-invalidation.c
cfe/trunk/test/Analysis/global_region_invalidation.mm
cfe/trunk/test/Analysis/gtest.cpp
cfe/trunk/test/Analysis/inline-plist.c
cfe/trunk/test/Analysis/inline.cpp
cfe/trunk/test/Analysis/inlining/InlineObjCClassMethod.m
cfe/trunk/test/Analysis/inlining/containers.cpp
cfe/trunk/test/Analysis/inlining/dyn-dispatch-bifurcate.cpp
cfe/trunk/test/Analysis/inlining/false-positive-suppression.c
cfe/trunk/test/Analysis/inlining/stl.cpp
cfe/trunk/test/Analysis/invalidated-iterator.cpp
cfe/trunk/test/Analysis/iterator-range.cpp
cfe/trunk/test/Analysis/ivars.m
cfe/trunk/test/Analysis/lifetime-extension.cpp
cfe/trunk/test/Analysis/logical-ops.c
cfe/trunk/test/Analysis/loop-widening-notes.cpp
cfe/trunk/test/Analysis/loop-widening.c
cfe/trunk/test/Analysis/malloc-plist.c
cfe/trunk/test/Analysis/misc-ps-eager-assume.m
cfe/trunk/test/Analysis/misc-ps.c
cfe/trunk/test/Analysis/missing-bind-temporary.cpp
cfe/trunk/test/Analysis/new-ctor-conservative.cpp
cfe/trunk/test/Analysis/new-ctor-inlined.cpp
cfe/trunk/test/Analysis/new-ctor-recursive.cpp
cfe/trunk/test/Analysis/new-ctor-symbolic.cpp
cfe/trunk/test/Analysis/new.cpp
cfe/trunk/test/Analysis/null-deref-path-notes.cpp
cfe/trunk/test/Analysis/objc-for.m
cfe/trunk/test/Analysis/plist-macros.cpp
cfe/trunk/test/Analysis/plist-output.m
cfe/trunk/test/Analysis/pr22954.c
cfe/trunk/test/Analysis/properties.m
cfe/trunk/test/Analysis/ptr-arith.c
cfe/trunk/test/Analysis/reference.cpp
cfe/trunk/test/Analysis/region-store.c
cfe/trunk/test/Analysis/self-assign.cpp
cfe/trunk/test/Analysis/std-c-library-functions.c
cfe/trunk/test/Analysis/string.c
cfe/trunk/test/Analysis/svalbuilder-rearrange-comparisons.c
cfe/trunk/test/Analysis/switch-case.c
cfe/trunk/test/Analysis/temp-obj-dtors-option.cpp
cfe/trunk/test/Analysis/templates.cpp
cfe/trunk/test/Analysis/temporaries.cpp
cfe/trunk/test/Analysis/test-after-div-zero.c
cfe/trunk/test/Analysis/unions.cpp
cfe/trunk/test/Analysis/unix-fns.c
cfe/trunk/test/Analysis/weak-functions.c

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=340963&r1=340962&r2=340963&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Wed Aug 29 13:29:17 2018
@@ -76,8 +76,6 @@ def analyzer_display_progress : Flag<["-
 def analyze_function : Separate<["-"], "analyze-function">,
   HelpText<"Run analysis on specific function (for C++ include parameters in 
name)">;
 def analyze_function_EQ : Joined<["-"], "analyze-function=">, 
Alias;
-def analyzer_eagerly_assume : Flag<["-"], "analyzer-eagerly-assume">,
-  HelpText<"Eagerly assume the truth/falseness of some symbolic constraints">;
 def trim_egraph : Flag<["-"], "trim-egraph">,
   HelpText<"Only show error-related paths in the analysis graph">;
 def analyzer_viz_egraph_graphviz : Flag<["-"], "analyzer-viz-egraph-graphviz">,

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/

r340965 - [analyzer] Resolve the crash in ReturnUndefChecker

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 13:29:59 2018
New Revision: 340965

URL: http://llvm.org/viewvc/llvm-project?rev=340965&view=rev
Log:
[analyzer] Resolve the crash in ReturnUndefChecker

By making sure the returned value from getKnownSVal is consistent with
the value used inside expression engine.

PR38427

Differential Revision: https://reviews.llvm.org/D51252

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/casts.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp?rev=340965&r1=340964&r2=340965&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp Wed Aug 29 
13:29:59 2018
@@ -69,6 +69,7 @@ static bool isLeftShiftResultUnrepresent
   ProgramStateRef State = C.getState();
   const llvm::APSInt *LHS = SB.getKnownValue(State, C.getSVal(B->getLHS()));
   const llvm::APSInt *RHS = SB.getKnownValue(State, C.getSVal(B->getRHS()));
+  assert(LHS && RHS && "Values unknown, inconsistent state");
   return (unsigned)RHS->getZExtValue() > LHS->countLeadingZeros();
 }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=340965&r1=340964&r2=340965&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Wed Aug 29 13:29:59 
2018
@@ -1201,6 +1201,7 @@ SVal SimpleSValBuilder::evalBinOpLN(Prog
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
+  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 

Modified: cfe/trunk/test/Analysis/casts.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/casts.c?rev=340965&r1=340964&r2=340965&view=diff
==
--- cfe/trunk/test/Analysis/casts.c (original)
+++ cfe/trunk/test/Analysis/casts.c Wed Aug 29 13:29:59 2018
@@ -1,5 +1,6 @@
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-analyzer-config eagerly-assume=false -verify %s
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-analyzer-config eagerly-assume=false -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-verify -analyzer-config eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-verify -analyzer-config eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify 
-DEAGERLY_ASSUME=1 -w %s
 
 extern void clang_analyzer_eval(_Bool);
 
@@ -16,6 +17,8 @@ struct sockaddr_storage {};
 
 void getsockname();
 
+#ifndef EAGERLY_ASSUME
+
 void f(int sock) {
   struct sockaddr_storage storage;
   struct sockaddr* sockaddr = (struct sockaddr*)&storage; // 
expected-warning{{Casting data to a larger structure type and accessing a field 
can lead to memory access errors or data corruption}}
@@ -188,3 +191,21 @@ void testSwitchWithSizeofs() {
   case sizeof(char):; // no-crash
   }
 }
+
+#endif
+
+#ifdef EAGERLY_ASSUME
+
+// expected-no-diagnostics
+
+int globalA; // TODO: the example is not representative.
+extern int globalFunc();
+void no_crash_on_symsym_cast_to_long() {
+  char c = globalFunc() - 5;
+  c == 0;
+  globalA -= c;
+  globalA == 3;
+  (long)globalA << 48; // no-crash
+}
+
+#endif


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340972 - [analyzer] Fix tests on 32-bit platforms by specifying the tuple explicitly

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 14:18:47 2018
New Revision: 340972

URL: http://llvm.org/viewvc/llvm-project?rev=340972&view=rev
Log:
[analyzer] Fix tests on 32-bit platforms by specifying the tuple explicitly

Modified:
cfe/trunk/test/Analysis/casts.c

Modified: cfe/trunk/test/Analysis/casts.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/casts.c?rev=340972&r1=340971&r2=340972&view=diff
==
--- cfe/trunk/test/Analysis/casts.c (original)
+++ cfe/trunk/test/Analysis/casts.c Wed Aug 29 14:18:47 2018
@@ -1,6 +1,7 @@
 // RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-verify -analyzer-config eagerly-assume=false %s
 // RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -analyzer-store=region 
-verify -analyzer-config eagerly-assume=false %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify 
-DEAGERLY_ASSUME=1 -w %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify 
-DEAGERLY_ASSUME=1 -w %s
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify 
-DEAGERLY_ASSUME=1 -DBIT32=1 -w %s
 
 extern void clang_analyzer_eval(_Bool);
 
@@ -196,16 +197,19 @@ void testSwitchWithSizeofs() {
 
 #ifdef EAGERLY_ASSUME
 
-// expected-no-diagnostics
-
-int globalA; // TODO: the example is not representative.
+int globalA;
 extern int globalFunc();
 void no_crash_on_symsym_cast_to_long() {
   char c = globalFunc() - 5;
   c == 0;
   globalA -= c;
   globalA == 3;
-  (long)globalA << 48; // no-crash
+  (long)globalA << 48;
+  #ifdef BIT32
+  // expected-warning@-2{{The result of the left shift is undefined due to 
shifting by '48', which is greater or equal to the width of type 'long'}}
+  #else
+  // expected-no-diagnostics
+  #endif
 }
 
 #endif


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r340986 - [analyzer] Improve tracing for uninitialized struct fields

2018-08-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Aug 29 15:48:50 2018
New Revision: 340986

URL: http://llvm.org/viewvc/llvm-project?rev=340986&view=rev
Log:
[analyzer] Improve tracing for uninitialized struct fields

rdar://13729267

Differential Revision: https://reviews.llvm.org/D51323

Added:
cfe/trunk/test/Analysis/uninit-vals.c
Removed:
cfe/trunk/test/Analysis/uninit-vals-ps-region.m
cfe/trunk/test/Analysis/uninit-vals-ps.c
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
cfe/trunk/test/Analysis/uninit-vals.cpp
cfe/trunk/test/Analysis/uninit-vals.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp?rev=340986&r1=340985&r2=340986&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp Wed Aug 29 
15:48:50 2018
@@ -304,6 +304,8 @@ bool CallAndMessageChecker::PreVisitProc
 auto R = llvm::make_unique(*BT, os.str(), N);
 R->addRange(ArgRange);
 
+if (ArgEx)
+  bugreporter::trackNullOrUndefValue(N, ArgEx, *R);
 // FIXME: enhance track back for uninitialized value for arbitrary
 // memregions
 C.emitReport(std::move(R));

Removed: cfe/trunk/test/Analysis/uninit-vals-ps-region.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/uninit-vals-ps-region.m?rev=340985&view=auto
==
--- cfe/trunk/test/Analysis/uninit-vals-ps-region.m (original)
+++ cfe/trunk/test/Analysis/uninit-vals-ps-region.m (removed)
@@ -1,93 +0,0 @@
-// RUN: %clang_analyze_cc1 -analyzer-store=region -analyzer-checker=core 
-verify %s
-
-struct s {
-  int data;
-};
-
-struct s global;
-
-void g(int);
-
-void f4() {
-  int a;
-  if (global.data == 0)
-a = 3;
-  if (global.data == 0) // When the true branch is feasible 'a = 3'.
-g(a); // no-warning
-}
-
-
-// Test uninitialized value due to part of the structure being uninitialized.
-struct TestUninit { int x; int y; };
-struct TestUninit test_uninit_aux();
-void test_unit_aux2(int);
-void test_uninit_pos() {
-  struct TestUninit v1 = { 0, 0 };
-  struct TestUninit v2 = test_uninit_aux();
-  int z;
-  v1.y = z; // expected-warning{{Assigned value is garbage or undefined}}
-  test_unit_aux2(v2.x + v1.y);
-}
-void test_uninit_pos_2() {
-  struct TestUninit v1 = { 0, 0 };
-  struct TestUninit v2;
-  test_unit_aux2(v2.x + v1.y);  // expected-warning{{The left operand of '+' 
is a garbage value}}
-}
-void test_uninit_pos_3() {
-  struct TestUninit v1 = { 0, 0 };
-  struct TestUninit v2;
-  test_unit_aux2(v1.y + v2.x);  // expected-warning{{The right operand of '+' 
is a garbage value}}
-}
-
-void test_uninit_neg() {
-  struct TestUninit v1 = { 0, 0 };
-  struct TestUninit v2 = test_uninit_aux();
-  test_unit_aux2(v2.x + v1.y);
-}
-
-extern void test_uninit_struct_arg_aux(struct TestUninit arg);
-void test_uninit_struct_arg() {
-  struct TestUninit x;
-  test_uninit_struct_arg_aux(x); // expected-warning{{Passed-by-value struct 
argument contains uninitialized data (e.g., field: 'x')}}
-}
-
-@interface Foo
-- (void) passVal:(struct TestUninit)arg;
-@end
-void testFoo(Foo *o) {
-  struct TestUninit x;
-  [o passVal:x]; // expected-warning{{Passed-by-value struct argument contains 
uninitialized data (e.g., field: 'x')}}
-}
-
-// Test case from .  That shows an uninitialized value
-// being used in the LHS of a compound assignment.
-void rdar_7780304() {
-  typedef struct s_r7780304 { int x; } s_r7780304;
-  s_r7780304 b;
-  b.x |= 1; // expected-warning{{The left expression of the compound 
assignment is an uninitialized value. The computed value will also be garbage}}
-}
-
-
-// The flip side of PR10163 -- float arrays that are actually uninitialized
-// (The main test is in uninit-vals.m)
-void test_PR10163(float);
-void PR10163 (void) {
-  float x[2];
-  test_PR10163(x[1]); // expected-warning{{uninitialized value}}
-}
-
-struct MyStr {
-  int x;
-  int y;
-};
-void swap(struct MyStr *To, struct MyStr *From) {
-  // This is not really a swap but close enough for our test.
-  To->x = From->x;
-  To->y = From->y; // no warning
-}
-int test_undefined_member_assignment_in_swap(struct MyStr *s2) {
-  struct MyStr s1;
-  s1.x = 5;
-  swap(s2, &s1);
-  return s2->y; // expected-warning{{Undefined or garbage value returned to 
caller}}
-}

Removed: cfe/trunk/test/Analysis/uninit-vals-ps.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/uninit-vals-ps.c?rev=340985&view=auto
==
--- cfe/trunk/test/Analysis/uninit-vals-ps.c (original)
+++ cfe/trunk/test/Analysis/uninit-vals-ps.c (removed)
@@ -1,157 +0,0 @@
-// RUN: %clang_analyz

r341600 - [analyzer] Dump a reproducible, deterministic ID of program state to exploded graph

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 16:07:26 2018
New Revision: 341600

URL: http://llvm.org/viewvc/llvm-project?rev=341600&view=rev
Log:
[analyzer] Dump a reproducible, deterministic ID of program state to exploded 
graph

Differential Revision: https://reviews.llvm.org/D51395

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h?rev=341600&r1=341599&r2=341600&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
Thu Sep  6 16:07:26 2018
@@ -107,6 +107,8 @@ public:
 
   ~ProgramState();
 
+  int64_t getID() const;
+
   /// Return the ProgramStateManager associated with this state.
   ProgramStateManager &getStateManager() const {
 return *stateMgr;

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=341600&r1=341599&r2=341600&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Sep  6 16:07:26 2018
@@ -3141,7 +3141,8 @@ struct DOTGraphTraits : p
 }
 
 ProgramStateRef state = N->getState();
-Out << "\\|StateID: " << (const void*) state.get()
+Out << "\\|StateID: " << state->getID() << " ("
+<< (const void*) state.get() << ")"
 << " NodeID: " << (const void*) N << "\\|";
 
 state->printDOT(Out, N->getLocationContext());

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp?rev=341600&r1=341599&r2=341600&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp Thu Sep  6 16:07:26 2018
@@ -69,6 +69,13 @@ ProgramState::~ProgramState() {
 stateMgr->getStoreManager().decrementReferenceCount(store);
 }
 
+int64_t ProgramState::getID() const {
+  Optional Out = getStateManager().Alloc.identifyObject(this);
+  assert(Out && "Wrong allocator used");
+  assert(*Out % alignof(ProgramState) == 0 && "Wrong alignment information");
+  return *Out / alignof(ProgramState);
+}
+
 ProgramStateManager::ProgramStateManager(ASTContext &Ctx,
  StoreManagerCreator CreateSMgr,
  ConstraintManagerCreator CreateCMgr,


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341601 - [analyzer] Remove traces of ubigraph visualization

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 16:07:47 2018
New Revision: 341601

URL: http://llvm.org/viewvc/llvm-project?rev=341601&view=rev
Log:
[analyzer] Remove traces of ubigraph visualization

Ubigraph project has been dead since about 2008, and to the best of my
knowledge, no one was using it.
Previously, I wasn't able to launch the existing binary at all.

Differential Revision: https://reviews.llvm.org/D51655

Removed:
cfe/trunk/test/Analysis/ubigraph-viz.cpp
cfe/trunk/utils/analyzer/ubiviz
Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/tools/scan-build-py/libscanbuild/analyze.py
cfe/trunk/tools/scan-build/libexec/ccc-analyzer

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=341601&r1=341600&r2=341601&view=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Thu Sep  6 16:07:47 2018
@@ -80,8 +80,6 @@ def trim_egraph : Flag<["-"], "trim-egra
   HelpText<"Only show error-related paths in the analysis graph">;
 def analyzer_viz_egraph_graphviz : Flag<["-"], "analyzer-viz-egraph-graphviz">,
   HelpText<"Display exploded graph using GraphViz">;
-def analyzer_viz_egraph_ubigraph : Flag<["-"], "analyzer-viz-egraph-ubigraph">,
-  HelpText<"Display exploded graph using Ubigraph">;
 
 def analyzer_inline_max_stack_depth : Separate<["-"], 
"analyzer-inline-max-stack-depth">,
   HelpText<"Bound on stack depth while inlining (4 by default)">;

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h?rev=341601&r1=341600&r2=341601&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h Thu Sep  6 
16:07:47 2018
@@ -164,7 +164,6 @@ public:
 
   unsigned TrimGraph : 1;
   unsigned visualizeExplodedGraphWithGraphViz : 1;
-  unsigned visualizeExplodedGraphWithUbiGraph : 1;
   unsigned UnoptimizedCFG : 1;
   unsigned PrintStats : 1;
 
@@ -361,7 +360,7 @@ public:
 AnalyzerDisplayProgress(false), AnalyzeNestedBlocks(false),
 eagerlyAssumeBinOpBifurcation(false), TrimGraph(false),
 visualizeExplodedGraphWithGraphViz(false),
-visualizeExplodedGraphWithUbiGraph(false), UnoptimizedCFG(false),
+UnoptimizedCFG(false),
 PrintStats(false), NoRetryExhausted(false), CXXMemberInliningMode() {}
 
   /// Interprets an option's string value as a boolean. The "true" string is

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h?rev=341601&r1=341600&r2=341601&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h 
Thu Sep  6 16:07:47 2018
@@ -100,8 +100,7 @@ public:
   void FlushDiagnostics();
 
   bool shouldVisualize() const {
-return options.visualizeExplodedGraphWithGraphViz ||
-   options.visualizeExplodedGraphWithUbiGraph;
+return options.visualizeExplodedGraphWithGraphViz;
   }
 
   bool shouldInlineCall() const {

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h?rev=341601&r1=341600&r2=341601&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
Thu Sep  6 16:07:47 2018
@@ -240,18 +240,6 @@ public:
 return const_cast(this)->succ_end();
   }
 
-  // For debugging.
-
-public:
-  class Auditor {
-  public:
-virtual ~Auditor();
-
-virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) = 0;
-  };
-
-  static void SetAuditor(Auditor* A);
-
 private:
   void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
   void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }

Modified: cf

r341602 - [analyzer] Dump stable identifiers for exploded nodes

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 16:08:07 2018
New Revision: 341602

URL: http://llvm.org/viewvc/llvm-project?rev=341602&view=rev
Log:
[analyzer] Dump stable identifiers for exploded nodes

Differential Revision: https://reviews.llvm.org/D51667

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h?rev=341602&r1=341601&r2=341602&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
Thu Sep  6 16:08:07 2018
@@ -240,6 +240,8 @@ public:
 return const_cast(this)->succ_end();
   }
 
+  int64_t getID(ExplodedGraph *G) const;
+
 private:
   void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
   void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp?rev=341602&r1=341601&r2=341602&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp Thu Sep  6 16:08:07 2018
@@ -283,6 +283,13 @@ ExplodedNode * const *ExplodedNode::Node
   return Storage.getAddrOfPtr1() + 1;
 }
 
+int64_t ExplodedNode::getID(ExplodedGraph *G) const {
+  Optional Out = G->getAllocator().identifyObject(this);
+  assert(Out && "Wrong allocator used");
+  assert(*Out % alignof(ExplodedNode) == 0 && "Wrong alignment information");
+  return *Out / alignof(ExplodedNode);
+}
+
 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
  ProgramStateRef State,
  bool IsSink,

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=341602&r1=341601&r2=341602&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Sep  6 16:08:07 2018
@@ -3141,9 +3141,13 @@ struct DOTGraphTraits : p
 }
 
 ProgramStateRef state = N->getState();
-Out << "\\|StateID: " << state->getID() << " ("
-<< (const void*) state.get() << ")"
-<< " NodeID: " << (const void*) N << "\\|";
+ExplodedGraph &Graph =
+static_cast(state->getStateManager().getOwningEngine())
+->getGraph();
+
+Out << "\\|StateID: " << state->getID() << " (" << (const void 
*)state.get()
+<< ")"
+<< " NodeID: " << N->getID(&Graph) << " (" << (const void *)N << 
")\\|";
 
 state->printDOT(Out, N->getLocationContext());
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341603 - [analyzer] [NFC] Move dumping program point into a separate function

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 16:08:27 2018
New Revision: 341603

URL: http://llvm.org/viewvc/llvm-project?rev=341603&view=rev
Log:
[analyzer] [NFC] Move dumping program point into a separate function

Differential Revision: https://reviews.llvm.org/D51666

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=341603&r1=341602&r2=341603&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Sep  6 16:08:27 2018
@@ -2973,172 +2973,173 @@ struct DOTGraphTraits : p
 }
   }
 
-  static std::string getNodeLabel(const ExplodedNode *N, void*){
-std::string sbuf;
-llvm::raw_string_ostream Out(sbuf);
-
-// Program Location.
-ProgramPoint Loc = N->getLocation();
-
+  static void dumpProgramPoint(ProgramPoint Loc,
+   llvm::raw_string_ostream &Out) {
 switch (Loc.getKind()) {
-  case ProgramPoint::BlockEntranceKind:
-Out << "Block Entrance: B"
-<< Loc.castAs().getBlock()->getBlockID();
-break;
-
-  case ProgramPoint::BlockExitKind:
-assert(false);
-break;
-
-  case ProgramPoint::CallEnterKind:
-Out << "CallEnter";
-break;
-
-  case ProgramPoint::CallExitBeginKind:
-Out << "CallExitBegin";
-break;
-
-  case ProgramPoint::CallExitEndKind:
-Out << "CallExitEnd";
-break;
-
-  case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
-Out << "PostStmtPurgeDeadSymbols";
-break;
-
-  case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
-Out << "PreStmtPurgeDeadSymbols";
-break;
-
-  case ProgramPoint::EpsilonKind:
-Out << "Epsilon Point";
-break;
-
-  case ProgramPoint::LoopExitKind: {
-LoopExit LE = Loc.castAs();
-Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
-break;
-  }
+case ProgramPoint::BlockEntranceKind:
+  Out << "Block Entrance: B"
+  << Loc.castAs().getBlock()->getBlockID();
+  break;
+
+case ProgramPoint::BlockExitKind:
+  assert(false);
+  break;
+
+case ProgramPoint::CallEnterKind:
+  Out << "CallEnter";
+  break;
+
+case ProgramPoint::CallExitBeginKind:
+  Out << "CallExitBegin";
+  break;
+
+case ProgramPoint::CallExitEndKind:
+  Out << "CallExitEnd";
+  break;
+
+case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
+  Out << "PostStmtPurgeDeadSymbols";
+  break;
+
+case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
+  Out << "PreStmtPurgeDeadSymbols";
+  break;
+
+case ProgramPoint::EpsilonKind:
+  Out << "Epsilon Point";
+  break;
+
+case ProgramPoint::LoopExitKind: {
+  LoopExit LE = Loc.castAs();
+  Out << "LoopExit: " << LE.getLoopStmt()->getStmtClassName();
+  break;
+}
 
-  case ProgramPoint::PreImplicitCallKind: {
-ImplicitCallPoint PC = Loc.castAs();
-Out << "PreCall: ";
-
-// FIXME: Get proper printing options.
-PC.getDecl()->print(Out, LangOptions());
-printLocation(Out, PC.getLocation());
-break;
-  }
+case ProgramPoint::PreImplicitCallKind: {
+  ImplicitCallPoint PC = Loc.castAs();
+  Out << "PreCall: ";
+
+  // FIXME: Get proper printing options.
+  PC.getDecl()->print(Out, LangOptions());
+  printLocation(Out, PC.getLocation());
+  break;
+}
 
-  case ProgramPoint::PostImplicitCallKind: {
-ImplicitCallPoint PC = Loc.castAs();
-Out << "PostCall: ";
-
-// FIXME: Get proper printing options.
-PC.getDecl()->print(Out, LangOptions());
-printLocation(Out, PC.getLocation());
-break;
-  }
+case ProgramPoint::PostImplicitCallKind: {
+  ImplicitCallPoint PC = Loc.castAs();
+  Out << "PostCall: ";
+
+  // FIXME: Get proper printing options.
+  PC.getDecl()->print(Out, LangOptions());
+  printLocation(Out, PC.getLocation());
+  break;
+}
 
-  case ProgramPoint::PostInitializerKind: {
-Out << "PostInitializer: ";
-const CXXCtorInitializer *Init =
+case ProgramPoint::PostInitializerKind: {
+  Out << "PostInitializer: ";
+  const CXXCtorInitializer *Init =
   Loc.castAs().getInitializer();
-if (const FieldDecl *FD = Init->getAnyMember())
-  Out << *FD;
-else {
-  QualType Ty = Init->getTypeSourceInfo()->getType();
-  Ty = Ty.getLocalUnqualifiedType();
-  LangOptions LO; // FIXME.
-  Ty.print(Out, LO);
-}
-break;
+  if (const FieldDecl *FD = Init->getAnyMember())
+Out << *FD;
+  else {
+QualType Ty = Init->getTyp

r341617 - [analyzer] Push updating-the-executed-lines logic into the BugReporter.

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 17:42:53 2018
New Revision: 341617

URL: http://llvm.org/viewvc/llvm-project?rev=341617&view=rev
Log:
[analyzer] Push updating-the-executed-lines logic into the BugReporter.

So it can be reused across different consumers.

Differential Revision: https://reviews.llvm.org/D51514

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h?rev=341617&r1=341616&r2=341617&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
Thu Sep  6 17:42:53 2018
@@ -858,13 +858,13 @@ public:
   meta_iterator meta_end() const { return OtherDesc.end(); }
   void addMeta(StringRef s) { OtherDesc.push_back(s); }
 
-  using filesmap_iterator = FilesToLineNumsMap::const_iterator;
-
-  filesmap_iterator executedLines_begin() const {
-return ExecutedLines->begin();
+  const FilesToLineNumsMap &getExecutedLines() const {
+return *ExecutedLines;
   }
 
-  filesmap_iterator executedLines_end() const { return ExecutedLines->end(); }
+  FilesToLineNumsMap &getExecutedLines() {
+return *ExecutedLines;
+  }
 
   PathDiagnosticLocation getLocation() const {
 return Loc;

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=341617&r1=341616&r2=341617&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Thu Sep  6 17:42:53 2018
@@ -1881,6 +1881,21 @@ static void dropFunctionEntryEdge(PathPi
 using VisitorsDiagnosticsTy = llvm::DenseMap>>;
 
+/// Populate executes lines with lines containing at least one diagnostics.
+static void updateExecutedLinesWithDiagnosticPieces(
+  PathDiagnostic &PD) {
+
+  PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
+  FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
+
+  for (const auto &P : path) {
+FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
+FileID FID = Loc.getFileID();
+unsigned LineNo = Loc.getLineNumber();
+ExecutedLines[FID.getHashValue()].insert(LineNo);
+  }
+}
+
 /// This function is responsible for generating diagnostic pieces that are
 /// *not* provided by bug report visitors.
 /// These diagnostics may differ depending on the consumer's settings,
@@ -2985,6 +3000,7 @@ void BugReporter::FlushReport(BugReportE
 for (const auto &i : Meta)
   PD->addMeta(i);
 
+updateExecutedLinesWithDiagnosticPieces(*PD);
 Consumer->HandlePathDiagnostic(std::move(PD));
   }
 }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=341617&r1=341616&r2=341617&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Thu Sep  6 17:42:53 
2018
@@ -337,23 +337,8 @@ static void serializeExecutedLines(
 const PathDiagnostic &D,
 const PathPieces &path,
 llvm::raw_string_ostream &os) {
-  // Copy executed lines from path diagnostics.
-  std::map> ExecutedLines;
-  for (auto I = D.executedLines_begin(),
-E = D.executedLines_end(); I != E; ++I) {
-std::set &LinesInFile = ExecutedLines[I->first];
-for (unsigned LineNo : I->second) {
-  LinesInFile.insert(LineNo);
-}
-  }
 
-  // We need to include all lines for which any kind of diagnostics appears.
-  for (const auto &P : path) {
-FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
-FileID FID = Loc.getFileID();
-unsigned LineNo = Loc.getLineNumber();
-ExecutedLines[FID.getHashValue()].insert(LineNo);
-  }
+  const FilesToLineNumsMap &ExecutedLines = D.getExecutedLines();
 
   os << "var relevant_lines = {";
   for (auto I = ExecutedLines.begin(),


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341616 - [analyzer] Skip printing trivial nodes in exploded graph

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 17:42:32 2018
New Revision: 341616

URL: http://llvm.org/viewvc/llvm-project?rev=341616&view=rev
Log:
[analyzer] Skip printing trivial nodes in exploded graph

A node is considered to be trivial if it only has one successor, one
predecessor, and a state equal to the predecessor.
Can drastically (> 2x) reduce the size of the generated exploded
graph.

Differential Revision: https://reviews.llvm.org/D51665

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h?rev=341616&r1=341615&r2=341616&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
Thu Sep  6 17:42:32 2018
@@ -242,6 +242,11 @@ public:
 
   int64_t getID(ExplodedGraph *G) const;
 
+  /// The node is trivial if it has only one successor, only one predecessor,
+  /// and its program state is the same as the program state of the previous
+  /// node.
+  bool isTrivial() const;
+
 private:
   void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); }
   void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); }
@@ -463,9 +468,19 @@ namespace llvm {
 
 static NodeRef getEntryNode(NodeRef N) { return N; }
 
-static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
-
-static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
+static ChildIteratorType child_begin(NodeRef N) {
+  if (N->succ_size() == 1 && (*N->succ_begin())->isTrivial()) {
+return child_begin(*N->succ_begin());
+  }
+  return N->succ_begin();
+}
+
+static ChildIteratorType child_end(NodeRef N) {
+  if (N->succ_size() == 1 && (*N->succ_begin())->isTrivial()) {
+return child_end(*N->succ_begin());
+  }
+  return N->succ_end();
+}
 
 static nodes_iterator nodes_begin(NodeRef N) { return df_begin(N); }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp?rev=341616&r1=341615&r2=341616&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp Thu Sep  6 17:42:32 2018
@@ -290,6 +290,11 @@ int64_t ExplodedNode::getID(ExplodedGrap
   return *Out / alignof(ExplodedNode);
 }
 
+bool ExplodedNode::isTrivial() const {
+  return pred_size() == 1 && succ_size() == 1 &&
+ (*pred_begin())->getState()->getID() == getState()->getID();
+}
+
 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
  ProgramStateRef State,
  bool IsSink,

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=341616&r1=341615&r2=341616&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Sep  6 17:42:32 2018
@@ -2974,6 +2974,7 @@ struct DOTGraphTraits : p
   }
 
   static void dumpProgramPoint(ProgramPoint Loc,
+   const PrintingPolicy &PP,
llvm::raw_string_ostream &Out) {
 switch (Loc.getKind()) {
 case ProgramPoint::BlockEntranceKind:
@@ -3112,8 +3113,7 @@ struct DOTGraphTraits : p
   assert(S != nullptr && "Expecting non-null Stmt");
 
   Out << S->getStmtClassName() << ' ' << (const void *)S << ' ';
-  LangOptions LO; // FIXME.
-  S->printPretty(Out, nullptr, PrintingPolicy(LO));
+  S->printPretty(Out, nullptr, PP);
   printLocation(Out, S->getBeginLoc());
 
   if (Loc.getAs())
@@ -3132,32 +3132,52 @@ struct DOTGraphTraits : p
 }
   }
 
+  static bool isNodeHidden(const ExplodedNode *N) {
+return N->isTrivial();
+  }
+
   static std::string getNodeLabel(const ExplodedNode *N, void*){
 std::string sbuf;
 llvm::raw_string_ostream Out(sbuf);
 
-// Program Location.
-ProgramPoint Loc = N->getLocation();
+// Find the first node which program point and tag has to be included in
+// the output.
+const ExplodedNode *FirstHiddenNode = N;
+while (FirstHiddenNode->pred_size() == 1 &&
+   isNodeHidden(*FirstHiddenNode->pred_begin())) {
+  FirstHiddenNode = *FirstHiddenNode->pred_begin();
+   

r341619 - [analyzer] Executed lines: store file IDs, not hashes.

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 17:43:37 2018
New Revision: 341619

URL: http://llvm.org/viewvc/llvm-project?rev=341619&view=rev
Log:
[analyzer] Executed lines: store file IDs, not hashes.

Raw FileIDs are needed for the PlistDiagnostics to produce stable filenames.

Differential Revision: https://reviews.llvm.org/D51668

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h?rev=341619&r1=341618&r2=341619&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
Thu Sep  6 17:43:37 2018
@@ -759,7 +759,7 @@ public:
 };
 
 /// File IDs mapped to sets of line numbers.
-using FilesToLineNumsMap = std::map>;
+using FilesToLineNumsMap = std::map>;
 
 /// PathDiagnostic - PathDiagnostic objects represent a single path-sensitive
 ///  diagnostic.  It represents an ordered-collection of PathDiagnosticPieces,

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=341619&r1=341618&r2=341619&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Thu Sep  6 17:43:37 2018
@@ -1893,7 +1893,7 @@ static void updateExecutedLinesWithDiagn
 FileID FID = Loc.getFileID();
 unsigned LineNo = Loc.getLineNumber();
 assert(FID.isValid());
-ExecutedLines[FID.getHashValue()].insert(LineNo);
+ExecutedLines[FID].insert(LineNo);
   }
 }
 
@@ -3030,7 +3030,7 @@ static void populateExecutedLinesWithFun
 
   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
   for (unsigned Line = StartLine; Line <= EndLine; Line++)
-ExecutedLines->operator[](FID.getHashValue()).insert(Line);
+ExecutedLines->operator[](FID).insert(Line);
 }
 
 static void populateExecutedLinesWithStmt(
@@ -3042,7 +3042,7 @@ static void populateExecutedLinesWithStm
   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
   FileID FID = SM.getFileID(ExpansionLoc);
   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
-  ExecutedLines->operator[](FID.getHashValue()).insert(LineNo);
+  ExecutedLines->operator[](FID).insert(LineNo);
 }
 
 /// \return all executed lines including function signatures on the path

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=341619&r1=341618&r2=341619&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Thu Sep  6 17:43:37 
2018
@@ -346,7 +346,7 @@ static void serializeExecutedLines(
 if (I != ExecutedLines.begin())
   os << ", ";
 
-os << "\"" << I->first << "\": {";
+os << "\"" << I->first.getHashValue() << "\": {";
 for (unsigned LineNo : I->second) {
   if (LineNo != *(I->second.begin()))
 os << ", ";


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


cfe-commits@lists.llvm.org

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 17:43:55 2018
New Revision: 341620

URL: http://llvm.org/viewvc/llvm-project?rev=341620&view=rev
Log:
[analyzer] [NFC] Prefer passing around reference to std::unique_ptr&

When object is owned elsewhere

Differential Revision: https://reviews.llvm.org/D51669

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=341620&r1=341619&r2=341620&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Thu Sep  6 17:43:55 2018
@@ -3010,7 +3010,7 @@ void BugReporter::FlushReport(BugReportE
 /// into \p ExecutedLines.
 static void populateExecutedLinesWithFunctionSignature(
 const Decl *Signature, SourceManager &SM,
-std::unique_ptr &ExecutedLines) {
+FilesToLineNumsMap &ExecutedLines) {
   SourceRange SignatureSourceRange;
   const Stmt* Body = Signature->getBody();
   if (const auto FD = dyn_cast(Signature)) {
@@ -3030,19 +3030,19 @@ static void populateExecutedLinesWithFun
 
   FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
   for (unsigned Line = StartLine; Line <= EndLine; Line++)
-ExecutedLines->operator[](FID).insert(Line);
+ExecutedLines[FID].insert(Line);
 }
 
 static void populateExecutedLinesWithStmt(
 const Stmt *S, SourceManager &SM,
-std::unique_ptr &ExecutedLines) {
+FilesToLineNumsMap &ExecutedLines) {
   SourceLocation Loc = S->getSourceRange().getBegin();
   if (!Loc.isValid())
 return;
   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
   FileID FID = SM.getFileID(ExpansionLoc);
   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
-  ExecutedLines->operator[](FID).insert(LineNo);
+  ExecutedLines[FID].insert(LineNo);
 }
 
 /// \return all executed lines including function signatures on the path
@@ -3055,13 +3055,13 @@ findExecutedLines(SourceManager &SM, con
 if (N->getFirstPred() == nullptr) {
   // First node: show signature of the entrance point.
   const Decl *D = N->getLocationContext()->getDecl();
-  populateExecutedLinesWithFunctionSignature(D, SM, ExecutedLines);
+  populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
 } else if (auto CE = N->getLocationAs()) {
   // Inlined function: show signature.
   const Decl* D = CE->getCalleeContext()->getDecl();
-  populateExecutedLinesWithFunctionSignature(D, SM, ExecutedLines);
+  populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
 } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
-  populateExecutedLinesWithStmt(S, SM, ExecutedLines);
+  populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
 
   // Show extra context for some parent kinds.
   const Stmt *P = N->getParentMap().getParent(S);
@@ -3070,12 +3070,12 @@ findExecutedLines(SourceManager &SM, con
   // return statement is generated, but we do want to show the whole
   // return.
   if (const auto *RS = dyn_cast_or_null(P)) {
-populateExecutedLinesWithStmt(RS, SM, ExecutedLines);
+populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
 P = N->getParentMap().getParent(RS);
   }
 
   if (P && (isa(P) || isa(P)))
-populateExecutedLinesWithStmt(P, SM, ExecutedLines);
+populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
 }
 
 N = N->getFirstPred();


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341618 - [analyzer] Do not add invalid source location to the coverage information

2018-09-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep  6 17:43:17 2018
New Revision: 341618

URL: http://llvm.org/viewvc/llvm-project?rev=341618&view=rev
Log:
[analyzer] Do not add invalid source location to the coverage information

Invalid source locations may arise from generated code.

Differential Revision: https://reviews.llvm.org/D51761

Added:
cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/synthesized_body.cpp
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=341618&r1=341617&r2=341618&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Thu Sep  6 17:43:17 2018
@@ -1892,6 +1892,7 @@ static void updateExecutedLinesWithDiagn
 FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
 FileID FID = Loc.getFileID();
 unsigned LineNo = Loc.getLineNumber();
+assert(FID.isValid());
 ExecutedLines[FID.getHashValue()].insert(LineNo);
   }
 }
@@ -3022,6 +3023,8 @@ static void populateExecutedLinesWithFun
   SourceLocation Start = SignatureSourceRange.getBegin();
   SourceLocation End = Body ? Body->getSourceRange().getBegin()
 : SignatureSourceRange.getEnd();
+  if (!Start.isValid() || !End.isValid())
+return;
   unsigned StartLine = SM.getExpansionLineNumber(Start);
   unsigned EndLine = SM.getExpansionLineNumber(End);
 
@@ -3034,6 +3037,8 @@ static void populateExecutedLinesWithStm
 const Stmt *S, SourceManager &SM,
 std::unique_ptr &ExecutedLines) {
   SourceLocation Loc = S->getSourceRange().getBegin();
+  if (!Loc.isValid())
+return;
   SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
   FileID FID = SM.getFileID(ExpansionLoc);
   unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);

Added: 
cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/synthesized_body.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/synthesized_body.cpp?rev=341618&view=auto
==
--- 
cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/synthesized_body.cpp 
(added)
+++ 
cfe/trunk/test/Analysis/html_diagnostics/relevant_lines/synthesized_body.cpp 
Thu Sep  6 17:43:17 2018
@@ -0,0 +1,25 @@
+// Faking std::call_once implementation.
+namespace std {
+typedef struct once_flag_s {
+  int _M_once = 0;
+} once_flag;
+
+template 
+void call_once(once_flag &o, Callable&& func, Args&&... args);
+} // namespace std
+
+int deref(int *x) {
+  return *x;
+}
+
+void call_deref_once() {
+  static std::once_flag once;
+  int *p = nullptr;
+  std::call_once(once, &deref, p);
+}
+
+
+// RUN: rm -rf %t.output
+// RUN: %clang_analyze_cc1 -analyze -analyzer-checker=core -analyzer-output 
html -o %t.output %s
+// RUN: cat %t.output/* | FileCheck %s --match-full-lines
+// CHECK: var relevant_lines = {"1": {"3": 1,  "8": 1, "11": 1, "12": 1, "15": 
1, "16": 1, "17": 1, "18": 1}};


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r341722 - [analyzer] Remove the "postponed" hack, deal with derived symbols using an extra map

2018-09-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep  7 15:07:57 2018
New Revision: 341722

URL: http://llvm.org/viewvc/llvm-project?rev=341722&view=rev
Log:
[analyzer] Remove the "postponed" hack, deal with derived symbols using an 
extra map

The "derived" symbols indicate children fields of a larger symbol.
As parents do not have pointers to their children, the garbage
collection algorithm the analyzer currently uses adds such symbols into
a "postponed" category, and then keeps running through the worklist
until the fixed point is reached.

The current patch rectifies that by instead using a helper map which
stores pointers from parents to children, so that no fixed point
calculation is necessary.

The current patch yields ~5% improvement in running time on sqlite.

Differential Revision: https://reviews.llvm.org/D51397

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h?rev=341722&r1=341721&r2=341722&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h Fri 
Sep  7 15:07:57 2018
@@ -769,6 +769,9 @@ class SymbolicRegion : public SubRegion
 assert(s->getType()->isAnyPointerType() ||
s->getType()->isReferenceType() ||
s->getType()->isBlockPointerType());
+
+// populateWorklistFromSymbol() relies on this assertion, and needs to be
+// updated if more cases are introduced.
 assert(isa(sreg) || isa(sreg));
   }
 

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h?rev=341722&r1=341721&r2=341722&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h Fri Sep  
7 15:07:57 2018
@@ -130,6 +130,8 @@ public:
   ///  used to query and manipulate MemRegion objects.
   MemRegionManager& getRegionManager() { return MRMgr; }
 
+  SValBuilder& getSValBuilder() { return svalBuilder; }
+
   virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) {
 return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
   }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=341722&r1=341721&r2=341722&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Sep  7 15:07:57 2018
@@ -2394,7 +2394,10 @@ RegionStoreManager::bindAggregate(Region
 namespace {
 class RemoveDeadBindingsWorker
 : public ClusterAnalysis {
-  SmallVector Postponed;
+  using ChildrenListTy = SmallVector;
+  using MapParentsToDerivedTy = llvm::DenseMap;
+
+  MapParentsToDerivedTy ParentsToDerived;
   SymbolReaper &SymReaper;
   const StackFrameContext *CurrentLCtx;
 
@@ -2415,8 +2418,10 @@ public:
 
   bool AddToWorkList(const MemRegion *R);
 
-  bool UpdatePostponed();
   void VisitBinding(SVal V);
+
+private:
+  void populateWorklistFromSymbol(SymbolRef s);
 };
 }
 
@@ -2436,10 +2441,11 @@ void RemoveDeadBindingsWorker::VisitAdde
   }
 
   if (const SymbolicRegion *SR = dyn_cast(baseR)) {
-if (SymReaper.isLive(SR->getSymbol()))
+if (SymReaper.isLive(SR->getSymbol())) {
   AddToWorkList(SR, &C);
-else
-  Postponed.push_back(SR);
+} else if (const auto *SD = dyn_cast(SR->getSymbol())) {
+  ParentsToDerived[SD->getParentSymbol()].push_back(SD);
+}
 
 return;
   }
@@ -2451,7 +2457,7 @@ void RemoveDeadBindingsWorker::VisitAdde
 
   // CXXThisRegion in the current or parent location context is live.
   if (const CXXThisRegion *TR = dyn_cast(baseR)) {
-const StackArgumentsSpaceRegion *StackReg =
+const auto *StackReg =
   cast(TR->getSuperRegion());
 const StackFrameContext *RegCtx = StackReg->getStackFrame();
 if (CurrentLCtx &&
@@ -2496,6 +2502,15 @@ void RemoveDeadBindingsWorker::VisitBind
   // If V is a region, then add it to the worklist.
   if (const MemRegion *R = V.getAsRegion()) {
 AddToWorkList(R);
+
+if (const auto *TVR = dyn_cast(R)) {
+  DefinedOrUnknownSVal RVS =
+  RM.getSValBuilder().getRegionValueSymbolVal(TVR);
+  if (const MemRegion *SR = RVS.getAsRegion()) {
+AddToWorkList(SR);
+  }
+}
+
 SymReaper.markLi

r341723 - [analyzer] [NFC] Use StringRef when returning a large string literal in HTMLDiagnostics

2018-09-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep  7 15:13:15 2018
New Revision: 341723

URL: http://llvm.org/viewvc/llvm-project?rev=341723&view=rev
Log:
[analyzer] [NFC] Use StringRef when returning a large string literal in 
HTMLDiagnostics

(NB: could be a clang-tidy / analyzer check)

Differential Revision: https://reviews.llvm.org/D51512

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=341723&r1=341722&r2=341723&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Fri Sep  7 15:13:15 
2018
@@ -115,12 +115,13 @@ public:
   void RewriteFile(Rewriter &R, const SourceManager& SMgr,
const PathPieces& path, FileID FID);
 
-  /// \return Javascript for navigating the HTML report using j/k keys.
-  std::string generateKeyboardNavigationJavascript();
 
 private:
   /// \return Javascript for displaying shortcuts help;
-  std::string showHelpJavascript();
+  StringRef showHelpJavascript();
+
+  /// \return Javascript for navigating the HTML report using j/k keys.
+  StringRef generateKeyboardNavigationJavascript();
 };
 
 } // namespace
@@ -571,7 +572,7 @@ void HTMLDiagnostics::FinalizeHTML(const
   html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
 }
 
-std::string HTMLDiagnostics::showHelpJavascript() {
+StringRef HTMLDiagnostics::showHelpJavascript() {
   return R"<<<(
 

r341724 - [analyzer] [NFC] Move methods for dumping the coverage in HTMLDiagnostics into the class

2018-09-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Sep  7 15:13:35 2018
New Revision: 341724

URL: http://llvm.org/viewvc/llvm-project?rev=341724&view=rev
Log:
[analyzer] [NFC] Move methods for dumping the coverage in HTMLDiagnostics into 
the class

Differential Revision: https://reviews.llvm.org/D51513

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp?rev=341724&r1=341723&r2=341724&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp Fri Sep  7 15:13:35 
2018
@@ -122,6 +122,15 @@ private:
 
   /// \return Javascript for navigating the HTML report using j/k keys.
   StringRef generateKeyboardNavigationJavascript();
+
+  /// \return JavaScript for an option to only show relevant lines.
+  std::string showRelevantLinesJavascript(
+const PathDiagnostic &D, const PathPieces &path);
+
+  /// Write executed lines from \p D in JSON format into \p os.
+  void dumpCoverageData(const PathDiagnostic &D,
+const PathPieces &path,
+llvm::raw_string_ostream &os);
 };
 
 } // namespace
@@ -333,8 +342,7 @@ std::string HTMLDiagnostics::GenerateHTM
   return os.str();
 }
 
-/// Write executed lines from \p D in JSON format into \p os.
-static void serializeExecutedLines(
+void HTMLDiagnostics::dumpCoverageData(
 const PathDiagnostic &D,
 const PathPieces &path,
 llvm::raw_string_ostream &os) {
@@ -360,13 +368,12 @@ static void serializeExecutedLines(
   os << "};";
 }
 
-/// \return JavaScript for an option to only show relevant lines.
-static std::string showRelevantLinesJavascript(
+std::string HTMLDiagnostics::showRelevantLinesJavascript(
   const PathDiagnostic &D, const PathPieces &path) {
   std::string s;
   llvm::raw_string_ostream os(s);
   os << "

r341978 - [analyzer] [NFC] Change the tests by making the version check more resilient

2018-09-11 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Sep 11 11:45:15 2018
New Revision: 341978

URL: http://llvm.org/viewvc/llvm-project?rev=341978&view=rev
Log:
[analyzer] [NFC] Change the tests by making the version check more resilient

Modified:
cfe/trunk/test/Analysis/MismatchedDeallocator-path-notes.cpp
cfe/trunk/test/Analysis/NewDelete-path-notes.cpp
cfe/trunk/test/Analysis/conditional-path-notes.c
cfe/trunk/test/Analysis/copypaste/plist-diagnostics-notes-as-events.cpp
cfe/trunk/test/Analysis/copypaste/plist-diagnostics.cpp
cfe/trunk/test/Analysis/cxx-for-range.cpp
cfe/trunk/test/Analysis/diagnostics/deref-track-symbolic-region.c
cfe/trunk/test/Analysis/diagnostics/plist-diagnostics-include-check.cpp
cfe/trunk/test/Analysis/diagnostics/plist-multi-file.c
cfe/trunk/test/Analysis/diagnostics/report-issues-within-main-file.cpp
cfe/trunk/test/Analysis/diagnostics/undef-value-caller.c
cfe/trunk/test/Analysis/diagnostics/undef-value-param.c
cfe/trunk/test/Analysis/diagnostics/undef-value-param.m
cfe/trunk/test/Analysis/edges-new.mm
cfe/trunk/test/Analysis/generics.m
cfe/trunk/test/Analysis/inline-plist.c
cfe/trunk/test/Analysis/inline-unique-reports.c
cfe/trunk/test/Analysis/inlining/eager-reclamation-path-notes.c
cfe/trunk/test/Analysis/inlining/eager-reclamation-path-notes.cpp
cfe/trunk/test/Analysis/inlining/path-notes.c
cfe/trunk/test/Analysis/inlining/path-notes.cpp
cfe/trunk/test/Analysis/inlining/path-notes.m
cfe/trunk/test/Analysis/lambda-notes.cpp
cfe/trunk/test/Analysis/malloc-plist.c
cfe/trunk/test/Analysis/method-call-path-notes.cpp
cfe/trunk/test/Analysis/model-file.cpp
cfe/trunk/test/Analysis/null-deref-path-notes.m
cfe/trunk/test/Analysis/nullability-notes.m
cfe/trunk/test/Analysis/objc-arc.m
cfe/trunk/test/Analysis/plist-macros.cpp
cfe/trunk/test/Analysis/plist-output-alternate.m
cfe/trunk/test/Analysis/plist-output.m
cfe/trunk/test/Analysis/retain-release-path-notes.m
cfe/trunk/test/Analysis/unix-fns.c

Modified: cfe/trunk/test/Analysis/MismatchedDeallocator-path-notes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/MismatchedDeallocator-path-notes.cpp?rev=341978&r1=341977&r2=341978&view=diff
==
--- cfe/trunk/test/Analysis/MismatchedDeallocator-path-notes.cpp (original)
+++ cfe/trunk/test/Analysis/MismatchedDeallocator-path-notes.cpp Tue Sep 11 
11:45:15 2018
@@ -1,6 +1,6 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator 
-analyzer-output=text -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.MismatchedDeallocator 
-analyzer-output=plist %s -o %t.plist
-// RUN: tail -n +11 %t.plist | diff -u -w -I "/" -I ".:" -I 
"clang version" - 
%S/copypaste/Inputs/expected-plists/MismatchedDeallocator-path-notes.cpp.plist
+// RUN: tail -n +11 %t.plist | diff -u -w -I "/" -I ".:" -I 
"version" - 
%S/copypaste/Inputs/expected-plists/MismatchedDeallocator-path-notes.cpp.plist
 
 void changePointee(int *p);
 int *allocIntArray(unsigned c) {

Modified: cfe/trunk/test/Analysis/NewDelete-path-notes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/NewDelete-path-notes.cpp?rev=341978&r1=341977&r2=341978&view=diff
==
--- cfe/trunk/test/Analysis/NewDelete-path-notes.cpp (original)
+++ cfe/trunk/test/Analysis/NewDelete-path-notes.cpp Tue Sep 11 11:45:15 2018
@@ -1,7 +1,7 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.NewDelete,unix.Malloc 
-analyzer-output=text -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.NewDelete,unix.Malloc 
-analyzer-output=text -analyzer-config c++-allocator-inlining=true -verify %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.NewDelete,unix.Malloc 
-analyzer-output=plist %s -o %t.plist
-// RUN: cat %t.plist | diff -u -w -I "/" -I ".:" -I "clang 
version" - %S/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
+// RUN: cat %t.plist | diff -u -w -I "/" -I ".:" -I "version" 
- %S/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
 
 void test() {
   int *p = new int;

Modified: cfe/trunk/test/Analysis/conditional-path-notes.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/conditional-path-notes.c?rev=341978&r1=341977&r2=341978&view=diff
==
--- cfe/trunk/test/Analysis/conditional-path-notes.c (original)
+++ cfe/trunk/test/Analysis/conditional-path-notes.c Tue Sep 11 11:45:15 2018
@@ -1,6 +1,6 @@
 // RUN: %clang_analyze_cc1 %s -analyzer-checker=core.NullDereference 
-analyzer-output=text -verify
 // RUN: %clang_analyze_cc1 %s -analyzer-checker=core.NullDereference 
-analyzer-output=plist -o %t
-// RUN: cat %t | diff -u -w -I "/" -I ".:" -I "clang version" 
- %S/Inputs/expected-plists/conditional-pa

r337635 - [Driver] Sanitizer support based on runtime library presence

2018-07-20 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul 20 16:34:39 2018
New Revision: 337635

URL: http://llvm.org/viewvc/llvm-project?rev=337635&view=rev
Log:
[Driver] Sanitizer support based on runtime library presence

The runtime libraries of sanitizers are built in compiler-rt, and Clang
can be built without compiler-rt, or compiler-rt can be configured to
only build certain sanitizers. The driver should provide reasonable
diagnostics and not a link-time error when a runtime library is missing.

This patch changes the driver for OS X to only support sanitizers of
which we can find the runtime libraries. The discussion for this patch
explains the rationale

Differential Revision: https://reviews.llvm.org/D15225

Added:
cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_ios_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_iossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_osx_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvos_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_tvossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchos_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.asan_watchossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.fuzzer_osx.a

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_ios_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_iossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_osx_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.lsan_tvossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_iossim_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_osx_dynamic.dylib

cfe/trunk/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.tsan_tvossim_dynamic.dylib
Modified:
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/lib/Driver/ToolChains/Darwin.h
cfe/trunk/test/Driver/darwin-asan-nofortify.c
cfe/trunk/test/Driver/darwin-sanitizer-ld.c
cfe/trunk/test/Driver/fsanitize.c
cfe/trunk/test/Driver/fuzzer.c
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=337635&r1=337634&r2=337635&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Fri Jul 20 16:34:39 2018
@@ -916,13 +916,26 @@ unsigned DarwinClang::GetDefaultDwarfVer
   return 4;
 }
 
+SmallString<128> MachO::runtimeLibDir(bool IsEmbedded) const {
+  SmallString<128> Dir(getDriver().ResourceDir);
+  llvm::sys::path::append(
+  Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
+  return Dir;
+}
+
+std::string Darwin::getFileNameForSanitizerLib(StringRef SanitizerName,
+  bool Shared) const {
+  return (Twine("libclang_rt.") + SanitizerName + "_" +
+  getOSLibraryNameSuffix() +
+  (Shared ? "_dynamic.dylib" : ".a")).str();
+
+}
+
 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
   StringRef DarwinLibName,
   RuntimeLinkOptions Opts) const {
-  SmallString<128> Dir(getDriver().ResourceDir);
-  llvm::sys::path::append(
-  Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
 
+  SmallString<128> Dir = runtimeLibDir(Opts & RLO_IsEmbedded);
   SmallString<128> P(Dir);
   llvm::sys::path::append(P, DarwinLibName);
 
@@ -1042,12 +1055,9 @@ void DarwinClang::AddLinkSanitizerLibArg
   StringRef Sanitizer,
   bool Shared) const {
   auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
-  AddLinkRuntimeLib(Args, CmdArgs,
-(Twine("libclang_rt.") + Sanitizer + "_" +
- getOSLibraryNameSuffix() +
- (Shared ? "_dynamic.dylib" : ".a"))
-.str(),
-RLO);
+  std::string SanitizerRelFilename =
+  getFileNameForSanitizerLib(Sanitizer, Shared);
+  AddLinkRuntimeLib(Args, CmdArgs, SanitizerRelFilename, RLO);
 }
 
 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
@@ -2285,24 +2295,43 @@ void Darwin::CheckObjCARC() const {
 SanitizerMask Darwin::getSupportedSanitizers() const {
   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
   SanitizerMask Res = ToolChain::getS

r337760 - [ASTMatchers] [NFC] Regenerate HTML docs.

2018-07-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Jul 23 15:29:10 2018
New Revision: 337760

URL: http://llvm.org/viewvc/llvm-project?rev=337760&view=rev
Log:
[ASTMatchers] [NFC] Regenerate HTML docs.

Modified:
cfe/trunk/docs/LibASTMatchersReference.html

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=337760&r1=337759&r2=337760&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Mon Jul 23 15:29:10 2018
@@ -3275,9 +3275,9 @@ Example
 matcher = objcMessagaeExpr(isInstanceMessage())
 matches
   NSString *x = @"hello";
-  [x containsString:@"h"]
+  [x containsString:@"h"];
 but not
-  [NSString stringWithFormat:@"format"]
+  [NSString stringWithFormat:@"format"];
 
 
 
@@ -5894,7 +5894,7 @@ and the inner matcher matches on that in
 
 For example the method call in
   NSString *x = @"hello";
-  [x containsString:@"h"]
+  [x containsString:@"h"];
 is matched by
 objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))
 
@@ -6564,7 +6564,7 @@ type of the matched node.
 For example, in:
   class A {};
   using B = A;
-The matcher type(hasUnqualifeidDesugaredType(recordType())) matches
+The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
 both B and A.
 
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r337761 - [ASTMatchers] Add an isMain() matcher

2018-07-23 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Jul 23 15:29:35 2018
New Revision: 337761

URL: http://llvm.org/viewvc/llvm-project?rev=337761&view=rev
Log:
[ASTMatchers] Add an isMain() matcher

Differential Revision: https://reviews.llvm.org/D49615

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=337761&r1=337760&r2=337761&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Mon Jul 23 15:29:35 2018
@@ -2919,6 +2919,12 @@ namespaceDecl(isInline()) will match n::
 
 
 
+MatcherFunctionDecl>isMain
+Determines whether the 
function is "main", which is the entry point
+into an executable program.
+
+
+
 MatcherFunctionDecl>isNoReturn
 Matches FunctionDecls 
that have a noreturn attribute.
 

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=337761&r1=337760&r2=337761&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Mon Jul 23 15:29:35 2018
@@ -616,6 +616,12 @@ AST_MATCHER_P(FieldDecl, hasInClassIniti
   InnerMatcher.matches(*Initializer, Finder, Builder));
 }
 
+/// Determines whether the function is "main", which is the entry point
+/// into an executable program.
+AST_MATCHER(FunctionDecl, isMain) {
+  return Node.isMain();
+}
+
 /// Matches the specialized template of a specialization declaration.
 ///
 /// Given

Modified: cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp?rev=337761&r1=337760&r2=337761&view=diff
==
--- cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp (original)
+++ cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp Mon Jul 23 15:29:35 2018
@@ -359,6 +359,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(isInTemplateInstantiation);
   REGISTER_MATCHER(isLambda);
   REGISTER_MATCHER(isListInitialization);
+  REGISTER_MATCHER(isMain);
   REGISTER_MATCHER(isMemberInitializer);
   REGISTER_MATCHER(isMoveAssignmentOperator);
   REGISTER_MATCHER(isMoveConstructor);

Modified: cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp?rev=337761&r1=337760&r2=337761&view=diff
==
--- cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp (original)
+++ cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp Mon Jul 23 
15:29:35 2018
@@ -2158,5 +2158,13 @@ TEST(IsAssignmentOperator, Basic) {
   notMatches("void x() { int a; if(a == 0) return; }", BinAsgmtOperator));
 }
 
+TEST(Matcher, isMain) {
+  EXPECT_TRUE(
+matches("int main() {}", functionDecl(isMain(;
+
+  EXPECT_TRUE(
+notMatches("int main2() {}", functionDecl(isMain(;
+}
+
 } // namespace ast_matchers
 } // namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r337864 - [analyzer] Extend NoStoreFuncVisitor to insert a note on IVars

2018-07-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jul 24 16:14:29 2018
New Revision: 337864

URL: http://llvm.org/viewvc/llvm-project?rev=337864&view=rev
Log:
[analyzer] Extend NoStoreFuncVisitor to insert a note on IVars

The note is added in the following situation:

 - We are throwing a nullability-related warning on an IVar
 - The path goes through a method which *could have* (syntactically
 determined) written into that IVar, but did not

rdar://4260

Differential Revision: https://reviews.llvm.org/D49689

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.m

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=337864&r1=337863&r2=337864&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Tue Jul 24 
16:14:29 2018
@@ -22,6 +22,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -306,15 +307,26 @@ public:
 
 CallEventRef<> Call =
 BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
-
 const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
 const SourceManager &SM = BRC.getSourceManager();
+
+// Region of interest corresponds to an IVar, exiting a method
+// which could have written into that IVar, but did not.
+if (const auto *MC = dyn_cast(Call))
+  if (const auto *IvarR = dyn_cast(RegionOfInterest))
+if (potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
+  IvarR->getDecl()) &&
+!isRegionOfInterestModifiedInFrame(N))
+  return notModifiedMemberDiagnostics(
+  Ctx, SM, PP, *CallExitLoc, Call,
+  MC->getReceiverSVal().getAsRegion());
+
 if (const auto *CCall = dyn_cast(Call)) {
   const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
   if (RegionOfInterest->isSubRegionOf(ThisRegion)
   && !CCall->getDecl()->isImplicit()
   && !isRegionOfInterestModifiedInFrame(N))
-return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
+return notModifiedMemberDiagnostics(Ctx, SM, PP, *CallExitLoc,
CCall, ThisRegion);
 }
 
@@ -331,7 +343,7 @@ public:
   if (isRegionOfInterestModifiedInFrame(N))
 return nullptr;
 
-  return notModifiedDiagnostics(
+  return notModifiedParameterDiagnostics(
   Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
 }
 QualType PT = T->getPointeeType();
@@ -346,6 +358,22 @@ public:
   }
 
 private:
+
+  /// \return Whether the method declaration \p Parent
+  /// syntactically has a binary operation writing into the ivar \p Ivar.
+  bool potentiallyWritesIntoIvar(const Decl *Parent,
+ const ObjCIvarDecl *Ivar) {
+using namespace ast_matchers;
+if (!Parent)
+  return false;
+StatementMatcher WriteIntoIvarM = binaryOperator(
+hasOperatorName("="), hasLHS(ignoringParenImpCasts(objcIvarRefExpr(
+  hasDeclaration(equalsNode(Ivar));
+StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
+auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
+return !Matches.empty();
+  }
+
   /// Check and lazily calculate whether the region of interest is
   /// modified in the stack frame to which \p N belongs.
   /// The calculation is cached in FramesModifyingRegion.
@@ -414,19 +442,21 @@ private:
Ty->getPointeeType().getCanonicalType().isConstQualified();
   }
 
-  std::shared_ptr notModifiedInConstructorDiagnostics(
+  /// \return Diagnostics piece for the member field not modified
+  /// in a given function.
+  std::shared_ptr notModifiedMemberDiagnostics(
   const LocationContext *Ctx,
   const SourceManager &SM,
   const PrintingPolicy &PP,
   CallExitBegin &CallExitLoc,
-  const CXXConstructorCall *Call,
+  CallEventRef<> Call,
   const MemRegion *ArgRegion) {
+const char *TopRegionName = isa(Call) ? "self" : "this";
 SmallString<256> sbuf;
 llvm::raw_svector_ostream os(sbuf);
 os << DiagnosticsMsg;
-bool out = prettyPrintRegionName(
-"this", "->", /*IsReference=*/true,
-/*IndirectionLevel=*/1, ArgRegion, os, PP);
+bool out = prettyPrintRegionName(TopRegionName, "->", /*IsReference=*/true,
+ 

r337866 - Revert "[analyzer] Extend NoStoreFuncVisitor to insert a note on IVars"

2018-07-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jul 24 16:23:33 2018
New Revision: 337866

URL: http://llvm.org/viewvc/llvm-project?rev=337866&view=rev
Log:
Revert "[analyzer] Extend NoStoreFuncVisitor to insert a note on IVars"

This reverts commit a9e21bd727112cd69eabc1af648c5da6b773d06e.
Reverted because the dependency has not landed yet.

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.m

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=337866&r1=337865&r2=337866&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Tue Jul 24 
16:23:33 2018
@@ -22,7 +22,6 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/Type.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -307,26 +306,15 @@ public:
 
 CallEventRef<> Call =
 BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
+
 const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
 const SourceManager &SM = BRC.getSourceManager();
-
-// Region of interest corresponds to an IVar, exiting a method
-// which could have written into that IVar, but did not.
-if (const auto *MC = dyn_cast(Call))
-  if (const auto *IvarR = dyn_cast(RegionOfInterest))
-if (potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
-  IvarR->getDecl()) &&
-!isRegionOfInterestModifiedInFrame(N))
-  return notModifiedMemberDiagnostics(
-  Ctx, SM, PP, *CallExitLoc, Call,
-  MC->getReceiverSVal().getAsRegion());
-
 if (const auto *CCall = dyn_cast(Call)) {
   const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
   if (RegionOfInterest->isSubRegionOf(ThisRegion)
   && !CCall->getDecl()->isImplicit()
   && !isRegionOfInterestModifiedInFrame(N))
-return notModifiedMemberDiagnostics(Ctx, SM, PP, *CallExitLoc,
+return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
CCall, ThisRegion);
 }
 
@@ -343,7 +331,7 @@ public:
   if (isRegionOfInterestModifiedInFrame(N))
 return nullptr;
 
-  return notModifiedParameterDiagnostics(
+  return notModifiedDiagnostics(
   Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
 }
 QualType PT = T->getPointeeType();
@@ -358,22 +346,6 @@ public:
   }
 
 private:
-
-  /// \return Whether the method declaration \p Parent
-  /// syntactically has a binary operation writing into the ivar \p Ivar.
-  bool potentiallyWritesIntoIvar(const Decl *Parent,
- const ObjCIvarDecl *Ivar) {
-using namespace ast_matchers;
-if (!Parent)
-  return false;
-StatementMatcher WriteIntoIvarM = binaryOperator(
-hasOperatorName("="), hasLHS(ignoringParenImpCasts(objcIvarRefExpr(
-  hasDeclaration(equalsNode(Ivar));
-StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
-auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
-return !Matches.empty();
-  }
-
   /// Check and lazily calculate whether the region of interest is
   /// modified in the stack frame to which \p N belongs.
   /// The calculation is cached in FramesModifyingRegion.
@@ -442,21 +414,19 @@ private:
Ty->getPointeeType().getCanonicalType().isConstQualified();
   }
 
-  /// \return Diagnostics piece for the member field not modified
-  /// in a given function.
-  std::shared_ptr notModifiedMemberDiagnostics(
+  std::shared_ptr notModifiedInConstructorDiagnostics(
   const LocationContext *Ctx,
   const SourceManager &SM,
   const PrintingPolicy &PP,
   CallExitBegin &CallExitLoc,
-  CallEventRef<> Call,
+  const CXXConstructorCall *Call,
   const MemRegion *ArgRegion) {
-const char *TopRegionName = isa(Call) ? "self" : "this";
 SmallString<256> sbuf;
 llvm::raw_svector_ostream os(sbuf);
 os << DiagnosticsMsg;
-bool out = prettyPrintRegionName(TopRegionName, "->", /*IsReference=*/true,
- /*IndirectionLevel=*/1, ArgRegion, os, 
PP);
+bool out = prettyPrintRegionName(
+"this", "->", /*IsReference=*/true,
+/*IndirectionLevel=*/1, ArgRegion, os, PP);
 
 // Return nothing if we have failed to pretty-print.
 if (!out)
@@ -464,16 +434,14

r337876 - [analyzer] Syntactic matcher for leaks associated with run loop and autoreleasepool

2018-07-24 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jul 24 18:27:15 2018
New Revision: 337876

URL: http://llvm.org/viewvc/llvm-project?rev=337876&view=rev
Log:
[analyzer] Syntactic matcher for leaks associated with run loop and 
autoreleasepool

A checker for detecting leaks resulting from allocating temporary
autoreleasing objects before starting the main run loop.

Checks for two antipatterns:

1. ObjCMessageExpr followed by [[NARunLoop mainRunLoop] run] in the same
autorelease pool.

2. ObjCMessageExpr followed by [[NARunLoop mainRunLoop] run] in no
autorelease pool.

Happens-before relationship is modeled purely syntactically.

rdar://39299145

Differential Revision: https://reviews.llvm.org/D49528

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
cfe/trunk/test/Analysis/Checkers/
cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
cfe/trunk/test/Analysis/Inputs/system-header-simulator-for-objc-dealloc.h

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=337876&r1=337875&r2=337876&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Tue Jul 24 
18:27:15 2018
@@ -568,6 +568,10 @@ def ObjCPropertyChecker : Checker<"ObjCP
 
 let ParentPackage = Cocoa in {
 
+def RunLoopAutoreleaseLeakChecker : Checker<"RunLoopAutoreleaseLeak">,
+  HelpText<"Check for leaked memory in autorelease pools that will never be 
drained">,
+  DescFile<"RunLoopAutoreleaseLeakChecker.cpp">;
+
 def ObjCAtSyncChecker : Checker<"AtSync">,
   HelpText<"Check for nil pointers used as mutexes for @synchronized">,
   DescFile<"ObjCAtSyncChecker.cpp">;

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=337876&r1=337875&r2=337876&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Tue Jul 24 18:27:15 
2018
@@ -79,6 +79,7 @@ add_clang_library(clangStaticAnalyzerChe
   RetainCountChecker.cpp
   ReturnPointerRangeChecker.cpp
   ReturnUndefChecker.cpp
+  RunLoopAutoreleaseLeakChecker.cpp
   SimpleStreamChecker.cpp
   StackAddrEscapeChecker.cpp
   StdLibraryFunctionsChecker.cpp

Added: cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp?rev=337876&view=auto
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp 
(added)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp Tue 
Jul 24 18:27:15 2018
@@ -0,0 +1,217 @@
+//=- RunLoopAutoreleaseLeakChecker.cpp --*- C++ -*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//
+//===--===//
+//
+// A checker for detecting leaks resulting from allocating temporary
+// autoreleased objects before starting the main run loop.
+//
+// Checks for two antipatterns:
+// 1. ObjCMessageExpr followed by [[NSRunLoop mainRunLoop] run] in the same
+// autorelease pool.
+// 2. ObjCMessageExpr followed by [[NSRunLoop mainRunLoop] run] in no
+// autorelease pool.
+//
+// Any temporary objects autoreleased in code called in those expressions
+// will not be deallocated until the program exits, and are effectively leaks.
+//
+//===--===//
+//
+
+#include "ClangSACheckers.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+
+using namespace clang;
+using namespace ento;
+using namespace ast_matchers;
+
+namespace {
+
+const char * RunLoopBind = "NSRunLoopM";
+const char * RunLoopRunBind = "RunLoopRunM";
+const char * OtherMsgBind = "OtherMessageSentM";
+const char *

r338137 - [ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's declaration.

2018-07-27 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul 27 10:26:11 2018
New Revision: 338137

URL: http://llvm.org/viewvc/llvm-project?rev=338137&view=rev
Log:
[ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's 
declaration.

ObjCIvarExpr is *not* a subclass of MemberExpr, and a separate matcher
is required to support it.
Adding a hasDeclaration support as well, as it's not very useful without
it.

Differential Revision: https://reviews.llvm.org/D49701

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h
cfe/trunk/lib/ASTMatchers/ASTMatchersInternal.cpp
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=338137&r1=338136&r2=338137&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Fri Jul 27 10:26:11 2018
@@ -1267,6 +1267,20 @@ Example matches @finally
 
 
 
+MatcherStmt>objcIvarRefExprMatcherObjCIvarRefExpr>...
+Matches a reference 
to an ObjCIvar.
+
+Example: matches "a" in "init" method:
+@implementation A {
+  NSString *a;
+}
+- (void) init {
+  a = @"hello";
+}
+}
+
+
+
 MatcherStmt>objcMessageExprMatcherObjCMessageExpr>...
 Matches ObjectiveC 
Message invocation expressions.
 
@@ -4251,6 +4265,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -4547,6 +4562,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -4750,6 +4766,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -4900,6 +4917,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -5061,6 +5079,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -5247,6 +5266,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -5667,6 +5687,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -5700,6 +5721,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration of the constructor
 - for CXXNewExpr, the declaration of the operator new
+- for ObjCIvarExpr, the declaration of the ivar
 
 For type nodes, hasDeclaration will generally match the declaration of the
 sugared type. Given
@@ -5733,6 +5755,7 @@ The associated declaration is:
 - for MemberExpr, the declaration of the referenced member
 - for CXXConstructExpr, the declaration

r338140 - [ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's declaration

2018-07-27 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul 27 10:40:59 2018
New Revision: 338140

URL: http://llvm.org/viewvc/llvm-project?rev=338140&view=rev
Log:
[ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's 
declaration

ObjCIvarExpr is *not* a subclass of MemberExpr, and a separate matcher
is required to support it.
Adding a hasDeclaration support as well, as it's not very useful without
it.

Differential Revision: https://reviews.llvm.org/D49701

Modified:
cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h?rev=338140&r1=338139&r2=338140&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchersInternal.h Fri Jul 27 
10:40:59 2018
@@ -41,6 +41,7 @@
 #include "clang/AST/DeclFriend.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/NestedNameSpecifier.h"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338149 - [analyzer] Extend NoStoreFuncVisitor to insert a note on IVars

2018-07-27 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul 27 11:26:40 2018
New Revision: 338149

URL: http://llvm.org/viewvc/llvm-project?rev=338149&view=rev
Log:
[analyzer] Extend NoStoreFuncVisitor to insert a note on IVars

The note is added in the following situation:

 - We are throwing a nullability-related warning on an IVar
 - The path goes through a method which *could have* (syntactically
   determined) written into that IVar, but did not

rdar://4260

Differential Revision: https://reviews.llvm.org/D49689

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.m

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=338149&r1=338148&r2=338149&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Fri Jul 27 
11:26:40 2018
@@ -22,6 +22,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -306,15 +307,26 @@ public:
 
 CallEventRef<> Call =
 BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
-
 const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
 const SourceManager &SM = BRC.getSourceManager();
+
+// Region of interest corresponds to an IVar, exiting a method
+// which could have written into that IVar, but did not.
+if (const auto *MC = dyn_cast(Call))
+  if (const auto *IvarR = dyn_cast(RegionOfInterest))
+if (potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
+  IvarR->getDecl()) &&
+!isRegionOfInterestModifiedInFrame(N))
+  return notModifiedMemberDiagnostics(
+  Ctx, SM, PP, *CallExitLoc, Call,
+  MC->getReceiverSVal().getAsRegion());
+
 if (const auto *CCall = dyn_cast(Call)) {
   const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
   if (RegionOfInterest->isSubRegionOf(ThisRegion)
   && !CCall->getDecl()->isImplicit()
   && !isRegionOfInterestModifiedInFrame(N))
-return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
+return notModifiedMemberDiagnostics(Ctx, SM, PP, *CallExitLoc,
CCall, ThisRegion);
 }
 
@@ -331,7 +343,7 @@ public:
   if (isRegionOfInterestModifiedInFrame(N))
 return nullptr;
 
-  return notModifiedDiagnostics(
+  return notModifiedParameterDiagnostics(
   Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
 }
 QualType PT = T->getPointeeType();
@@ -346,6 +358,22 @@ public:
   }
 
 private:
+
+  /// \return Whether the method declaration \p Parent
+  /// syntactically has a binary operation writing into the ivar \p Ivar.
+  bool potentiallyWritesIntoIvar(const Decl *Parent,
+ const ObjCIvarDecl *Ivar) {
+using namespace ast_matchers;
+if (!Parent || !Parent->getBody())
+  return false;
+StatementMatcher WriteIntoIvarM = binaryOperator(
+hasOperatorName("="), hasLHS(ignoringParenImpCasts(objcIvarRefExpr(
+  hasDeclaration(equalsNode(Ivar));
+StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
+auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
+return !Matches.empty();
+  }
+
   /// Check and lazily calculate whether the region of interest is
   /// modified in the stack frame to which \p N belongs.
   /// The calculation is cached in FramesModifyingRegion.
@@ -414,19 +442,21 @@ private:
Ty->getPointeeType().getCanonicalType().isConstQualified();
   }
 
-  std::shared_ptr notModifiedInConstructorDiagnostics(
+  /// \return Diagnostics piece for the member field not modified
+  /// in a given function.
+  std::shared_ptr notModifiedMemberDiagnostics(
   const LocationContext *Ctx,
   const SourceManager &SM,
   const PrintingPolicy &PP,
   CallExitBegin &CallExitLoc,
-  const CXXConstructorCall *Call,
+  CallEventRef<> Call,
   const MemRegion *ArgRegion) {
+const char *TopRegionName = isa(Call) ? "self" : "this";
 SmallString<256> sbuf;
 llvm::raw_svector_ostream os(sbuf);
 os << DiagnosticsMsg;
-bool out = prettyPrintRegionName(
-"this", "->", /*IsReference=*/true,
-/*IndirectionLevel=*/1, ArgRegion, os, PP);
+bool out = prettyPrintRegionName(TopRegionName, "->", 

r338187 - [AST] Add a convenient getter from QualType to RecordDecl

2018-07-27 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul 27 19:16:13 2018
New Revision: 338187

URL: http://llvm.org/viewvc/llvm-project?rev=338187&view=rev
Log:
[AST] Add a convenient getter from QualType to RecordDecl

Differential Revision: https://reviews.llvm.org/D49951

Modified:
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/Type.cpp
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/lib/CodeGen/CGExprConstant.cpp
cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/include/clang/AST/Type.h (original)
+++ cfe/trunk/include/clang/AST/Type.h Fri Jul 27 19:16:13 2018
@@ -2017,6 +2017,9 @@ public:
   /// type of a class template or class template partial specialization.
   CXXRecordDecl *getAsCXXRecordDecl() const;
 
+  /// Retrieves the RecordDecl this type refers to.
+  RecordDecl *getAsRecordDecl() const;
+
   /// Retrieves the TagDecl that this type refers to, either
   /// because the type is a TagType or because it is the injected-class-name
   /// type of a class template or class template partial specialization.

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Fri Jul 27 19:16:13 2018
@@ -3149,12 +3149,9 @@ SourceRange FunctionDecl::getExceptionSp
 
 const Attr *FunctionDecl::getUnusedResultAttr() const {
   QualType RetType = getReturnType();
-  if (RetType->isRecordType()) {
-if (const auto *Ret =
-dyn_cast_or_null(RetType->getAsTagDecl())) {
-  if (const auto *R = Ret->getAttr())
-return R;
-}
+  if (const auto *Ret = RetType->getAsRecordDecl()) {
+if (const auto *R = Ret->getAttr())
+  return R;
   } else if (const auto *ET = RetType->getAs()) {
 if (const EnumDecl *ED = ET->getDecl()) {
   if (const auto *R = ED->getAttr())

Modified: cfe/trunk/lib/AST/Type.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Type.cpp?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/lib/AST/Type.cpp (original)
+++ cfe/trunk/lib/AST/Type.cpp Fri Jul 27 19:16:13 2018
@@ -1628,6 +1628,10 @@ CXXRecordDecl *Type::getAsCXXRecordDecl(
   return dyn_cast_or_null(getAsTagDecl());
 }
 
+RecordDecl *Type::getAsRecordDecl() const {
+  return dyn_cast_or_null(getAsTagDecl());
+}
+
 TagDecl *Type::getAsTagDecl() const {
   if (const auto *TT = getAs())
 return TT->getDecl();

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Fri Jul 27 19:16:13 2018
@@ -342,7 +342,7 @@ static Stmt *create_call_once(ASTContext
   // Nullable pointer, non-null iff function is a CXXRecordDecl.
   CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
   QualType FlagType = Flag->getType().getNonReferenceType();
-  auto *FlagRecordDecl = 
dyn_cast_or_null(FlagType->getAsTagDecl());
+  auto *FlagRecordDecl = FlagType->getAsRecordDecl();
 
   if (!FlagRecordDecl) {
 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "

Modified: cfe/trunk/lib/CodeGen/CGExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprConstant.cpp?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExprConstant.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprConstant.cpp Fri Jul 27 19:16:13 2018
@@ -2064,8 +2064,7 @@ static llvm::Constant *EmitNullConstant(
 if (record->isUnion()) {
   if (Field->getIdentifier())
 break;
-  if (const auto *FieldRD =
-  dyn_cast_or_null(Field->getType()->getAsTagDecl()))
+  if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
 if (FieldRD->findFirstNamedDataMember())
   break;
 }

Modified: cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp?rev=338187&r1=338186&r2=338187&view=diff
==
--- cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGRecordLayoutBuilder.cpp Fri Jul 27 19:16:13 2018
@@ -313,9 +313,8 @@ void CGRecordLowering::lowerUnion() {
 if (!SeenNamedMember) {
   

r338286 - [analyzer] Store ValueDecl in DeclRegion

2018-07-30 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Jul 30 11:57:13 2018
New Revision: 338286

URL: http://llvm.org/viewvc/llvm-project?rev=338286&view=rev
Log:
[analyzer] Store ValueDecl in DeclRegion

All use cases of DeclRegion actually have ValueDecl there,
and getting the name from declaration comes in very handy.

Differential Revision: https://reviews.llvm.org/D49998

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h?rev=338286&r1=338285&r2=338286&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h Mon 
Jul 30 11:57:13 2018
@@ -897,9 +897,9 @@ public:
 
 class DeclRegion : public TypedValueRegion {
 protected:
-  const Decl *D;
+  const ValueDecl *D;
 
-  DeclRegion(const Decl *d, const MemRegion *sReg, Kind k)
+  DeclRegion(const ValueDecl *d, const MemRegion *sReg, Kind k)
   : TypedValueRegion(sReg, k), D(d) {
 assert(classof(this));
 assert(d);
@@ -909,7 +909,7 @@ protected:
   const MemRegion* superRegion, Kind k);
 
 public:
-  const Decl *getDecl() const { return D; }
+  const ValueDecl *getDecl() const { return D; }
   void Profile(llvm::FoldingSetNodeID& ID) const override;
 
   static bool classof(const MemRegion* R) {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338312 - [analyzer] Fix crash in RunLoopAutoreleaseChecker on empty children

2018-07-30 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Mon Jul 30 14:44:15 2018
New Revision: 338312

URL: http://llvm.org/viewvc/llvm-project?rev=338312&view=rev
Log:
[analyzer] Fix crash in RunLoopAutoreleaseChecker on empty children

Differential Revision: https://reviews.llvm.org/D50012

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp?rev=338312&r1=338311&r2=338312&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RunLoopAutoreleaseLeakChecker.cpp Mon 
Jul 30 14:44:15 2018
@@ -46,8 +46,7 @@ const char * RunLoopRunBind = "RunLoopRu
 const char * OtherMsgBind = "OtherMessageSentM";
 const char * AutoreleasePoolBind = "AutoreleasePoolM";
 
-class RunLoopAutoreleaseLeakChecker : public Checker<
-  check::ASTCodeBody> {
+class RunLoopAutoreleaseLeakChecker : public Checker {
 
 public:
   void checkASTCodeBody(const Decl *D,
@@ -66,6 +65,8 @@ static TriBoolTy
 seenBeforeRec(const Stmt *Parent, const Stmt *A, const Stmt *B,
   MemoizationMapTy &Memoization) {
   for (const Stmt *C : Parent->children()) {
+if (!C) continue;
+
 if (C == A)
   return true;
 

Modified: cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m?rev=338312&r1=338311&r2=338312&view=diff
==
--- cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m (original)
+++ cfe/trunk/test/Analysis/Checkers/RunLoopAutoreleaseLeakChecker.m Mon Jul 30 
14:44:15 2018
@@ -43,7 +43,7 @@ void runloop_init_before_two_objects() {
 NSObject *object2 = [[NSObject alloc] init]; // no-warning, warning on the 
first one is enough.
 (void) object;
 (void) object2;
-[[NSRunLoop mainRunLoop] run]; 
+[[NSRunLoop mainRunLoop] run];
   }
 }
 
@@ -60,6 +60,15 @@ void runloop_init_after() { // No warnin
 (void) object;
   }
 }
+
+void no_crash_on_empty_children() {
+  @autoreleasepool {
+for (;;) {}
+NSObject *object = [[NSObject alloc] init]; // expected-warning{{Temporary 
objects allocated in the autorelease pool followed by the launch of main run 
loop may never get released; consider moving them to a separate autorelease 
pool}}
+[[NSRunLoop mainRunLoop] run];
+(void) object;
+  }
+}
 
 #endif
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   >