[clang] dd6738d - [clang][Lifetimes] Fix false positive warning from BUG 49342

2021-02-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2021-02-27T08:09:57-08:00
New Revision: dd6738d93de148f2239ef5be82a61cf8f5f71124

URL: 
https://github.com/llvm/llvm-project/commit/dd6738d93de148f2239ef5be82a61cf8f5f71124
DIFF: 
https://github.com/llvm/llvm-project/commit/dd6738d93de148f2239ef5be82a61cf8f5f71124.diff

LOG: [clang][Lifetimes] Fix false positive warning from BUG 49342

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

Added: 


Modified: 
clang/lib/Sema/SemaInit.cpp
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index c1a2be744853..f387e9a33708 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@ static bool 
pathOnlyInitializesGslPointer(IndirectLocalPath ) {
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }

diff  --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 3319d5aa2db8..b3ca173c1fdb 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@ struct basic_string_view {
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@ std::vector::iterator 
noFalsePositiveWithVectorOfPointers() {
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}



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


[clang] 643dee9 - [analyzer] Move fuchsia.Lock checker to alpha

2020-02-05 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-02-05T16:11:06-08:00
New Revision: 643dee903cebdfc5e0101d305add6a5235211465

URL: 
https://github.com/llvm/llvm-project/commit/643dee903cebdfc5e0101d305add6a5235211465
DIFF: 
https://github.com/llvm/llvm-project/commit/643dee903cebdfc5e0101d305add6a5235211465.diff

LOG: [analyzer] Move fuchsia.Lock checker to alpha

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
clang/test/Analysis/fuchsia_lock.c
clang/test/Analysis/fuchsia_lock_impl.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 50610de6843e..76cf92af9113 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -109,6 +109,7 @@ def CloneDetectionAlpha : Package<"clone">, 
ParentPackage;
 def NonDeterminismAlpha : Package<"nondeterminism">, ParentPackage;
 
 def Fuchsia : Package<"fuchsia">;
+def FuchsiaAlpha : Package<"fuchsia">, ParentPackage;
 
 
//===--===//
 // Core Checkers.
@@ -1477,6 +1478,10 @@ def FuchsiaHandleChecker : Checker<"HandleChecker">,
   HelpText<"A Checker that detect leaks related to Fuchsia handles">,
   Documentation;
 
+}
+
+let ParentPackage = FuchsiaAlpha in {
+
 def FuchsiaLockChecker : Checker<"Lock">,
   HelpText<"Check for the correct usage of locking APIs.">,
   Dependencies<[PthreadLockBase]>,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
index 0bfe3b890e94..b89e1671cfad 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -13,6 +13,8 @@
 //  * FuchsiaLocksChecker, which is also rather similar.
 //  * C11LockChecker which also closely follows Pthread semantics.
 //
+//  TODO: Path notes.
+//
 
//===--===//
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"

diff  --git a/clang/test/Analysis/fuchsia_lock.c 
b/clang/test/Analysis/fuchsia_lock.c
index 9f2a7ec09fa3..944220f89f2b 100644
--- a/clang/test/Analysis/fuchsia_lock.c
+++ b/clang/test/Analysis/fuchsia_lock.c
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=fuchsia.Lock -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.fuchsia.Lock -verify %s
 
 typedef int spin_lock_t;
 typedef int zx_status_t;

diff  --git a/clang/test/Analysis/fuchsia_lock_impl.c 
b/clang/test/Analysis/fuchsia_lock_impl.c
index e4c5ea501c3a..03b4a6390a69 100644
--- a/clang/test/Analysis/fuchsia_lock_impl.c
+++ b/clang/test/Analysis/fuchsia_lock_impl.c
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=fuchsia.Lock -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.fuchsia.Lock -verify %s
 // expected-no-diagnostics
 typedef int spin_lock_t;
 



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


[clang] e4f4a6c - [analyzer] Prevent an assertion failure in PThreadLockChecker

2020-02-05 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-02-05T15:56:56-08:00
New Revision: e4f4a6c0f5bbda5dc0b922816b3fdfce4b75f404

URL: 
https://github.com/llvm/llvm-project/commit/e4f4a6c0f5bbda5dc0b922816b3fdfce4b75f404
DIFF: 
https://github.com/llvm/llvm-project/commit/e4f4a6c0f5bbda5dc0b922816b3fdfce4b75f404.diff

LOG: [analyzer] Prevent an assertion failure in PThreadLockChecker

When the implementations of the locking functions are available.

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

Added: 
clang/test/Analysis/fuchsia_lock_impl.c

Modified: 
clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
index d3470dad0a43..0bfe3b890e94 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -256,7 +256,9 @@ void PthreadLockChecker::checkPostCall(const CallEvent 
,
   // are global C functions.
   // TODO: Maybe make this the default behavior of CallDescription
   // with exactly one identifier?
-  if (!Call.isGlobalCFunction())
+  // FIXME: Try to handle cases when the implementation was inlined rather
+  // than just giving up.
+  if (!Call.isGlobalCFunction() || C.wasInlined)
 return;
 
   if (const FnCheck *Callback = PThreadCallbacks.lookup(Call))

diff  --git a/clang/test/Analysis/fuchsia_lock_impl.c 
b/clang/test/Analysis/fuchsia_lock_impl.c
new file mode 100644
index ..e4c5ea501c3a
--- /dev/null
+++ b/clang/test/Analysis/fuchsia_lock_impl.c
@@ -0,0 +1,18 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=fuchsia.Lock -verify %s
+// expected-no-diagnostics
+typedef int spin_lock_t;
+
+void spin_lock(spin_lock_t *lock);
+int getCond();
+int spin_trylock(spin_lock_t *lock) {
+if (getCond())
+return 0;
+return -1;
+}
+void spin_unlock(spin_lock_t *lock);
+
+spin_lock_t mtx;
+void no_crash() {
+  if (spin_trylock() == 0)
+spin_unlock();
+}



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


[clang] f4c26d9 - [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-27T13:55:56-08:00
New Revision: f4c26d993bdcb8e5250d774c0d2a6d91fee5ca00

URL: 
https://github.com/llvm/llvm-project/commit/f4c26d993bdcb8e5250d774c0d2a6d91fee5ca00
DIFF: 
https://github.com/llvm/llvm-project/commit/f4c26d993bdcb8e5250d774c0d2a6d91fee5ca00.diff

LOG: [analyzer] Add FuchsiaLockChecker and C11LockChecker

These are mostly trivial additions as both of them are reusing existing
PThreadLockChecker logic. I only needed to add the list of functions to
check and do some plumbing to make sure that we display the right
checker name in the diagnostic.

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

Added: 
clang/test/Analysis/c11lock.c
clang/test/Analysis/fuchsia_lock.c

Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index fc1529f2ea1c..83d78e4f8994 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -227,6 +227,16 @@ def StackAddrAsyncEscapeChecker : 
Checker<"StackAddressAsyncEscape">,
   Dependencies<[StackAddrEscapeBase]>,
   Documentation;
 
+def PthreadLockBase : Checker<"PthreadLockBase">,
+  HelpText<"Helper registering multiple checks.">,
+  Documentation,
+  Hidden;
+
+def C11LockChecker : Checker<"C11Lock">,
+  HelpText<"Simple lock -> unlock checker">,
+  Dependencies<[PthreadLockBase]>,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
@@ -431,6 +441,7 @@ def ChrootChecker : Checker<"Chroot">,
 
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
+  Dependencies<[PthreadLockBase]>,
   Documentation;
 
 def StreamChecker : Checker<"Stream">,
@@ -1442,5 +1453,10 @@ def FuchsiaHandleChecker : Checker<"HandleChecker">,
   HelpText<"A Checker that detect leaks related to Fuchsia handles">,
   Documentation;
 
+def FuchsiaLockChecker : Checker<"Lock">,
+  HelpText<"Check for the correct usage of locking APIs.">,
+  Dependencies<[PthreadLockBase]>,
+  Documentation;
+
 } // end fuchsia
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
index ed0fc0f98c2c..d3470dad0a43 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -6,8 +6,12 @@
 //
 
//===--===//
 //
-// This defines PthreadLockChecker, a simple lock -> unlock checker.
-// Also handles XNU locks, which behave similarly enough to share code.
+// This file defines:
+//  * PthreadLockChecker, a simple lock -> unlock checker.
+//Which also checks for XNU locks, which behave similarly enough to share
+//code.
+//  * FuchsiaLocksChecker, which is also rather similar.
+//  * C11LockChecker which also closely follows Pthread semantics.
 //
 
//===--===//
 
@@ -15,8 +19,8 @@
 #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/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 
 using namespace clang;
 using namespace ento;
@@ -46,9 +50,7 @@ struct LockState {
 return LockState(UnlockedAndPossiblyDestroyed);
   }
 
-  bool operator==(const LockState ) const {
-return K == X.K;
-  }
+  bool operator==(const LockState ) const { return K == X.K; }
 
   bool isLocked() const { return K == Locked; }
   bool isUnlocked() const { return K == Unlocked; }
@@ -60,98 +62,149 @@ struct LockState {
 return K == UnlockedAndPossiblyDestroyed;
   }
 
-  void Profile(llvm::FoldingSetNodeID ) const {
-ID.AddInteger(K);
-  }
+  void Profile(llvm::FoldingSetNodeID ) const { ID.AddInteger(K); }
 };
 
-class PthreadLockChecker
-: public Checker {
-  BugType BT_doublelock{this, "Double locking", "Lock checker"},
-  BT_doubleunlock{this, "Double unlocking", "Lock checker"},
-  BT_destroylock{this, "Use destroyed lock", "Lock checker"},
-  BT_initlock{this, "Init invalid lock", "Lock checker"},
-  BT_lor{this, "Lock order reversal", "Lock checker"};
-
-  enum LockingSemantics {
-NotApplicable = 0,
-PthreadSemantics,
-XNUSemantics
+class PthreadLockChecker : public Checker {
+public:
+  enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics };
+  enum CheckerKind {
+

[clang] c98d98b - [analyzer] Fix handle leak false positive when the handle dies too early

2020-01-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-27T09:52:06-08:00
New Revision: c98d98ba9b0f917385c753becec4ddfef51bc47c

URL: 
https://github.com/llvm/llvm-project/commit/c98d98ba9b0f917385c753becec4ddfef51bc47c
DIFF: 
https://github.com/llvm/llvm-project/commit/c98d98ba9b0f917385c753becec4ddfef51bc47c.diff

LOG: [analyzer] Fix handle leak false positive when the handle dies too early

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
clang/test/Analysis/fuchsia_handle.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
index 36d4f489214e..3a56a941ff31 100644
--- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -149,6 +149,10 @@ class HandleState {
   CASE(Kind::Released)
   CASE(Kind::Escaped)
 }
+if (ErrorSym) {
+  OS << " ErrorSym: ";
+  ErrorSym->dumpToStream(OS);
+}
   }
 
   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
@@ -401,7 +405,13 @@ void FuchsiaHandleChecker::checkDeadSymbols(SymbolReaper 
,
   SmallVector LeakedSyms;
   HStateMapTy TrackedHandles = State->get();
   for (auto  : TrackedHandles) {
-if (!SymReaper.isDead(CurItem.first))
+SymbolRef ErrorSym = CurItem.second.getErrorSym();
+// Keeping zombie handle symbols. In case the error symbol is dying later
+// than the handle symbol we might produce spurious leak warnings (in case
+// we find out later from the status code that the handle allocation failed
+// in the first place).
+if (!SymReaper.isDead(CurItem.first) ||
+(ErrorSym && !SymReaper.isDead(ErrorSym)))
   continue;
 if (CurItem.second.isAllocated() || CurItem.second.maybeAllocated())
   LeakedSyms.push_back(CurItem.first);

diff  --git a/clang/test/Analysis/fuchsia_handle.cpp 
b/clang/test/Analysis/fuchsia_handle.cpp
index ed8b695a1915..c20622be543f 100644
--- a/clang/test/Analysis/fuchsia_handle.cpp
+++ b/clang/test/Analysis/fuchsia_handle.cpp
@@ -66,6 +66,26 @@ void checkInvalidHandle2() {
 zx_handle_close(sa);
 }
 
+void handleDieBeforeErrorSymbol01() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, , );
+  if (status < 0)
+return;
+  __builtin_trap();
+}
+
+void handleDieBeforeErrorSymbol02() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, , );
+  // expected-note@-1 {{Handle allocated through 2nd parameter}}
+  if (status == 0) { // expected-note {{Assuming 'status' is equal to 0}}
+ // expected-note@-1 {{Taking true branch}}
+return; // expected-warning {{Potential leak of handle}}
+// expected-note@-1 {{Potential leak of handle}}
+  }
+  __builtin_trap();
+}
+
 void checkNoCrash01() {
   zx_handle_t sa, sb;
   zx_channel_create(0, , );



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


[clang] 5911268 - [analyzer] Improve FuchsiaHandleChecker's diagnostic messages

2020-01-23 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-23T09:16:40-08:00
New Revision: 5911268e441cc78f7c81f931dd64ed2c63078e8e

URL: 
https://github.com/llvm/llvm-project/commit/5911268e441cc78f7c81f931dd64ed2c63078e8e
DIFF: 
https://github.com/llvm/llvm-project/commit/5911268e441cc78f7c81f931dd64ed2c63078e8e.diff

LOG: [analyzer] Improve FuchsiaHandleChecker's diagnostic messages

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
clang/test/Analysis/fuchsia_handle.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
index 3c04983df443..36d4f489214e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -314,6 +314,17 @@ void FuchsiaHandleChecker::checkPostCall(const CallEvent 
,
   // Function returns an open handle.
   if (hasFuchsiaAttr(FuncDecl)) {
 SymbolRef RetSym = Call.getReturnValue().getAsSymbol();
+Notes.push_back([RetSym, FuncDecl](BugReport ) -> std::string {
+  auto *PathBR = static_cast();
+  if (auto IsInteresting = PathBR->getInterestingnessKind(RetSym)) {
+std::string SBuf;
+llvm::raw_string_ostream OS(SBuf);
+OS << "Function '" << FuncDecl->getNameAsString()
+   << "' returns an open handle";
+return OS.str();
+  } else
+return "";
+});
 State =
 State->set(RetSym, HandleState::getMaybeAllocated(nullptr));
   }
@@ -322,6 +333,7 @@ void FuchsiaHandleChecker::checkPostCall(const CallEvent 
,
 if (Arg >= FuncDecl->getNumParams())
   break;
 const ParmVarDecl *PVD = FuncDecl->getParamDecl(Arg);
+unsigned ParamDiagIdx = PVD->getFunctionScopeIndex() + 1;
 SymbolRef Handle =
 getFuchsiaHandleSymbol(PVD->getType(), Call.getArgSVal(Arg), State);
 if (!Handle)
@@ -335,20 +347,28 @@ void FuchsiaHandleChecker::checkPostCall(const CallEvent 
,
 reportDoubleRelease(Handle, Call.getArgSourceRange(Arg), C);
 return;
   } else {
-Notes.push_back([Handle](BugReport ) {
+Notes.push_back([Handle, ParamDiagIdx](BugReport ) -> std::string {
   auto *PathBR = static_cast();
   if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
-return "Handle released here.";
+std::string SBuf;
+llvm::raw_string_ostream OS(SBuf);
+OS << "Handle released through " << ParamDiagIdx
+   << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
+return OS.str();
   } else
 return "";
 });
 State = State->set(Handle, HandleState::getReleased());
   }
 } else if (hasFuchsiaAttr(PVD)) {
-  Notes.push_back([Handle](BugReport ) {
+  Notes.push_back([Handle, ParamDiagIdx](BugReport ) -> std::string {
 auto *PathBR = static_cast();
 if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
-  return "Handle allocated here.";
+  std::string SBuf;
+  llvm::raw_string_ostream OS(SBuf);
+  OS << "Handle allocated through " << ParamDiagIdx
+ << llvm::getOrdinalSuffix(ParamDiagIdx) << " parameter";
+  return OS.str();
 } else
   return "";
   });

diff  --git a/clang/test/Analysis/fuchsia_handle.cpp 
b/clang/test/Analysis/fuchsia_handle.cpp
index 0543eb92d01f..ed8b695a1915 100644
--- a/clang/test/Analysis/fuchsia_handle.cpp
+++ b/clang/test/Analysis/fuchsia_handle.cpp
@@ -26,6 +26,9 @@ zx_status_t zx_channel_create(
 zx_status_t zx_handle_close(
 zx_handle_t handle ZX_HANDLE_RELEASE);
 
+ZX_HANDLE_ACQUIRE
+zx_handle_t return_handle();
+
 void escape1(zx_handle_t *in);
 void escape2(zx_handle_t in);
 void (*escape3)(zx_handle_t) = escape2; 
@@ -117,7 +120,7 @@ void checkNoLeak06() {
 
 void checkLeak01(int tag) {
   zx_handle_t sa, sb;
-  if (zx_channel_create(0, , )) // expected-note{{Handle allocated 
here}}
+  if (zx_channel_create(0, , )) // expected-note{{Handle allocated 
through 2nd parameter}}
 return;   // expected-note@-1 {{Assuming the 
condition is false}}
   // expected-note@-2 {{Taking false 
branch}}
   use1();
@@ -129,9 +132,15 @@ void checkLeak01(int tag) {
   zx_handle_close(sb);
 }
 
+void checkLeakFromReturn01(int tag) {
+  zx_handle_t sa = return_handle(); // expected-note {{Function 
'return_handle' returns an open handle}}
+  (void)sa;
+} // expected-note {{Potential leak of handle}}
+  // expected-warning@-1 {{Potential leak of handle}}
+
 void checkReportLeakOnOnePath(int tag) {
   zx_handle_t sa, sb;
-  if (zx_channel_create(0, , )) // expected-note {{Handle allocated 
here}}
+  if (zx_channel_create(0, 

[clang] 05c7dc6 - [DataFlow] Factor two worklist implementations out

2020-01-17 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-17T08:11:15-08:00
New Revision: 05c7dc66480999574a599ac34d99a4c192d51ba7

URL: 
https://github.com/llvm/llvm-project/commit/05c7dc66480999574a599ac34d99a4c192d51ba7
DIFF: 
https://github.com/llvm/llvm-project/commit/05c7dc66480999574a599ac34d99a4c192d51ba7.diff

LOG: [DataFlow] Factor two worklist implementations out

Right now every dataflow algorithm uses its own worklist implementation.
This is a first step to reduce this duplication. Some upcoming
algorithms such as the lifetime analysis is going to use the factored
out implementations.

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

Added: 
clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h

Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
clang/lib/Analysis/LiveVariables.cpp
clang/lib/Analysis/UninitializedValues.cpp
clang/unittests/Analysis/CFGBuildResult.h
clang/unittests/Analysis/CFGTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
index 709753339eb5..68d935c6a400 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
@@ -168,4 +168,4 @@ class DataflowValues {
 };
 
 } // end namespace clang
-#endif
+#endif // LLVM_CLANG_ANALYSES_DATAFLOW_VALUES

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
new file mode 100644
index ..90095735ad3d
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowWorklist.h
@@ -0,0 +1,94 @@
+//===- DataflowWorklist.h ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// A simple and reusable worklist for flow-sensitive analyses.
+//
+//===--===//
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWWORKLIST_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWWORKLIST_H
+
+#include "clang/Analysis/Analyses/PostOrderCFGView.h"
+#include "clang/Analysis/CFG.h"
+#include "llvm/ADT/PriorityQueue.h"
+
+namespace clang {
+/// A worklist implementation where the enqueued blocks will be dequeued based
+/// on the order defined by 'Comp'.
+template  class DataflowWorklistBase {
+  llvm::BitVector EnqueuedBlocks;
+  PostOrderCFGView *POV;
+  llvm::PriorityQueue, Comp>
+  WorkList;
+
+public:
+  DataflowWorklistBase(const CFG , PostOrderCFGView *POV, Comp C)
+  : EnqueuedBlocks(Cfg.getNumBlockIDs()), POV(POV), WorkList(C) {}
+
+  const PostOrderCFGView *getCFGView() const { return POV; }
+
+  void enqueueBlock(const CFGBlock *Block) {
+if (Block && !EnqueuedBlocks[Block->getBlockID()]) {
+  EnqueuedBlocks[Block->getBlockID()] = true;
+  WorkList.push(Block);
+}
+  }
+
+  const CFGBlock *dequeue() {
+if (WorkList.empty())
+  return nullptr;
+const CFGBlock *B = WorkList.top();
+WorkList.pop();
+EnqueuedBlocks[B->getBlockID()] = false;
+return B;
+  }
+};
+
+struct ReversePostOrderCompare {
+  PostOrderCFGView::BlockOrderCompare Cmp;
+  bool operator()(const CFGBlock *lhs, const CFGBlock *rhs) const {
+return Cmp(rhs, lhs);
+  }
+};
+
+/// A worklist implementation for forward dataflow analysis. The enqueued
+/// blocks will be dequeued in reverse post order. The worklist cannot contain
+/// the same block multiple times at once.
+struct ForwardDataflowWorklist
+: DataflowWorklistBase {
+  ForwardDataflowWorklist(const CFG , AnalysisDeclContext )
+  : DataflowWorklistBase(
+Cfg, Ctx.getAnalysis(),
+ReversePostOrderCompare{
+Ctx.getAnalysis()->getComparator()}) {}
+
+  void enqueueSuccessors(const CFGBlock *Block) {
+for (auto B : Block->succs())
+  enqueueBlock(B);
+  }
+};
+
+/// A worklist implementation for backward dataflow analysis. The enqueued
+/// block will be dequeued in post order. The worklist cannot contain the same
+/// block multiple times at once.
+struct BackwardDataflowWorklist
+: DataflowWorklistBase {
+  BackwardDataflowWorklist(const CFG , AnalysisDeclContext )
+  : DataflowWorklistBase(
+Cfg, Ctx.getAnalysis(),
+Ctx.getAnalysis()->getComparator()) {}
+
+  void enqueuePredecessors(const CFGBlock *Block) {
+for (auto B : Block->preds())
+  enqueueBlock(B);
+  }
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_ANALYSES_CONSUMED_H

diff  --git a/clang/lib/Analysis/LiveVariables.cpp 

[clang] b2fb6a7 - [NFC] Whitespace fixes

2020-01-08 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-08T16:41:18-08:00
New Revision: b2fb6a7ba118f651cc76580ecb48eb5f877920aa

URL: 
https://github.com/llvm/llvm-project/commit/b2fb6a7ba118f651cc76580ecb48eb5f877920aa
DIFF: 
https://github.com/llvm/llvm-project/commit/b2fb6a7ba118f651cc76580ecb48eb5f877920aa.diff

LOG: [NFC] Whitespace fixes

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index d9ca121b6510..c992d6459f0c 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -178,8 +178,8 @@ class FunctionArgument : Argument;
 class NamedArgument : Argument;
+   opt,
+   fake>;
 class TypeArgument : Argument;
 class UnsignedArgument : Argument;
 class VariadicUnsignedArgument : Argument;

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 515476df3fdd..70bf2517cdcb 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4378,7 +4378,7 @@ below. The explicit attribute annotation indicates that 
the third parameter
 (`start_routine`) is called zero or more times by the `pthread_create` 
function,
 and that the fourth parameter (`arg`) is passed along. Note that the callback
 behavior of `pthread_create` is automatically recognized by Clang. In addition,
-the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for 
+the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
 `#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
 automatically recognized as broker functions. Further functions might be added
 in the future.



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


[clang] 46ac6a4 - [analyzer] Update help text to reflect sarif support

2020-01-07 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-07T08:37:49-08:00
New Revision: 46ac6a4dcd9b629188b75fafbe04008c24d1fb55

URL: 
https://github.com/llvm/llvm-project/commit/46ac6a4dcd9b629188b75fafbe04008c24d1fb55
DIFF: 
https://github.com/llvm/llvm-project/commit/46ac6a4dcd9b629188b75fafbe04008c24d1fb55.diff

LOG: [analyzer] Update help text to reflect sarif support

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index e48817931efd..33b331fd8777 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2862,7 +2862,7 @@ def _CLASSPATH : Separate<["--"], "CLASSPATH">, 
Alias;
 def _all_warnings : Flag<["--"], "all-warnings">, Alias;
 def _analyzer_no_default_checks : Flag<["--"], "analyzer-no-default-checks">, 
Flags<[DriverOption]>;
 def _analyzer_output : JoinedOrSeparate<["--"], "analyzer-output">, 
Flags<[DriverOption]>,
-  HelpText<"Static analyzer report output format 
(html|plist|plist-multi-file|plist-html|text).">;
+  HelpText<"Static analyzer report output format 
(html|plist|plist-multi-file|plist-html|sarif|text).">;
 def _analyze : Flag<["--"], "analyze">, Flags<[DriverOption, CoreOption]>,
   HelpText<"Run the static analyzer">;
 def _assemble : Flag<["--"], "assemble">, Alias;



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


[clang] 247a603 - [LifetimeAnalysis] Do not forbid void deref type in gsl::Pointer/gsl::Owner annotations

2020-01-07 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-07T08:32:40-08:00
New Revision: 247a6032549efb03c14b79c035a47c660b75263e

URL: 
https://github.com/llvm/llvm-project/commit/247a6032549efb03c14b79c035a47c660b75263e
DIFF: 
https://github.com/llvm/llvm-project/commit/247a6032549efb03c14b79c035a47c660b75263e.diff

LOG: [LifetimeAnalysis] Do not forbid void deref type in 
gsl::Pointer/gsl::Owner annotations

It turns out it is useful to be able to define the deref type as void.
In case we have a type erased owner, we want to express that the pointee
can be basically any type. It should not be unnatural to have a void
deref type as we already familiar with "pointers to void".

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

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/SemaCXX/attr-gsl-owner-pointer.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 9b4afa8f128e..515476df3fdd 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4590,7 +4590,7 @@ object of type ``T``:
 
 The argument ``T`` is optional and is ignored.
 This attribute may be used by analysis tools and has no effect on code
-generation.
+generation. A ``void`` argument means that the class can own any type.
 
 See Pointer_ for an example.
 }];
@@ -4616,7 +4616,7 @@ like pointers to an object of type ``T``:
 
 The argument ``T`` is optional and is ignored.
 This attribute may be used by analysis tools and has no effect on code
-generation.
+generation. A ``void`` argument means that the pointer can point to any type.
 
 Example:
 When constructing an instance of a class annotated like this (a Pointer) from

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a8f49fef9f1f..dd9649bcb5c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2631,7 +2631,7 @@ def err_nsobject_attribute : Error<
 def err_attributes_are_not_compatible : Error<
   "%0 and %1 attributes are not compatible">;
 def err_attribute_invalid_argument : Error<
-  "%select{'void'|a reference type|an array type|a non-vector or "
+  "%select{a reference type|an array type|a non-vector or "
   "non-vectorizable scalar type}0 is an invalid argument to attribute %1">;
 def err_attribute_wrong_number_arguments : Error<
   "%0 attribute %plural{0:takes no arguments|1:takes one argument|"

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 50951ad60228..02aebbea4a8b 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2913,7 +2913,7 @@ static void handleVecTypeHint(Sema , Decl *D, const 
ParsedAttr ) {
   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
   (ParmType->isBooleanType() ||
!ParmType->isIntegralType(S.getASTContext( {
-S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 3 << AL;
+S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
 return;
   }
 
@@ -4454,12 +4454,10 @@ static void handleLifetimeCategoryAttr(Sema , Decl 
*D, const ParsedAttr ) {
 ParmType = S.GetTypeFromParser(AL.getTypeArg(), );
 
 unsigned SelectIdx = ~0U;
-if (ParmType->isVoidType())
+if (ParmType->isReferenceType())
   SelectIdx = 0;
-else if (ParmType->isReferenceType())
-  SelectIdx = 1;
 else if (ParmType->isArrayType())
-  SelectIdx = 2;
+  SelectIdx = 1;
 
 if (SelectIdx != ~0U) {
   S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)

diff  --git a/clang/test/SemaCXX/attr-gsl-owner-pointer.cpp 
b/clang/test/SemaCXX/attr-gsl-owner-pointer.cpp
index 5b438822ba21..6c1bfe405e86 100644
--- a/clang/test/SemaCXX/attr-gsl-owner-pointer.cpp
+++ b/clang/test/SemaCXX/attr-gsl-owner-pointer.cpp
@@ -31,9 +31,11 @@ class [[gsl::Owner(int)]] [[gsl::Pointer(int)]] 
BothOwnerPointer{};
 // CHECK: OwnerAttr {{.*}} int
 
 class [[gsl::Owner(void)]] OwnerVoidDerefType{};
-// expected-error@-1 {{'void' is an invalid argument to attribute 'Owner'}}
+// CHECK: CXXRecordDecl {{.*}} OwnerVoidDerefType
+// CHECK: OwnerAttr {{.*}} void
 class [[gsl::Pointer(void)]] PointerVoidDerefType{};
-// expected-error@-1 {{'void' is an invalid argument to attribute 'Pointer'}}
+// CHECK: CXXRecordDecl {{.*}} PointerVoidDerefType
+// CHECK: PointerAttr {{.*}} void
 
 class [[gsl::Pointer(int)]] AddConflictLater{};
 // CHECK: CXXRecordDecl {{.*}} AddConflictLater



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


[clang] 0458e63 - [fuchsia] Enable Clang Static Analyzer

2020-01-03 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-03T15:49:32-08:00
New Revision: 0458e63d28a6685dae3d17cc210ef838be533612

URL: 
https://github.com/llvm/llvm-project/commit/0458e63d28a6685dae3d17cc210ef838be533612
DIFF: 
https://github.com/llvm/llvm-project/commit/0458e63d28a6685dae3d17cc210ef838be533612.diff

LOG: [fuchsia] Enable Clang Static Analyzer

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

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake
clang/cmake/caches/Fuchsia.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index d1533b8e7259..b338f1b8a08f 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -25,7 +25,7 @@ if(NOT APPLE)
 endif()
 set(CLANG_DEFAULT_RTLIB compiler-rt CACHE STRING "")
 set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "")
-set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "")
+set(CLANG_ENABLE_STATIC_ANALYZER ON CACHE BOOL "")
 set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")
 
 set(ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER ON CACHE BOOL "")

diff  --git a/clang/cmake/caches/Fuchsia.cmake 
b/clang/cmake/caches/Fuchsia.cmake
index 97e272db4aa3..2a65de2039c2 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -20,7 +20,7 @@ if(NOT APPLE)
 endif()
 set(CLANG_DEFAULT_RTLIB compiler-rt CACHE STRING "")
 set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "")
-set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "")
+set(CLANG_ENABLE_STATIC_ANALYZER ON CACHE BOOL "")
 set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")
 
 set(ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER ON CACHE BOOL "")



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


[clang] 379613d - [CFG] Fix an assertion failure with static initializers

2019-12-23 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-23T16:35:37-08:00
New Revision: 379613d7c7fa9698a2c300f4067165b5309a5e6e

URL: 
https://github.com/llvm/llvm-project/commit/379613d7c7fa9698a2c300f4067165b5309a5e6e
DIFF: 
https://github.com/llvm/llvm-project/commit/379613d7c7fa9698a2c300f4067165b5309a5e6e.diff

LOG: [CFG] Fix an assertion failure with static initializers

The CFGBlock::getLastCondition was not prepared for static initializer
branches.

This patch also revamps CFG unit tests. Earlier the lifetime of the AST
was smaller than the CFG. So all the AST pointers within the CFG blocks
were dangling. This was OK, since none of the tests dereferenced those
pointers. This was, however, a timed bomb. There were patches in the
past that were reverted partially due to this problem.

Differential revision: https://reviews.llvm.org/D71791

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/unittests/Analysis/CFGBuildResult.h
clang/unittests/Analysis/CFGTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 07945a80a311..4c1ea8995f9f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -5919,7 +5919,7 @@ const Expr *CFGBlock::getLastCondition() const {
 return nullptr;
 
   const Stmt *Cond = StmtElem->getStmt();
-  if (isa(Cond))
+  if (isa(Cond) || isa(Cond))
 return nullptr;
 
   // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence

diff  --git a/clang/unittests/Analysis/CFGBuildResult.h 
b/clang/unittests/Analysis/CFGBuildResult.h
index 17511dcd46c8..252e608d28e8 100644
--- a/clang/unittests/Analysis/CFGBuildResult.h
+++ b/clang/unittests/Analysis/CFGBuildResult.h
@@ -6,9 +6,10 @@
 //
 
//===--===//
 
-#include "clang/Analysis/CFG.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Analysis/CFG.h"
 #include "clang/Tooling/Tooling.h"
+#include 
 
 namespace clang {
 namespace analysis {
@@ -22,20 +23,27 @@ class BuildResult {
 BuiltCFG,
   };
 
-  BuildResult(Status S, std::unique_ptr Cfg = nullptr)
-  : S(S), Cfg(std::move(Cfg)) {}
+  BuildResult(Status S, std::unique_ptr Cfg = nullptr,
+  std::unique_ptr AST = nullptr)
+  : S(S), Cfg(std::move(Cfg)), AST(std::move(AST)) {}
 
   Status getStatus() const { return S; }
   CFG *getCFG() const { return Cfg.get(); }
+  ASTUnit *getAST() const { return AST.get(); }
 
 private:
   Status S;
   std::unique_ptr Cfg;
+  std::unique_ptr AST;
 };
 
 class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
 public:
+  CFGCallback(std::unique_ptr AST) : AST(std::move(AST)) {}
+
+  std::unique_ptr AST;
   BuildResult TheBuildResult = BuildResult::ToolRan;
+  CFG::BuildOptions Options;
 
   void run(const ast_matchers::MatchFinder::MatchResult ) override {
 const auto *Func = Result.Nodes.getNodeAs("func");
@@ -43,25 +51,26 @@ class CFGCallback : public 
ast_matchers::MatchFinder::MatchCallback {
 if (!Body)
   return;
 TheBuildResult = BuildResult::SawFunctionBody;
-CFG::BuildOptions Options;
 Options.AddImplicitDtors = true;
 if (std::unique_ptr Cfg =
 CFG::buildCFG(nullptr, Body, Result.Context, Options))
-  TheBuildResult = {BuildResult::BuiltCFG, std::move(Cfg)};
+  TheBuildResult = {BuildResult::BuiltCFG, std::move(Cfg), std::move(AST)};
   }
 };
 
-inline BuildResult BuildCFG(const char *Code) {
-  CFGCallback Callback;
-
-  ast_matchers::MatchFinder Finder;
-  Finder.addMatcher(ast_matchers::functionDecl().bind("func"), );
-  std::unique_ptr Factory(
-  tooling::newFrontendActionFactory());
+inline BuildResult BuildCFG(const char *Code, CFG::BuildOptions Options = {}) {
   std::vector Args = {"-std=c++11",
"-fno-delayed-template-parsing"};
-  if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args))
+  std::unique_ptr AST = tooling::buildASTFromCodeWithArgs(Code, Args);
+  if (!AST)
 return BuildResult::ToolFailed;
+
+  CFGCallback Callback(std::move(AST));
+  Callback.Options = Options;
+  ast_matchers::MatchFinder Finder;
+  Finder.addMatcher(ast_matchers::functionDecl().bind("func"), );
+
+  Finder.matchAST(Callback.AST->getASTContext());
   return std::move(Callback.TheBuildResult);
 }
 

diff  --git a/clang/unittests/Analysis/CFGTest.cpp 
b/clang/unittests/Analysis/CFGTest.cpp
index 27071dc5a5d9..1994658bed56 100644
--- a/clang/unittests/Analysis/CFGTest.cpp
+++ b/clang/unittests/Analysis/CFGTest.cpp
@@ -30,6 +30,22 @@ TEST(CFG, RangeBasedForOverDependentType) {
   EXPECT_EQ(BuildResult::SawFunctionBody, BuildCFG(Code).getStatus());
 }
 
+TEST(CFG, StaticInitializerLastCondition) {
+  const char *Code = "void f() {\n"
+ "  int i = 5 ;\n"
+ "  static int j = 3 ;\n"
+ "}\n";
+  

[clang] 59878ec - [analyzer] Add path notes to FuchsiaHandleCheck.

2019-12-20 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-20T12:40:41-08:00
New Revision: 59878ec8092bef656a71d22261fd3b70651e8318

URL: 
https://github.com/llvm/llvm-project/commit/59878ec8092bef656a71d22261fd3b70651e8318
DIFF: 
https://github.com/llvm/llvm-project/commit/59878ec8092bef656a71d22261fd3b70651e8318.diff

LOG: [analyzer] Add path notes to FuchsiaHandleCheck.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
clang/test/Analysis/fuchsia_handle.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
index e94b544172a0..69593e2b6c93 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -386,7 +386,7 @@ class PathSensitiveBugReport : public BugReport {
   /// to the user. This method allows to rest the location which should be used
   /// for uniquing reports. For example, memory leaks checker, could set this 
to
   /// the allocation site, rather then the location where the bug is reported.
-  PathSensitiveBugReport(BugType , StringRef desc,
+  PathSensitiveBugReport(const BugType , StringRef desc,
  const ExplodedNode *errorNode,
  PathDiagnosticLocation LocationToUnique,
  const Decl *DeclToUnique)

diff  --git a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
index 25eb4f5ba82d..861dfef02393 100644
--- a/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -199,6 +199,28 @@ class FuchsiaHandleChecker
 
 REGISTER_MAP_WITH_PROGRAMSTATE(HStateMap, SymbolRef, HandleState)
 
+static const ExplodedNode *getAcquireSite(const ExplodedNode *N, SymbolRef Sym,
+  CheckerContext ) {
+  ProgramStateRef State = N->getState();
+  // When bug type is handle leak, exploded node N does not have state info for
+  // leaking handle. Get the predecessor of N instead.
+  if (!State->get(Sym))
+N = N->getFirstPred();
+
+  const ExplodedNode *Pred = N;
+  while (N) {
+State = N->getState();
+if (!State->get(Sym)) {
+  const HandleState *HState = Pred->getState()->get(Sym);
+  if (HState && (HState->isAllocated() || HState->maybeAllocated()))
+return N;
+}
+Pred = N;
+N = N->getFirstPred();
+  }
+  return nullptr;
+}
+
 /// Returns the symbols extracted from the argument or null if it cannot be
 /// found.
 SymbolRef getFuchsiaHandleSymbol(QualType QT, SVal Arg, ProgramStateRef State) 
{
@@ -282,6 +304,7 @@ void FuchsiaHandleChecker::checkPostCall(const CallEvent 
,
 
   ProgramStateRef State = C.getState();
 
+  std::vector> Notes;
   SymbolRef ResultSymbol = nullptr;
   if (const auto *TypeDefTy = FuncDecl->getReturnType()->getAs())
 if (TypeDefTy->getDecl()->getName() == ErrorTypeName)
@@ -310,14 +333,45 @@ void FuchsiaHandleChecker::checkPostCall(const CallEvent 
,
   if (HState && HState->isReleased()) {
 reportDoubleRelease(Handle, Call.getArgSourceRange(Arg), C);
 return;
-  } else
+  } else {
+Notes.push_back([Handle](BugReport ) {
+  auto *PathBR = static_cast();
+  if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
+return "Handle released here.";
+  } else
+return "";
+});
 State = State->set(Handle, HandleState::getReleased());
+  }
 } else if (hasFuchsiaAttr(PVD)) {
+  Notes.push_back([Handle](BugReport ) {
+auto *PathBR = static_cast();
+if (auto IsInteresting = PathBR->getInterestingnessKind(Handle)) {
+  return "Handle allocated here.";
+} else
+  return "";
+  });
   State = State->set(
   Handle, HandleState::getMaybeAllocated(ResultSymbol));
 }
   }
-  C.addTransition(State);
+  const NoteTag *T = nullptr;
+  if (!Notes.empty()) {
+T = C.getNoteTag(
+[this, Notes{std::move(Notes)}](BugReport ) -> std::string {
+  if (() !=  &&
+  () !=  &&
+  () != )
+return "";
+  for (auto  : Notes) {
+std::string Text = Note(BR);
+if (!Text.empty())
+  return Text;
+  }
+  return "";
+});
+  }
+  C.addTransition(State, T);
 }
 
 void FuchsiaHandleChecker::checkDeadSymbols(SymbolReaper ,
@@ -353,6 +407,7 @@ void FuchsiaHandleChecker::checkDeadSymbols(SymbolReaper 
,
 ProgramStateRef FuchsiaHandleChecker::evalAssume(ProgramStateRef State,
  

[clang] 82923c7 - [analyzer] Add Fuchsia Handle checker

2019-12-20 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-20T12:33:16-08:00
New Revision: 82923c71efa57600d015dbc281202941d3d64dde

URL: 
https://github.com/llvm/llvm-project/commit/82923c71efa57600d015dbc281202941d3d64dde
DIFF: 
https://github.com/llvm/llvm-project/commit/82923c71efa57600d015dbc281202941d3d64dde.diff

LOG: [analyzer] Add Fuchsia Handle checker

The checker can diagnose handle use after releases, double releases, and
handle leaks.

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

Added: 
clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
clang/test/Analysis/fuchsia_handle.cpp

Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index b410c0858789..34d29ba344c9 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1335,6 +1335,31 @@ Warns if 'CFArray', 'CFDictionary', 'CFSet' are created 
with non-pointer-size va
 ); // warn
  }
 
+Fuchsia
+^^^
+
+Fuchsia is an open source capability-based operating system currently being
+developed by Google. This section describes checkers that can find various
+misuses of Fuchsia APIs.
+
+.. _fuchsia-HandleChecker:
+
+fuchsia.HandleChecker
+
+Handles identify resources. Similar to pointers they can be leaked,
+double freed, or use after freed. This check attempts to find such problems.
+
+.. code-block:: cpp
+
+ void checkLeak08(int tag) {
+   zx_handle_t sa, sb;
+   zx_channel_create(0, , );
+   if (tag)
+ zx_handle_close(sa);
+   use(sb); // Warn: Potential leak of handle
+   zx_handle_close(sb);
+ }
+
 
 .. _alpha-checkers:
 

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 5b23de418999..6d68d8215597 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -108,6 +108,8 @@ def CloneDetectionAlpha : Package<"clone">, 
ParentPackage;
 
 def NonDeterminismAlpha : Package<"nondeterminism">, ParentPackage;
 
+def Fuchsia : Package<"fuchsia">;
+
 
//===--===//
 // Core Checkers.
 
//===--===//
@@ -1423,3 +1425,16 @@ def PointerSortingChecker : Checker<"PointerSorting">,
   Documentation;
 
 } // end alpha.nondeterminism
+
+//===--===//
+// Fuchsia checkers.
+//===--===//
+
+let ParentPackage = Fuchsia in {
+
+def FuchsiaHandleChecker : Checker<"HandleChecker">,
+  HelpText<"A Checker that detect leaks related to Fuchsia handles">,
+  Documentation;
+
+} // end fuchsia
+

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
index 7f4df0d88def..bd8760cf0ce0 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -213,6 +213,22 @@ class CheckerContext {
 return addTransition(State, (Tag ? Tag : Location.getTag()));
   }
 
+  /// Generate a transition to a node that will be used to report
+  /// an error. This node will not be a sink. That is, exploration will
+  /// continue along this path.
+  ///
+  /// @param State The state of the generated node.
+  /// @param Pred The transition will be generated from the specified Pred node
+  /// to the newly generated node.
+  /// @param Tag The tag to uniquely identify the creation site. If null,
+  ///the default tag for the checker will be used.
+  ExplodedNode *
+  generateNonFatalErrorNode(ProgramStateRef State,
+ExplodedNode *Pred,
+const ProgramPointTag *Tag = nullptr) {
+return addTransition(State, Pred, (Tag ? Tag : Location.getTag()));
+  }
+
   /// Emit the diagnostics report.
   void emitReport(std::unique_ptr R) {
 Changed = true;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 1347c3de913e..2ebfc763705f 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2794,6 +2794,8 @@ static void RenderAnalyzerOptions(const ArgList , 
ArgStringList ,
   CmdArgs.push_back(
   "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
 }
+else if (Triple.isOSFuchsia())

[clang] fe17b30 - [attributes][analyzer] Add annotations for handles.

2019-12-20 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-20T11:47:55-08:00
New Revision: fe17b30a79572f0d50fe78f6a07d5194cbf90860

URL: 
https://github.com/llvm/llvm-project/commit/fe17b30a79572f0d50fe78f6a07d5194cbf90860
DIFF: 
https://github.com/llvm/llvm-project/commit/fe17b30a79572f0d50fe78f6a07d5194cbf90860.diff

LOG: [attributes][analyzer] Add annotations for handles.

These annotations will be used in an upcomming static analyzer check
that finds handle leaks, use after releases, and double releases.

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

Added: 
clang/test/Sema/attr-handles.cpp

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/AST/TypePrinter.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaType.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 286807ec779f..d9ca121b6510 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3471,3 +3471,27 @@ def NoBuiltin : Attr {
   let Subjects = SubjectList<[Function]>;
   let Documentation = [NoBuiltinDocs];
 }
+
+// FIXME: This attribute is not inheritable, it will not be propagated to
+// redecls. [[clang::lifetimebound]] has the same problems. This should be
+// fixed in TableGen (by probably adding a new inheritable flag).
+def AcquireHandle : DeclOrTypeAttr {
+  let Spellings = [Clang<"acquire_handle">];
+  let Args = [StringArgument<"HandleType">];
+  let Subjects = SubjectList<[Function, TypedefName, ParmVar]>;
+  let Documentation = [AcquireHandleDocs];
+}
+
+def UseHandle : InheritableParamAttr {
+  let Spellings = [Clang<"use_handle">];
+  let Args = [StringArgument<"HandleType">];
+  let Subjects = SubjectList<[ParmVar]>;
+  let Documentation = [UseHandleDocs];
+}
+
+def ReleaseHandle : InheritableParamAttr {
+  let Spellings = [Clang<"release_handle">];
+  let Args = [StringArgument<"HandleType">];
+  let Subjects = SubjectList<[ParmVar]>;
+  let Documentation = [ReleaseHandleDocs];
+}

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 3fa6993a5fd0..9b4afa8f128e 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4696,3 +4696,64 @@ once.
   }
   }];
 }
+
+def HandleDocs : DocumentationCategory<"Handle Attributes"> {
+  let Content = [{
+Handles are a way to identify resources like files, sockets, and processes.
+They are more opaque than pointers and widely used in system programming. They
+have similar risks such as never releasing a resource associated with a handle,
+attempting to use a handle that was already released, or trying to release a
+handle twice. Using the annotations below it is possible to make the ownership
+of the handles clear: whose responsibility is to release them. They can also
+aid static analysis tools to find bugs.
+  }];
+}
+
+def AcquireHandleDocs : Documentation {
+  let Category = HandleDocs;
+  let Content = [{
+If this annotation is on a function or a function type it is assumed to return
+a new handle. In case this annotation is on an output parameter,
+the function is assumed to fill the corresponding argument with a new
+handle.
+
+.. code-block:: c++
+
+  // Output arguments from Zircon.
+  zx_status_t zx_socket_create(uint32_t options,
+   zx_handle_t __attribute__((acquire_handle)) * 
out0,
+   zx_handle_t* out1 [[clang::acquire_handle]]);
+
+
+  // Returned handle.
+  [[clang::acquire_handle]] int open(const char *path, int oflag, ... );
+  int open(const char *path, int oflag, ... ) __attribute__((acquire_handle));
+  }];
+}
+
+def UseHandleDocs : Documentation {
+  let Category = HandleDocs;
+  let Content = [{
+A function taking a handle by value might close the handle. If a function
+parameter is annotated with `use_handle` it is assumed to not to change
+the state of the handle. It is also assumed to require an open handle to work 
with.
+
+.. code-block:: c++
+
+  zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle]],
+   zx_time_t deadline,
+   zx_port_packet_t* packet);
+  }];
+}
+
+def ReleaseHandleDocs : Documentation {
+  let Category = HandleDocs;
+  let Content = [{
+If a function parameter is annotated with `release_handle` it is assumed to
+close the handle. It is also assumed to require an open handle to work with.
+
+.. code-block:: c++
+
+  zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle]]);
+  }];
+}

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b714cb81f0ca..1d81f69a7bd2 100644
--- 

[clang] ea93d7d - [CFG] Add an option to expand CXXDefaultInitExpr into aggregate initialization

2019-12-17 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-17T17:56:06-08:00
New Revision: ea93d7d6421612e9ea51b321eaf97fbdd64fe39b

URL: 
https://github.com/llvm/llvm-project/commit/ea93d7d6421612e9ea51b321eaf97fbdd64fe39b
DIFF: 
https://github.com/llvm/llvm-project/commit/ea93d7d6421612e9ea51b321eaf97fbdd64fe39b.diff

LOG: [CFG] Add an option to expand CXXDefaultInitExpr into aggregate 
initialization

This is useful for clients that are relying on linearized CFGs for evaluating
subexpressions and want the default initializer to be evaluated properly.

The upcoming lifetime analysis is using this but it might also be useful
for the static analyzer at some point.

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

Added: 
clang/test/Analysis/aggrinit-cfg-output.cpp

Modified: 
clang/include/clang/Analysis/CFG.h
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/Analysis/CFG.cpp
clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
clang/test/Analysis/analyzer-config.c

Removed: 




diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index ea3d8b2921a7..93de3178e661 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -1248,6 +1248,7 @@ class CFG {
 bool AddStaticInitBranches = false;
 bool AddCXXNewAllocator = false;
 bool AddCXXDefaultInitExprInCtors = false;
+bool AddCXXDefaultInitExprInAggregates = false;
 bool AddRichCXXConstructors = false;
 bool MarkElidedCXXConstructors = false;
 bool AddVirtualBaseBranches = false;

diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index d853fb74f9c7..00febf688195 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -112,6 +112,12 @@ ANALYZER_OPTION(
 bool, ShouldIncludeScopesInCFG, "cfg-scopes",
 "Whether or not scope information should be included in the CFG.", false)
 
+ANALYZER_OPTION(bool, ShouldIncludeDefaultInitForAggregates,
+"cfg-expand-default-aggr-inits",
+"Whether or not inline CXXDefaultInitializers for aggregate "
+"initialization in the CFG.",
+false)
+
 ANALYZER_OPTION(
 bool, MayInlineTemplateFunctions, "c++-template-inlining",
 "Whether or not templated functions may be considered for inlining.", true)

diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index e10bfd805933..07945a80a311 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -542,6 +542,7 @@ class CFGBuilder {
 
 private:
   // Visitors to walk an AST and construct the CFG.
+  CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
   CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
   CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
   CFGBlock *VisitBreakStmt(BreakStmt *B);
@@ -2140,6 +2141,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 return Block;
   return VisitStmt(S, asc);
 
+case Stmt::InitListExprClass:
+  return VisitInitListExpr(cast(S), asc);
+
 case Stmt::AddrLabelExprClass:
   return VisitAddrLabelExpr(cast(S), asc);
 
@@ -2346,15 +2350,37 @@ CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
   // Visit the children in their reverse order so that they appear in
   // left-to-right (natural) order in the CFG.
   reverse_children RChildren(S);
-  for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
-   I != E; ++I) {
-if (Stmt *Child = *I)
+  for (Stmt *Child : RChildren) {
+if (Child)
   if (CFGBlock *R = Visit(Child))
 B = R;
   }
   return B;
 }
 
+CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, ILE)) {
+autoCreateBlock();
+appendStmt(Block, ILE);
+  }
+  CFGBlock *B = Block;
+
+  reverse_children RChildren(ILE);
+  for (Stmt *Child : RChildren) {
+if (!Child)
+  continue;
+if (CFGBlock *R = Visit(Child))
+  B = R;
+if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
+  if (auto *DIE = dyn_cast(Child))
+if (Stmt *Child = DIE->getExpr())
+  if (CFGBlock *R = Visit(Child))
+B = R;
+}
+  }
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
  AddStmtChoice asc) {
   AddressTakenLabels.insert(A->getLabel());

diff  --git a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp 
b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
index 94fc09e64aa0..fdd03c75920d 100644
--- a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
@@ -44,6 +44,8 @@ AnalysisManager::AnalysisManager(ASTContext ,
   

[clang] 9fdcae7 - [analyzer] Do not cache out on some shared implicit AST nodes

2019-12-11 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-11T17:15:12-08:00
New Revision: 9fdcae7c81f5ff92ad694f5d993a042a525fd6bc

URL: 
https://github.com/llvm/llvm-project/commit/9fdcae7c81f5ff92ad694f5d993a042a525fd6bc
DIFF: 
https://github.com/llvm/llvm-project/commit/9fdcae7c81f5ff92ad694f5d993a042a525fd6bc.diff

LOG: [analyzer] Do not cache out on some shared implicit AST nodes

Some AST nodes which stands for implicit initialization is shared. The analyzer
will do the same evaluation on the same nodes resulting in the same state. The
analyzer will "cache out", i.e. it thinks that it visited an already existing
node in the exploded graph. This is not true in this case and we lose coverage.
Since these nodes do not really require any processing from the analyzer
we just omit them from the CFG.

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

Added: 
clang/test/Analysis/designated-initializer-values.c

Modified: 
clang/include/clang/Analysis/CFG.h
clang/lib/Analysis/CFG.cpp
clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/Analysis/designated-initializer.c
clang/test/Analysis/initializers-cfg-output.cpp
clang/test/Analysis/temp-obj-dtors-cfg-output.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index a8301a0e0063..ea3d8b2921a7 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -1251,6 +1251,7 @@ class CFG {
 bool AddRichCXXConstructors = false;
 bool MarkElidedCXXConstructors = false;
 bool AddVirtualBaseBranches = false;
+bool OmitImplicitValueInitializers = false;
 
 BuildOptions() = default;
 

diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index bc21d1c9076d..e10bfd805933 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2135,6 +2135,11 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 default:
   return VisitStmt(S, asc);
 
+case Stmt::ImplicitValueInitExprClass:
+  if (BuildOpts.OmitImplicitValueInitializers)
+return Block;
+  return VisitStmt(S, asc);
+
 case Stmt::AddrLabelExprClass:
   return VisitAddrLabelExpr(cast(S), asc);
 

diff  --git a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp 
b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
index 73e1a0df..94fc09e64aa0 100644
--- a/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp
@@ -43,6 +43,7 @@ AnalysisManager::AnalysisManager(ASTContext ,
   CreateConstraintMgr(constraintmgr), CheckerMgr(checkerMgr),
   options(Options) {
   AnaCtxMgr.getCFGBuildOptions().setAllAlwaysAdd();
+  AnaCtxMgr.getCFGBuildOptions().OmitImplicitValueInitializers = true;
 }
 
 AnalysisManager::~AnalysisManager() {

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 2a23d1cae7b5..f917a4c8637b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1321,6 +1321,11 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
 case Stmt::WhileStmtClass:
 case Expr::MSDependentExistsStmtClass:
   llvm_unreachable("Stmt should not be in analyzer evaluation loop");
+case Stmt::ImplicitValueInitExprClass:
+  // These nodes are shared in the CFG and would case caching out.
+  // Moreover, no additional evaluation required for them, the
+  // analyzer can reconstruct these values from the AST.
+  llvm_unreachable("Should be pruned from CFG");
 
 case Stmt::ObjCSubscriptRefExprClass:
 case Stmt::ObjCPropertyRefExprClass:
@@ -1391,7 +1396,6 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
 case Stmt::IntegerLiteralClass:
 case Stmt::FixedPointLiteralClass:
 case Stmt::CharacterLiteralClass:
-case Stmt::ImplicitValueInitExprClass:
 case Stmt::CXXScalarValueInitExprClass:
 case Stmt::CXXBoolLiteralExprClass:
 case Stmt::ObjCBoolLiteralExprClass:

diff  --git a/clang/test/Analysis/designated-initializer-values.c 
b/clang/test/Analysis/designated-initializer-values.c
new file mode 100644
index ..1efc10aece60
--- /dev/null
+++ b/clang/test/Analysis/designated-initializer-values.c
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-std=c99 -verify %s
+
+void clang_analyzer_eval(int);
+
+void array_init() {
+  int a[5] = {[4] = 29, [2] = 15, [0] = 4};
+  clang_analyzer_eval(a[0] == 4);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(a[1] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(a[2] == 15); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a[3] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(a[4] == 29); // expected-warning{{TRUE}}
+  int b[5] = {[0 ... 2] = 1, [4] 

[clang] 5882e6f - [analyzer] Escape symbols conjured into specific regions during a conservative EvalCall

2019-12-11 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-11T11:44:10-08:00
New Revision: 5882e6f36fd9bfc7382e6763c5591b3497428d83

URL: 
https://github.com/llvm/llvm-project/commit/5882e6f36fd9bfc7382e6763c5591b3497428d83
DIFF: 
https://github.com/llvm/llvm-project/commit/5882e6f36fd9bfc7382e6763c5591b3497428d83.diff

LOG: [analyzer] Escape symbols conjured into specific regions during a 
conservative EvalCall

This patch introduced additional PointerEscape callbacks after conservative
calls for output parameters. This should not really affect the current
checkers but the upcoming FuchsiaHandleChecker relies on this heavily.

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

Added: 
clang/test/Analysis/pointer-escape-on-conservative-calls.c

Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/include/clang/StaticAnalyzer/Core/CheckerManager.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
clang/test/Analysis/analyzer-config.c
clang/test/Analysis/expr-inspection.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index be455ae14f57..43632e801d2b 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1266,6 +1266,12 @@ def AnalysisOrderChecker : Checker<"AnalysisOrder">,
   "false",
   Released,
   Hide>,
+CmdLineOption,
 CmdLineOption> LocAndVals,
+  const LocationContext *LCtx, PointerEscapeKind Kind,
+  const CallEvent *Call) override;
+
+  ProgramStateRef
+  processPointerEscapedOnBind(ProgramStateRef State,
+  SVal Loc, SVal Val,
+  const LocationContext *LCtx);
+
   /// Call PointerEscape callback when a value escapes as a result of
   /// region invalidation.
   /// \param[in] ITraits Specifies invalidation traits for regions/symbols.
@@ -628,9 +634,10 @@ class ExprEngine : public SubEngine {
RegionAndSymbolInvalidationTraits ) 
override;
 
   /// A simple wrapper when you only need to notify checkers of pointer-escape
-  /// of a single value.
-  ProgramStateRef escapeValue(ProgramStateRef State, SVal V,
-  PointerEscapeKind K) const;
+  /// of some values.
+  ProgramStateRef escapeValues(ProgramStateRef State, ArrayRef Vs,
+   PointerEscapeKind K,
+   const CallEvent *Call = nullptr) const;
 
 public:
   // FIXME: 'tag' should be removed, and a LocationContext should be used

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
index 7789b431c0a6..a7f3c28d4373 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
@@ -15,6 +15,7 @@
 #include "clang/Analysis/ProgramPoint.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 
 namespace clang {
 
@@ -148,8 +149,10 @@ class SubEngine {
 return processRegionChanges(state, nullptr, MR, MR, LCtx, nullptr);
   }
 
-  virtual ProgramStateRef
-  processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val, const 
LocationContext *LCtx) = 0;
+  virtual ProgramStateRef processPointerEscapedOnBind(
+  ProgramStateRef State, ArrayRef> LocAndVals,
+  const LocationContext *LCtx, PointerEscapeKind Kind,
+  const CallEvent *Call) = 0;
 
   virtual ProgramStateRef
   notifyCheckersOfPointerEscape(ProgramStateRef State,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
index d0def6918932..2ef50a727ece 100644
--- a/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
@@ -40,6 +40,7 @@ class AnalysisOrderChecker
  check::EndFunction,
  check::NewAllocator,
  check::Bind,
+ check::PointerEscape,
  check::RegionChanges,
  check::LiveSymbols> {
 
@@ -165,6 +166,15 @@ class AnalysisOrderChecker
   llvm::errs() << "RegionChanges\n";
 return State;
   }
+
+  ProgramStateRef checkPointerEscape(ProgramStateRef State,
+ 

[clang] 8434fbb - Revert "[analyzer] Keep track of escaped locals"

2019-12-10 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-10T16:42:03-08:00
New Revision: 8434fbbee62e382376a39787785909bd55ae1696

URL: 
https://github.com/llvm/llvm-project/commit/8434fbbee62e382376a39787785909bd55ae1696
DIFF: 
https://github.com/llvm/llvm-project/commit/8434fbbee62e382376a39787785909bd55ae1696.diff

LOG: Revert "[analyzer] Keep track of escaped locals"

It was a step in the right direction but it is not clear how can this
fit into the checker API at this point. The pre-escape happens in the
analyzer core and the checker has no control over it. If the checker
is not interestd in a pre-escape it would need to do additional work
on each escape to check if the escaped symbol is originated from an
"uninteresting" pre-escaped memory region. In order to keep the
checker API simple we abandoned this solution for now.

We will reland this once we have a better answer for what to do on the
checker side.

This reverts commit f3a28202ef58551db15818f8f51afd21e0f3e231.

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ProgramState.cpp
clang/test/Analysis/symbol-escape.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index c85a66db3457..2d0967616ff2 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -627,9 +627,6 @@ class ExprEngine : public SubEngine {
const CallEvent *Call,
RegionAndSymbolInvalidationTraits ) 
override;
 
-  ProgramStateRef processLocalRegionEscape(ProgramStateRef State,
-   const MemRegion *R) const override;
-
   /// A simple wrapper when you only need to notify checkers of pointer-escape
   /// of a single value.
   ProgramStateRef escapeValue(ProgramStateRef State, SVal V,

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
index b6b4a86acbb2..bdd12a3ffe33 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -27,7 +27,7 @@
 
 namespace llvm {
 class APSInt;
-} // namespace llvm
+}
 
 namespace clang {
 class ASTContext;
@@ -872,8 +872,8 @@ class ScanReachableSymbols {
   bool scan(const SymExpr *sym);
 };
 
-} // namespace ento
+} // end ento namespace
 
-} // namespace clang
+} // end clang namespace
 
 #endif

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
index 5866be2b2e7c..7789b431c0a6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
@@ -149,16 +149,14 @@ class SubEngine {
   }
 
   virtual ProgramStateRef
-  processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val,
-  const LocationContext *LCtx) = 0;
-
-  virtual ProgramStateRef notifyCheckersOfPointerEscape(
-  ProgramStateRef State, const InvalidatedSymbols *Invalidated,
-  ArrayRef ExplicitRegions, const CallEvent *Call,
-  RegionAndSymbolInvalidationTraits ) = 0;
+  processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val, const 
LocationContext *LCtx) = 0;
 
   virtual ProgramStateRef
-  processLocalRegionEscape(ProgramStateRef State, const MemRegion *R) const = 
0;
+  notifyCheckersOfPointerEscape(ProgramStateRef State,
+   const InvalidatedSymbols *Invalidated,
+   ArrayRef ExplicitRegions,
+   const CallEvent *Call,
+   RegionAndSymbolInvalidationTraits ) = 0;
 
   /// printJson - Called by ProgramStateManager to print checker-specific data.
   virtual void printJson(raw_ostream , ProgramStateRef State,

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index b6f6481c369d..efbc20f09250 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -193,8 +193,6 @@ typedef llvm::ImmutableMap
 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  ObjectsUnderConstructionMap)
 
-REGISTER_SET_WITH_PROGRAMSTATE(EscapedLocals, const MemRegion *)
-
 
//===--===//
 // Engine construction and 

[clang] f3a2820 - [analyzer] Keep track of escaped locals

2019-12-10 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-10T08:51:33-08:00
New Revision: f3a28202ef58551db15818f8f51afd21e0f3e231

URL: 
https://github.com/llvm/llvm-project/commit/f3a28202ef58551db15818f8f51afd21e0f3e231
DIFF: 
https://github.com/llvm/llvm-project/commit/f3a28202ef58551db15818f8f51afd21e0f3e231.diff

LOG: [analyzer] Keep track of escaped locals

We want to escape all symbols that are stored into escaped regions.
The problem is, we did not know which local regions were escaped. Until now.
This should fix some false positives like the one in the tests.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ProgramState.cpp
clang/test/Analysis/symbol-escape.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 2d0967616ff2..c85a66db3457 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -627,6 +627,9 @@ class ExprEngine : public SubEngine {
const CallEvent *Call,
RegionAndSymbolInvalidationTraits ) 
override;
 
+  ProgramStateRef processLocalRegionEscape(ProgramStateRef State,
+   const MemRegion *R) const override;
+
   /// A simple wrapper when you only need to notify checkers of pointer-escape
   /// of a single value.
   ProgramStateRef escapeValue(ProgramStateRef State, SVal V,

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
index bdd12a3ffe33..b6b4a86acbb2 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -27,7 +27,7 @@
 
 namespace llvm {
 class APSInt;
-}
+} // namespace llvm
 
 namespace clang {
 class ASTContext;
@@ -872,8 +872,8 @@ class ScanReachableSymbols {
   bool scan(const SymExpr *sym);
 };
 
-} // end ento namespace
+} // namespace ento
 
-} // end clang namespace
+} // namespace clang
 
 #endif

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
index 7789b431c0a6..5866be2b2e7c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
@@ -149,14 +149,16 @@ class SubEngine {
   }
 
   virtual ProgramStateRef
-  processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val, const 
LocationContext *LCtx) = 0;
+  processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val,
+  const LocationContext *LCtx) = 0;
+
+  virtual ProgramStateRef notifyCheckersOfPointerEscape(
+  ProgramStateRef State, const InvalidatedSymbols *Invalidated,
+  ArrayRef ExplicitRegions, const CallEvent *Call,
+  RegionAndSymbolInvalidationTraits ) = 0;
 
   virtual ProgramStateRef
-  notifyCheckersOfPointerEscape(ProgramStateRef State,
-   const InvalidatedSymbols *Invalidated,
-   ArrayRef ExplicitRegions,
-   const CallEvent *Call,
-   RegionAndSymbolInvalidationTraits ) = 0;
+  processLocalRegionEscape(ProgramStateRef State, const MemRegion *R) const = 
0;
 
   /// printJson - Called by ProgramStateManager to print checker-specific data.
   virtual void printJson(raw_ostream , ProgramStateRef State,

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index efbc20f09250..b6f6481c369d 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -193,6 +193,8 @@ typedef llvm::ImmutableMap
 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  ObjectsUnderConstructionMap)
 
+REGISTER_SET_WITH_PROGRAMSTATE(EscapedLocals, const MemRegion *)
+
 
//===--===//
 // Engine construction and deletion.
 
//===--===//
@@ -723,6 +725,12 @@ void ExprEngine::removeDead(ExplodedNode *Pred, 
ExplodedNodeSet ,
   SymReaper.markLive(MR);
   }
 
+  EscapedLocalsTy EscapedRegions = CleanedState->get();
+  for (const MemRegion *MR : EscapedRegions) {
+if (!SymReaper.isLiveRegion(MR))

[clang] 8994d63 - [scan-build-py] Set of small fixes

2019-12-05 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-12-05T09:00:16-08:00
New Revision: 8994d632c8d31d527490e8693b0881d9278464e6

URL: 
https://github.com/llvm/llvm-project/commit/8994d632c8d31d527490e8693b0881d9278464e6
DIFF: 
https://github.com/llvm/llvm-project/commit/8994d632c8d31d527490e8693b0881d9278464e6.diff

LOG: [scan-build-py] Set of small fixes

* Unhandled exceptions
* Typos

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

Added: 


Modified: 
clang/tools/scan-build-py/libscanbuild/analyze.py
clang/tools/scan-build-py/libscanbuild/clang.py

Removed: 




diff  --git a/clang/tools/scan-build-py/libscanbuild/analyze.py 
b/clang/tools/scan-build-py/libscanbuild/analyze.py
index 49de387c7042..ffdf7f7c7d61 100644
--- a/clang/tools/scan-build-py/libscanbuild/analyze.py
+++ b/clang/tools/scan-build-py/libscanbuild/analyze.py
@@ -33,7 +33,8 @@
 from libscanbuild.report import document
 from libscanbuild.compilation import split_command, classify_source, \
 compiler_language
-from libscanbuild.clang import get_version, get_arguments, get_triple_arch
+from libscanbuild.clang import get_version, get_arguments, get_triple_arch, \
+ClangErrorException
 from libscanbuild.shell import decode
 
 __all__ = ['scan_build', 'analyze_build', 'analyze_compiler_wrapper']
@@ -435,7 +436,7 @@ def run(opts):
 of the compilation database.
 
 This complex task is decomposed into smaller methods which are calling
-each other in chain. If the analyzis is not possible the given method
+each other in chain. If the analysis is not possible the given method
 just return and break the chain.
 
 The passed parameter is a python dictionary. Each method first check
@@ -451,7 +452,7 @@ def run(opts):
 
 return arch_check(opts)
 except Exception:
-logging.error("Problem occurred during analyzis.", exc_info=1)
+logging.error("Problem occurred during analysis.", exc_info=1)
 return None
 
 
@@ -490,10 +491,15 @@ def destination():
 os.close(handle)
 # Execute Clang again, but run the syntax check only.
 cwd = opts['directory']
-cmd = get_arguments(
-[opts['clang'], '-fsyntax-only', '-E'
- ] + opts['flags'] + [opts['file'], '-o', name], cwd)
-run_command(cmd, cwd=cwd)
+cmd = [opts['clang'], '-fsyntax-only', '-E'] + opts['flags'] + \
+[opts['file'], '-o', name]
+try:
+cmd = get_arguments(cmd, cwd)
+run_command(cmd, cwd=cwd)
+except subprocess.CalledProcessError:
+pass
+except ClangErrorException:
+pass
 # write general information about the crash
 with open(name + '.info.txt', 'w') as handle:
 handle.write(opts['file'] + os.linesep)
@@ -542,6 +548,12 @@ def target():
 opts.update(result)
 continuation(opts)
 return result
+except ClangErrorException as ex:
+result = {'error_output': ex.error, 'exit_code': 0}
+if opts.get('output_failures', False):
+opts.update(result)
+continuation(opts)
+return result
 
 
 def extdef_map_list_src_to_ast(extdef_src_list):

diff  --git a/clang/tools/scan-build-py/libscanbuild/clang.py 
b/clang/tools/scan-build-py/libscanbuild/clang.py
index 3451b98dbd02..4f02cb20d3fe 100644
--- a/clang/tools/scan-build-py/libscanbuild/clang.py
+++ b/clang/tools/scan-build-py/libscanbuild/clang.py
@@ -19,6 +19,11 @@
 ACTIVE_CHECKER_PATTERN = re.compile(r'^-analyzer-checker=(.*)$')
 
 
+class ClangErrorException(Exception):
+def __init__(self, error):
+self.error = error
+
+
 def get_version(clang):
 """ Returns the compiler version as string.
 
@@ -39,13 +44,14 @@ def get_arguments(command, cwd):
 
 cmd = command[:]
 cmd.insert(1, '-###')
+cmd.append('-fno-color-diagnostics')
 
 output = run_command(cmd, cwd=cwd)
 # The relevant information is in the last line of the output.
 # Don't check if finding last line fails, would throw exception anyway.
 last_line = output[-1]
 if re.search(r'clang(.*): error:', last_line):
-raise Exception(last_line)
+raise ClangErrorException(last_line)
 return decode(last_line)
 
 



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


[clang-tools-extra] 5c5e860 - [clang-tidy] Fix PR35824

2019-11-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-11-27T11:07:16-08:00
New Revision: 5c5e860535d8924a3d6eb950bb8a4945df01e9b7

URL: 
https://github.com/llvm/llvm-project/commit/5c5e860535d8924a3d6eb950bb8a4945df01e9b7
DIFF: 
https://github.com/llvm/llvm-project/commit/5c5e860535d8924a3d6eb950bb8a4945df01e9b7.diff

LOG: [clang-tidy] Fix PR35824

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

Added: 

clang-tools-extra/test/clang-tidy/bugprone-suspicious-semicolon-constexpr.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp
index d94731beba94..9b34f5ab55a7 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp
@@ -20,7 +20,8 @@ namespace bugprone {
 void SuspiciousSemicolonCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   stmt(anyOf(ifStmt(hasThen(nullStmt().bind("semi")),
-unless(hasElse(stmt(,
+unless(hasElse(stmt())),
+unless(isConstexpr())),
  forStmt(hasBody(nullStmt().bind("semi"))),
  cxxForRangeStmt(hasBody(nullStmt().bind("semi"))),
  whileStmt(hasBody(nullStmt().bind("semi")

diff  --git 
a/clang-tools-extra/test/clang-tidy/bugprone-suspicious-semicolon-constexpr.cpp 
b/clang-tools-extra/test/clang-tidy/bugprone-suspicious-semicolon-constexpr.cpp
new file mode 100644
index ..c18dd7bd1e93
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/bugprone-suspicious-semicolon-constexpr.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s bugprone-suspicious-semicolon %t -- -- -std=c++17
+
+void fail()
+{
+  int x = 0;
+  if(x > 5); (void)x;
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: potentially unintended 
semicolon [bugprone-suspicious-semicolon]
+  // CHECK-FIXES: if(x > 5) (void)x;
+}
+
+template 
+int foo(int a) {
+if constexpr(X > 0) {
+return a;
+}
+return a + 1;
+}
+
+template 
+int foo2(int a) {
+// FIXME: diagnose the case below. See https://reviews.llvm.org/D46234
+// for details.
+if constexpr(X > 0);
+return a;
+return a + 1;
+}
+
+int main(void) {
+foo2<0>(1);
+return foo<0>(1);
+}



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


[clang] bcd0798 - [LifetimeAnalysis] Fix PR44150

2019-11-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2019-11-27T09:15:14-08:00
New Revision: bcd0798c47ca865f95226859893016a17402441e

URL: 
https://github.com/llvm/llvm-project/commit/bcd0798c47ca865f95226859893016a17402441e
DIFF: 
https://github.com/llvm/llvm-project/commit/bcd0798c47ca865f95226859893016a17402441e.diff

LOG: [LifetimeAnalysis] Fix PR44150

References need somewhat special treatment. While copying a gsl::Pointer
will propagate the points-to set, creating an object from a reference
often behaves more like a dereference operation.

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

Added: 


Modified: 
clang/lib/Sema/SemaInit.cpp
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 80d7cfed711a..7421754d95ca 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -6653,6 +6653,7 @@ struct IndirectLocalPathEntry {
 VarInit,
 LValToRVal,
 LifetimeBoundCall,
+GslReferenceInit,
 GslPointerInit
   } Kind;
   Expr *E;
@@ -6783,12 +6784,24 @@ static bool shouldTrackFirstArgument(const FunctionDecl 
*FD) {
 
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
 LocalVisitor Visit) {
-  auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
+  auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
 // We are not interested in the temporary base objects of gsl Pointers:
 //   Temp().ptr; // Here ptr might not dangle.
 if (isa(Arg->IgnoreImpCasts()))
   return;
-Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
+// Once we initialized a value with a reference, it can no longer dangle.
+if (!Value) {
+  for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
+if (It->Kind == IndirectLocalPathEntry::GslReferenceInit)
+  continue;
+if (It->Kind == IndirectLocalPathEntry::GslPointerInit)
+  return;
+break;
+  }
+}
+Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
+  : IndirectLocalPathEntry::GslReferenceInit,
+Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
 Visit,
@@ -6802,18 +6815,21 @@ static void handleGslAnnotatedTypes(IndirectLocalPath 
, Expr *Call,
   if (auto *MCE = dyn_cast(Call)) {
 const auto *MD = cast_or_null(MCE->getDirectCallee());
 if (MD && shouldTrackImplicitObjectArg(MD))
-  VisitPointerArg(MD, MCE->getImplicitObjectArgument());
+  VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
+  !MD->getReturnType()->isReferenceType());
 return;
   } else if (auto *OCE = dyn_cast(Call)) {
 FunctionDecl *Callee = OCE->getDirectCallee();
 if (Callee && Callee->isCXXInstanceMember() &&
 shouldTrackImplicitObjectArg(cast(Callee)))
-  VisitPointerArg(Callee, OCE->getArg(0));
+  VisitPointerArg(Callee, OCE->getArg(0),
+  !Callee->getReturnType()->isReferenceType());
 return;
   } else if (auto *CE = dyn_cast(Call)) {
 FunctionDecl *Callee = CE->getDirectCallee();
 if (Callee && shouldTrackFirstArgument(Callee))
-  VisitPointerArg(Callee, CE->getArg(0));
+  VisitPointerArg(Callee, CE->getArg(0),
+  !Callee->getReturnType()->isReferenceType());
 return;
   }
 
@@ -6821,7 +6837,7 @@ static void handleGslAnnotatedTypes(IndirectLocalPath 
, Expr *Call,
 const auto *Ctor = CCE->getConstructor();
 const CXXRecordDecl *RD = Ctor->getParent();
 if (CCE->getNumArgs() > 0 && RD->hasAttr())
-  VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
+  VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
   }
 }
 
@@ -7287,6 +7303,7 @@ static SourceRange nextPathEntryRange(const 
IndirectLocalPath , unsigned I,
 case IndirectLocalPathEntry::AddressOf:
 case IndirectLocalPathEntry::LValToRVal:
 case IndirectLocalPathEntry::LifetimeBoundCall:
+case IndirectLocalPathEntry::GslReferenceInit:
 case IndirectLocalPathEntry::GslPointerInit:
   // These exist primarily to mark the path as not permitting or
   // supporting lifetime extension.
@@ -7309,7 +7326,8 @@ static bool 
pathOnlyInitializesGslPointer(IndirectLocalPath ) {
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
-return It->Kind == IndirectLocalPathEntry::GslPointerInit;
+return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
+   It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }
   return false;
 }
@@ -7532,6 +7550,7 @@ void Sema::checkInitializerLifetime(const 
InitializedEntity ,
 
   case IndirectLocalPathEntry::LifetimeBoundCall:
   case 

r370773 - [LifetimeAnalysis] Fix some false positives

2019-09-03 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Sep  3 09:17:24 2019
New Revision: 370773

URL: http://llvm.org/viewvc/llvm-project?rev=370773=rev
Log:
[LifetimeAnalysis] Fix some false positives

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=370773=370772=370773=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Tue Sep  3 09:17:24 2019
@@ -6775,6 +6775,10 @@ static bool shouldTrackFirstArgument(con
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
 LocalVisitor Visit) {
   auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
+// We are not interested in the temporary base objects of gsl Pointers:
+//   Temp().ptr; // Here ptr might not dangle.
+if (isa(Arg->IgnoreImpCasts()))
+  return;
 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
@@ -7295,6 +7299,8 @@ static bool pathOnlyInitializesGslPointe
   for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
 if (It->Kind == IndirectLocalPathEntry::VarInit)
   continue;
+if (It->Kind == IndirectLocalPathEntry::AddressOf)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit;
   }
   return false;

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=370773=370772=370773=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Tue Sep  3 09:17:24 
2019
@@ -7,13 +7,21 @@ struct [[gsl::Owner(int)]] MyIntOwner {
 struct [[gsl::Pointer(int)]] MyIntPointer {
   MyIntPointer(int *p = nullptr);
   // Conversion operator and constructor conversion will result in two
-  // different ASTs. The former is tested with another owner and 
+  // different ASTs. The former is tested with another owner and
   // pointer type.
   MyIntPointer(const MyIntOwner &);
   int *();
   MyIntOwner toOwner();
 };
 
+struct MySpecialIntPointer : MyIntPointer {
+};
+
+// We did see examples in the wild when a derived class changes
+// the ownership model. So we have a test for it.
+struct [[gsl::Owner(int)]] MyOwnerIntPointer : MyIntPointer {
+};
+
 struct [[gsl::Pointer(long)]] MyLongPointerFromConversion {
   MyLongPointerFromConversion(long *p = nullptr);
   long *();
@@ -56,21 +64,21 @@ struct Y {
 };
 
 void dangligGslPtrFromTemporary() {
-  MyIntPointer p = Y{}.a; // expected-warning {{temporary whose address is 
used as value of local variable 'p' will be destroyed at the end of the 
full-expression}}
+  MyIntPointer p = Y{}.a; // TODO
   (void)p;
 }
 
 struct DanglingGslPtrField {
-  MyIntPointer p; // expected-note 2{{pointer member declared here}}
+  MyIntPointer p; // expected-note {{pointer member declared here}}
   MyLongPointerFromConversion p2; // expected-note {{pointer member declared 
here}}
-  DanglingGslPtrField(int i) : p() {} // expected-warning {{initializing 
pointer member 'p' with the stack address of parameter 'i'}}
+  DanglingGslPtrField(int i) : p() {} // TODO
   DanglingGslPtrField() : p2(MyLongOwnerWithConversion{}) {} // 
expected-warning {{initializing pointer member 'p2' to point to a temporary 
object whose lifetime is shorter than the lifetime of the constructed object}}
   DanglingGslPtrField(double) : p(MyIntOwner{}) {} // expected-warning 
{{initializing pointer member 'p' to point to a temporary object whose lifetime 
is shorter than the lifetime of the constructed object}}
 };
 
 MyIntPointer danglingGslPtrFromLocal() {
   int j;
-  return  // expected-warning {{address of stack memory associated with 
local variable 'j' returned}}
+  return  // TODO
 }
 
 MyIntPointer returningLocalPointer() {
@@ -124,6 +132,7 @@ template 
 struct basic_iterator {
   basic_iterator operator++();
   T& operator*() const;
+  T* operator->() const;
 };
 
 template
@@ -141,6 +150,12 @@ typename remove_reference::type &
 template 
 auto data(const C ) -> decltype(c.data());
 
+template 
+auto begin(C ) -> decltype(c.begin());
+
+template
+T *begin(T ()[N]);
+
 template 
 struct vector {
   typedef __gnu_cxx::basic_iterator iterator;
@@ -158,6 +173,8 @@ struct basic_string_view {
 
 template
 struct basic_string {
+  basic_string();
+  basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
 };
@@ -188,8 +205,23 @@ struct any {};
 
 template
 T any_cast(const any& operand);
+
+template
+struct reference_wrapper {
+ 

r369928 - [NFC] Add comments to some bool arguments for better readability

2019-08-26 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Aug 26 10:03:01 2019
New Revision: 369928

URL: http://llvm.org/viewvc/llvm-project?rev=369928=rev
Log:
[NFC] Add comments to some bool arguments for better readability

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=369928=369927=369928=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Aug 26 10:03:01 2019
@@ -6648,9 +6648,11 @@ static void handleGslAnnotatedTypes(Indi
 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit, true);
+Visit,
+/*EnableLifetimeWarnings=*/true);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true, true);
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
+   /*EnableLifetimeWarnings=*/true);
 Path.pop_back();
   };
 
@@ -6725,9 +6727,11 @@ static void visitLifetimeBoundArguments(
 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit, false);
+Visit,
+/*EnableLifetimeWarnings=*/false);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true, false);
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
+   /*EnableLifetimeWarnings=*/false);
 Path.pop_back();
   };
 


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


r369820 - Fix a test to test what the name suggest.

2019-08-23 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug 23 15:26:49 2019
New Revision: 369820

URL: http://llvm.org/viewvc/llvm-project?rev=369820=rev
Log:
Fix a test to test what the name suggest.

Modified:
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp?rev=369820=369819=369820=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp Fri Aug 23 
15:26:49 2019
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wno-dangling -Wreturn-stack-address -verify 
%s
+// RUN: %clang_cc1 -fsyntax-only -Wno-dangling-gsl -Wreturn-stack-address 
-verify %s
 
 struct [[gsl::Owner(int)]] MyIntOwner {
   MyIntOwner();


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


r369817 - [LifetimeAnalysis] Make it possible to disable the new warnings

2019-08-23 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug 23 15:21:33 2019
New Revision: 369817

URL: http://llvm.org/viewvc/llvm-project?rev=369817=rev
Log:
[LifetimeAnalysis] Make it possible to disable the new warnings

Added:
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg-disabled.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaInit.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=369817=369816=369817=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Fri Aug 23 15:21:33 2019
@@ -289,9 +289,11 @@ def OverloadedShiftOpParentheses: DiagGr
 def DanglingElse: DiagGroup<"dangling-else">;
 def DanglingField : DiagGroup<"dangling-field">;
 def DanglingInitializerList : DiagGroup<"dangling-initializer-list">;
+def DanglingGsl : DiagGroup<"dangling-gsl">;
 def ReturnStackAddress : DiagGroup<"return-stack-address">;
 def Dangling : DiagGroup<"dangling", [DanglingField,
   DanglingInitializerList,
+  DanglingGsl,
   ReturnStackAddress]>;
 def DistributedObjectModifiers : DiagGroup<"distributed-object-modifiers">;
 def ExpansionToDefined : DiagGroup<"expansion-to-defined">;

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=369817=369816=369817=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Aug 23 15:21:33 
2019
@@ -8121,7 +8121,7 @@ def warn_dangling_member : Warning<
 def warn_dangling_lifetime_pointer_member : Warning<
   "initializing pointer member %0 to point to a temporary object "
   "whose lifetime is shorter than the lifetime of the constructed object">,
-  InGroup;
+  InGroup;
 def note_lifetime_extending_member_declared_here : Note<
   "%select{%select{reference|'std::initializer_list'}0 member|"
   "member with %select{reference|'std::initializer_list'}0 subobject}1 "
@@ -8143,7 +8143,7 @@ def warn_new_dangling_reference : Warnin
 def warn_dangling_lifetime_pointer : Warning<
   "object backing the pointer "
   "will be destroyed at the end of the full-expression">,
-  InGroup;
+  InGroup;
 def warn_new_dangling_initializer_list : Warning<
   "array backing "
   "%select{initializer list subobject of the allocated object|"

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=369817=369816=369817=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug 23 15:21:33 2019
@@ -6553,11 +6553,13 @@ static bool pathContainsInit(IndirectLoc
 
 static void visitLocalsRetainedByInitializer(IndirectLocalPath ,
  Expr *Init, LocalVisitor Visit,
- bool RevisitSubinits);
+ bool RevisitSubinits,
+ bool EnableLifetimeWarnings);
 
 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath ,
   Expr *Init, ReferenceKind RK,
-  LocalVisitor Visit);
+  LocalVisitor Visit,
+  bool EnableLifetimeWarnings);
 
 template  static bool isRecordWithAttr(QualType Type) {
   if (auto *RD = Type->getAsCXXRecordDecl())
@@ -6646,9 +6648,9 @@ static void handleGslAnnotatedTypes(Indi
 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit);
+Visit, true);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true, true);
 Path.pop_back();
   };
 
@@ -6723,9 +6725,9 @@ static void visitLifetimeBoundArguments(
 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit);
+Visit, false);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
+  

r369408 - [LifetimeAnalysis] Add support for free functions

2019-08-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Aug 20 09:45:06 2019
New Revision: 369408

URL: http://llvm.org/viewvc/llvm-project?rev=369408=rev
Log:
[LifetimeAnalysis] Add support for free functions

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=369408=369407=369408=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Tue Aug 20 09:45:06 2019
@@ -6616,6 +6616,30 @@ static bool shouldTrackImplicitObjectArg
   return false;
 }
 
+static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
+  if (!FD->getIdentifier() || FD->getNumParams() != 1)
+return false;
+  const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
+  if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
+return false;
+  if (!isRecordWithAttr(QualType(RD->getTypeForDecl(), 0)) &&
+  !isRecordWithAttr(QualType(RD->getTypeForDecl(), 0)))
+return false;
+  if (FD->getReturnType()->isPointerType() ||
+  isRecordWithAttr(FD->getReturnType())) {
+return llvm::StringSwitch(FD->getName())
+.Cases("begin", "rbegin", "cbegin", "crbegin", true)
+.Cases("end", "rend", "cend", "crend", true)
+.Case("data", true)
+.Default(false);
+  } else if (FD->getReturnType()->isReferenceType()) {
+return llvm::StringSwitch(FD->getName())
+.Cases("get", "any_cast", true)
+.Default(false);
+  }
+  return false;
+}
+
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
 LocalVisitor Visit) {
   auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
@@ -6639,6 +6663,11 @@ static void handleGslAnnotatedTypes(Indi
 shouldTrackImplicitObjectArg(cast(Callee)))
   VisitPointerArg(Callee, OCE->getArg(0));
 return;
+  } else if (auto *CE = dyn_cast(Call)) {
+FunctionDecl *Callee = CE->getDirectCallee();
+if (Callee && shouldTrackFirstArgument(Callee))
+  VisitPointerArg(Callee, CE->getArg(0));
+return;
   }
 
   if (auto *CCE = dyn_cast(Call)) {

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=369408=369407=369408=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Tue Aug 20 09:45:06 
2019
@@ -131,13 +131,16 @@ bool operator!=(basic_iterator, basic
 }
 
 namespace std {
-template struct remove_reference   { typedef T type; };
-template struct remove_reference  { typedef T type; };
-template struct remove_reference { typedef T type; };
+template struct remove_reference   { typedef T type; };
+template struct remove_reference  { typedef T type; };
+template struct remove_reference { typedef T type; };
 
-template
+template
 typename remove_reference::type &(T &) noexcept;
 
+template 
+auto data(const C ) -> decltype(c.data());
+
 template 
 struct vector {
   typedef __gnu_cxx::basic_iterator iterator;
@@ -180,6 +183,11 @@ template
 struct stack {
   T ();
 };
+
+struct any {};
+
+template
+T any_cast(const any& operand);
 }
 
 void modelIterators() {
@@ -191,6 +199,22 @@ std::vector::iterator modelIterator
   return std::vector().begin(); // expected-warning {{returning address 
of local temporary object}}
 }
 
+const int *modelFreeFunctions() {
+  return std::data(std::vector()); // expected-warning {{returning 
address of local temporary object}}
+}
+
+int () {
+  return std::any_cast(std::any{}); // expected-warning {{returning 
reference to local temporary object}}
+}
+
+int modelAnyCast2() {
+  return std::any_cast(std::any{}); // ok
+}
+
+int modelAnyCast3() {
+  return std::any_cast(std::any{}); // ok
+}
+
 const char *danglingRawPtrFromLocal() {
   std::basic_string s;
   return s.c_str(); // expected-warning {{address of stack memory associated 
with local variable 's' returned}}


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


r368871 - [LifetimeAnalysis] Fix false negatives of statement local lifetime analysis for some STL implementation

2019-08-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Aug 14 09:34:56 2019
New Revision: 368871

URL: http://llvm.org/viewvc/llvm-project?rev=368871=rev
Log:
[LifetimeAnalysis] Fix false negatives of statement local lifetime analysis for 
some STL implementation

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368871=368870=368871=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Wed Aug 14 09:34:56 2019
@@ -16,6 +16,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/Initialization.h"
@@ -6564,11 +6565,29 @@ template  static bool isReco
   return false;
 }
 
+// Decl::isInStdNamespace will return false for iterators in some STL
+// implementations due to them being defined in a namespace outside of the std
+// namespace.
+static bool isInStlNamespace(const Decl *D) {
+  const DeclContext *DC = D->getDeclContext();
+  if (!DC)
+return false;
+  if (const auto *ND = dyn_cast(DC))
+if (const IdentifierInfo *II = ND->getIdentifier()) {
+  StringRef Name = II->getName();
+  if (Name.size() >= 2 && Name.front() == '_' &&
+  (Name[1] == '_' || isUppercase(Name[1])))
+return true;
+}
+
+  return DC->isStdNamespace();
+}
+
 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace())
+  if (!isInStlNamespace(Callee->getParent()))
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
@@ -7107,25 +7126,29 @@ void Sema::checkInitializerLifetime(cons
 SourceLocation DiagLoc = DiagRange.getBegin();
 
 auto *MTE = dyn_cast(L);
-bool IsTempGslOwner = MTE && !MTE->getExtendingDecl() &&
-  isRecordWithAttr(MTE->getType());
-bool IsLocalGslOwner =
-isa(L) && isRecordWithAttr(L->getType());
-
-// Skipping a chain of initializing gsl::Pointer annotated objects.
-// We are looking only for the final source to find out if it was
-// a local or temporary owner or the address of a local variable/param. We
-// do not want to follow the references when returning a pointer 
originating
-// from a local owner to avoid the following false positive:
-//   int  = *localUniquePtr;
-//   someContainer.add(std::move(localUniquePtr));
-//   return p;
-if (!IsTempGslOwner && pathOnlyInitializesGslPointer(Path) &&
-!(IsLocalGslOwner && !pathContainsInit(Path)))
-  return true;
 
-bool IsGslPtrInitWithGslTempOwner =
-IsTempGslOwner && pathOnlyInitializesGslPointer(Path);
+bool IsGslPtrInitWithGslTempOwner = false;
+bool IsLocalGslOwner = false;
+if (pathOnlyInitializesGslPointer(Path)) {
+  if (isa(L)) {
+// We do not want to follow the references when returning a pointer 
originating
+// from a local owner to avoid the following false positive:
+//   int  = *localUniquePtr;
+//   someContainer.add(std::move(localUniquePtr));
+//   return p;
+IsLocalGslOwner = isRecordWithAttr(L->getType());
+if (pathContainsInit(Path) || !IsLocalGslOwner)
+  return false;
+  } else {
+IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
+isRecordWithAttr(MTE->getType());
+// Skipping a chain of initializing gsl::Pointer annotated objects.
+// We are looking only for the final source to find out if it was
+// a local or temporary owner or the address of a local variable/param.
+if (!IsGslPtrInitWithGslTempOwner)
+  return true;
+  }
+}
 
 switch (LK) {
 case LK_FullExpression:

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368871=368870=368871=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Wed Aug 14 09:34:56 
2019
@@ -119,14 +119,7 @@ void initLocalGslPtrWithTempOwner() {
   global2 = MyLongOwnerWithConversion{}; // TODO ?
 }
 
-namespace std {
-template struct remove_reference   { typedef T type; };
-template struct remove_reference  { typedef T type; };
-template struct remove_reference { typedef T type; };
-

r368588 - Fix multiple lifetime warning messages for range based for loop

2019-08-12 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Aug 12 09:19:39 2019
New Revision: 368588

URL: http://llvm.org/viewvc/llvm-project?rev=368588=rev
Log:
Fix multiple lifetime warning messages for range based for loop

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368588=368587=368588=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Aug 12 09:19:39 2019
@@ -7070,8 +7070,11 @@ static SourceRange nextPathEntryRange(co
   // supporting lifetime extension.
   break;
 
-case IndirectLocalPathEntry::DefaultInit:
 case IndirectLocalPathEntry::VarInit:
+  if (cast(Path[I].D)->isImplicit())
+return SourceRange();
+  LLVM_FALLTHROUGH;
+case IndirectLocalPathEntry::DefaultInit:
   return Path[I].E->getSourceRange();
 }
   }
@@ -7138,7 +7141,7 @@ void Sema::checkInitializerLifetime(cons
 return false;
   }
 
-  if (IsGslPtrInitWithGslTempOwner) {
+  if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
 return false;
   }

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368588=368587=368588=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Mon Aug 12 09:19:39 
2019
@@ -209,6 +209,13 @@ void danglingReferenceFromTempOwner() {
 std::vector getTempVec();
 std::optional> getTempOptVec();
 
+void testLoops() {
+  for (auto i : getTempVec()) // ok
+;
+  for (auto i : *getTempOptVec()) // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+;
+}
+
 int (std::vector ) {
   std::vector::iterator it = v.begin();
   int& value = *it;


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


r368534 - Properly detect temporary gsl::Owners through reference initialization chains.

2019-08-11 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sun Aug 11 07:39:42 2019
New Revision: 368534

URL: http://llvm.org/viewvc/llvm-project?rev=368534=rev
Log:
Properly detect temporary gsl::Owners through reference initialization chains.

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368534=368533=368534=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Sun Aug 11 07:39:42 2019
@@ -7104,7 +7104,8 @@ void Sema::checkInitializerLifetime(cons
 SourceLocation DiagLoc = DiagRange.getBegin();
 
 auto *MTE = dyn_cast(L);
-bool IsTempGslOwner = MTE && isRecordWithAttr(MTE->getType());
+bool IsTempGslOwner = MTE && !MTE->getExtendingDecl() &&
+  isRecordWithAttr(MTE->getType());
 bool IsLocalGslOwner =
 isa(L) && isRecordWithAttr(L->getType());
 

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368534=368533=368534=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Sun Aug 11 07:39:42 
2019
@@ -141,7 +141,7 @@ struct vector {
   typedef basic_iterator iterator;
   iterator begin();
   iterator end();
-  T *data();
+  const T *data() const;
   T (int n);
 };
 
@@ -235,8 +235,14 @@ struct X {
 };
 
 std::vector::iterator getIt();
+std::vector getVec();
 
-const int (const std::vector ) {
+const int () {
   const auto  = getIt(); // Ok, it is lifetime extended.
   return *it;
 }
+
+void handleGslPtrInitsThroughReference2() {
+  const std::vector  = getVec();
+  const int *val = v.data(); // Ok, it is lifetime extended.
+}


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


r368528 - Properly handle reference initialization when detecting gsl::Pointer initialization chains

2019-08-11 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sun Aug 11 01:05:28 2019
New Revision: 368528

URL: http://llvm.org/viewvc/llvm-project?rev=368528=rev
Log:
Properly handle reference initialization when detecting gsl::Pointer 
initialization chains

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368528=368527=368528=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Sun Aug 11 01:05:28 2019
@@ -7079,8 +7079,12 @@ static SourceRange nextPathEntryRange(co
 }
 
 static bool pathOnlyInitializesGslPointer(IndirectLocalPath ) {
-  return !Path.empty() &&
- Path.back().Kind == IndirectLocalPathEntry::GslPointerInit;
+  for (auto It = Path.rbegin(), End = Path.rend(); It != End; ++It) {
+if (It->Kind == IndirectLocalPathEntry::VarInit)
+  continue;
+return It->Kind == IndirectLocalPathEntry::GslPointerInit;
+  }
+  return false;
 }
 
 void Sema::checkInitializerLifetime(const InitializedEntity ,
@@ -7109,8 +7113,8 @@ void Sema::checkInitializerLifetime(cons
 // a local or temporary owner or the address of a local variable/param. We
 // do not want to follow the references when returning a pointer 
originating
 // from a local owner to avoid the following false positive:
-//   int  = *localOwner;
-//   someContainer.add(std::move(localOwner));
+//   int  = *localUniquePtr;
+//   someContainer.add(std::move(localUniquePtr));
 //   return p;
 if (!IsTempGslOwner && pathOnlyInitializesGslPointer(Path) &&
 !(IsLocalGslOwner && !pathContainsInit(Path)))
@@ -7217,7 +7221,7 @@ void Sema::checkInitializerLifetime(cons
 if (pathContainsInit(Path))
   return false;
 
-// Suppress false positives for code like the below:
+// Suppress false positives for code like the one below:
 //   Ctor(unique_ptr up) : member(*up), member2(move(up)) {}
 if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
   return false;

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368528=368527=368528=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Sun Aug 11 01:05:28 
2019
@@ -130,7 +130,7 @@ typename remove_reference::type &
 template 
 struct basic_iterator {
   basic_iterator operator++();
-  T& operator*();
+  T& operator*() const;
 };
 
 template
@@ -227,8 +227,16 @@ const char *trackThroughMultiplePointer(
 }
 
 struct X {
-  X(std::unique_ptr up) : pointee(*up), pointer(std::move(up)) {}
-
+  X(std::unique_ptr up) :
+pointee(*up), pointee2(up.get()), pointer(std::move(up)) {}
   int 
+  int *pointee2;
   std::unique_ptr pointer;
 };
+
+std::vector::iterator getIt();
+
+const int (const std::vector ) {
+  const auto  = getIt(); // Ok, it is lifetime extended.
+  return *it;
+}


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


r368501 - Fix a false positive warning when initializing members with gsl::Owners.

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 17:32:29 2019
New Revision: 368501

URL: http://llvm.org/viewvc/llvm-project?rev=368501=rev
Log:
Fix a false positive warning when initializing members with gsl::Owners.

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368501=368500=368501=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 17:32:29 2019
@@ -7217,6 +7217,11 @@ void Sema::checkInitializerLifetime(cons
 if (pathContainsInit(Path))
   return false;
 
+// Suppress false positives for code like the below:
+//   Ctor(unique_ptr up) : member(*up), member2(move(up)) {}
+if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
+  return false;
+
 auto *DRE = dyn_cast(L);
 auto *VD = DRE ? dyn_cast(DRE->getDecl()) : nullptr;
 if (!VD) {

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368501=368500=368501=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 17:32:29 
2019
@@ -120,6 +120,13 @@ void initLocalGslPtrWithTempOwner() {
 }
 
 namespace std {
+template struct remove_reference   { typedef T type; };
+template struct remove_reference  { typedef T type; };
+template struct remove_reference { typedef T type; };
+
+template
+typename remove_reference::type &(T &) noexcept;
+
 template 
 struct basic_iterator {
   basic_iterator operator++();
@@ -153,6 +160,7 @@ struct basic_string {
 
 template
 struct unique_ptr {
+  T *();
   T *get() const;
 };
 
@@ -217,3 +225,10 @@ int (
 const char *trackThroughMultiplePointer() {
   return std::basic_string_view(std::basic_string()).begin(); // 
expected-warning {{returning address of local temporary object}}
 }
+
+struct X {
+  X(std::unique_ptr up) : pointee(*up), pointer(std::move(up)) {}
+
+  int 
+  std::unique_ptr pointer;
+};


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


r368499 - Attempt to reapply "Even more warnings utilizing gsl::Owner/gsl::Pointer annotations"

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 16:03:50 2019
New Revision: 368499

URL: http://llvm.org/viewvc/llvm-project?rev=368499=rev
Log:
Attempt to reapply "Even more warnings utilizing gsl::Owner/gsl::Pointer 
annotations"

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368499=368498=368499=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 16:03:50 2019
@@ -6568,19 +6568,33 @@ static bool shouldTrackImplicitObjectArg
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace() || !Callee->getIdentifier())
+  if (!Callee->getParent()->isInStdNamespace())
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
 return false;
-  if (!isRecordWithAttr(Callee->getReturnType()) &&
-  !Callee->getReturnType()->isPointerType())
-return false;
-  return llvm::StringSwitch(Callee->getName())
-  .Cases("begin", "rbegin", "cbegin", "crbegin", true)
-  .Cases("end", "rend", "cend", "crend", true)
-  .Cases("c_str", "data", "get", true)
-  .Default(false);
+  if (Callee->getReturnType()->isPointerType() ||
+  isRecordWithAttr(Callee->getReturnType())) {
+if (!Callee->getIdentifier())
+  return false;
+return llvm::StringSwitch(Callee->getName())
+.Cases("begin", "rbegin", "cbegin", "crbegin", true)
+.Cases("end", "rend", "cend", "crend", true)
+.Cases("c_str", "data", "get", true)
+// Map and set types.
+.Cases("find", "equal_range", "lower_bound", "upper_bound", true)
+.Default(false);
+  } else if (Callee->getReturnType()->isReferenceType()) {
+if (!Callee->getIdentifier()) {
+  auto OO = Callee->getOverloadedOperator();
+  return OO == OverloadedOperatorKind::OO_Subscript ||
+ OO == OverloadedOperatorKind::OO_Star;
+}
+return llvm::StringSwitch(Callee->getName())
+.Cases("front", "back", "at", true)
+.Default(false);
+  }
+  return false;
 }
 
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
@@ -6600,6 +6614,12 @@ static void handleGslAnnotatedTypes(Indi
 if (MD && shouldTrackImplicitObjectArg(MD))
   VisitPointerArg(MD, MCE->getImplicitObjectArgument());
 return;
+  } else if (auto *OCE = dyn_cast(Call)) {
+FunctionDecl *Callee = OCE->getDirectCallee();
+if (Callee && Callee->isCXXInstanceMember() &&
+shouldTrackImplicitObjectArg(cast(Callee)))
+  VisitPointerArg(Callee, OCE->getArg(0));
+return;
   }
 
   if (auto *CCE = dyn_cast(Call)) {

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368499=368498=368499=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 16:03:50 
2019
@@ -121,24 +121,47 @@ void initLocalGslPtrWithTempOwner() {
 
 namespace std {
 template 
-struct basic_iterator {};
+struct basic_iterator {
+  basic_iterator operator++();
+  T& operator*();
+};
+
+template
+bool operator!=(basic_iterator, basic_iterator);
 
 template 
 struct vector {
   typedef basic_iterator iterator;
   iterator begin();
+  iterator end();
   T *data();
+  T (int n);
+};
+
+template
+struct basic_string_view {
+  basic_string_view(const T *);
+  const T *begin() const;
 };
 
 template
 struct basic_string {
   const T *c_str() const;
+  operator basic_string_view () const;
 };
 
+
 template
 struct unique_ptr {
   T *get() const;
 };
+
+template
+struct optional {
+  optional();
+  optional(const T&);
+  T *();
+};
 }
 
 void modelIterators() {
@@ -168,3 +191,29 @@ int *danglingUniquePtrFromTemp() {
 int *danglingUniquePtrFromTemp2() {
   return std::unique_ptr().get(); // expected-warning {{returning address 
of local temporary object}}
 }
+
+void danglingReferenceFromTempOwner() {
+  int  = *std::optional(); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+  int  = *std::optional(5); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+  int  = std::vector().at(3); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+}
+
+std::vector getTempVec();
+std::optional> getTempOptVec();
+
+int (std::vector ) {
+  std::vector::iterator it = v.begin();
+  int& value = *it;
+  return value; // ok
+}
+
+int () {
+  std::unique_ptr 

r368463 - Revert Even more warnings utilizing gsl::Owner/gsl::Pointer annotations

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 12:01:23 2019
New Revision: 368463

URL: http://llvm.org/viewvc/llvm-project?rev=368463=rev
Log:
Revert Even more warnings utilizing gsl::Owner/gsl::Pointer annotations

This reverts r368454 (git commit 7c3c8ba8daf40534e09f6fe8701b723e25e4e2dc)

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368463=368462=368463=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 12:01:23 2019
@@ -6568,33 +6568,19 @@ static bool shouldTrackImplicitObjectArg
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace())
+  if (!Callee->getParent()->isInStdNamespace() || !Callee->getIdentifier())
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
 return false;
-  if (Callee->getReturnType()->isPointerType() ||
-  isRecordWithAttr(Callee->getReturnType())) {
-if (!Callee->getIdentifier())
-  return false;
-return llvm::StringSwitch(Callee->getName())
-.Cases("begin", "rbegin", "cbegin", "crbegin", true)
-.Cases("end", "rend", "cend", "crend", true)
-.Cases("c_str", "data", "get", true)
-// Map and set types.
-.Cases("find", "equal_range", "lower_bound", "upper_bound", true)
-.Default(false);
-  } else if (Callee->getReturnType()->isReferenceType()) {
-if (!Callee->getIdentifier()) {
-  auto OO = Callee->getOverloadedOperator();
-  return OO == OverloadedOperatorKind::OO_Subscript ||
- OO == OverloadedOperatorKind::OO_Star;
-}
-return llvm::StringSwitch(Callee->getName())
-.Cases("front", "back", "at", true)
-.Default(false);
-  }
-  return false;
+  if (!isRecordWithAttr(Callee->getReturnType()) &&
+  !Callee->getReturnType()->isPointerType())
+return false;
+  return llvm::StringSwitch(Callee->getName())
+  .Cases("begin", "rbegin", "cbegin", "crbegin", true)
+  .Cases("end", "rend", "cend", "crend", true)
+  .Cases("c_str", "data", "get", true)
+  .Default(false);
 }
 
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
@@ -6614,12 +6600,6 @@ static void handleGslAnnotatedTypes(Indi
 if (MD && shouldTrackImplicitObjectArg(MD))
   VisitPointerArg(MD, MCE->getImplicitObjectArgument());
 return;
-  } else if (auto *OCE = dyn_cast(Call)) {
-FunctionDecl *Callee = OCE->getDirectCallee();
-if (Callee->isCXXInstanceMember() &&
-shouldTrackImplicitObjectArg(cast(Callee)))
-  VisitPointerArg(Callee, OCE->getArg(0));
-return;
   }
 
   if (auto *CCE = dyn_cast(Call)) {

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368463=368462=368463=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 12:01:23 
2019
@@ -121,47 +121,24 @@ void initLocalGslPtrWithTempOwner() {
 
 namespace std {
 template 
-struct basic_iterator {
-  basic_iterator operator++();
-  T& operator*();
-};
-
-template
-bool operator!=(basic_iterator, basic_iterator);
+struct basic_iterator {};
 
 template 
 struct vector {
   typedef basic_iterator iterator;
   iterator begin();
-  iterator end();
   T *data();
-  T (int n);
-};
-
-template
-struct basic_string_view {
-  basic_string_view(const T *);
-  const T *begin() const;
 };
 
 template
 struct basic_string {
   const T *c_str() const;
-  operator basic_string_view () const;
 };
 
-
 template
 struct unique_ptr {
   T *get() const;
 };
-
-template
-struct optional {
-  optional();
-  optional(const T&);
-  T *();
-};
 }
 
 void modelIterators() {
@@ -191,29 +168,3 @@ int *danglingUniquePtrFromTemp() {
 int *danglingUniquePtrFromTemp2() {
   return std::unique_ptr().get(); // expected-warning {{returning address 
of local temporary object}}
 }
-
-void danglingReferenceFromTempOwner() {
-  int  = *std::optional(); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
-  int  = *std::optional(5); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
-  int  = std::vector().at(3); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
-}
-
-std::vector getTempVec();
-std::optional> getTempOptVec();
-
-int (std::vector ) {
-  std::vector::iterator it = v.begin();
-  int& value = *it;
-  return 

r368462 - Revert Fix a build bot failure and multiple warnings instances for range base for loops

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 11:58:09 2019
New Revision: 368462

URL: http://llvm.org/viewvc/llvm-project?rev=368462=rev
Log:
Revert Fix a build bot failure and multiple warnings instances for range base 
for loops

This reverts r368459 (git commit 2bf522aea62e4fb653cacb68072167d25149099e)

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368462=368461=368462=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 11:58:09 2019
@@ -6616,7 +6616,7 @@ static void handleGslAnnotatedTypes(Indi
 return;
   } else if (auto *OCE = dyn_cast(Call)) {
 FunctionDecl *Callee = OCE->getDirectCallee();
-if (Callee && Callee->isCXXInstanceMember() &&
+if (Callee->isCXXInstanceMember() &&
 shouldTrackImplicitObjectArg(cast(Callee)))
   VisitPointerArg(Callee, OCE->getArg(0));
 return;
@@ -7070,11 +7070,8 @@ static SourceRange nextPathEntryRange(co
   // supporting lifetime extension.
   break;
 
-case IndirectLocalPathEntry::VarInit:
-  if (cast(Path[I].D)->isImplicit())
-return SourceRange();
-  LLVM_FALLTHROUGH;
 case IndirectLocalPathEntry::DefaultInit:
+case IndirectLocalPathEntry::VarInit:
   return Path[I].E->getSourceRange();
 }
   }
@@ -7136,7 +7133,7 @@ void Sema::checkInitializerLifetime(cons
 return false;
   }
 
-  if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
+  if (IsGslPtrInitWithGslTempOwner) {
 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
 return false;
   }

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368462=368461=368462=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 11:58:09 
2019
@@ -201,13 +201,6 @@ void danglingReferenceFromTempOwner() {
 std::vector getTempVec();
 std::optional> getTempOptVec();
 
-void testLoops() {
-  for (auto i : getTempVec()) // ok
-;
-  for (auto i : *getTempOptVec()) // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
-;
-}
-
 int (std::vector ) {
   std::vector::iterator it = v.begin();
   int& value = *it;


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


r368459 - Fix a build bot failure and multiple warnings instances for range base for loops

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 10:42:41 2019
New Revision: 368459

URL: http://llvm.org/viewvc/llvm-project?rev=368459=rev
Log:
Fix a build bot failure and multiple warnings instances for range base for loops

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368459=368458=368459=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 10:42:41 2019
@@ -6616,7 +6616,7 @@ static void handleGslAnnotatedTypes(Indi
 return;
   } else if (auto *OCE = dyn_cast(Call)) {
 FunctionDecl *Callee = OCE->getDirectCallee();
-if (Callee->isCXXInstanceMember() &&
+if (Callee && Callee->isCXXInstanceMember() &&
 shouldTrackImplicitObjectArg(cast(Callee)))
   VisitPointerArg(Callee, OCE->getArg(0));
 return;
@@ -7070,8 +7070,11 @@ static SourceRange nextPathEntryRange(co
   // supporting lifetime extension.
   break;
 
-case IndirectLocalPathEntry::DefaultInit:
 case IndirectLocalPathEntry::VarInit:
+  if (cast(Path[I].D)->isImplicit())
+return SourceRange();
+  LLVM_FALLTHROUGH;
+case IndirectLocalPathEntry::DefaultInit:
   return Path[I].E->getSourceRange();
 }
   }
@@ -7133,7 +7136,7 @@ void Sema::checkInitializerLifetime(cons
 return false;
   }
 
-  if (IsGslPtrInitWithGslTempOwner) {
+  if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
 Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
 return false;
   }

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368459=368458=368459=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 10:42:41 
2019
@@ -201,6 +201,13 @@ void danglingReferenceFromTempOwner() {
 std::vector getTempVec();
 std::optional> getTempOptVec();
 
+void testLoops() {
+  for (auto i : getTempVec()) // ok
+;
+  for (auto i : *getTempOptVec()) // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+;
+}
+
 int (std::vector ) {
   std::vector::iterator it = v.begin();
   int& value = *it;


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


r368454 - Even more warnings utilizing gsl::Owner/gsl::Pointer annotations

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 10:11:32 2019
New Revision: 368454

URL: http://llvm.org/viewvc/llvm-project?rev=368454=rev
Log:
Even more warnings utilizing gsl::Owner/gsl::Pointer annotations

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368454=368453=368454=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 10:11:32 2019
@@ -6568,19 +6568,33 @@ static bool shouldTrackImplicitObjectArg
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace() || !Callee->getIdentifier())
+  if (!Callee->getParent()->isInStdNamespace())
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
 return false;
-  if (!isRecordWithAttr(Callee->getReturnType()) &&
-  !Callee->getReturnType()->isPointerType())
-return false;
-  return llvm::StringSwitch(Callee->getName())
-  .Cases("begin", "rbegin", "cbegin", "crbegin", true)
-  .Cases("end", "rend", "cend", "crend", true)
-  .Cases("c_str", "data", "get", true)
-  .Default(false);
+  if (Callee->getReturnType()->isPointerType() ||
+  isRecordWithAttr(Callee->getReturnType())) {
+if (!Callee->getIdentifier())
+  return false;
+return llvm::StringSwitch(Callee->getName())
+.Cases("begin", "rbegin", "cbegin", "crbegin", true)
+.Cases("end", "rend", "cend", "crend", true)
+.Cases("c_str", "data", "get", true)
+// Map and set types.
+.Cases("find", "equal_range", "lower_bound", "upper_bound", true)
+.Default(false);
+  } else if (Callee->getReturnType()->isReferenceType()) {
+if (!Callee->getIdentifier()) {
+  auto OO = Callee->getOverloadedOperator();
+  return OO == OverloadedOperatorKind::OO_Subscript ||
+ OO == OverloadedOperatorKind::OO_Star;
+}
+return llvm::StringSwitch(Callee->getName())
+.Cases("front", "back", "at", true)
+.Default(false);
+  }
+  return false;
 }
 
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
@@ -6600,6 +6614,12 @@ static void handleGslAnnotatedTypes(Indi
 if (MD && shouldTrackImplicitObjectArg(MD))
   VisitPointerArg(MD, MCE->getImplicitObjectArgument());
 return;
+  } else if (auto *OCE = dyn_cast(Call)) {
+FunctionDecl *Callee = OCE->getDirectCallee();
+if (Callee->isCXXInstanceMember() &&
+shouldTrackImplicitObjectArg(cast(Callee)))
+  VisitPointerArg(Callee, OCE->getArg(0));
+return;
   }
 
   if (auto *CCE = dyn_cast(Call)) {

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368454=368453=368454=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 10:11:32 
2019
@@ -121,24 +121,47 @@ void initLocalGslPtrWithTempOwner() {
 
 namespace std {
 template 
-struct basic_iterator {};
+struct basic_iterator {
+  basic_iterator operator++();
+  T& operator*();
+};
+
+template
+bool operator!=(basic_iterator, basic_iterator);
 
 template 
 struct vector {
   typedef basic_iterator iterator;
   iterator begin();
+  iterator end();
   T *data();
+  T (int n);
+};
+
+template
+struct basic_string_view {
+  basic_string_view(const T *);
+  const T *begin() const;
 };
 
 template
 struct basic_string {
   const T *c_str() const;
+  operator basic_string_view () const;
 };
 
+
 template
 struct unique_ptr {
   T *get() const;
 };
+
+template
+struct optional {
+  optional();
+  optional(const T&);
+  T *();
+};
 }
 
 void modelIterators() {
@@ -168,3 +191,29 @@ int *danglingUniquePtrFromTemp() {
 int *danglingUniquePtrFromTemp2() {
   return std::unique_ptr().get(); // expected-warning {{returning address 
of local temporary object}}
 }
+
+void danglingReferenceFromTempOwner() {
+  int  = *std::optional(); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+  int  = *std::optional(5); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+  int  = std::vector().at(3); // expected-warning {{object backing the 
pointer will be destroyed at the end of the full-expression}}
+}
+
+std::vector getTempVec();
+std::optional> getTempOptVec();
+
+int (std::vector ) {
+  std::vector::iterator it = v.begin();
+  int& value = *it;
+  return value; // ok
+}
+
+int () {

r368446 - More warnings regarding gsl::Pointer and gsl::Owner attributes

2019-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Aug  9 08:16:35 2019
New Revision: 368446

URL: http://llvm.org/viewvc/llvm-project?rev=368446=rev
Log:
More warnings regarding gsl::Pointer and gsl::Owner attributes

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Analysis/inner-pointer.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368446=368445=368446=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Aug  9 08:16:35 2019
@@ -6564,6 +6564,25 @@ template  static bool isReco
   return false;
 }
 
+static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
+  if (auto *Conv = dyn_cast_or_null(Callee))
+if (isRecordWithAttr(Conv->getConversionType()))
+  return true;
+  if (!Callee->getParent()->isInStdNamespace() || !Callee->getIdentifier())
+return false;
+  if (!isRecordWithAttr(Callee->getThisObjectType()) &&
+  !isRecordWithAttr(Callee->getThisObjectType()))
+return false;
+  if (!isRecordWithAttr(Callee->getReturnType()) &&
+  !Callee->getReturnType()->isPointerType())
+return false;
+  return llvm::StringSwitch(Callee->getName())
+  .Cases("begin", "rbegin", "cbegin", "crbegin", true)
+  .Cases("end", "rend", "cend", "crend", true)
+  .Cases("c_str", "data", "get", true)
+  .Default(false);
+}
+
 static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
 LocalVisitor Visit) {
   auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
@@ -6577,10 +6596,9 @@ static void handleGslAnnotatedTypes(Indi
   };
 
   if (auto *MCE = dyn_cast(Call)) {
-const FunctionDecl *Callee = MCE->getDirectCallee();
-if (auto *Conv = dyn_cast_or_null(Callee))
-  if (isRecordWithAttr(Conv->getConversionType()))
-VisitPointerArg(Callee, MCE->getImplicitObjectArgument());
+const auto *MD = cast_or_null(MCE->getDirectCallee());
+if (MD && shouldTrackImplicitObjectArg(MD))
+  VisitPointerArg(MD, MCE->getImplicitObjectArgument());
 return;
   }
 

Modified: cfe/trunk/test/Analysis/inner-pointer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/inner-pointer.cpp?rev=368446=368445=368446=diff
==
--- cfe/trunk/test/Analysis/inner-pointer.cpp (original)
+++ cfe/trunk/test/Analysis/inner-pointer.cpp Fri Aug  9 08:16:35 2019
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.InnerPointer \
+// RUN: %clang_analyze_cc1 -analyzer-checker=cplusplus.InnerPointer   \
+// RUN:   -Wno-dangling -Wno-dangling-field -Wno-return-stack-address \
 // RUN:   %s -analyzer-output=text -verify
 
 #include "Inputs/system-header-simulator-cxx.h"

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368446=368445=368446=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Fri Aug  9 08:16:35 
2019
@@ -2,7 +2,6 @@
 struct [[gsl::Owner(int)]] MyIntOwner {
   MyIntOwner();
   int *();
-  int *c_str() const;
 };
 
 struct [[gsl::Pointer(int)]] MyIntPointer {
@@ -52,16 +51,6 @@ long *ownershipTransferToRawPointer() {
   return t.releaseAsRawPointer(); // ok
 }
 
-int *danglingRawPtrFromLocal() {
-  MyIntOwner t;
-  return t.c_str(); // TODO
-}
-
-int *danglingRawPtrFromTemp() {
-  MyIntPointer p;
-  return p.toOwner().c_str(); // TODO
-}
-
 struct Y {
   int a[4];
 };
@@ -103,6 +92,12 @@ MyIntPointer danglingGslPtrFromTemporary
   return MyIntOwner{}; // expected-warning {{returning address of local 
temporary object}}
 }
 
+MyIntOwner makeTempOwner();
+
+MyIntPointer danglingGslPtrFromTemporary2() {
+  return makeTempOwner(); // expected-warning {{returning address of local 
temporary object}}
+}
+
 MyLongPointerFromConversion danglingGslPtrFromTemporaryConv() {
   return MyLongOwnerWithConversion{}; // expected-warning {{returning address 
of local temporary object}}
 }
@@ -124,12 +119,52 @@ void initLocalGslPtrWithTempOwner() {
   global2 = MyLongOwnerWithConversion{}; // TODO ?
 }
 
-struct IntVector {
-  int *begin();
-  int *end();
+namespace std {
+template 
+struct basic_iterator {};
+
+template 
+struct vector {
+  typedef basic_iterator iterator;
+  iterator begin();
+  T *data();
+};
+
+template
+struct basic_string {
+  const T *c_str() const;
+};
+
+template
+struct unique_ptr {
+  T *get() const;
 };
+}
 
 void modelIterators() {
-  int *it = IntVector{}.begin(); // TODO ?
+  std::vector::iterator it = std::vector().begin(); // 

r368072 - Teach some warnings to respect gsl::Pointer and gsl::Owner attributes

2019-08-06 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Aug  6 12:13:29 2019
New Revision: 368072

URL: http://llvm.org/viewvc/llvm-project?rev=368072=rev
Log:
Teach some warnings to respect gsl::Pointer and gsl::Owner attributes

This patch extends some existing warnings to utilize the knowledge about the 
gsl::Pointer and gsl::Owner attributes.

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

Added:
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaInit.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=368072=368071=368072=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug  6 12:13:29 
2019
@@ -8107,6 +8107,10 @@ def warn_dangling_member : Warning<
   "%select{binds to|is}2 a temporary object "
   "whose lifetime is shorter than the lifetime of the constructed object">,
   InGroup;
+def warn_dangling_lifetime_pointer_member : Warning<
+  "initializing pointer member %0 to point to a temporary object "
+  "whose lifetime is shorter than the lifetime of the constructed object">,
+  InGroup;
 def note_lifetime_extending_member_declared_here : Note<
   "%select{%select{reference|'std::initializer_list'}0 member|"
   "member with %select{reference|'std::initializer_list'}0 subobject}1 "
@@ -8125,6 +8129,10 @@ def warn_new_dangling_reference : Warnin
   "temporary bound to reference member of allocated object "
   "will be destroyed at the end of the full-expression">,
   InGroup;
+def warn_dangling_lifetime_pointer : Warning<
+  "object backing the pointer "
+  "will be destroyed at the end of the full-expression">,
+  InGroup;
 def warn_new_dangling_initializer_list : Warning<
   "array backing "
   "%select{initializer list subobject of the allocated object|"

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368072=368071=368072=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Tue Aug  6 12:13:29 2019
@@ -6513,6 +6513,7 @@ struct IndirectLocalPathEntry {
 VarInit,
 LValToRVal,
 LifetimeBoundCall,
+GslPointerInit
   } Kind;
   Expr *E;
   const Decl *D = nullptr;
@@ -6557,6 +6558,40 @@ static void visitLocalsRetainedByReferen
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
+template  static bool isRecordWithAttr(QualType Type) {
+  if (auto *RD = Type->getAsCXXRecordDecl())
+return RD->getCanonicalDecl()->hasAttr();
+  return false;
+}
+
+static void handleGslAnnotatedTypes(IndirectLocalPath , Expr *Call,
+LocalVisitor Visit) {
+  auto VisitPointerArg = [&](const Decl *D, Expr *Arg) {
+Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
+if (Arg->isGLValue())
+  visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
+Visit);
+else
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true);
+Path.pop_back();
+  };
+
+  if (auto *MCE = dyn_cast(Call)) {
+const FunctionDecl *Callee = MCE->getDirectCallee();
+if (auto *Conv = dyn_cast_or_null(Callee))
+  if (isRecordWithAttr(Conv->getConversionType()))
+VisitPointerArg(Callee, MCE->getImplicitObjectArgument());
+return;
+  }
+
+  if (auto *CCE = dyn_cast(Call)) {
+const auto *Ctor = CCE->getConstructor();
+const CXXRecordDecl *RD = Ctor->getParent()->getCanonicalDecl();
+if (CCE->getNumArgs() > 0 && RD->hasAttr())
+  VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0]);
+  }
+}
+
 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
   if (!TSI)
@@ -6678,8 +6713,10 @@ static void visitLocalsRetainedByReferen
true);
   }
 
-  if (isa(Init))
+  if (isa(Init)) {
+handleGslAnnotatedTypes(Path, Init, Visit);
 return visitLifetimeBoundArguments(Path, Init, Visit);
+  }
 
   switch (Init->getStmtClass()) {
   case Stmt::DeclRefExprClass: {
@@ -6905,8 +6942,10 @@ static void visitLocalsRetainedByInitial
 }
   }
 
-  if (isa(Init) || isa(Init))
+  if (isa(Init) || isa(Init)) {
+handleGslAnnotatedTypes(Path, Init, Visit);
 return visitLifetimeBoundArguments(Path, Init, Visit);
+  }
 
   switch (Init->getStmtClass()) {
   case Stmt::UnaryOperatorClass: {
@@ -6988,6 +7027,7 @@ static SourceRange nextPathEntryRange(co
 case IndirectLocalPathEntry::AddressOf:
 case 

r352473 - [analyzer] Toning down invalidation a bit

2019-01-29 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Jan 29 02:27:14 2019
New Revision: 352473

URL: http://llvm.org/viewvc/llvm-project?rev=352473=rev
Log:
[analyzer] Toning down invalidation a bit

When a function takes the address of a field the analyzer will no longer
assume that the function will change other fields of the enclosing structs.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
cfe/trunk/test/Analysis/call-invalidation.cpp
cfe/trunk/test/Analysis/cxx-uninitialized-object.cpp
cfe/trunk/test/Analysis/malloc.c
cfe/trunk/test/Analysis/taint-generic.c
cfe/trunk/test/Analysis/taint-tester.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=352473=352472=352473=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Tue Jan 29 02:27:14 2019
@@ -303,11 +303,23 @@ ProgramStateRef CallEvent::invalidateReg
   for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
 // Mark this region for invalidation.  We batch invalidate regions
 // below for efficiency.
-if (PreserveArgs.count(Idx))
-  if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
-ETraits.setTrait(MR->getBaseRegion(),
-
RegionAndSymbolInvalidationTraits::TK_PreserveContents);
-// TODO: Factor this out + handle the lower level const pointers.
+if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) {
+  bool UseBaseRegion = true;
+  if (const auto *FR = MR->getAs()) {
+if (const auto *TVR = FR->getSuperRegion()->getAs()) 
{
+  if (!TVR->getValueType()->isUnionType()) {
+ETraits.setTrait(MR, RegionAndSymbolInvalidationTraits::
+ TK_DoNotInvalidateSuperRegion);
+UseBaseRegion = false;
+  }
+}
+  }
+  // todo: factor this out + handle the lower level const pointers.
+  if (PreserveArgs.count(Idx))
+ETraits.setTrait(
+UseBaseRegion ? MR->getBaseRegion() : MR,
+RegionAndSymbolInvalidationTraits::TK_PreserveContents);
+}
 
 ValuesToInvalidate.push_back(getArgSVal(Idx));
 

Modified: cfe/trunk/test/Analysis/call-invalidation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call-invalidation.cpp?rev=352473=352472=352473=diff
==
--- cfe/trunk/test/Analysis/call-invalidation.cpp (original)
+++ cfe/trunk/test/Analysis/call-invalidation.cpp Tue Jan 29 02:27:14 2019
@@ -132,18 +132,21 @@ void testInvalidationThroughBaseRegionPo
   PlainStruct s1;
   s1.x = 1;
   s1.z = 1;
+  s1.y = 1;
   clang_analyzer_eval(s1.x == 1); // expected-warning{{TRUE}}
   clang_analyzer_eval(s1.z == 1); // expected-warning{{TRUE}}
   // Not only passing a structure pointer through const pointer parameter,
   // but also passing a field pointer through const pointer parameter
   // should preserve the contents of the structure.
   useAnythingConst(&(s1.y));
+  clang_analyzer_eval(s1.y == 1); // expected-warning{{TRUE}}
   clang_analyzer_eval(s1.x == 1); // expected-warning{{TRUE}}
   // FIXME: Should say "UNKNOWN", because it is not uncommon to
   // modify a mutable member variable through const pointer.
   clang_analyzer_eval(s1.z == 1); // expected-warning{{TRUE}}
   useAnything(&(s1.y));
-  clang_analyzer_eval(s1.x == 1); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(s1.x == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(s1.y == 1); // expected-warning{{UNKNOWN}}
 }
 
 

Modified: cfe/trunk/test/Analysis/cxx-uninitialized-object.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cxx-uninitialized-object.cpp?rev=352473=352472=352473=diff
==
--- cfe/trunk/test/Analysis/cxx-uninitialized-object.cpp (original)
+++ cfe/trunk/test/Analysis/cxx-uninitialized-object.cpp Tue Jan 29 02:27:14 
2019
@@ -358,7 +358,7 @@ template 
 void wontInitialize(const T &);
 
 class PassingToUnknownFunctionTest1 {
-  int a, b;
+  int a, b; // expected-note{{uninitialized field 'this->b'}}
 
 public:
   PassingToUnknownFunctionTest1() {
@@ -368,8 +368,7 @@ public:
   }
 
   PassingToUnknownFunctionTest1(int) {
-mayInitialize(a);
-// All good!
+mayInitialize(a); // expected-warning{{1 uninitialized field at the end of 
the constructor call}}
   }
 
   PassingToUnknownFunctionTest1(int, int) {

Modified: cfe/trunk/test/Analysis/malloc.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/malloc.c?rev=352473=352472=352473=diff
==
--- cfe/trunk/test/Analysis/malloc.c 

r352470 - [analyzer] Added a checklist to help checker authors and reviewers

2019-01-29 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Jan 29 02:21:49 2019
New Revision: 352470

URL: http://llvm.org/viewvc/llvm-project?rev=352470=rev
Log:
[analyzer] Added a checklist to help checker authors and reviewers

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

Modified:
cfe/trunk/www/analyzer/checker_dev_manual.html

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=352470=352469=352470=diff
==
--- cfe/trunk/www/analyzer/checker_dev_manual.html (original)
+++ cfe/trunk/www/analyzer/checker_dev_manual.html Tue Jan 29 02:21:49 2019
@@ -675,6 +675,111 @@ to:
 (gdb) p C.getPredecessor()->getCodeDecl().getBody()->dump()
 
 
+Making Your Checker Better
+
+User facing documentation is important for adoption! Make sure the checker list is updated
+at the homepage of the analyzer. Also ensure the description is clear to
+non-analyzer-developers in Checkers.td.
+Warning and note messages should be clear and easy to understand, even if 
a bit long.
+
+  Messages should start with a capital letter (unlike Clang warnings!) and 
should not
+  end with ..
+  Articles are usually omitted, eg. Dereference of a null pointer 
->
+  Dereference of null pointer.
+  Introduce BugReporterVisitors to emit additional notes that 
explain the warning
+  to the user better. There are some existing visitors that might be 
useful for your check,
+  e.g. trackNullOrUndefValue. For example, SimpleStreamChecker 
should highlight
+  the event of opening the file when reporting a file descriptor leak.
+
+If the check tracks anything in the program state, it needs to implement 
the
+checkDeadSymbolscallback to clean the state up.
+The check should conservatively assume that the program is correct when a 
tracked symbol
+is passed to a function that is unknown to the analyzer.
+checkPointerEscape callback could help you handle that case.
+Use safe and convenient APIs!
+
+  Always use CheckerContext::generateErrorNode and
+CheckerContext::generateNonFatalErrorNode for emitting bug 
reports.
+Most importantly, never emit report against 
CheckerContext::getPredecessor.
+  Prefer checkPreCall and checkPostCall to
+checkPreStmtCallExpr and 
checkPostStmtCallExpr.
+  Use CallDescription to detect hardcoded API calls in the 
program.
+  Simplify C.getState()->getSVal(E, C.getLocationContext()) to 
C.getSVal(E).
+
+Common sources of crashes:
+
+  CallEvent::getOriginExpr is nullable - for example, it returns 
null for an
+automatic destructor of a variable. The same applies to some values 
generated while the
+call was modeled, eg. SymbolConjured::getStmt is nullable.
+  CallEvent::getDecl is nullable - for example, it returns null 
for a
+  call of symbolic function pointer.
+  addTransition, generateSink, 
generateNonFatalErrorNode,
+generateErrorNode are nullable because you can transition to a 
node that you have already visited.
+  Methods of CallExpr/FunctionDecl/CallEvent 
that
+return arguments crash when the argument is out-of-bounds. If you checked 
the function name,
+it doesn't mean that the function has the expected number of arguments!
+Which is why you should use CallDescription.
+  Nullability of different entities within different kinds of symbols and 
regions is usually
+  documented via assertions in their constructors.
+  NamedDecl::getName will fail if the name of the declaration is 
not a single token,
+e.g. for destructors. You could use NamedDecl::getNameAsString 
for those cases.
+Note that this method is much slower and should be used sparringly, e.g. 
only when generating reports
+but not during analysis.
+  Is -analyzer-checker=core included in all test RUN: 
lines? It was never supported
+to run the analyzer with the core checks disabled. It might cause 
unexpected behavior and
+crashes. You should do all your testing with the core checks enabled.
+
+
+Patterns that you should most likely avoid even if they're not technically 
wrong:
+
+  BugReporterVisitor should most likely not match the AST of the 
current program point
+  to decide when to emit a note. It is much easier to determine that by 
observing changes in
+  the program state.
+  In State->getSVal(Region), if Region is not known to 
be a TypedValueRegion
+  and the optional type argument is not specified, the checker may 
accidentally try to dereference a
+  void pointer.
+  Checker logic should not depend on whether a certain value is a 
Loc or NonLoc.
+It should be immediately obvious whether the SVal is a 
Loc or a
+NonLoc depending on the AST that is being checked. Checking 
whether a value
+is Loc or Unknown/Undefined or whether the 
value is
+NonLoc or Unknown/Undefined is totally 
fine.
+  New symbols should not be constructed in the checker via 

r352468 - [analyzer] Fix a typo in docs

2019-01-29 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Jan 29 02:15:52 2019
New Revision: 352468

URL: http://llvm.org/viewvc/llvm-project?rev=352468=rev
Log:
[analyzer] Fix a typo in docs

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

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp?rev=352468=352467=352468=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp Tue Jan 29 
02:15:52 2019
@@ -215,7 +215,7 @@ public:
 
   /// Evaluates function call.
   ///
-  /// The analysis core threats all function calls in the same way. However, 
some
+  /// The analysis core treats all function calls in the same way. However, 
some
   /// functions have special meaning, which should be reflected in the program
   /// state. This callback allows a checker to provide domain specific 
knowledge
   /// about the particular functions it knows about.


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


r349266 - [analyzer] Assume that we always have a SubEngine available

2018-12-15 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Dec 15 05:20:33 2018
New Revision: 349266

URL: http://llvm.org/viewvc/llvm-project?rev=349266=rev
Log:
[analyzer] Assume that we always have a SubEngine available

The removed codepath was dead.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
cfe/trunk/lib/StaticAnalyzer/Core/SValBuilder.cpp
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.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=349266=349265=349266=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
Sat Dec 15 05:20:33 2018
@@ -555,15 +555,15 @@ public:
   MemRegionManager& getRegionManager() {
 return svalBuilder->getRegionManager();
   }
-  const MemRegionManager& getRegionManager() const {
+  const MemRegionManager () const {
 return svalBuilder->getRegionManager();
   }
 
   CallEventManager () { return *CallEventMgr; }
 
-  StoreManager& getStoreManager() { return *StoreMgr; }
-  ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
-  SubEngine* getOwningEngine() { return Eng; }
+  StoreManager () { return *StoreMgr; }
+  ConstraintManager () { return *ConstraintMgr; }
+  SubEngine () { return *Eng; }
 
   ProgramStateRef removeDeadBindings(ProgramStateRef St,
 const StackFrameContext *LCtx,

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp?rev=349266=349265=349266=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp Sat Dec 15 
05:20:33 2018
@@ -56,7 +56,7 @@ class AnalysisOrderChecker
 
   bool isCallbackEnabled(ProgramStateRef State, StringRef CallbackName) const {
 AnalyzerOptions  = State->getStateManager().getOwningEngine()
- ->getAnalysisManager().getAnalyzerOptions();
+ .getAnalysisManager().getAnalyzerOptions();
 return isCallbackEnabled(Opts, CallbackName);
   }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=349266=349265=349266=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Sat Dec 15 05:20:33 2018
@@ -550,15 +550,15 @@ RuntimeDefinition AnyFunctionCall::getRu
 return RuntimeDefinition(Decl);
   }
 
-  SubEngine *Engine = getState()->getStateManager().getOwningEngine();
-  AnalyzerOptions  = Engine->getAnalysisManager().options;
+  SubEngine  = getState()->getStateManager().getOwningEngine();
+  AnalyzerOptions  = Engine.getAnalysisManager().options;
 
   // Try to get CTU definition only if CTUDir is provided.
   if (!Opts.IsNaiveCTUEnabled)
 return {};
 
   cross_tu::CrossTranslationUnitContext  =
-  *Engine->getCrossTranslationUnitContext();
+  *Engine.getCrossTranslationUnitContext();
   llvm::Expected CTUDeclOrError =
   CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
   Opts.DisplayCTUProgress);
@@ -1087,7 +1087,7 @@ bool ObjCMethodCall::canBeOverridenInSub
  Selector Sel) const {
   assert(IDecl);
   AnalysisManager  =
-  getState()->getStateManager().getOwningEngine()->getAnalysisManager();
+  getState()->getStateManager().getOwningEngine().getAnalysisManager();
   // If the class interface is declared inside the main file, assume it is not
   // subcassed.
   // TODO: It could actually be subclassed if the subclass is private as well.

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=349266=349265=349266=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Sat Dec 15 05:20:33 2018
@@ -2951,8 +2951,8 @@ struct 

r348848 - [analyzer] Fix a minor typo.

2018-12-11 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Dec 11 06:40:48 2018
New Revision: 348848

URL: http://llvm.org/viewvc/llvm-project?rev=348848=rev
Log:
[analyzer] Fix a minor typo.

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=348848=348847=348848=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h Tue 
Dec 11 06:40:48 2018
@@ -1081,7 +1081,7 @@ public:
   void dump() const;
 };
 
-/// ElementRegin is used to represent both array elements and casts.
+/// ElementRegion is used to represent both array elements and casts.
 class ElementRegion : public TypedValueRegion {
   friend class MemRegionManager;
 


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


r345965 - [analyzer][CTU] Correctly signal in the function index generation tool if there was an error

2018-11-02 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Nov  2 04:22:22 2018
New Revision: 345965

URL: http://llvm.org/viewvc/llvm-project?rev=345965=rev
Log:
[analyzer][CTU] Correctly signal in the function index generation tool if there 
was an error

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

Modified:
cfe/trunk/tools/clang-func-mapping/CMakeLists.txt
cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp

Modified: cfe/trunk/tools/clang-func-mapping/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-func-mapping/CMakeLists.txt?rev=345965=345964=345965=diff
==
--- cfe/trunk/tools/clang-func-mapping/CMakeLists.txt (original)
+++ cfe/trunk/tools/clang-func-mapping/CMakeLists.txt Fri Nov  2 04:22:22 2018
@@ -1,8 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   ${LLVM_TARGETS_TO_BUILD}
-  asmparser
   support
-  mc
   )
 
 add_clang_executable(clang-func-mapping
@@ -15,7 +13,6 @@ target_link_libraries(clang-func-mapping
   clangBasic
   clangCrossTU
   clangFrontend
-  clangIndex
   clangTooling
   )
 

Modified: cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp?rev=345965=345964=345965=diff
==
--- cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp (original)
+++ cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp Fri Nov  2 04:22:22 
2018
@@ -14,23 +14,16 @@
 
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/GlobalDecl.h"
-#include "clang/AST/Mangle.h"
-#include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/SourceManager.h"
-#include "clang/Basic/TargetInfo.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
-#include "clang/Index/USRGeneration.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/Path.h"
 #include "llvm/Support/Signals.h"
 #include 
 #include 
-#include 
 
 using namespace llvm;
 using namespace clang;
@@ -41,21 +34,22 @@ static cl::OptionCategory ClangFnMapGenC
 
 class MapFunctionNamesConsumer : public ASTConsumer {
 public:
-  MapFunctionNamesConsumer(ASTContext ) : Ctx(Context) {}
+  MapFunctionNamesConsumer(ASTContext )
+  : SM(Context.getSourceManager()) {}
 
   ~MapFunctionNamesConsumer() {
 // Flush results to standard output.
 llvm::outs() << createCrossTUIndexString(Index);
   }
 
-  virtual void HandleTranslationUnit(ASTContext ) {
+  void HandleTranslationUnit(ASTContext ) override {
 handleDecl(Ctx.getTranslationUnitDecl());
   }
 
 private:
   void handleDecl(const Decl *D);
 
-  ASTContext 
+  SourceManager 
   llvm::StringMap Index;
   std::string CurrentFileName;
 };
@@ -67,8 +61,6 @@ void MapFunctionNamesConsumer::handleDec
   if (const auto *FD = dyn_cast(D)) {
 if (FD->isThisDeclarationADefinition()) {
   if (const Stmt *Body = FD->getBody()) {
-std::string LookupName = 
CrossTranslationUnitContext::getLookupName(FD);
-const SourceManager  = Ctx.getSourceManager();
 if (CurrentFileName.empty()) {
   CurrentFileName =
   SM.getFileEntryForID(SM.getMainFileID())->tryGetRealPathName();
@@ -80,8 +72,11 @@ void MapFunctionNamesConsumer::handleDec
 case ExternalLinkage:
 case VisibleNoLinkage:
 case UniqueExternalLinkage:
-  if (SM.isInMainFile(Body->getBeginLoc()))
+  if (SM.isInMainFile(Body->getBeginLoc())) {
+std::string LookupName =
+CrossTranslationUnitContext::getLookupName(FD);
 Index[LookupName] = CurrentFileName;
+  }
   break;
 default:
   break;
@@ -99,9 +94,7 @@ class MapFunctionNamesAction : public AS
 protected:
   std::unique_ptr CreateASTConsumer(CompilerInstance ,
  llvm::StringRef) {
-std::unique_ptr PFC(
-new MapFunctionNamesConsumer(CI.getASTContext()));
-return PFC;
+return llvm::make_unique(CI.getASTContext());
   }
 };
 
@@ -120,6 +113,6 @@ int main(int argc, const char **argv) {
 
   ClangTool Tool(OptionsParser.getCompilations(),
  OptionsParser.getSourcePathList());
-  Tool.run(newFrontendActionFactory().get());
-  return 0;
+
+  return Tool.run(newFrontendActionFactory().get());
 }


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


r344017 - [analyzer] Support Reinitializes attribute in MisusedMovedObject check

2018-10-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Oct  9 00:28:57 2018
New Revision: 344017

URL: http://llvm.org/viewvc/llvm-project?rev=344017=rev
Log:
[analyzer] Support Reinitializes attribute in MisusedMovedObject check

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp
cfe/trunk/test/Analysis/MisusedMovedObject.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp?rev=344017=344016=344017=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MisusedMovedObjectChecker.cpp Tue Oct 
 9 00:28:57 2018
@@ -314,17 +314,18 @@ bool MisusedMovedObjectChecker::isMoveSa
   return true;
   }
   // Function call `empty` can be skipped.
-  if (MethodDec && MethodDec->getDeclName().isIdentifier() &&
+  return (MethodDec && MethodDec->getDeclName().isIdentifier() &&
   (MethodDec->getName().lower() == "empty" ||
-   MethodDec->getName().lower() == "isempty"))
-return true;
-
-  return false;
+   MethodDec->getName().lower() == "isempty"));
 }
 
 bool MisusedMovedObjectChecker::isStateResetMethod(
 const CXXMethodDecl *MethodDec) const {
-  if (MethodDec && MethodDec->getDeclName().isIdentifier()) {
+  if (!MethodDec)
+  return false;
+  if (MethodDec->hasAttr())
+  return true;
+  if (MethodDec->getDeclName().isIdentifier()) {
 std::string MethodName = MethodDec->getName().lower();
 if (MethodName == "reset" || MethodName == "clear" ||
 MethodName == "destroy")
@@ -429,8 +430,7 @@ void MisusedMovedObjectChecker::checkPre
 
   // We want to investigate the whole object, not only sub-object of a parent
   // class in which the encountered method defined.
-  while (const CXXBaseObjectRegion *BR =
- dyn_cast(ThisRegion))
+  while (const auto *BR = dyn_cast(ThisRegion))
 ThisRegion = BR->getSuperRegion();
 
   if (isMoveSafeMethod(MethodDecl))
@@ -487,13 +487,9 @@ ProgramStateRef MisusedMovedObjectChecke
 ThisRegion = IC->getCXXThisVal().getAsRegion();
   }
 
-  for (ArrayRef::iterator I = ExplicitRegions.begin(),
- E = ExplicitRegions.end();
-   I != E; ++I) {
-const auto *Region = *I;
-if (ThisRegion != Region) {
+  for (const auto *Region : ExplicitRegions) {
+if (ThisRegion != Region)
   State = removeFromState(State, Region);
-}
   }
 
   return State;

Modified: cfe/trunk/test/Analysis/MisusedMovedObject.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/MisusedMovedObject.cpp?rev=344017=344016=344017=diff
==
--- cfe/trunk/test/Analysis/MisusedMovedObject.cpp (original)
+++ cfe/trunk/test/Analysis/MisusedMovedObject.cpp Tue Oct  9 00:28:57 2018
@@ -638,7 +638,10 @@ void ifStmtSequencesDeclAndConditionTest
   }
 }
 
-class C : public A {};
+struct C : public A {
+  [[clang::reinitializes]] void reinit();
+};
+
 void subRegionMoveTest() {
   {
 A a;
@@ -672,6 +675,13 @@ void resetSuperClass() {
   C c2 = c; // no-warning
 }
 
+void resetSuperClass2() {
+  C c;
+  C c1 = std::move(c);
+  c.reinit();
+  C c2 = c; // no-warning
+}
+
 void reportSuperClass() {
   C c;
   C c1 = std::move(c); // expected-note {{'c' became 'moved-from' here}}


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


r331759 - [ASTMatchers] Overload isConstexpr for ifStmts

2018-05-08 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue May  8 04:53:32 2018
New Revision: 331759

URL: http://llvm.org/viewvc/llvm-project?rev=331759=rev
Log:
[ASTMatchers] Overload isConstexpr for ifStmts

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

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
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=331759=331758=331759=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Tue May  8 04:53:32 2018
@@ -2789,15 +2789,19 @@ auto Y() - int {}
 
 
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDeclisConstexpr
-Matches constexpr 
variable and function declarations.
+Matches constexpr 
variable and function declarations,
+   and if constexpr.
 
 Given:
   constexpr int foo = 42;
   constexpr int bar();
+  void baz() { if constexpr(1  0) {} }
 varDecl(isConstexpr())
   matches the declaration of foo.
 functionDecl(isConstexpr())
   matches the declaration of bar.
+ifStmt(isConstexpr())
+  matches the if statement in baz.
 
 
 
@@ -3039,6 +3043,23 @@ functionProtoType(parameterCountIs(3))
 
 
 
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1IfStmt.html;>IfStmtisConstexpr
+Matches constexpr 
variable and function declarations,
+   and if constexpr.
+
+Given:
+  constexpr int foo = 42;
+  constexpr int bar();
+  void baz() { if constexpr(1  0) {} }
+varDecl(isConstexpr())
+  matches the declaration of foo.
+functionDecl(isConstexpr())
+  matches the declaration of bar.
+ifStmt(isConstexpr())
+  matches the if statement in baz.
+
+
+
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html;>IntegerLiteralequalsbool Value
 
 
@@ -3803,15 +3824,19 @@ int a;
 
 
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1VarDecl.html;>VarDeclisConstexpr
-Matches constexpr 
variable and function declarations.
+Matches constexpr 
variable and function declarations,
+   and if constexpr.
 
 Given:
   constexpr int foo = 42;
   constexpr int bar();
+  void baz() { if constexpr(1  0) {} }
 varDecl(isConstexpr())
   matches the declaration of foo.
 functionDecl(isConstexpr())
   matches the declaration of bar.
+ifStmt(isConstexpr())
+  matches the if statement in baz.
 
 
 

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=331759=331758=331759=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Tue May  8 04:53:32 2018
@@ -3763,20 +3763,25 @@ AST_POLYMORPHIC_MATCHER(isNoThrow,
   return FnTy->isNothrow();
 }
 
-/// \brief Matches constexpr variable and function declarations.
+/// \brief Matches constexpr variable and function declarations,
+///and if constexpr.
 ///
 /// Given:
 /// \code
 ///   constexpr int foo = 42;
 ///   constexpr int bar();
+///   void baz() { if constexpr(1 > 0) {} }
 /// \endcode
 /// varDecl(isConstexpr())
 ///   matches the declaration of foo.
 /// functionDecl(isConstexpr())
 ///   matches the declaration of bar.
+/// ifStmt(isConstexpr())
+///   matches the if statement in baz.
 AST_POLYMORPHIC_MATCHER(isConstexpr,
 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
-FunctionDecl)) {
+FunctionDecl,
+IfStmt)) {
   return Node.isConstexpr();
 }
 

Modified: cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp?rev=331759=331758=331759=diff
==
--- cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp (original)
+++ cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp Tue May  8 
04:53:32 2018
@@ -894,6 +894,10 @@ TEST(isConstexpr, MatchesConstexprDeclar
   varDecl(hasName("foo"), isConstexpr(;
   EXPECT_TRUE(matches("constexpr int bar();",
   functionDecl(hasName("bar"), isConstexpr(;
+  EXPECT_TRUE(matchesConditionally("void baz() { if constexpr(1 > 0) {} }",
+   ifStmt(isConstexpr()), true, "-std=c++17"));
+  EXPECT_TRUE(matchesConditionally("void baz() { if (1 > 0) {} }",
+   ifStmt(isConstexpr()), false, 
"-std=c++17"));
 }
 
 TEST(TemplateArgumentCountIs, Matches) {



[clang-tools-extra] r330719 - [clang-tidy] Fix PR35468

2018-04-24 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Apr 24 07:45:58 2018
New Revision: 330719

URL: http://llvm.org/viewvc/llvm-project?rev=330719=rev
Log:
[clang-tidy] Fix PR35468

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

Added:

clang-tools-extra/trunk/test/clang-tidy/misc-unconventional-assign-operator-cxx17.cpp
Modified:

clang-tools-extra/trunk/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp?rev=330719=330718=330719=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp 
Tue Apr 24 07:45:58 2018
@@ -24,9 +24,9 @@ void UnconventionalAssignOperatorCheck::
   if (!getLangOpts().CPlusPlus)
 return;
 
-  const auto HasGoodReturnType = cxxMethodDecl(returns(
-  lValueReferenceType(pointee(unless(isConstQualified()),
-  hasDeclaration(equalsBoundNode("class"));
+  const auto HasGoodReturnType = cxxMethodDecl(returns(lValueReferenceType(
+  pointee(unless(isConstQualified()),
+  anyOf(autoType(), hasDeclaration(equalsBoundNode("class")));
 
   const auto IsSelf = qualType(
   anyOf(hasDeclaration(equalsBoundNode("class")),

Added: 
clang-tools-extra/trunk/test/clang-tidy/misc-unconventional-assign-operator-cxx17.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-unconventional-assign-operator-cxx17.cpp?rev=330719=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/misc-unconventional-assign-operator-cxx17.cpp
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/misc-unconventional-assign-operator-cxx17.cpp
 Tue Apr 24 07:45:58 2018
@@ -0,0 +1,12 @@
+// RUN: %check_clang_tidy %s misc-unconventional-assign-operator %t -- -- 
-std=c++17 -fno-delayed-template-parsing
+
+struct BadModifier {
+  BadModifier& operator=(const BadModifier&) const;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should not be marked 
'const'
+};
+
+struct PR35468 {
+  template auto =(const T &) {
+return *this;
+  }
+};


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


r330009 - [analyzer] Fix null deref in AnyFunctionCall::getRuntimeDefinition

2018-04-13 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Apr 13 05:36:08 2018
New Revision: 330009

URL: http://llvm.org/viewvc/llvm-project?rev=330009=rev
Log:
[analyzer] Fix null deref in AnyFunctionCall::getRuntimeDefinition

Patch by: Rafael Stahl!

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

Added:
cfe/trunk/test/Analysis/undef-call.c
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=330009=330008=330009=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Fri Apr 13 05:36:08 2018
@@ -389,23 +389,24 @@ ArrayRef AnyFunctionCall::
 
 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
   const FunctionDecl *FD = getDecl();
+  if (!FD)
+return {};
+
   // Note that the AnalysisDeclContext will have the FunctionDecl with
   // the definition (if one exists).
-  if (FD) {
-AnalysisDeclContext *AD =
-  getLocationContext()->getAnalysisDeclContext()->
-  getManager()->getContext(FD);
-bool IsAutosynthesized;
-Stmt* Body = AD->getBody(IsAutosynthesized);
-DEBUG({
-if (IsAutosynthesized)
-  llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
-   << "\n";
-});
-if (Body) {
-  const Decl* Decl = AD->getDecl();
-  return RuntimeDefinition(Decl);
-}
+  AnalysisDeclContext *AD =
+getLocationContext()->getAnalysisDeclContext()->
+getManager()->getContext(FD);
+  bool IsAutosynthesized;
+  Stmt* Body = AD->getBody(IsAutosynthesized);
+  DEBUG({
+  if (IsAutosynthesized)
+llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
+ << "\n";
+  });
+  if (Body) {
+const Decl* Decl = AD->getDecl();
+return RuntimeDefinition(Decl);
   }
 
   SubEngine *Engine = getState()->getStateManager().getOwningEngine();
@@ -413,7 +414,7 @@ RuntimeDefinition AnyFunctionCall::getRu
 
   // Try to get CTU definition only if CTUDir is provided.
   if (!Opts.naiveCTUEnabled())
-return RuntimeDefinition();
+return {};
 
   cross_tu::CrossTranslationUnitContext  =
   *Engine->getCrossTranslationUnitContext();

Added: cfe/trunk/test/Analysis/undef-call.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/undef-call.c?rev=330009=auto
==
--- cfe/trunk/test/Analysis/undef-call.c (added)
+++ cfe/trunk/test/Analysis/undef-call.c Fri Apr 13 05:36:08 2018
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fsyntax-only -analyze 
-analyzer-checker=debug.ExprInspection -analyzer-config 
experimental-enable-naive-ctu-analysis=true -analyzer-config ctu-dir=%T/ctudir 
-verify %s
+// expected-no-diagnostics
+
+struct S {
+  void (*fp)();
+};
+
+int main() {
+  struct S s;
+  // This will cause the analyzer to look for a function definition that has
+  // no FunctionDecl. It used to cause a crash in 
AnyFunctionCall::getRuntimeDefinition.
+  // It would only occur when CTU analysis is enabled.
+  s.fp();
+}


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


r326324 - [analyzer] Fix a compiler warning

2018-02-28 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Feb 28 06:01:48 2018
New Revision: 326324

URL: http://llvm.org/viewvc/llvm-project?rev=326324=rev
Log:
[analyzer] Fix a compiler warning

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

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=326324=326323=326324=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Wed 
Feb 28 06:01:48 2018
@@ -155,7 +155,8 @@ public:
 
   BugReporter& getBugReporter() { return BR; }
 
-  cross_tu::CrossTranslationUnitContext *getCrossTranslationUnitContext() {
+  cross_tu::CrossTranslationUnitContext *
+  getCrossTranslationUnitContext() override {
 return 
   }
 


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


r326323 - [analyzer] Support for naive cross translation unit analysis

2018-02-28 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Feb 28 05:23:10 2018
New Revision: 326323

URL: http://llvm.org/viewvc/llvm-project?rev=326323=rev
Log:
[analyzer] Support for naive cross translation unit analysis

The aim of this patch is to be minimal to enable incremental development of
the feature on the top of the tree. This patch should be an NFC when the
feature is turned off. It is turned off by default and still considered as
experimental.

Technical details are available in the EuroLLVM Talk: 
http://llvm.org/devmtg/2017-03//2017/02/20/accepted-sessions.html#7

Note that the initial prototype was done by A. Sidorin et al.: 
http://lists.llvm.org/pipermail/cfe-dev/2015-October/045730.html

Contributions to the measurements and the new version of the code: Peter 
Szecsi, Zoltan Gera, Daniel Krupp, Kareem Khazem.

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

Added:
cfe/trunk/test/Analysis/Inputs/ctu-chain.cpp
cfe/trunk/test/Analysis/Inputs/ctu-other.cpp
cfe/trunk/test/Analysis/Inputs/externalFnMap.txt
cfe/trunk/test/Analysis/ctu-main.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CMakeLists.txt
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/CMakeLists.txt
cfe/trunk/test/Analysis/analyzer-config.cpp
cfe/trunk/tools/scan-build-py/README.md
cfe/trunk/tools/scan-build-py/libscanbuild/__init__.py
cfe/trunk/tools/scan-build-py/libscanbuild/analyze.py
cfe/trunk/tools/scan-build-py/libscanbuild/arguments.py
cfe/trunk/tools/scan-build-py/libscanbuild/clang.py
cfe/trunk/tools/scan-build-py/libscanbuild/report.py
cfe/trunk/tools/scan-build-py/tests/unit/test_analyze.py
cfe/trunk/tools/scan-build-py/tests/unit/test_clang.py

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=326323=326322=326323=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h Wed Feb 28 
05:23:10 2018
@@ -308,6 +308,16 @@ private:
   /// \sa shouldDisplayNotesAsEvents
   Optional DisplayNotesAsEvents;
 
+  /// \sa getCTUDir
+  Optional CTUDir;
+
+  /// \sa getCTUIndexName
+  Optional CTUIndexName;
+
+  /// \sa naiveCTUEnabled
+  Optional NaiveCTU;
+
+
   /// A helper function that retrieves option for a given full-qualified
   /// checker name.
   /// Options for checkers can be specified via 'analyzer-config' command-line
@@ -637,6 +647,17 @@ public:
   /// to false when unset.
   bool shouldDisplayNotesAsEvents();
 
+  /// Returns the directory containing the CTU related files.
+  StringRef getCTUDir();
+
+  /// Returns the name of the file containing the CTU index of functions.
+  StringRef getCTUIndexName();
+
+  /// Returns true when naive cross translation unit analysis is enabled.
+  /// This is an experimental feature to inline functions from another
+  /// translation units.
+  bool naiveCTUEnabled();
+
 public:
   AnalyzerOptions() :
 AnalysisStoreOpt(RegionStoreModel),

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=326323=326322=326323=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Wed 
Feb 28 05:23:10 2018
@@ -38,6 +38,10 @@ class CXXThisExpr;
 class MaterializeTemporaryExpr;
 class ObjCAtSynchronizedStmt;
 class ObjCForCollectionStmt;
+
+namespace cross_tu {
+class CrossTranslationUnitContext;
+}
   
 namespace ento {
 
@@ -74,6 +78,8 @@ public:
   };
 
 private:
+  cross_tu::CrossTranslationUnitContext 
+
   AnalysisManager 
   
   AnalysisDeclContextManager 
@@ -115,10 +121,9 @@ private:
   InliningModes HowToInline;
 
 public:
-  ExprEngine(AnalysisManager , bool gcEnabled,
- SetOfConstDecls *VisitedCalleesIn,
- FunctionSummariesTy *FS,
- InliningModes HowToInlineIn);
+  ExprEngine(cross_tu::CrossTranslationUnitContext , AnalysisManager ,
+ bool gcEnabled, SetOfConstDecls *VisitedCalleesIn,
+ FunctionSummariesTy *FS, InliningModes HowToInlineIn);
 
   ~ExprEngine() override;
 
@@ -150,6 

[clang-tools-extra] r325572 - [clang-tidy] Replace the usage of std::uncaught_exception with std::uncaught_exceptions

2018-02-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Feb 20 02:48:38 2018
New Revision: 325572

URL: http://llvm.org/viewvc/llvm-project?rev=325572=rev
Log:
[clang-tidy] Replace the usage of std::uncaught_exception with 
std::uncaught_exceptions

Patch by: Daniel Kolozsvari!

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

Added:
clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp
clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-use-uncaught-exceptions.rst

clang-tools-extra/trunk/test/clang-tidy/modernize-use-uncaught-exceptions.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt?rev=325572=325571=325572=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt Tue Feb 20 
02:48:38 2018
@@ -27,6 +27,7 @@ add_clang_library(clangTidyModernizeModu
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
   UseTransparentFunctorsCheck.cpp
+  UseUncaughtExceptionsCheck.cpp
   UseUsingCheck.cpp
 
   LINK_LIBS

Modified: clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp?rev=325572=325571=325572=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp Tue 
Feb 20 02:48:38 2018
@@ -33,6 +33,7 @@
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
 #include "UseTransparentFunctorsCheck.h"
+#include "UseUncaughtExceptionsCheck.h"
 #include "UseUsingCheck.h"
 
 using namespace clang::ast_matchers;
@@ -78,6 +79,8 @@ public:
 CheckFactories.registerCheck("modernize-use-override");
 CheckFactories.registerCheck(
 "modernize-use-transparent-functors");
+CheckFactories.registerCheck(
+"modernize-use-uncaught-exceptions");
 CheckFactories.registerCheck("modernize-use-using");
   }
 

Added: 
clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp?rev=325572=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp 
Tue Feb 20 02:48:38 2018
@@ -0,0 +1,104 @@
+//===--- UseUncaughtExceptionsCheck.cpp - clang-tidy===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "UseUncaughtExceptionsCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+void UseUncaughtExceptionsCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus17)
+return;
+
+  std::string MatchText = "::std::uncaught_exception";
+
+  // Using declaration: warning and fix-it.
+  Finder->addMatcher(
+  usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(hasName(MatchText
+  .bind("using_decl"),
+  this);
+
+  // DeclRefExpr: warning, no fix-it.
+  Finder->addMatcher(declRefExpr(allOf(to(functionDecl(hasName(MatchText))),
+   unless(callExpr(
+ .bind("decl_ref_expr"),
+ this);
+
+  // CallExpr: warning, fix-it.
+  Finder->addMatcher(
+  callExpr(allOf(hasDeclaration(functionDecl(hasName(MatchText))),
+ unless(hasAncestor(initListExpr()
+  .bind("call_expr"),
+  this);
+  // CallExpr in initialisation list: warning, fix-it with avoiding narrowing
+  // conversions.
+  Finder->addMatcher(
+  callExpr(allOf(hasAncestor(initListExpr()),
+ hasDeclaration(functionDecl(hasName(MatchText)
+  .bind("init_call_expr"),
+  this);
+}
+
+void UseUncaughtExceptionsCheck::check(const MatchFinder::MatchResult ) 
{
+  SourceLocation BeginLoc;
+  SourceLocation EndLoc;
+  const CallExpr *C = 

[clang-tools-extra] r325225 - [clang-tidy] Make a test pass on platforms where exceptions disabled by default.

2018-02-15 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Feb 15 01:24:55 2018
New Revision: 325225

URL: http://llvm.org/viewvc/llvm-project?rev=325225=rev
Log:
[clang-tidy] Make a test pass on platforms where exceptions disabled by default.

Modified:
clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp?rev=325225=325224=325225=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp 
Thu Feb 15 01:24:55 2018
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-throw-keyword-missing %t
+// RUN: %check_clang_tidy %s bugprone-throw-keyword-missing %t -- -- 
-fexceptions
 
 namespace std {
 


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


[clang-tools-extra] r325223 - [clang-tidy] Minor documentation fix

2018-02-15 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Feb 15 01:19:23 2018
New Revision: 325223

URL: http://llvm.org/viewvc/llvm-project?rev=325223=rev
Log:
[clang-tidy] Minor documentation fix

Modified:

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst?rev=325223=325222=325223=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst
 Thu Feb 15 01:19:23 2018
@@ -10,6 +10,7 @@ object's type derives from (or is the sa
 Example:
 
 .. code-block:: c++
+
   void f(int i) {
 if (i < 0) {
   // Exception is created but is not thrown.


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


[clang-tools-extra] r325222 - [clang-tidy] New checker for exceptions that are created but not thrown

2018-02-15 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Feb 15 01:08:51 2018
New Revision: 325222

URL: http://llvm.org/viewvc/llvm-project?rev=325222=rev
Log:
[clang-tidy] New checker for exceptions that are created but not thrown

Patch by: Kristof Umann

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

Added:
clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-throw-keyword-missing.rst
clang-tools-extra/trunk/test/clang-tidy/bugprone-throw-keyword-missing.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=325222=325221=325222=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Thu Feb 
15 01:08:51 2018
@@ -25,6 +25,7 @@
 #include "MultipleStatementMacroCheck.h"
 #include "StringConstructorCheck.h"
 #include "SuspiciousMemsetUsageCheck.h"
+#include "ThrowKeywordMissingCheck.h"
 #include "UndefinedMemoryManipulationCheck.h"
 #include "UseAfterMoveCheck.h"
 #include "VirtualNearMissCheck.h"
@@ -66,6 +67,8 @@ public:
 "bugprone-string-constructor");
 CheckFactories.registerCheck(
 "bugprone-suspicious-memset-usage");
+CheckFactories.registerCheck(
+"bugprone-throw-keyword-missing");
 CheckFactories.registerCheck(
 "bugprone-undefined-memory-manipulation");
 CheckFactories.registerCheck(

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt?rev=325222=325221=325222=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt Thu Feb 15 
01:08:51 2018
@@ -17,6 +17,7 @@ add_clang_library(clangTidyBugproneModul
   MultipleStatementMacroCheck.cpp
   StringConstructorCheck.cpp
   SuspiciousMemsetUsageCheck.cpp
+  ThrowKeywordMissingCheck.cpp
   UndefinedMemoryManipulationCheck.cpp
   UseAfterMoveCheck.cpp
   VirtualNearMissCheck.cpp

Added: clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp?rev=325222=auto
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp 
Thu Feb 15 01:08:51 2018
@@ -0,0 +1,52 @@
+//===--- ThrowKeywordMissingCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ThrowKeywordMissingCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+void ThrowKeywordMissingCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus)
+return;
+
+  auto CtorInitializerList =
+  cxxConstructorDecl(hasAnyConstructorInitializer(anything()));
+
+  Finder->addMatcher(
+  expr(anyOf(cxxFunctionalCastExpr(), cxxBindTemporaryExpr(),
+ cxxTemporaryObjectExpr()),
+   hasType(cxxRecordDecl(
+   isSameOrDerivedFrom(matchesName("[Ee]xception|EXCEPTION",
+   unless(anyOf(hasAncestor(stmt(
+anyOf(cxxThrowExpr(), callExpr(), returnStmt(,
+hasAncestor(varDecl()),
+allOf(hasAncestor(CtorInitializerList),
+  unless(hasAncestor(cxxCatchStmt()))
+  .bind("temporary-exception-not-thrown"),
+  this); 
+}
+
+void ThrowKeywordMissingCheck::check(const MatchFinder::MatchResult ) {
+  const auto *TemporaryExpr =
+  Result.Nodes.getNodeAs("temporary-exception-not-thrown");
+
+  diag(TemporaryExpr->getLocStart(), "suspicious exception object created but "
+ "not thrown; did you mean 'throw %0'?")
+  << 

r324809 - Make a build bot happy.

2018-02-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Feb 10 06:26:53 2018
New Revision: 324809

URL: http://llvm.org/viewvc/llvm-project?rev=324809=rev
Log:
Make a build bot happy.

Modified:
cfe/trunk/lib/Frontend/FrontendActions.cpp
cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp

Modified: cfe/trunk/lib/Frontend/FrontendActions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/FrontendActions.cpp?rev=324809=324808=324809=diff
==
--- cfe/trunk/lib/Frontend/FrontendActions.cpp (original)
+++ cfe/trunk/lib/Frontend/FrontendActions.cpp Sat Feb 10 06:26:53 2018
@@ -309,17 +309,17 @@ class DefaultTemplateInstCallback : publ
   using CodeSynthesisContext = Sema::CodeSynthesisContext;
 
 public:
-  virtual void initialize(const Sema &) {}
+  void initialize(const Sema &) override {}
 
-  virtual void finalize(const Sema &) {}
+  void finalize(const Sema &) override {}
 
-  virtual void atTemplateBegin(const Sema ,
-   const CodeSynthesisContext ) override {
+  void atTemplateBegin(const Sema ,
+   const CodeSynthesisContext ) override {
 displayTemplightEntry(llvm::outs(), TheSema, Inst);
   }
 
-  virtual void atTemplateEnd(const Sema ,
- const CodeSynthesisContext ) override {
+  void atTemplateEnd(const Sema ,
+ const CodeSynthesisContext ) override {
 displayTemplightEntry(llvm::outs(), TheSema, Inst);
   }
 

Modified: cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp?rev=324809=324808=324809=diff
==
--- cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp (original)
+++ cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp Sat Feb 10 
06:26:53 2018
@@ -258,4 +258,4 @@ bool ExecuteCompilerInvocation(CompilerI
   return Success;
 }
 
-} //namespace clang 
+} // namespace clang 


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


r324808 - [Templight] Template Instantiation Observer

2018-02-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Feb 10 06:04:45 2018
New Revision: 324808

URL: http://llvm.org/viewvc/llvm-project?rev=324808=rev
Log:
[Templight] Template Instantiation Observer

This patch adds a base-class called TemplateInstantiationObserver which gets
notified whenever a template instantiation is entered or exited during
semantic analysis. This is a base class used to implement the template
profiling and debugging tool called
Templight (https://github.com/mikael-s-persson/templight).

The patch also makes a few more changes:

* ActiveTemplateInstantiation class is moved out of the Sema class (so it can 
be used with inclusion of Sema.h).
* CreateFrontendAction function in front-end utilities is given external 
linkage (not longer a hidden static function).
* TemplateInstObserverChain data member added to Sema class to hold the list of 
template-inst observers.
* Notifications to the template-inst observer are added at the key places where 
templates are instantiated.

Patch by: Abel Sinkovics!

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

Added:
cfe/trunk/include/clang/Sema/TemplateInstCallback.h
cfe/trunk/test/Templight/
cfe/trunk/test/Templight/templight-deduced-func.cpp
cfe/trunk/test/Templight/templight-default-arg-inst.cpp
cfe/trunk/test/Templight/templight-default-func-arg.cpp
cfe/trunk/test/Templight/templight-default-template-arg.cpp
cfe/trunk/test/Templight/templight-exception-spec-func.cpp
cfe/trunk/test/Templight/templight-explicit-template-arg.cpp
cfe/trunk/test/Templight/templight-memoization.cpp
cfe/trunk/test/Templight/templight-nested-memoization.cpp
cfe/trunk/test/Templight/templight-nested-template-instantiation.cpp
cfe/trunk/test/Templight/templight-one-instantiation.cpp
cfe/trunk/test/Templight/templight-prior-template-arg.cpp
Modified:
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/include/clang/Frontend/FrontendActions.h
cfe/trunk/include/clang/Frontend/FrontendOptions.h
cfe/trunk/include/clang/FrontendTool/Utils.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/Frontend/FrontendActions.cpp
cfe/trunk/lib/FrontendTool/ExecuteCompilerInvocation.cpp
cfe/trunk/lib/Parse/ParseAST.cpp
cfe/trunk/lib/Sema/Sema.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/lib/Sema/SemaType.cpp

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=324808=324807=324808=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Sat Feb 10 06:04:45 2018
@@ -533,6 +533,8 @@ def ast_dump : Flag<["-"], "ast-dump">,
   HelpText<"Build ASTs and then debug dump them">;
 def ast_dump_all : Flag<["-"], "ast-dump-all">,
   HelpText<"Build ASTs and then debug dump them, forcing deserialization">;
+def templight_dump : Flag<["-"], "templight-dump">,
+  HelpText<"Dump templight information to stdout">;
 def ast_dump_lookups : Flag<["-"], "ast-dump-lookups">,
   HelpText<"Build ASTs and then debug dump their name lookup tables">;
 def ast_view : Flag<["-"], "ast-view">,

Modified: cfe/trunk/include/clang/Frontend/FrontendActions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/FrontendActions.h?rev=324808=324807=324808=diff
==
--- cfe/trunk/include/clang/Frontend/FrontendActions.h (original)
+++ cfe/trunk/include/clang/Frontend/FrontendActions.h Sat Feb 10 06:04:45 2018
@@ -167,6 +167,14 @@ public:
   bool hasCodeCompletionSupport() const override { return false; }
 };
 
+class TemplightDumpAction : public ASTFrontendAction {
+protected:
+  std::unique_ptr CreateASTConsumer(CompilerInstance ,
+ StringRef InFile) override;
+
+  void ExecuteAction() override;
+};
+
 /**
  * \brief Frontend action adaptor that merges ASTs together.
  *

Modified: cfe/trunk/include/clang/Frontend/FrontendOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/FrontendOptions.h?rev=324808=324807=324808=diff
==
--- cfe/trunk/include/clang/Frontend/FrontendOptions.h (original)
+++ cfe/trunk/include/clang/Frontend/FrontendOptions.h Sat Feb 10 06:04:45 2018
@@ -58,6 +58,7 @@ namespace frontend {
 RewriteObjC,///< ObjC->C Rewriter.
 RewriteTest,///< Rewriter playground
 RunAnalysis,///< Run one or more source code analyses.
+TemplightDump,  ///< Dump template instantiations
 MigrateSource,  ///< Run migrator.
 RunPreprocessorOnly ///< Just lex, no output.
   };


r323590 - Attempt to make the PS4 build bot happy.

2018-01-27 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Jan 27 08:38:56 2018
New Revision: 323590

URL: http://llvm.org/viewvc/llvm-project?rev=323590=rev
Log:
Attempt to make the PS4 build bot happy.

Modified:
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=323590=323589=323590=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Sat Jan 27 08:38:56 2018
@@ -40,10 +40,10 @@ static RunOptions getRunOptionsForLangua
 BasicArgs = {"-x", "c", "-std=c89"};
 break;
   case Lang_CXX:
-BasicArgs = {"-std=c++98"};
+BasicArgs = {"-std=c++98", "-frtti"};
 break;
   case Lang_CXX11:
-BasicArgs = {"-std=c++11"};
+BasicArgs = {"-std=c++11", "-frtti"};
 break;
   case Lang_OpenCL:
   case Lang_OBJCXX:


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


r323589 - [ASTImporter] Add support to import some AST nodes:

2018-01-27 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Jan 27 08:11:45 2018
New Revision: 323589

URL: http://llvm.org/viewvc/llvm-project?rev=323589=rev
Log:
[ASTImporter] Add support to import some AST nodes:

* CXXOperatorCallExpr
* SizeOfPackExpr
* DependentTemplateSpecializationType
* DependentSizedArray
* CXXTypeidExpr
* Fix importing CXXTemporaryObjectExpr

Some of the changes are based on
https://github.com/haoNoQ/clang/blob/summary-ipa-draft/lib/AST/ASTImporter.cpp

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

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=323589=323588=323589=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Sat Jan 27 08:11:45 2018
@@ -52,7 +52,7 @@ namespace clang {
 QualType VisitConstantArrayType(const ConstantArrayType *T);
 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
 QualType VisitVariableArrayType(const VariableArrayType *T);
-// FIXME: DependentSizedArrayType
+QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
 // FIXME: DependentSizedExtVectorType
 QualType VisitVectorType(const VectorType *T);
 QualType VisitExtVectorType(const ExtVectorType *T);
@@ -78,7 +78,8 @@ namespace clang {
 QualType VisitElaboratedType(const ElaboratedType *T);
 // FIXME: DependentNameType
 QualType VisitPackExpansionType(const PackExpansionType *T);
-// FIXME: DependentTemplateSpecializationType
+QualType VisitDependentTemplateSpecializationType(
+const DependentTemplateSpecializationType *T);
 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 QualType VisitObjCObjectType(const ObjCObjectType *T);
 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
@@ -294,6 +295,7 @@ namespace clang {
 Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
 Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
 Expr *VisitPackExpansionExpr(PackExpansionExpr *E);
+Expr *VisitSizeOfPackExpr(SizeOfPackExpr *E);
 Expr *VisitCXXNewExpr(CXXNewExpr *CE);
 Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
@@ -315,6 +317,7 @@ namespace clang {
 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
 Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
 Expr *VisitTypeTraitExpr(TypeTraitExpr *E);
+Expr *VisitCXXTypeidExpr(CXXTypeidExpr *E);
 
 
 template
@@ -527,6 +530,24 @@ QualType ASTNodeImporter::VisitVariableA
   Brackets);
 }
 
+QualType ASTNodeImporter::VisitDependentSizedArrayType(
+const DependentSizedArrayType *T) {
+  QualType ToElementType = Importer.Import(T->getElementType());
+  if (ToElementType.isNull())
+return QualType();
+
+  // SizeExpr may be null if size is not specified directly.
+  // For example, 'int a[]'.
+  Expr *Size = Importer.Import(T->getSizeExpr());
+  if (!Size && T->getSizeExpr())
+return QualType();
+
+  SourceRange Brackets = Importer.Import(T->getBracketsRange());
+  return Importer.getToContext().getDependentSizedArrayType(
+  ToElementType, Size, T->getSizeModifier(), 
T->getIndexTypeCVRQualifiers(),
+  Brackets);
+}
+
 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
   QualType ToElementType = Importer.Import(T->getElementType());
   if (ToElementType.isNull())
@@ -827,6 +848,25 @@ QualType ASTNodeImporter::VisitPackExpan
   T->getNumExpansions());
 }
 
+QualType ASTNodeImporter::VisitDependentTemplateSpecializationType(
+const DependentTemplateSpecializationType *T) {
+  NestedNameSpecifier *Qualifier = Importer.Import(T->getQualifier());
+  if (!Qualifier && T->getQualifier())
+return QualType();
+
+  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
+  if (!Name && T->getIdentifier())
+return QualType();
+
+  SmallVector ToPack;
+  ToPack.reserve(T->getNumArgs());
+  if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack))
+return QualType();
+
+  return Importer.getToContext().getDependentTemplateSpecializationType(
+T->getKeyword(), Qualifier, Name, ToPack);
+}
+
 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
   ObjCInterfaceDecl *Class
 = dyn_cast_or_null(Importer.Import(T->getDecl()));
@@ -5709,6 +5749,11 @@ Expr *ASTNodeImporter::VisitCXXTemporary
   if (T.isNull())
 return nullptr;
 
+
+  TypeSourceInfo *TInfo = Importer.Import(CE->getTypeSourceInfo());
+  if (!TInfo)
+return nullptr;
+
   SmallVector Args(CE->getNumArgs());
   if (ImportContainerChecked(CE->arguments(), Args))

r323115 - [analyzer] Model and check unrepresentable left shifts

2018-01-22 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Jan 22 05:32:10 2018
New Revision: 323115

URL: http://llvm.org/viewvc/llvm-project?rev=323115=rev
Log:
[analyzer] Model and check unrepresentable left shifts

Patch by: Reka Nikolett Kovacs

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
cfe/trunk/test/Analysis/bitwise-ops.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp?rev=323115=323114=323115=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp Mon Jan 22 
05:32:10 2018
@@ -63,6 +63,15 @@ static bool isShiftOverflow(const Binary
   B->getRHS(), C.getASTContext().getIntWidth(B->getLHS()->getType()));
 }
 
+static bool isLeftShiftResultUnrepresentable(const BinaryOperator *B,
+ CheckerContext ) {
+  SValBuilder  = C.getSValBuilder();
+  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()));
+  return (unsigned)RHS->getZExtValue() > LHS->countLeadingZeros();
+}
+
 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
CheckerContext ) const {
   if (C.getSVal(B).isUndef()) {
@@ -138,6 +147,19 @@ void UndefResultChecker::checkPostStmt(c
  C.isNegative(B->getLHS())) {
 OS << "The result of the left shift is undefined because the left "
   "operand is negative";
+  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
+ isLeftShiftResultUnrepresentable(B, C)) {
+ProgramStateRef State = C.getState();
+SValBuilder  = C.getSValBuilder();
+const llvm::APSInt *LHS =
+SB.getKnownValue(State, C.getSVal(B->getLHS()));
+const llvm::APSInt *RHS =
+SB.getKnownValue(State, C.getSVal(B->getRHS()));
+OS << "The result of the left shift is undefined due to shifting \'"
+   << LHS->getSExtValue() << "\' by \'" << RHS->getZExtValue()
+   << "\', which is unrepresentable in the unsigned version of "
+   << "the return type \'" << B->getLHS()->getType().getAsString()
+   << "\'";
   } else {
 OS << "The result of the '"
<< BinaryOperator::getOpcodeStr(B->getOpcode())

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp?rev=323115=323114=323115=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp Mon Jan 22 05:32:10 
2018
@@ -224,7 +224,6 @@ BasicValueFactory::evalAPSInt(BinaryOper
   // FIXME: This logic should probably go higher up, where we can
   // test these conditions symbolically.
 
-  // FIXME: Expand these checks to include all undefined behavior.
   if (V1.isSigned() && V1.isNegative())
 return nullptr;
 
@@ -236,6 +235,9 @@ BasicValueFactory::evalAPSInt(BinaryOper
   if (Amt >= V1.getBitWidth())
 return nullptr;
 
+  if (V1.isSigned() && Amt > V1.countLeadingZeros())
+  return nullptr;
+
   return ( V1.operator<<( (unsigned) Amt ));
 }
 
@@ -244,8 +246,6 @@ BasicValueFactory::evalAPSInt(BinaryOper
   // FIXME: This logic should probably go higher up, where we can
   // test these conditions symbolically.
 
-  // FIXME: Expand these checks to include all undefined behavior.
-
   if (V2.isSigned() && V2.isNegative())
 return nullptr;
 

Modified: cfe/trunk/test/Analysis/bitwise-ops.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/bitwise-ops.c?rev=323115=323114=323115=diff
==
--- cfe/trunk/test/Analysis/bitwise-ops.c (original)
+++ cfe/trunk/test/Analysis/bitwise-ops.c Mon Jan 22 05:32:10 2018
@@ -51,3 +51,9 @@ int testNegativeLeftShift(int a) {
   }
   return 0;
 }
+
+int testUnrepresentableLeftShift(int a) {
+  if (a == 8)
+return a << 30; // expected-warning{{The result of the left shift is 
undefined due to shifting '8' by '30', which is unrepresentable in the unsigned 
version of the return type 'int'}}
+  return 0;
+}


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


r321933 - [analyzer] Fix some check's output plist not containing the check name

2018-01-06 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Sat Jan  6 02:51:00 2018
New Revision: 321933

URL: http://llvm.org/viewvc/llvm-project?rev=321933=rev
Log:
[analyzer] Fix some check's output plist not containing the check name

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
cfe/trunk/test/Analysis/malloc.c

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h?rev=321933=321932=321933=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h Sat Jan  
6 02:51:00 2018
@@ -32,27 +32,39 @@ private:
   const CheckName Check;
   const std::string Name;
   const std::string Category;
-  bool SuppressonSink;
+  const CheckerBase *Checker;
+  bool SuppressOnSink;
 
   virtual void anchor();
+
 public:
-  BugType(class CheckName check, StringRef name, StringRef cat)
-  : Check(check), Name(name), Category(cat), SuppressonSink(false) {}
-  BugType(const CheckerBase *checker, StringRef name, StringRef cat)
-  : Check(checker->getCheckName()), Name(name), Category(cat),
-SuppressonSink(false) {}
-  virtual ~BugType() {}
+  BugType(CheckName Check, StringRef Name, StringRef Cat)
+  : Check(Check), Name(Name), Category(Cat), Checker(nullptr),
+SuppressOnSink(false) {}
+  BugType(const CheckerBase *Checker, StringRef Name, StringRef Cat)
+  : Check(Checker->getCheckName()), Name(Name), Category(Cat),
+Checker(Checker), SuppressOnSink(false) {}
+  virtual ~BugType() = default;
 
-  // FIXME: Should these be made strings as well?
   StringRef getName() const { return Name; }
   StringRef getCategory() const { return Category; }
-  StringRef getCheckName() const { return Check.getName(); }
+  StringRef getCheckName() const {
+// FIXME: This is a workaround to ensure that the correct check name is 
used
+// The check names are set after the constructors are run.
+// In case the BugType object is initialized in the checker's ctor
+// the Check field will be empty. To circumvent this problem we use 
+// CheckerBase whenever it is possible.
+StringRef CheckName =
+Checker ? Checker->getCheckName().getName() : Check.getName();
+assert(!CheckName.empty() && "Check name is not set properly.");
+return CheckName;
+  }
 
   /// isSuppressOnSink - Returns true if bug reports associated with this bug
   ///  type should be suppressed if the end node of the report is 
post-dominated
   ///  by a sink node.
-  bool isSuppressOnSink() const { return SuppressonSink; }
-  void setSuppressOnSink(bool x) { SuppressonSink = x; }
+  bool isSuppressOnSink() const { return SuppressOnSink; }
+  void setSuppressOnSink(bool x) { SuppressOnSink = x; }
 
   virtual void FlushReports(BugReporter& BR);
 };
@@ -74,7 +86,7 @@ public:
   StringRef getDescription() const { return desc; }
 };
 
-} // end GR namespace
+} // end ento namespace
 
 } // end clang namespace
 #endif

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp?rev=321933=321932=321933=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp Sat Jan  6 02:51:00 
2018
@@ -2900,8 +2900,13 @@ void ento::registerNewDeleteLeaksChecker
   mgr.getCurrentCheckName();
   // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
   // checker.
-  if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
+  if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
+// FIXME: This does not set the correct name, but without this workaround
+//no name will be set at all.
+checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
+mgr.getCurrentCheckName();
+  }
 }
 
 #define REGISTER_CHECKER(name) 
\

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp?rev=321933=321932=321933=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp Sat Jan  6 02:51:00 
2018
@@ -64,7 +64,7 @@ private:
  

r321190 - Make DiagnosticIDs::getAllDiagnostics use std::vector. NFC.

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 08:55:41 2017
New Revision: 321190

URL: http://llvm.org/viewvc/llvm-project?rev=321190=rev
Log:
Make DiagnosticIDs::getAllDiagnostics use std::vector. NFC.

The size of the result vector is currently around 4600 with
Flavor::WarningOrError, which makes std::vector a better candidate than
llvm::SmallVector.

Patch by: Andras Leitereg!

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticIDs.h
cfe/trunk/lib/Basic/Diagnostic.cpp
cfe/trunk/lib/Basic/DiagnosticIDs.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticIDs.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticIDs.h?rev=321190=321189=321190=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticIDs.h (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticIDs.h Wed Dec 20 08:55:41 2017
@@ -297,7 +297,7 @@ public:
 
   /// \brief Get the set of all diagnostic IDs.
   static void getAllDiagnostics(diag::Flavor Flavor,
-SmallVectorImpl );
+std::vector );
 
   /// \brief Get the diagnostic option with the closest edit distance to the
   /// given group name.

Modified: cfe/trunk/lib/Basic/Diagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Diagnostic.cpp?rev=321190=321189=321190=diff
==
--- cfe/trunk/lib/Basic/Diagnostic.cpp (original)
+++ cfe/trunk/lib/Basic/Diagnostic.cpp Wed Dec 20 08:55:41 2017
@@ -363,7 +363,7 @@ void DiagnosticsEngine::setSeverityForAl
   diag::Severity Map,
   SourceLocation Loc) {
   // Get all the diagnostics.
-  SmallVector AllDiags;
+  std::vector AllDiags;
   DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
 
   // Set the mapping.

Modified: cfe/trunk/lib/Basic/DiagnosticIDs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/DiagnosticIDs.cpp?rev=321190=321189=321190=diff
==
--- cfe/trunk/lib/Basic/DiagnosticIDs.cpp (original)
+++ cfe/trunk/lib/Basic/DiagnosticIDs.cpp Wed Dec 20 08:55:41 2017
@@ -583,7 +583,7 @@ DiagnosticIDs::getDiagnosticsInGroup(dia
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
-  SmallVectorImpl ) {
+  std::vector ) {
   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
 if (StaticDiagInfo[i].getFlavor() == Flavor)
   Diags.push_back(StaticDiagInfo[i].DiagID);


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


[clang-tools-extra] r321169 - Fix an error in the release notes.

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 04:30:27 2017
New Revision: 321169

URL: http://llvm.org/viewvc/llvm-project?rev=321169=rev
Log:
Fix an error in the release notes.

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=321169=321168=321169=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Wed Dec 20 04:30:27 2017
@@ -269,7 +269,7 @@ Improvements to clang-tidy
 - Added the ability to suppress specific checks (or all checks) in a 
``NOLINT`` or ``NOLINTNEXTLINE`` comment.
 
 - Added new functionality to `misc-redundant-expression
-  
http://clang.llvm.org/extra/clang-tidy/checks/misc-redundant-expression.html`_ 
check
+  
`_
 check
 
   Finds redundant binary operator expressions where the operators are 
overloaded,
   and ones that contain the same macros twice.


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


[clang-tools-extra] r321168 - [clang-tidy] Misc redundant expression checker updated for ineffective bitwise operator expressions

2017-12-20 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Dec 20 04:22:16 2017
New Revision: 321168

URL: http://llvm.org/viewvc/llvm-project?rev=321168=rev
Log:
[clang-tidy] Misc redundant expression checker updated for ineffective bitwise 
operator expressions

Examples:
* Always evaluates to 0:

```
  int X;
  if (0 & X) return;
```

* Always evaluates to ~0:

```
  int Y;
  if (Y | ~0) return;
```

* The symbol is unmodified:

```
  int Z;
  Z &= ~0;
```

Patch by: Lilla Barancsuk!

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

Modified:
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp

Modified: clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp?rev=321168=321167=321168=diff
==
--- clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp Wed 
Dec 20 04:22:16 2017
@@ -22,6 +22,7 @@
 #include "llvm/Support/Casting.h"
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -198,7 +199,7 @@ static bool areExclusiveRanges(BinaryOpe
 }
 
 // Returns whether the ranges covered by the union of both relational
-// expressions covers the whole domain (i.e. x < 10  and  x > 0).
+// expressions cover the whole domain (i.e. x < 10  and  x > 0).
 static bool rangesFullyCoverDomain(BinaryOperatorKind OpcodeLHS,
const APSInt ,
BinaryOperatorKind OpcodeRHS,
@@ -519,6 +520,9 @@ static bool retrieveRelationalIntegerCon
 if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
   return false;
 
+if (canOverloadedOperatorArgsBeModified(OverloadedFunctionDecl, false))
+  return false;
+
 if (!OverloadedOperatorExpr->getArg(1)->isIntegerConstantExpr(
 Value, *Result.Context))
   return false;
@@ -559,7 +563,7 @@ static bool areSidesBinaryConstExpressio
 }
 
 // Retrieves integer constant subexpressions from binary operator expressions
-// that have two equivalent sides
+// that have two equivalent sides.
 // E.g.: from (X == 5) && (X == 5) retrieves 5 and 5.
 static bool retrieveConstExprFromBothSides(const BinaryOperator *,
BinaryOperatorKind ,
@@ -675,6 +679,33 @@ void RedundantExpressionCheck::registerM
   .bind("call"),
   this);
 
+  // Match expressions like: !(1 | 2 | 3)
+  Finder->addMatcher(
+  implicitCastExpr(
+  hasImplicitDestinationType(isInteger()),
+  has(unaryOperator(
+  hasOperatorName("!"),
+  hasUnaryOperand(ignoringParenImpCasts(binaryOperator(
+  anyOf(hasOperatorName("|"), hasOperatorName("&")),
+  hasLHS(anyOf(binaryOperator(anyOf(hasOperatorName("|"),
+hasOperatorName("&"))),
+   integerLiteral())),
+  hasRHS(integerLiteral())
+  .bind("logical-bitwise-confusion"))),
+  this);
+
+  // Match expressions like: (X << 8) & 0xFF
+  Finder->addMatcher(
+  binaryOperator(hasOperatorName("&"),
+ hasEitherOperand(ignoringParenImpCasts(binaryOperator(
+ hasOperatorName("<<"),
+ hasRHS(ignoringParenImpCasts(
+ integerLiteral().bind("shift-const")),
+ hasEitherOperand(ignoringParenImpCasts(
+ integerLiteral().bind("and-const"
+  .bind("left-right-shift-confusion"),
+  this);
+
   // Match common expressions and apply more checks to find redundant
   // sub-expressions.
   //   a) Expr  K1 == K2
@@ -783,6 +814,21 @@ void RedundantExpressionCheck::checkArit
   }
 }
 
+static bool exprEvaluatesToZero(BinaryOperatorKind Opcode, APSInt Value) {
+  return (Opcode == BO_And || Opcode == BO_AndAssign) && Value == 0;
+}
+
+static bool exprEvaluatesToBitwiseNegatedZero(BinaryOperatorKind Opcode,
+  APSInt Value) {
+  return (Opcode == BO_Or || Opcode == BO_OrAssign) && ~Value == 0;
+}
+
+static bool exprEvaluatesToSymbolic(BinaryOperatorKind Opcode, APSInt Value) {
+  return ((Opcode == BO_Or || Opcode == BO_OrAssign) && Value == 0) ||
+ ((Opcode == BO_And || Opcode == BO_AndAssign) && ~Value == 0);
+}
+
+
 void RedundantExpressionCheck::checkBitwiseExpr(
 const MatchFinder::MatchResult ) {
   if (const auto *ComparisonOperator = Result.Nodes.getNodeAs(
@@ -816,6 +862,43 @@ void RedundantExpressionCheck::checkBitw
   else if (Opcode == BO_NE)
 diag(Loc, "logical 

[clang-tools-extra] r319170 - [clang-tidy] Fix tests for ReplaceRandomShuffleCheck

2017-11-28 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Nov 28 05:54:52 2017
New Revision: 319170

URL: http://llvm.org/viewvc/llvm-project?rev=319170=rev
Log:
[clang-tidy] Fix tests for ReplaceRandomShuffleCheck

Patch by: Daniel Kolozsvari!

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

Modified:
clang-tools-extra/trunk/test/clang-tidy/modernize-replace-random-shuffle.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/modernize-replace-random-shuffle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-replace-random-shuffle.cpp?rev=319170=319169=319170=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/modernize-replace-random-shuffle.cpp 
(original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/modernize-replace-random-shuffle.cpp 
Tue Nov 28 05:54:52 2017
@@ -34,21 +34,21 @@ int main() {
   std::vector vec;
 
   std::random_shuffle(vec.begin(), vec.end());
-  // CHECK-MESSAGE: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' instead
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' instead
   // CHECK-FIXES: std::shuffle(vec.begin(), vec.end(), 
std::mt19937(std::random_device()()));
 
   std::shuffle(vec.begin(), vec.end());
 
   random_shuffle(vec.begin(), vec.end());
-  // CHECK-MESSAGE: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' instead
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' instead
   // CHECK-FIXES: shuffle(vec.begin(), vec.end(), 
std::mt19937(std::random_device()()));
   
   std::random_shuffle(vec.begin(), vec.end(), myrandom);
-  // CHECK-MESSAGE: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' and an alternative random mechanism instead
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' and an alternative random mechanism instead
   // CHECK-FIXES: std::shuffle(vec.begin(), vec.end(), 
std::mt19937(std::random_device()()));
 
   random_shuffle(vec.begin(), vec.end(), myrandom);
-  // CHECK-MESSAGE: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' and an alternative random mechanism instead
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: 'std::random_shuffle' has been 
removed in C++17; use 'std::shuffle' and an alternative random mechanism instead
   // CHECK-FIXES: shuffle(vec.begin(), vec.end(), 
std::mt19937(std::random_device()()));
 
   shuffle(vec.begin(), vec.end());


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


[clang-tools-extra] r319033 - [clang-tidy] Misc redundant expressions check updated for overloaded operators

2017-11-27 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Nov 27 07:05:24 2017
New Revision: 319033

URL: http://llvm.org/viewvc/llvm-project?rev=319033=rev
Log:
[clang-tidy] Misc redundant expressions check updated for overloaded operators

Patch by: Lilla Barancsuk

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

Modified:
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp

Modified: clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp?rev=319033=319032=319033=diff
==
--- clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp Mon 
Nov 27 07:05:24 2017
@@ -98,6 +98,9 @@ static bool areEquivalentExpr(const Expr
   case Stmt::StringLiteralClass:
 return cast(Left)->getBytes() ==
cast(Right)->getBytes();
+  case Stmt::CXXOperatorCallExprClass:
+return cast(Left)->getOperator() ==
+   cast(Right)->getOperator();
   case Stmt::DependentScopeDeclRefExprClass:
 if (cast(Left)->getDeclName() !=
 cast(Right)->getDeclName())
@@ -410,6 +413,7 @@ matchRelationalIntegerConstantExpr(Strin
   std::string CastId = (Id + "-cast").str();
   std::string SwapId = (Id + "-swap").str();
   std::string NegateId = (Id + "-negate").str();
+  std::string OverloadId = (Id + "-overload").str();
 
   const auto RelationalExpr = ignoringParenImpCasts(binaryOperator(
   isComparisonOperator(), expr().bind(Id),
@@ -437,12 +441,54 @@ matchRelationalIntegerConstantExpr(Strin
 hasOperatorName("!"),
 hasUnaryOperand(anyOf(CastExpr, RelationalExpr);
 
+  const auto OverloadedOperatorExpr =
+  cxxOperatorCallExpr(
+  anyOf(hasOverloadedOperatorName("=="),
+hasOverloadedOperatorName("!="), 
hasOverloadedOperatorName("<"),
+hasOverloadedOperatorName("<="), 
hasOverloadedOperatorName(">"),
+hasOverloadedOperatorName(">=")),
+  // Filter noisy false positives.
+  unless(isMacro()), unless(isInTemplateInstantiation()))
+  .bind(OverloadId);
+
   return anyOf(RelationalExpr, CastExpr, NegateRelationalExpr,
-   NegateNegateRelationalExpr);
+   NegateNegateRelationalExpr, OverloadedOperatorExpr);
 }
 
-// Retrieves sub-expressions matched by 'matchRelationalIntegerConstantExpr' 
with
-// name 'Id'.
+// Checks whether a function param is non constant reference type, and may
+// be modified in the function.
+static bool isNonConstReferenceType(QualType ParamType) {
+  return ParamType->isReferenceType() &&
+ !ParamType.getNonReferenceType().isConstQualified();
+}
+
+// Checks whether the arguments of an overloaded operator can be modified in 
the
+// function.
+// For operators that take an instance and a constant as arguments, only the
+// first argument (the instance) needs to be checked, since the constant itself
+// is a temporary expression. Whether the second parameter is checked is
+// controlled by the parameter `ParamsToCheckCount`.
+static bool
+canOverloadedOperatorArgsBeModified(const FunctionDecl *OperatorDecl,
+bool checkSecondParam) {
+  unsigned ParamCount = OperatorDecl->getNumParams();
+
+  // Overloaded operators declared inside a class have only one param.
+  // These functions must be declared const in order to not be able to modify
+  // the instance of the class they are called through.
+  if (ParamCount == 1 &&
+  !OperatorDecl->getType()->getAs()->isConst())
+return true;
+
+  if (isNonConstReferenceType(OperatorDecl->getParamDecl(0)->getType()))
+return true;
+
+  return checkSecondParam && ParamCount == 2 &&
+ isNonConstReferenceType(OperatorDecl->getParamDecl(1)->getType());
+}
+
+// Retrieves sub-expressions matched by 'matchRelationalIntegerConstantExpr'
+// with name 'Id'.
 static bool retrieveRelationalIntegerConstantExpr(
 const MatchFinder::MatchResult , StringRef Id,
 const Expr *, BinaryOperatorKind , const Expr *,
@@ -450,6 +496,7 @@ static bool retrieveRelationalIntegerCon
   std::string CastId = (Id + "-cast").str();
   std::string SwapId = (Id + "-swap").str();
   std::string NegateId = (Id + "-negate").str();
+  std::string OverloadId = (Id + "-overload").str();
 
   if (const auto *Bin = Result.Nodes.getNodeAs(Id)) {
 // Operand received with explicit comparator.
@@ -458,12 +505,29 @@ static bool retrieveRelationalIntegerCon
 
 if (!retrieveIntegerConstantExpr(Result, Id, Value, ConstExpr))
   return false;
-
   } else if (const auto *Cast = Result.Nodes.getNodeAs(CastId)) {
 // Operand received with implicit comparator (cast).
 Opcode = BO_NE;
 

[clang-tools-extra] r318523 - [clang-tidy] Fix an oversight after renaming a check

2017-11-17 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Nov 17 04:28:58 2017
New Revision: 318523

URL: http://llvm.org/viewvc/llvm-project?rev=318523=rev
Log:
[clang-tidy] Fix an oversight after renaming a check

Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=318523=318522=318523=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Fri Nov 
17 04:28:58 2017
@@ -23,7 +23,7 @@ class BugproneModule : public ClangTidyM
 public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
-"misc-copy-constructor-init");
+"bugprone-copy-constructor-init");
 CheckFactories.registerCheck(
 "bugprone-integer-division");
 CheckFactories.registerCheck(

Modified: 
clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp?rev=318523=318522=318523=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp 
Fri Nov 17 04:28:58 2017
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s misc-copy-constructor-init %t
+// RUN: %check_clang_tidy %s bugprone-copy-constructor-init %t
 
 class NonCopyable {
 public:
@@ -79,7 +79,7 @@ class X : public Copyable, public EmptyC
 
 class X2 : public Copyable2 {
   X2(const X2 ) {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling a base constructor other 
than the copy constructor [misc-copy-constructor-init]
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: calling a base constructor other 
than the copy constructor [bugprone-copy-constructor-init]
   // CHECK-FIXES: X2(const X2 )  : Copyable2(other) {}
 };
 


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


[clang-tools-extra] r318522 - [clang-tidy] Add a check for undelegated copy of base classes

2017-11-17 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Nov 17 04:23:30 2017
New Revision: 318522

URL: http://llvm.org/viewvc/llvm-project?rev=318522=rev
Log:
[clang-tidy] Add a check for undelegated copy of base classes

Finds copy constructors where the constructor don't call
the copy constructor of the base class.

```
class X : public Copyable {
X(const X ) {} // Copyable(other) is missing
};
```

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

Added:
clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-copy-constructor-init.rst
clang-tools-extra/trunk/test/clang-tidy/bugprone-copy-constructor-init.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=318522=318521=318522=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Fri Nov 
17 04:23:30 2017
@@ -10,6 +10,7 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "CopyConstructorInitCheck.h"
 #include "IntegerDivisionCheck.h"
 #include "SuspiciousMemsetUsageCheck.h"
 #include "UndefinedMemoryManipulationCheck.h"
@@ -21,6 +22,8 @@ namespace bugprone {
 class BugproneModule : public ClangTidyModule {
 public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
+CheckFactories.registerCheck(
+"misc-copy-constructor-init");
 CheckFactories.registerCheck(
 "bugprone-integer-division");
 CheckFactories.registerCheck(

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt?rev=318522=318521=318522=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt Fri Nov 17 
04:23:30 2017
@@ -2,6 +2,7 @@ set(LLVM_LINK_COMPONENTS support)
 
 add_clang_library(clangTidyBugproneModule
   BugproneTidyModule.cpp
+  CopyConstructorInitCheck.cpp
   IntegerDivisionCheck.cpp
   SuspiciousMemsetUsageCheck.cpp
   UndefinedMemoryManipulationCheck.cpp

Added: clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.cpp?rev=318522=auto
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CopyConstructorInitCheck.cpp 
Fri Nov 17 04:23:30 2017
@@ -0,0 +1,121 @@
+//===--- CopyConstructorInitCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "CopyConstructorInitCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+void CopyConstructorInitCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus)
+return;
+
+  // In the future this might be extended to move constructors?
+  Finder->addMatcher(
+  cxxConstructorDecl(
+  isCopyConstructor(),
+  hasAnyConstructorInitializer(cxxCtorInitializer(
+  isBaseInitializer(),
+  withInitializer(cxxConstructExpr(hasDeclaration(
+  cxxConstructorDecl(isDefaultConstructor())),
+  unless(isInstantiated()))
+  .bind("ctor"),
+  this);
+}
+
+void CopyConstructorInitCheck::check(const MatchFinder::MatchResult ) {
+  const auto *Ctor = Result.Nodes.getNodeAs("ctor");
+  std::string ParamName = Ctor->getParamDecl(0)->getNameAsString();
+
+  // We want only one warning (and FixIt) for each ctor.
+  std::string FixItInitList;
+  bool HasRelevantBaseInit = false;
+  bool ShouldNotDoFixit = false;
+  bool HasWrittenInitializer = false;
+  SmallVector SafeFixIts;
+  for (const auto *Init : Ctor->inits()) {
+bool 

r318150 - Make DiagnosticIDs::getAllDiagnostics static. NFC.

2017-11-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Nov 14 04:14:49 2017
New Revision: 318150

URL: http://llvm.org/viewvc/llvm-project?rev=318150=rev
Log:
Make DiagnosticIDs::getAllDiagnostics static. NFC.

Patch by: Andras Leitereg!

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticIDs.h
cfe/trunk/lib/Basic/Diagnostic.cpp
cfe/trunk/lib/Basic/DiagnosticIDs.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticIDs.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticIDs.h?rev=318150=318149=318150=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticIDs.h (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticIDs.h Tue Nov 14 04:14:49 2017
@@ -296,8 +296,8 @@ public:
  SmallVectorImpl ) const;
 
   /// \brief Get the set of all diagnostic IDs.
-  void getAllDiagnostics(diag::Flavor Flavor,
- SmallVectorImpl ) const;
+  static void getAllDiagnostics(diag::Flavor Flavor,
+SmallVectorImpl );
 
   /// \brief Get the diagnostic option with the closest edit distance to the
   /// given group name.

Modified: cfe/trunk/lib/Basic/Diagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Diagnostic.cpp?rev=318150=318149=318150=diff
==
--- cfe/trunk/lib/Basic/Diagnostic.cpp (original)
+++ cfe/trunk/lib/Basic/Diagnostic.cpp Tue Nov 14 04:14:49 2017
@@ -364,7 +364,7 @@ void DiagnosticsEngine::setSeverityForAl
   SourceLocation Loc) {
   // Get all the diagnostics.
   SmallVector AllDiags;
-  Diags->getAllDiagnostics(Flavor, AllDiags);
+  DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
 
   // Set the mapping.
   for (diag::kind Diag : AllDiags)

Modified: cfe/trunk/lib/Basic/DiagnosticIDs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/DiagnosticIDs.cpp?rev=318150=318149=318150=diff
==
--- cfe/trunk/lib/Basic/DiagnosticIDs.cpp (original)
+++ cfe/trunk/lib/Basic/DiagnosticIDs.cpp Tue Nov 14 04:14:49 2017
@@ -583,7 +583,7 @@ DiagnosticIDs::getDiagnosticsInGroup(dia
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
- SmallVectorImpl ) const 
{
+  SmallVectorImpl ) {
   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
 if (StaticDiagInfo[i].getFlavor() == Flavor)
   Diags.push_back(StaticDiagInfo[i].DiagID);


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


r318147 - [ASTImporter] TypeAliasTemplate and PackExpansion importing capability

2017-11-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Nov 14 03:30:38 2017
New Revision: 318147

URL: http://llvm.org/viewvc/llvm-project?rev=318147=rev
Log:
[ASTImporter] TypeAliasTemplate and PackExpansion importing capability

Patch by: Zoltan Gera!

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

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=318147=318146=318147=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Tue Nov 14 03:30:38 2017
@@ -77,6 +77,7 @@ namespace clang {
 QualType VisitTemplateSpecializationType(const TemplateSpecializationType 
*T);
 QualType VisitElaboratedType(const ElaboratedType *T);
 // FIXME: DependentNameType
+QualType VisitPackExpansionType(const PackExpansionType *T);
 // FIXME: DependentTemplateSpecializationType
 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
 QualType VisitObjCObjectType(const ObjCObjectType *T);
@@ -149,6 +150,7 @@ namespace clang {
 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
 Decl *VisitTypedefDecl(TypedefDecl *D);
 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
+Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
 Decl *VisitLabelDecl(LabelDecl *D);
 Decl *VisitEnumDecl(EnumDecl *D);
 Decl *VisitRecordDecl(RecordDecl *D);
@@ -265,6 +267,7 @@ namespace clang {
 Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
 Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
 Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
+Expr *VisitPackExpansionExpr(PackExpansionExpr *E);
 Expr *VisitCXXNewExpr(CXXNewExpr *CE);
 Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
@@ -767,6 +770,15 @@ QualType ASTNodeImporter::VisitElaborate
ToQualifier, ToNamedType);
 }
 
+QualType ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
+  QualType Pattern = Importer.Import(T->getPattern());
+  if (Pattern.isNull())
+return QualType();
+
+  return Importer.getToContext().getPackExpansionType(Pattern,
+  T->getNumExpansions());
+}
+
 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
   ObjCInterfaceDecl *Class
 = dyn_cast_or_null(Importer.Import(T->getDecl()));
@@ -1487,6 +1499,63 @@ Decl *ASTNodeImporter::VisitTypeAliasDec
   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
 }
 
+Decl *ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
+  // Import the major distinguishing characteristics of this typedef.
+  DeclContext *DC, *LexicalDC;
+  DeclarationName Name;
+  SourceLocation Loc;
+  NamedDecl *ToD;
+  if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
+return nullptr;
+  if (ToD)
+return ToD;
+
+  // If this typedef is not in block scope, determine whether we've
+  // seen a typedef with the same name (that we can merge with) or any
+  // other entity by that name (which name lookup could conflict with).
+  if (!DC->isFunctionOrMethod()) {
+SmallVector ConflictingDecls;
+unsigned IDNS = Decl::IDNS_Ordinary;
+SmallVector FoundDecls;
+DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
+for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
+  if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
+continue;
+  if (auto *FoundAlias =
+dyn_cast(FoundDecls[I]))
+  return Importer.Imported(D, FoundAlias);
+  ConflictingDecls.push_back(FoundDecls[I]);
+}
+
+if (!ConflictingDecls.empty()) {
+  Name = Importer.HandleNameConflict(Name, DC, IDNS,
+ ConflictingDecls.data(),
+ ConflictingDecls.size());
+  if (!Name)
+return nullptr;
+}
+  }
+
+  TemplateParameterList *Params = ImportTemplateParameterList(
+D->getTemplateParameters());
+  if (!Params)
+return nullptr;
+
+  NamedDecl *TemplDecl = cast_or_null(
+Importer.Import(D->getTemplatedDecl()));
+  if (!TemplDecl)
+return nullptr;
+
+  TypeAliasTemplateDecl *ToAlias = TypeAliasTemplateDecl::Create(
+Importer.getToContext(), DC, Loc, Name, Params, TemplDecl);
+
+  ToAlias->setAccess(D->getAccess());
+  ToAlias->setLexicalDeclContext(LexicalDC);
+  Importer.Imported(D, ToAlias);
+  LexicalDC->addDeclInternal(ToAlias);
+  return ToD;
+}
+
 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
   // Import the major distinguishing characteristics of this label.
   DeclContext *DC, *LexicalDC;
@@ -5180,6 +5249,20 @@ ASTNodeImporter::VisitMaterializeTempora
   return ToMTE;
 }
 

r318030 - [analyzer] Document the issue hash debugging facility

2017-11-13 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Nov 13 03:13:02 2017
New Revision: 318030

URL: http://llvm.org/viewvc/llvm-project?rev=318030=rev
Log:
[analyzer] Document the issue hash debugging facility

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

Modified:
cfe/trunk/docs/analyzer/DebugChecks.rst

Modified: cfe/trunk/docs/analyzer/DebugChecks.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/analyzer/DebugChecks.rst?rev=318030=318029=318030=diff
==
--- cfe/trunk/docs/analyzer/DebugChecks.rst (original)
+++ cfe/trunk/docs/analyzer/DebugChecks.rst Mon Nov 13 03:13:02 2017
@@ -242,6 +242,19 @@ ExprInspection checks
   clang_analyzer_printState(); // Read the stderr!
 }
 
+- ``void clang_analyzer_hashDump(int);``
+
+  The analyzer can generate a hash to identify reports. To debug what 
information
+  is used to calculate this hash it is possible to dump the hashed string as a
+  warning of an arbitrary expression using the function above.
+
+  Example usage::
+
+void foo() {
+  int x = 1;
+  clang_analyzer_hashDump(x); // expected-warning{{hashed string for x}}
+}
+
 Statistics
 ==
 


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


[clang-tools-extra] r317570 - [clang-tidy] Misc redundant expressions checker updated for macros

2017-11-07 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Nov  7 05:17:58 2017
New Revision: 317570

URL: http://llvm.org/viewvc/llvm-project?rev=317570=rev
Log:
[clang-tidy] Misc redundant expressions checker updated for macros

Redundant Expression Checker is updated to be able to detect expressions that
contain macros. Also, other small details are modified to improve the current
implementation.

The improvements in detail are as follows:
* Binary and ternary operator expressions containing two constants, with at
least one of them from a macro, are detected and tested for redundancy.

Macro expressions are treated somewhat differently from other expressions,
because the particular values of macros can vary across builds.
They can be considered correct and intentional, even if macro values equal,
produce ranges that exclude each other or fully overlap, etc. 

* The code structure is slightly modified: typos are corrected,
comments are added and some functions are renamed to improve comprehensibility,
both in the checker and the test file. A few test cases are moved to another
function.

* The checker is now able to detect redundant CXXFunctionalCastExprs as well.
A corresponding test case is added.

Patch by: Lilla Barancsuk!

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

Modified:
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-redundant-expression.rst
clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp

Modified: clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp?rev=317570=317569=317570=diff
==
--- clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp Tue 
Nov  7 05:17:58 2017
@@ -23,7 +23,6 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 
@@ -38,8 +37,8 @@ namespace {
 using llvm::APSInt;
 } // namespace
 
-static const char KnownBannedMacroNames[] =
-"EAGAIN;EWOULDBLOCK;SIGCLD;SIGCHLD;";
+static const llvm::StringSet<> KnownBannedMacroNames = {"EAGAIN", 
"EWOULDBLOCK",
+"SIGCLD", "SIGCHLD"};
 
 static bool incrementWithoutOverflow(const APSInt , APSInt ) {
   Result = Value;
@@ -99,7 +98,6 @@ static bool areEquivalentExpr(const Expr
   case Stmt::StringLiteralClass:
 return cast(Left)->getBytes() ==
cast(Right)->getBytes();
-
   case Stmt::DependentScopeDeclRefExprClass:
 if (cast(Left)->getDeclName() !=
 cast(Right)->getDeclName())
@@ -113,16 +111,14 @@ static bool areEquivalentExpr(const Expr
   case Stmt::MemberExprClass:
 return cast(Left)->getMemberDecl() ==
cast(Right)->getMemberDecl();
-
+  case Stmt::CXXFunctionalCastExprClass:
   case Stmt::CStyleCastExprClass:
-return cast(Left)->getTypeAsWritten() ==
-   cast(Right)->getTypeAsWritten();
-
+return cast(Left)->getTypeAsWritten() ==
+   cast(Right)->getTypeAsWritten();
   case Stmt::CallExprClass:
   case Stmt::ImplicitCastExprClass:
   case Stmt::ArraySubscriptExprClass:
 return true;
-
   case Stmt::UnaryOperatorClass:
 if (cast(Left)->isIncrementDecrementOp())
   return false;
@@ -282,7 +278,8 @@ static bool rangeSubsumesRange(BinaryOpe
   }
 }
 
-static void canonicalNegateExpr(BinaryOperatorKind , APSInt ) {
+static void transformSubToCanonicalAddExpr(BinaryOperatorKind ,
+   APSInt ) {
   if (Opcode == BO_Sub) {
 Opcode = BO_Add;
 Value = -Value;
@@ -295,32 +292,77 @@ AST_MATCHER(Expr, isIntegerConstantExpr)
   return Node.isIntegerConstantExpr(Finder->getASTContext());
 }
 
-// Returns a matcher for integer constant expression.
+AST_MATCHER(BinaryOperator, operandsAreEquivalent) {
+  return areEquivalentExpr(Node.getLHS(), Node.getRHS());
+}
+
+AST_MATCHER(ConditionalOperator, expressionsAreEquivalent) {
+  return areEquivalentExpr(Node.getTrueExpr(), Node.getFalseExpr());
+}
+
+AST_MATCHER(CallExpr, parametersAreEquivalent) {
+  return Node.getNumArgs() == 2 &&
+ areEquivalentExpr(Node.getArg(0), Node.getArg(1));
+}
+
+AST_MATCHER(BinaryOperator, binaryOperatorIsInMacro) {
+  return Node.getOperatorLoc().isMacroID();
+}
+
+AST_MATCHER(ConditionalOperator, conditionalOperatorIsInMacro) {
+  return Node.getQuestionLoc().isMacroID() || Node.getColonLoc().isMacroID();
+}
+
+AST_MATCHER(Expr, isMacro) { return Node.getExprLoc().isMacroID(); }
+
+AST_MATCHER_P(Expr, expandedByMacro, llvm::StringSet<>, Names) {
+  const SourceManager  = Finder->getASTContext().getSourceManager();
+  const LangOptions  = Finder->getASTContext().getLangOpts();
+  SourceLocation Loc = 

[clang-tools-extra] r317468 - [clang-tidy] Support relative paths in run-clang-tidy.py

2017-11-06 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Nov  6 02:36:02 2017
New Revision: 317468

URL: http://llvm.org/viewvc/llvm-project?rev=317468=rev
Log:
[clang-tidy] Support relative paths in run-clang-tidy.py

Unfortunately, these python scripts are not tested currently. I did the testing
manually on LLVM by editing the CMake generated compilation database to
contain relative paths for some of the files. 

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

Modified:
clang-tools-extra/trunk/clang-tidy/tool/run-clang-tidy.py

Modified: clang-tools-extra/trunk/clang-tidy/tool/run-clang-tidy.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/tool/run-clang-tidy.py?rev=317468=317467=317468=diff
==
--- clang-tools-extra/trunk/clang-tidy/tool/run-clang-tidy.py (original)
+++ clang-tools-extra/trunk/clang-tidy/tool/run-clang-tidy.py Mon Nov  6 
02:36:02 2017
@@ -68,6 +68,12 @@ def find_compilation_database(path):
   return os.path.realpath(result)
 
 
+def make_absolute(f, directory):
+  if os.path.isabs(f):
+return f
+  return os.path.normpath(os.path.join(directory, f))
+
+
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, extra_arg, extra_arg_before, quiet):
   """Gets a command line for clang-tidy."""
@@ -223,7 +229,8 @@ def main():
 
   # Load the database and extract all files.
   database = json.load(open(os.path.join(build_path, db_path)))
-  files = [entry['file'] for entry in database]
+  files = [make_absolute(entry['file'], entry['directory'])
+   for entry in database]
 
   max_task = args.j
   if max_task == 0:


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


r316924 - [analyzer] Left shifting a negative value is undefined

2017-10-30 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Oct 30 10:06:42 2017
New Revision: 316924

URL: http://llvm.org/viewvc/llvm-project?rev=316924=rev
Log:
[analyzer] Left shifting a negative value is undefined

The analyzer did not return an UndefVal in case a negative value was left
shifted. I also altered the UndefResultChecker to emit a clear warning in this
case.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
cfe/trunk/test/Analysis/bitwise-ops.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp?rev=316924=316923=316924=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp Mon Oct 30 
10:06:42 2017
@@ -137,6 +137,10 @@ void UndefResultChecker::checkPostStmt(c
 
 OS << " greater or equal to the width of type '"
<< B->getLHS()->getType().getAsString() << "'.";
+  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
+ C.isNegative(B->getLHS())) {
+OS << "The result of the left shift is undefined because the left "
+  "operand is negative";
   } else {
 OS << "The result of the '"
<< BinaryOperator::getOpcodeStr(B->getOpcode())

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp?rev=316924=316923=316924=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BasicValueFactory.cpp Mon Oct 30 10:06:42 
2017
@@ -225,6 +225,8 @@ BasicValueFactory::evalAPSInt(BinaryOper
   // test these conditions symbolically.
 
   // FIXME: Expand these checks to include all undefined behavior.
+  if (V1.isSigned() && V1.isNegative())
+return nullptr;
 
   if (V2.isSigned() && V2.isNegative())
 return nullptr;

Modified: cfe/trunk/test/Analysis/bitwise-ops.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/bitwise-ops.c?rev=316924=316923=316924=diff
==
--- cfe/trunk/test/Analysis/bitwise-ops.c (original)
+++ cfe/trunk/test/Analysis/bitwise-ops.c Mon Oct 30 10:06:42 2017
@@ -44,3 +44,10 @@ int testNegativeShift(int a) {
   }
   return 0;
 }
+
+int testNegativeLeftShift(int a) {
+  if (a == -3) {
+return a << 1; // expected-warning{{The result of the left shift is 
undefined because the left operand is negative}}
+  }
+  return 0;
+}


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


r316900 - [analyzer] Use the signature of the primary template for issue hash calculation

2017-10-30 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Oct 30 05:16:07 2017
New Revision: 316900

URL: http://llvm.org/viewvc/llvm-project?rev=316900=rev
Log:
[analyzer] Use the signature of the primary template for issue hash calculation

Now when a template is instantiated more times and there is a bug found in the
instantiations the issue hash will be different for each instantiation even if
every other property of the bug (path, message, location) is the same.

This patch aims to resolve this issue. Note that explicit specializations still
generate different hashes but that is intended.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/IssueHash.cpp
cfe/trunk/test/Analysis/bug_hash_test.cpp
cfe/trunk/test/Analysis/edges-new.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Core/IssueHash.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/IssueHash.cpp?rev=316900=316899=316900=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/IssueHash.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/IssueHash.cpp Mon Oct 30 05:16:07 2017
@@ -33,6 +33,13 @@ static std::string GetSignature(const Fu
 return "";
   std::string Signature;
 
+  // When a flow sensitive bug happens in templated code we should not generate
+  // distinct hash value for every instantiation. Use the signature from the
+  // primary template.
+  if (const FunctionDecl *InstantiatedFrom =
+  Target->getTemplateInstantiationPattern())
+Target = InstantiatedFrom;
+
   if (!isa(Target) && !isa(Target) &&
   !isa(Target))
 Signature.append(Target->getReturnType().getAsString()).append(" ");

Modified: cfe/trunk/test/Analysis/bug_hash_test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/bug_hash_test.cpp?rev=316900=316899=316900=diff
==
--- cfe/trunk/test/Analysis/bug_hash_test.cpp (original)
+++ cfe/trunk/test/Analysis/bug_hash_test.cpp Mon Oct 30 05:16:07 2017
@@ -71,15 +71,13 @@ void testLambda() {
 
 template 
 void f(T) {
-  clang_analyzer_hashDump(5); // expected-warning {{debug.ExprInspection$void 
f(double)$27$clang_analyzer_hashDump(5);$Category}}
-   // 
expected-warning@-1{{debug.ExprInspection$void 
f(int)$27$clang_analyzer_hashDump(5);$Category}}
+  clang_analyzer_hashDump(5); // expected-warning {{debug.ExprInspection$void 
f(T)$27$clang_analyzer_hashDump(5);$Category}}
 }
 
 template 
 struct TX {
   void f(T) {
-clang_analyzer_hashDump(5); // expected-warning 
{{debug.ExprInspection$void 
TX::f(double)$29$clang_analyzer_hashDump(5);$Category}}
- // 
expected-warning@-1{{debug.ExprInspection$void 
TX::f(int)$29$clang_analyzer_hashDump(5);$Category}}
+clang_analyzer_hashDump(5); // expected-warning 
{{debug.ExprInspection$void TX::f(T)$29$clang_analyzer_hashDump(5);$Category}}
   }
 };
 
@@ -99,11 +97,17 @@ template 
 struct TTX {
   template
   void f(T, S) {
-clang_analyzer_hashDump(5); // expected-warning 
{{debug.ExprInspection$void TTX::f(int, 
int)$29$clang_analyzer_hashDump(5);$Category}}
+clang_analyzer_hashDump(5); // expected-warning 
{{debug.ExprInspection$void TTX::f(T, 
S)$29$clang_analyzer_hashDump(5);$Category}}
   }
 };
 
 void g() {
+  // TX and TX is instantiated from the same code with the same
+  // source locations. The same error happining in both of the instantiations
+  // should share the common hash. This means we should not include the
+  // template argument for these types in the function signature.
+  // Note that, we still want the hash to be different for explicit
+  // specializations.
   TX x;
   TX y;
   TX xl;

Modified: cfe/trunk/test/Analysis/edges-new.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/edges-new.mm?rev=316900=316899=316900=diff
==
--- cfe/trunk/test/Analysis/edges-new.mm (original)
+++ cfe/trunk/test/Analysis/edges-new.mm Mon Oct 30 05:16:07 2017
@@ -20288,7 +20288,7 @@ namespace rdar14960554 {
 // CHECK-NEXT:typeBad deallocator
 // CHECK-NEXT:
check_nameunix.MismatchedDeallocator
 // CHECK-NEXT:
-// CHECK-NEXT:
issue_hash_content_of_line_in_contextd9dbbf68db41ab74e2158f4b131abe34
+// CHECK-NEXT:
issue_hash_content_of_line_in_context046c88d1c91ff46d6506dff5ff880756
 // CHECK-NEXT:   issue_hash_function_offset0
 // CHECK-NEXT:   location
 // CHECK-NEXT:   


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


r316892 - [analyzer] lock_guard and unique_lock extension for BlockInCriticalSection checker

2017-10-30 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Oct 30 03:09:55 2017
New Revision: 316892

URL: http://llvm.org/viewvc/llvm-project?rev=316892=rev
Log:
[analyzer] lock_guard and unique_lock extension for BlockInCriticalSection 
checker

A patch by zdtorok (Zoltán Dániel Török)!

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
cfe/trunk/test/Analysis/block-in-critical-section.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp?rev=316892=316891=316892=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
(original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp Mon 
Oct 30 03:09:55 2017
@@ -26,15 +26,22 @@ using namespace ento;
 
 namespace {
 
-class BlockInCriticalSectionChecker : public Checker {
+class BlockInCriticalSectionChecker : public Checker {
+
+  mutable IdentifierInfo *IILockGuard, *IIUniqueLock;
 
   CallDescription LockFn, UnlockFn, SleepFn, GetcFn, FgetsFn, ReadFn, RecvFn,
   PthreadLockFn, PthreadTryLockFn, PthreadUnlockFn,
   MtxLock, MtxTimedLock, MtxTryLock, MtxUnlock;
 
+  StringRef ClassLockGuard, ClassUniqueLock;
+
+  mutable bool IdentifierInfoInitialized;
+
   std::unique_ptr BlockInCritSectionBugType;
 
+  void initIdentifierInfo(ASTContext ) const;
+
   void reportBlockInCritSection(SymbolRef FileDescSym,
 const CallEvent ,
 CheckerContext ) const;
@@ -46,13 +53,10 @@ public:
   bool isLockFunction(const CallEvent ) const;
   bool isUnlockFunction(const CallEvent ) const;
 
-  void checkPreCall(const CallEvent , CheckerContext ) const;
-
   /// Process unlock.
   /// Process lock.
   /// Process blocking functions (sleep, getc, fgets, read, recv)
   void checkPostCall(const CallEvent , CheckerContext ) const;
-
 };
 
 } // end anonymous namespace
@@ -60,7 +64,8 @@ public:
 REGISTER_TRAIT_WITH_PROGRAMSTATE(MutexCounter, unsigned)
 
 BlockInCriticalSectionChecker::BlockInCriticalSectionChecker()
-: LockFn("lock"), UnlockFn("unlock"), SleepFn("sleep"), GetcFn("getc"),
+: IILockGuard(nullptr), IIUniqueLock(nullptr),
+  LockFn("lock"), UnlockFn("unlock"), SleepFn("sleep"), GetcFn("getc"),
   FgetsFn("fgets"), ReadFn("read"), RecvFn("recv"),
   PthreadLockFn("pthread_mutex_lock"),
   PthreadTryLockFn("pthread_mutex_trylock"),
@@ -68,13 +73,29 @@ BlockInCriticalSectionChecker::BlockInCr
   MtxLock("mtx_lock"),
   MtxTimedLock("mtx_timedlock"),
   MtxTryLock("mtx_trylock"),
-  MtxUnlock("mtx_unlock") {
+  MtxUnlock("mtx_unlock"),
+  ClassLockGuard("lock_guard"),
+  ClassUniqueLock("unique_lock"),
+  IdentifierInfoInitialized(false) {
   // Initialize the bug type.
   BlockInCritSectionBugType.reset(
   new BugType(this, "Call to blocking function in critical section",
 "Blocking Error"));
 }
 
+void BlockInCriticalSectionChecker::initIdentifierInfo(ASTContext ) const {
+  if (!IdentifierInfoInitialized) {
+/* In case of checking C code, or when the corresponding headers are not
+ * included, we might end up query the identifier table every time when 
this
+ * function is called instead of early returning it. To avoid this, a bool
+ * variable (IdentifierInfoInitialized) is used and the function will be 
run
+ * only once. */
+IILockGuard  = (ClassLockGuard);
+IIUniqueLock = (ClassUniqueLock);
+IdentifierInfoInitialized = true;
+  }
+}
+
 bool BlockInCriticalSectionChecker::isBlockingFunction(const CallEvent ) 
const {
   if (Call.isCalled(SleepFn)
   || Call.isCalled(GetcFn)
@@ -87,6 +108,12 @@ bool BlockInCriticalSectionChecker::isBl
 }
 
 bool BlockInCriticalSectionChecker::isLockFunction(const CallEvent ) 
const {
+  if (const auto *Ctor = dyn_cast()) {
+auto IdentifierInfo = Ctor->getDecl()->getParent()->getIdentifier();
+if (IdentifierInfo == IILockGuard || IdentifierInfo == IIUniqueLock)
+  return true;
+  }
+
   if (Call.isCalled(LockFn)
   || Call.isCalled(PthreadLockFn)
   || Call.isCalled(PthreadTryLockFn)
@@ -99,6 +126,13 @@ bool BlockInCriticalSectionChecker::isLo
 }
 
 bool BlockInCriticalSectionChecker::isUnlockFunction(const CallEvent ) 
const {
+  if (const auto *Dtor = dyn_cast()) {
+const auto *DRecordDecl = 
dyn_cast(Dtor->getDecl()->getParent());
+auto IdentifierInfo = DRecordDecl->getIdentifier();
+if (IdentifierInfo == IILockGuard || IdentifierInfo == IIUniqueLock)
+  return true;
+  }
+
   if (Call.isCalled(UnlockFn)
|| Call.isCalled(PthreadUnlockFn)
|| 

r316886 - Add missing expected-no-diagnostics comment to test.

2017-10-30 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Oct 30 02:01:48 2017
New Revision: 316886

URL: http://llvm.org/viewvc/llvm-project?rev=316886=rev
Log:
Add missing expected-no-diagnostics comment to test.

Modified:
cfe/trunk/test/Analysis/block-in-critical-section.m

Modified: cfe/trunk/test/Analysis/block-in-critical-section.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/block-in-critical-section.m?rev=316886=316885=316886=diff
==
--- cfe/trunk/test/Analysis/block-in-critical-section.m (original)
+++ cfe/trunk/test/Analysis/block-in-critical-section.m Mon Oct 30 02:01:48 2017
@@ -1,4 +1,5 @@
 // RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.unix.BlockInCriticalSection -verify 
-Wno-objc-root-class %s
+// expected-no-diagnostics
 
 @interface SomeClass
 -(void)someMethod;


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


r316885 - [analyzer] Handle ObjC messages conservatively in CallDescription

2017-10-30 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Oct 30 01:47:13 2017
New Revision: 316885

URL: http://llvm.org/viewvc/llvm-project?rev=316885=rev
Log:
[analyzer] Handle ObjC messages conservatively in CallDescription

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

Added:
cfe/trunk/test/Analysis/block-in-critical-section.m
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=316885=316884=316885=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Mon Oct 30 01:47:13 2017
@@ -211,7 +211,9 @@ ProgramPoint CallEvent::getProgramPoint(
 }
 
 bool CallEvent::isCalled(const CallDescription ) const {
-  assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported");
+  // FIXME: Add ObjC Message support.
+  if (getKind() == CE_ObjCMessage)
+return false;
   if (!CD.IsLookupDone) {
 CD.IsLookupDone = true;
 CD.II = 
()->getStateManager().getContext().Idents.get(CD.FuncName);

Added: cfe/trunk/test/Analysis/block-in-critical-section.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/block-in-critical-section.m?rev=316885=auto
==
--- cfe/trunk/test/Analysis/block-in-critical-section.m (added)
+++ cfe/trunk/test/Analysis/block-in-critical-section.m Mon Oct 30 01:47:13 2017
@@ -0,0 +1,9 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.unix.BlockInCriticalSection -verify 
-Wno-objc-root-class %s
+
+@interface SomeClass
+-(void)someMethod;
+@end
+
+void shouldNotCrash(SomeClass *o) {
+  [o someMethod];
+}


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


r316764 - [CrossTU] Fix handling of Cross Translation Unit directory path

2017-10-27 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Oct 27 05:53:37 2017
New Revision: 316764

URL: http://llvm.org/viewvc/llvm-project?rev=316764=rev
Log:
[CrossTU] Fix handling of Cross Translation Unit directory path

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

Modified:
cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp

Modified: cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp?rev=316764=316763=316764=diff
==
--- cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp (original)
+++ cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp Fri Oct 27 05:53:37 2017
@@ -93,10 +93,7 @@ parseCrossTUIndex(StringRef IndexPath, S
 index_error_code::multiple_definitions, IndexPath.str(), LineNo);
   StringRef FileName = LineRef.substr(Pos + 1);
   SmallString<256> FilePath = CrossTUDir;
-  if (llvm::sys::path::is_absolute(FileName))
-FilePath = FileName;
-  else
-llvm::sys::path::append(FilePath, FileName);
+  llvm::sys::path::append(FilePath, FileName);
   Result[FunctionLookupName] = FilePath.str().str();
 } else
   return llvm::make_error(

Modified: cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp?rev=316764=316763=316764=diff
==
--- cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp (original)
+++ cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp Fri Oct 27 
05:53:37 2017
@@ -109,9 +109,9 @@ TEST(CrossTranslationUnit, CanLoadFuncti
 
 TEST(CrossTranslationUnit, IndexFormatCanBeParsed) {
   llvm::StringMap Index;
-  Index["a"] = "b";
-  Index["c"] = "d";
-  Index["e"] = "f";
+  Index["a"] = "/b/f1";
+  Index["c"] = "/d/f2";
+  Index["e"] = "/f/f3";
   std::string IndexText = createCrossTUIndexString(Index);
 
   int IndexFD;
@@ -134,5 +134,25 @@ TEST(CrossTranslationUnit, IndexFormatCa
 EXPECT_TRUE(Index.count(E.getKey()));
 }
 
+TEST(CrossTranslationUnit, CTUDirIsHandledCorrectly) {
+  llvm::StringMap Index;
+  Index["a"] = "/b/c/d";
+  std::string IndexText = createCrossTUIndexString(Index);
+
+  int IndexFD;
+  llvm::SmallString<256> IndexFileName;
+  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("index", "txt", IndexFD,
+  IndexFileName));
+  llvm::ToolOutputFile IndexFile(IndexFileName, IndexFD);
+  IndexFile.os() << IndexText;
+  IndexFile.os().flush();
+  EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
+  llvm::Expected IndexOrErr =
+  parseCrossTUIndex(IndexFileName, "/ctudir");
+  EXPECT_TRUE((bool)IndexOrErr);
+  llvm::StringMap ParsedIndex = IndexOrErr.get();
+  EXPECT_EQ(ParsedIndex["a"], "/ctudir/b/c/d");
+}
+
 } // end namespace cross_tu
 } // end namespace clang


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


r316157 - [analyzer] Dump signed integers in SymIntExpr and IntSymExpr correctly

2017-10-19 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Oct 19 04:58:21 2017
New Revision: 316157

URL: http://llvm.org/viewvc/llvm-project?rev=316157=rev
Log:
[analyzer] Dump signed integers in SymIntExpr and IntSymExpr correctly

Patch by: Adam Balogh!

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp
cfe/trunk/test/Analysis/expr-inspection.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp?rev=316157=316156=316157=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp Thu Oct 19 04:58:21 2017
@@ -31,14 +31,20 @@ void SymIntExpr::dumpToStream(raw_ostrea
   os << '(';
   getLHS()->dumpToStream(os);
   os << ") "
- << BinaryOperator::getOpcodeStr(getOpcode()) << ' '
- << getRHS().getZExtValue();
+ << BinaryOperator::getOpcodeStr(getOpcode()) << ' ';
+  if (getRHS().isUnsigned())
+os << getRHS().getZExtValue();
+  else
+os << getRHS().getSExtValue();
   if (getRHS().isUnsigned())
 os << 'U';
 }
 
 void IntSymExpr::dumpToStream(raw_ostream ) const {
-  os << getLHS().getZExtValue();
+  if (getLHS().isUnsigned())
+os << getLHS().getZExtValue();
+  else
+os << getLHS().getSExtValue();
   if (getLHS().isUnsigned())
 os << 'U';
   os << ' '

Modified: cfe/trunk/test/Analysis/expr-inspection.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/expr-inspection.c?rev=316157=316156=316157=diff
==
--- cfe/trunk/test/Analysis/expr-inspection.c (original)
+++ cfe/trunk/test/Analysis/expr-inspection.c Thu Oct 19 04:58:21 2017
@@ -8,6 +8,7 @@ void clang_analyzer_numTimesReached();
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
   int y = 1;
   clang_analyzer_printState();
   for (; y < 3; ++y)


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


r316069 - [ASTImporter] Import SubStmt of CaseStmt

2017-10-18 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Oct 18 02:25:18 2017
New Revision: 316069

URL: http://llvm.org/viewvc/llvm-project?rev=316069=rev
Log:
[ASTImporter] Import SubStmt of CaseStmt

Patch by: Rafael Stahl!

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

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=316069=316068=316069=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Wed Oct 18 02:25:18 2017
@@ -3983,12 +3983,16 @@ Stmt *ASTNodeImporter::VisitCaseStmt(Cas
   Expr *ToRHS = Importer.Import(S->getRHS());
   if (!ToRHS && S->getRHS())
 return nullptr;
+  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
+  if (!ToSubStmt && S->getSubStmt())
+return nullptr;
   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
-  return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
-ToCaseLoc, ToEllipsisLoc,
-ToColonLoc);
+  CaseStmt *ToStmt = new (Importer.getToContext())
+  CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
+  ToStmt->setSubStmt(ToSubStmt);
+  return ToStmt;
 }
 
 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=316069=316068=316069=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Wed Oct 18 02:25:18 2017
@@ -97,6 +97,10 @@ testImport(const std::string ,
   llvm::raw_svector_ostream ToNothing(ImportChecker);
   ToCtx.getTranslationUnitDecl()->print(ToNothing);
 
+  // This traverses the AST to catch certain bugs like poorly or not
+  // implemented subtrees.
+  Imported->dump(ToNothing);
+
   return Verifier.match(Imported, AMatcher);
 }
 
@@ -267,6 +271,15 @@ TEST(ImportExpr, ImportParenListExpr) {
   
hasUnaryOperand(cxxThisExpr();
 }
 
+TEST(ImportExpr, ImportSwitch) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(
+  testImport("void declToImport() { int b; switch (b) { case 1: break; } 
}",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(
+ has(switchStmt(has(compoundStmt(has(caseStmt()));
+}
+
 TEST(ImportExpr, ImportStmtExpr) {
   MatchVerifier Verifier;
   // NOTE: has() ignores implicit casts, using hasDescendant() to match it


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


r315296 - [analyzer] Implement pointer arithmetic on constants

2017-10-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Oct 10 04:01:49 2017
New Revision: 315296

URL: http://llvm.org/viewvc/llvm-project?rev=315296=rev
Log:
[analyzer] Implement pointer arithmetic on constants

Patch by: Rafael Stahl!

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

Added:
cfe/trunk/test/Analysis/pointer-arithmetic.c
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=315296=315295=315296=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Tue Oct 10 04:01:49 
2017
@@ -922,6 +922,10 @@ SVal SimpleSValBuilder::evalBinOpLN(Prog
   if (rhs.isZeroConstant())
 return lhs;
 
+  // Perserve the null pointer so that it can be found by the DerefChecker.
+  if (lhs.isZeroConstant())
+return lhs;
+
   // We are dealing with pointer arithmetic.
 
   // Handle pointer arithmetic on constant values.
@@ -937,6 +941,8 @@ SVal SimpleSValBuilder::evalBinOpLN(Prog
 
   // Offset the increment by the pointer size.
   llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
+  QualType pointeeType = resultTy->getPointeeType();
+  Multiplicand = 
getContext().getTypeSizeInChars(pointeeType).getQuantity();
   rightI *= Multiplicand;
 
   // Compute the adjusted pointer.

Added: cfe/trunk/test/Analysis/pointer-arithmetic.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/pointer-arithmetic.c?rev=315296=auto
==
--- cfe/trunk/test/Analysis/pointer-arithmetic.c (added)
+++ cfe/trunk/test/Analysis/pointer-arithmetic.c Tue Oct 10 04:01:49 2017
@@ -0,0 +1,30 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+int test1() {
+  int *p = (int *)sizeof(int);
+  p -= 1;
+  return *p; // expected-warning {{Dereference of null pointer}}
+}
+
+int test2() {
+  int *p = (int *)sizeof(int);
+  p -= 2;
+  p += 1;
+  return *p; // expected-warning {{Dereference of null pointer}}
+}
+
+int test3() {
+  int *p = (int *)sizeof(int);
+  p++;
+  p--;
+  p--;
+  return *p; // expected-warning {{Dereference of null pointer}}
+}
+
+int test4() {
+  // This is a special case where pointer arithmetic is not calculated to
+  // preserve useful warnings on dereferences of null pointers.
+  int *p = 0;
+  p += 1;
+  return *p; // expected-warning {{Dereference of null pointer}}
+}


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


[clang-tools-extra] r314785 - [clang-tidy] Fixed a small code example in docs. NFC.

2017-10-03 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Oct  3 04:40:07 2017
New Revision: 314785

URL: http://llvm.org/viewvc/llvm-project?rev=314785=rev
Log:
[clang-tidy] Fixed a small code example in docs. NFC.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-string-constructor.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-string-constructor.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/misc-string-constructor.rst?rev=314785=314784=314785=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/misc-string-constructor.rst 
(original)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/misc-string-constructor.rst 
Tue Oct  3 04:40:07 2017
@@ -11,7 +11,7 @@ Examples:
 
 .. code-block:: c++
 
-  std::string('x', 50) str; // should be std::string(50, 'x')
+  std::string str('x', 50); // should be str(50, 'x')
 
 Calling the string-literal constructor with a length bigger than the literal is
 suspicious and adds extra random characters to the string.


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


r313975 - Add Cross Translation Unit support library

2017-09-22 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Sep 22 04:11:01 2017
New Revision: 313975

URL: http://llvm.org/viewvc/llvm-project?rev=313975=rev
Log:
Add Cross Translation Unit support library

This patch introduces a class that can help to build tools that require cross
translation unit facilities. This class allows function definitions to be loaded
from external AST files based on an index. In order to use this functionality an
index is required. The index format is a flat text file but it might be
replaced with a different solution in the near future. USRs are used as names to
look up the functions definitions. This class also does caching to avoid
redundant loading of AST files.

Right now only function defnitions can be loaded using this API because this is
what the in progress cross translation unit feature of the Static Analyzer
requires. In to future this might be extended to classes, types etc.

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

Added:
cfe/trunk/include/clang/Basic/DiagnosticCrossTUKinds.td
cfe/trunk/include/clang/CrossTU/
cfe/trunk/include/clang/CrossTU/CrossTUDiagnostic.h
cfe/trunk/include/clang/CrossTU/CrossTranslationUnit.h
cfe/trunk/lib/CrossTU/
cfe/trunk/lib/CrossTU/CMakeLists.txt
cfe/trunk/lib/CrossTU/CrossTranslationUnit.cpp
cfe/trunk/test/Analysis/func-mapping-test.cpp
cfe/trunk/tools/clang-func-mapping/
cfe/trunk/tools/clang-func-mapping/CMakeLists.txt
cfe/trunk/tools/clang-func-mapping/ClangFnMapGen.cpp
cfe/trunk/unittests/CrossTU/
cfe/trunk/unittests/CrossTU/CMakeLists.txt
cfe/trunk/unittests/CrossTU/CrossTranslationUnitTest.cpp
Modified:
cfe/trunk/include/clang/Basic/AllDiagnostics.h
cfe/trunk/include/clang/Basic/CMakeLists.txt
cfe/trunk/include/clang/Basic/Diagnostic.td
cfe/trunk/include/clang/Basic/DiagnosticIDs.h
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/lib/Basic/DiagnosticIDs.cpp
cfe/trunk/lib/CMakeLists.txt
cfe/trunk/test/CMakeLists.txt
cfe/trunk/test/lit.cfg.py
cfe/trunk/tools/CMakeLists.txt
cfe/trunk/tools/diagtool/DiagnosticNames.cpp
cfe/trunk/unittests/CMakeLists.txt

Modified: cfe/trunk/include/clang/Basic/AllDiagnostics.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AllDiagnostics.h?rev=313975=313974=313975=diff
==
--- cfe/trunk/include/clang/Basic/AllDiagnostics.h (original)
+++ cfe/trunk/include/clang/Basic/AllDiagnostics.h Fri Sep 22 04:11:01 2017
@@ -18,6 +18,7 @@
 #include "clang/AST/ASTDiagnostic.h"
 #include "clang/AST/CommentDiagnostic.h"
 #include "clang/Analysis/AnalysisDiagnostic.h"
+#include "clang/CrossTU/CrossTUDiagnostic.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/LexDiagnostic.h"

Modified: cfe/trunk/include/clang/Basic/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/CMakeLists.txt?rev=313975=313974=313975=diff
==
--- cfe/trunk/include/clang/Basic/CMakeLists.txt (original)
+++ cfe/trunk/include/clang/Basic/CMakeLists.txt Fri Sep 22 04:11:01 2017
@@ -9,6 +9,7 @@ clang_diag_gen(Analysis)
 clang_diag_gen(AST)
 clang_diag_gen(Comment)
 clang_diag_gen(Common)
+clang_diag_gen(CrossTU)
 clang_diag_gen(Driver)
 clang_diag_gen(Frontend)
 clang_diag_gen(Lex)

Modified: cfe/trunk/include/clang/Basic/Diagnostic.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Diagnostic.td?rev=313975=313974=313975=diff
==
--- cfe/trunk/include/clang/Basic/Diagnostic.td (original)
+++ cfe/trunk/include/clang/Basic/Diagnostic.td Fri Sep 22 04:11:01 2017
@@ -133,6 +133,7 @@ include "DiagnosticASTKinds.td"
 include "DiagnosticAnalysisKinds.td"
 include "DiagnosticCommentKinds.td"
 include "DiagnosticCommonKinds.td"
+include "DiagnosticCrossTUKinds.td"
 include "DiagnosticDriverKinds.td"
 include "DiagnosticFrontendKinds.td"
 include "DiagnosticLexKinds.td"

Added: cfe/trunk/include/clang/Basic/DiagnosticCrossTUKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticCrossTUKinds.td?rev=313975=auto
==
--- cfe/trunk/include/clang/Basic/DiagnosticCrossTUKinds.td (added)
+++ cfe/trunk/include/clang/Basic/DiagnosticCrossTUKinds.td Fri Sep 22 04:11:01 
2017
@@ -0,0 +1,18 @@
+//==--- DiagnosticCrossTUKinds.td - Cross Translation Unit diagnostics 
===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+let Component = "CrossTU" in {
+
+def err_fnmap_parsing : Error<
+  "error 

r313973 - [analyzer] Add new delete with non-virtual destructor check

2017-09-22 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Sep 22 03:16:33 2017
New Revision: 313973

URL: http://llvm.org/viewvc/llvm-project?rev=313973=rev
Log:
[analyzer] Add new delete with non-virtual destructor check

Patch by: Reka Nikolett Kovacs

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

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
cfe/trunk/test/Analysis/DeleteWithNonVirtualDtor.cpp
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=313973=313972=313973=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Fri Sep 22 
03:16:33 2017
@@ -284,6 +284,11 @@ def VirtualCallChecker : Checker<"Virtua
 
 let ParentPackage = CplusplusAlpha in {
 
+def DeleteWithNonVirtualDtorChecker : Checker<"DeleteWithNonVirtualDtor">,
+  HelpText<"Reports destructions of polymorphic objects with a non-virtual "
+   "destructor in their base class">,
+  DescFile<"DeleteWithNonVirtualDtorChecker.cpp">;
+
 def IteratorRangeChecker : Checker<"IteratorRange">,
   HelpText<"Check for iterators used outside their valid ranges">,
   DescFile<"IteratorChecker.cpp">;

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=313973=313972=313973=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Fri Sep 22 03:16:33 
2017
@@ -29,6 +29,7 @@ add_clang_library(clangStaticAnalyzerChe
   CXXSelfAssignmentChecker.cpp
   DeadStoresChecker.cpp
   DebugCheckers.cpp
+  DeleteWithNonVirtualDtorChecker.cpp
   DereferenceChecker.cpp
   DirectIvarAssignment.cpp
   DivZeroChecker.cpp

Added: cfe/trunk/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp?rev=313973=auto
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp 
(added)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp 
Fri Sep 22 03:16:33 2017
@@ -0,0 +1,153 @@
+//===-- DeleteWithNonVirtualDtorChecker.cpp ---*- C++ 
-*--//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// Defines a checker for the OOP52-CPP CERT rule: Do not delete a polymorphic
+// object without a virtual destructor.
+//
+// Diagnostic flags -Wnon-virtual-dtor and -Wdelete-non-virtual-dtor report if
+// an object with a virtual function but a non-virtual destructor exists or is
+// deleted, respectively.
+//
+// This check exceeds them by comparing the dynamic and static types of the
+// object at the point of destruction and only warns if it happens through a
+// pointer to a base type without a virtual destructor. The check places a note
+// at the last point where the conversion from derived to base happened.
+//
+//===--===//
+
+#include "ClangSACheckers.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/DynamicTypeMap.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class DeleteWithNonVirtualDtorChecker
+: public Checker {
+  mutable std::unique_ptr BT;
+
+  class DeleteBugVisitor : public BugReporterVisitorImpl {
+  public:
+DeleteBugVisitor() : Satisfied(false) {}
+void Profile(llvm::FoldingSetNodeID ) const override {
+  static int X = 0;
+  ID.AddPointer();
+}
+std::shared_ptr VisitNode(const ExplodedNode *N,
+   const ExplodedNode *PrevN,
+   BugReporterContext ,
+   BugReport ) override;
+
+  private:
+

r313866 - [analyzer] Fix an assertion fail in VirtualCallChecker

2017-09-21 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Sep 21 01:18:59 2017
New Revision: 313866

URL: http://llvm.org/viewvc/llvm-project?rev=313866=rev
Log:
[analyzer] Fix an assertion fail in VirtualCallChecker

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
cfe/trunk/test/Analysis/virtualcall.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp?rev=313866=313865=313866=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp Thu Sep 21 
01:18:59 2017
@@ -146,7 +146,7 @@ static bool isVirtualCall(const CallExpr
 if (CME->getQualifier())
   CallIsNonVirtual = true;
 
-if (const Expr *Base = CME->getBase()->IgnoreImpCasts()) {
+if (const Expr *Base = CME->getBase()) {
   // The most derived class is marked final.
   if (Base->getBestDynamicClassType()->hasAttr())
 CallIsNonVirtual = true;

Modified: cfe/trunk/test/Analysis/virtualcall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/virtualcall.cpp?rev=313866=313865=313866=diff
==
--- cfe/trunk/test/Analysis/virtualcall.cpp (original)
+++ cfe/trunk/test/Analysis/virtualcall.cpp Thu Sep 21 01:18:59 2017
@@ -271,3 +271,24 @@ int main() {
 #if !PUREONLY
//expected-note-re@-2 2^}}Calling '~E'}}
 #endif
+
+namespace PR34451 {
+struct a {
+  void b() {
+a c[1];
+c->b();
+  }
+};
+
+class e {
+ public:
+  void b() const;
+};
+
+class c {
+  void m_fn2() const;
+  e d[];
+};
+
+void c::m_fn2() const { d->b(); }
+}


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


r311877 - [analyzer][GSoC] Re-implemente current virtual calls checker in a path-sensitive way

2017-08-28 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Aug 28 01:44:43 2017
New Revision: 311877

URL: http://llvm.org/viewvc/llvm-project?rev=311877=rev
Log:
[analyzer][GSoC] Re-implemente current virtual calls checker in a 
path-sensitive way

Patch by: Xin Wang

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
cfe/trunk/test/Analysis/virtualcall.cpp
cfe/trunk/test/Analysis/virtualcall.h

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp?rev=311877=311876=311877=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp Mon Aug 28 
01:44:43 2017
@@ -14,279 +14,272 @@
 
 #include "ClangSACheckers.h"
 #include "clang/AST/DeclCXX.h"
-#include "clang/AST/StmtVisitor.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/PathSensitive/AnalysisManager.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/Support/SaveAndRestore.h"
-#include "llvm/Support/raw_ostream.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
 
 using namespace clang;
 using namespace ento;
 
 namespace {
-
-class WalkAST : public StmtVisitor {
-  const CheckerBase *Checker;
-  BugReporter 
-  AnalysisDeclContext *AC;
-
-  /// The root constructor or destructor whose callees are being analyzed.
-  const CXXMethodDecl *RootMethod = nullptr;
-
-  /// Whether the checker should walk into bodies of called functions.
-  /// Controlled by the "Interprocedural" analyzer-config option.
-  bool IsInterprocedural = false;
-
-  /// Whether the checker should only warn for calls to pure virtual functions
-  /// (which is undefined behavior) or for all virtual functions (which may
-  /// may result in unexpected behavior).
-  bool ReportPureOnly = false;
-
-  typedef const CallExpr * WorkListUnit;
-  typedef SmallVector DFSWorkList;
-
-  /// A vector representing the worklist which has a chain of CallExprs.
-  DFSWorkList WList;
-
-  // PreVisited : A CallExpr to this FunctionDecl is in the worklist, but the
-  // body has not been visited yet.
-  // PostVisited : A CallExpr to this FunctionDecl is in the worklist, and the
-  // body has been visited.
-  enum Kind { NotVisited,
-  PreVisited,  /**< A CallExpr to this FunctionDecl is in the
-worklist, but the body has not yet been
-visited. */
-  PostVisited  /**< A CallExpr to this FunctionDecl is in the
-worklist, and the body has been visited. */
-  };
-
-  /// A DenseMap that records visited states of FunctionDecls.
-  llvm::DenseMap VisitedFunctions;
-
-  /// The CallExpr whose body is currently being visited.  This is used for
-  /// generating bug reports.  This is null while visiting the body of a
-  /// constructor or destructor.
-  const CallExpr *visitingCallExpr;
-
-public:
-  WalkAST(const CheckerBase *checker, BugReporter , AnalysisDeclContext *ac,
-  const CXXMethodDecl *rootMethod, bool isInterprocedural,
-  bool reportPureOnly)
-  : Checker(checker), BR(br), AC(ac), RootMethod(rootMethod),
-IsInterprocedural(isInterprocedural), ReportPureOnly(reportPureOnly),
-visitingCallExpr(nullptr) {
-// Walking should always start from either a constructor or a destructor.
-assert(isa(rootMethod) ||
-   isa(rootMethod));
+enum class ObjectState : bool { CtorCalled, DtorCalled };
+} // end namespace
+  // FIXME: Ascending over StackFrameContext maybe another method.
+
+namespace llvm {
+template <> struct FoldingSetTrait {
+  static inline void Profile(ObjectState X, FoldingSetNodeID ) {
+ID.AddInteger(static_cast(X));
   }
+};
+} // end namespace llvm
 
-  bool hasWork() const { return !WList.empty(); }
-
-  /// This method adds a CallExpr to the worklist and marks the callee as
-  /// being PreVisited.
-  void Enqueue(WorkListUnit WLUnit) {
-const FunctionDecl *FD = WLUnit->getDirectCallee();
-if (!FD || !FD->getBody())
-  return;
-Kind  = VisitedFunctions[FD];
-if (K != NotVisited)
-  return;
-K = PreVisited;
-WList.push_back(WLUnit);
-  }
+namespace {
+class VirtualCallChecker
+: public Checker 
{
+  mutable std::unique_ptr BT;
 
-  /// This method returns an item from the worklist without 

[clang-tools-extra] r310589 - [clang-tidy] Add integer division check

2017-08-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Aug 10 06:30:30 2017
New Revision: 310589

URL: http://llvm.org/viewvc/llvm-project?rev=310589=rev
Log:
[clang-tidy] Add integer division check

Patch by: Reka Nikolett Kovacs

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

Added:
clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-integer-division.rst
clang-tools-extra/trunk/test/clang-tidy/bugprone-integer-division.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=310589=310588=310589=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Thu Aug 
10 06:30:30 2017
@@ -10,6 +10,7 @@
 #include "../ClangTidy.h"
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
+#include "IntegerDivisionCheck.h"
 #include "SuspiciousMemsetUsageCheck.h"
 #include "UndefinedMemoryManipulationCheck.h"
 
@@ -20,6 +21,8 @@ namespace bugprone {
 class BugproneModule : public ClangTidyModule {
 public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
+CheckFactories.registerCheck(
+"bugprone-integer-division");
 CheckFactories.registerCheck(
 "bugprone-suspicious-memset-usage");
 CheckFactories.registerCheck(

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt?rev=310589=310588=310589=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt Thu Aug 10 
06:30:30 2017
@@ -2,6 +2,7 @@ set(LLVM_LINK_COMPONENTS support)
 
 add_clang_library(clangTidyBugproneModule
   BugproneTidyModule.cpp
+  IntegerDivisionCheck.cpp
   SuspiciousMemsetUsageCheck.cpp
   UndefinedMemoryManipulationCheck.cpp
 

Added: clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.cpp?rev=310589=auto
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/IntegerDivisionCheck.cpp Thu 
Aug 10 06:30:30 2017
@@ -0,0 +1,57 @@
+//===--- IntegerDivisionCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "IntegerDivisionCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IntType = hasType(isInteger());
+
+  const auto BinaryOperators = binaryOperator(anyOf(
+  hasOperatorName("%"), hasOperatorName("<<"), hasOperatorName(">>"),
+  hasOperatorName("<<"), hasOperatorName("^"), hasOperatorName("|"),
+  hasOperatorName("&"), hasOperatorName("||"), hasOperatorName("&&"),
+  hasOperatorName("<"), hasOperatorName(">"), hasOperatorName("<="),
+  hasOperatorName(">="), hasOperatorName("=="), hasOperatorName("!=")));
+
+  const auto UnaryOperators =
+  unaryOperator(anyOf(hasOperatorName("~"), hasOperatorName("!")));
+
+  const auto Exceptions =
+  anyOf(BinaryOperators, conditionalOperator(), 
binaryConditionalOperator(),
+callExpr(IntType), explicitCastExpr(IntType), UnaryOperators);
+
+  Finder->addMatcher(
+  binaryOperator(
+  hasOperatorName("/"), hasLHS(expr(IntType)), hasRHS(expr(IntType)),
+  hasAncestor(
+  castExpr(hasCastKind(CK_IntegralToFloating)).bind("FloatCast")),
+  unless(hasAncestor(
+  expr(Exceptions,
+   hasAncestor(castExpr(equalsBoundNode("FloatCast")))
+  .bind("IntDiv"),
+  this);
+}
+
+void IntegerDivisionCheck::check(const MatchFinder::MatchResult ) {
+  const auto *IntDiv = Result.Nodes.getNodeAs("IntDiv");
+  

[clang-tools-extra] r310560 - [clang-tidy] Fix a check-fixes line

2017-08-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Aug 10 02:29:39 2017
New Revision: 310560

URL: http://llvm.org/viewvc/llvm-project?rev=310560=rev
Log:
[clang-tidy] Fix a check-fixes line

Modified:

clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp?rev=310560=310559=310560=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
 Thu Aug 10 02:29:39 2017
@@ -118,7 +118,7 @@ template  void f(T t, C c) {
   t.x; // OK, t is a template parameter.
   c.x;
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
-  // CHECK-FIXES: {{^}}  C::x; // 1{{$}}
+  // CHECK-FIXES: {{^}}  C::x;{{$}}
 }
 
 template  struct S { static int x; };


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


[clang-tools-extra] r310559 - [clang-tidy] Minor documentation improvement

2017-08-10 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Aug 10 02:13:26 2017
New Revision: 310559

URL: http://llvm.org/viewvc/llvm-project?rev=310559=rev
Log:
[clang-tidy] Minor documentation improvement

Patch by: Lilla Barancsuk

Modified:

clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst

clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst?rev=310559=310558=310559=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst
 Thu Aug 10 02:13:26 2017
@@ -25,6 +25,7 @@ is changed to:
 
 .. code-block:: c++
 
+  C *c1 = new C();
   C::foo();
   C::x;
 

Modified: 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp?rev=310559=310558=310559=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
 Thu Aug 10 02:13:26 2017
@@ -116,7 +116,7 @@ using E = D;
 
 template  void f(T t, C c) {
   t.x; // OK, t is a template parameter.
-  c.x; // 1
+  c.x;
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
   // CHECK-FIXES: {{^}}  C::x; // 1{{$}}
 }


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


r310521 - [Sema] Assign new flag -Wenum-compare-switch to switch-related parts of -Wenum-compare

2017-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Aug  9 13:56:43 2017
New Revision: 310521

URL: http://llvm.org/viewvc/llvm-project?rev=310521=rev
Log:
[Sema] Assign new flag -Wenum-compare-switch to switch-related parts of 
-Wenum-compare

Patch by: Reka Nikolett Kovacs

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/test/Sema/switch.c
cfe/trunk/test/SemaCXX/warn-enum-compare.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=310521=310520=310521=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Wed Aug  9 13:56:43 2017
@@ -454,6 +454,8 @@ def CoveredSwitchDefault : DiagGroup<"co
 def SwitchBool : DiagGroup<"switch-bool">;
 def SwitchEnum : DiagGroup<"switch-enum">;
 def Switch : DiagGroup<"switch">;
+def EnumCompareSwitch : DiagGroup<"enum-compare-switch">;
+def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareSwitch]>;
 def ImplicitFallthroughPerFunction :
   DiagGroup<"implicit-fallthrough-per-function">;
 def ImplicitFallthrough  : DiagGroup<"implicit-fallthrough",

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=310521=310520=310521=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed Aug  9 13:56:43 
2017
@@ -5918,7 +5918,11 @@ def warn_runsigned_always_true_compariso
 def warn_comparison_of_mixed_enum_types : Warning<
   "comparison of two values with different enumeration types"
   "%diff{ ($ and $)|}0,1">,
-  InGroup>;
+  InGroup;
+def warn_comparison_of_mixed_enum_types_switch : Warning<
+  "comparison of two values with different enumeration types in switch 
statement"
+  "%diff{ ($ and $)|}0,1">,
+  InGroup;
 def warn_null_in_arithmetic_operation : Warning<
   "use of NULL in arithmetic operation">,
   InGroup;

Modified: cfe/trunk/lib/Sema/SemaStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaStmt.cpp?rev=310521=310520=310521=diff
==
--- cfe/trunk/lib/Sema/SemaStmt.cpp (original)
+++ cfe/trunk/lib/Sema/SemaStmt.cpp Wed Aug  9 13:56:43 2017
@@ -762,7 +762,7 @@ static void checkEnumTypesInSwitchStmt(S
   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
 return;
 
-  S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types)
+  S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
   << CondType << CaseType << Cond->getSourceRange()
   << Case->getSourceRange();
 }

Modified: cfe/trunk/test/Sema/switch.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/switch.c?rev=310521=310520=310521=diff
==
--- cfe/trunk/test/Sema/switch.c (original)
+++ cfe/trunk/test/Sema/switch.c Wed Aug  9 13:56:43 2017
@@ -372,7 +372,7 @@ void switch_on_ExtendedEnum1(enum Extend
   case EE1_b: break;
   case EE1_c: break; // no-warning
   case EE1_d: break; // expected-warning {{case value not in enumerated type 
'enum ExtendedEnum1'}}
-  // expected-warning@-1 {{comparison of two values with different enumeration 
types ('enum ExtendedEnum1' and 'const enum ExtendedEnum1_unrelated')}}
+  // expected-warning@-1 {{comparison of two values with different enumeration 
types in switch statement ('enum ExtendedEnum1' and 'const enum 
ExtendedEnum1_unrelated')}}
   }
 }
 

Modified: cfe/trunk/test/SemaCXX/warn-enum-compare.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-enum-compare.cpp?rev=310521=310520=310521=diff
==
--- cfe/trunk/test/SemaCXX/warn-enum-compare.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-enum-compare.cpp Wed Aug  9 13:56:43 2017
@@ -212,19 +212,19 @@ void test () {
   switch (a) {
 case name1::F1: break;
 case name1::F3: break;
-case name2::B2: break; // expected-warning {{comparison of two values with 
different enumeration types ('name1::Foo' and 'name2::Baz')}}
+case name2::B2: break; // expected-warning {{comparison of two values with 
different enumeration types in switch statement ('name1::Foo' and 
'name2::Baz')}}
   }
 
   switch (x) {
 case FooB: break;
 case FooC: break;
-case BarD: break; // expected-warning {{comparison of two values with 
different enumeration types ('Foo' and 'Bar')}}
+

r310468 - [Sema] -Wenum-compare no longer warn on anonymous enums in switch statements

2017-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Aug  9 05:34:58 2017
New Revision: 310468

URL: http://llvm.org/viewvc/llvm-project?rev=310468=rev
Log:
[Sema] -Wenum-compare no longer warn on anonymous enums in switch statements

Patch by: Reka Nikolett Kovacs

Modified:
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/test/SemaCXX/warn-enum-compare.cpp

Modified: cfe/trunk/lib/Sema/SemaStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaStmt.cpp?rev=310468=310467=310468=diff
==
--- cfe/trunk/lib/Sema/SemaStmt.cpp (original)
+++ cfe/trunk/lib/Sema/SemaStmt.cpp Wed Aug  9 05:34:58 2017
@@ -753,6 +753,12 @@ static void checkEnumTypesInSwitchStmt(S
   if (!CondEnumType || !CaseEnumType)
 return;
 
+  // Ignore anonymous enums.
+  if (!CondEnumType->getDecl()->getIdentifier())
+return;
+  if (!CaseEnumType->getDecl()->getIdentifier())
+return;
+
   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
 return;
 

Modified: cfe/trunk/test/SemaCXX/warn-enum-compare.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-enum-compare.cpp?rev=310468=310467=310468=diff
==
--- cfe/trunk/test/SemaCXX/warn-enum-compare.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-enum-compare.cpp Wed Aug  9 05:34:58 2017
@@ -226,4 +226,11 @@ void test () {
 case BarF: break;
 case FooA: break; // expected-warning {{comparison of two values with 
different enumeration types ('Bar' and 'Foo')}}
   }
+
+  switch(x) {
+case AnonAA: break; // expected-warning {{case value not in enumerated 
type 'Foo'}}
+case FooA: break;
+case FooB: break;
+case FooC: break;
+  }
 }


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


r310449 - [Sema] Extend -Wenum-compare to handle mixed enum comparisons in switch statements

2017-08-09 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Aug  9 01:57:09 2017
New Revision: 310449

URL: http://llvm.org/viewvc/llvm-project?rev=310449=rev
Log:
[Sema] Extend -Wenum-compare to handle mixed enum comparisons in switch 
statements

Patch by: Reka Nikolett Kovacs

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

Modified:
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/test/Sema/switch.c
cfe/trunk/test/SemaCXX/warn-enum-compare.cpp

Modified: cfe/trunk/lib/Sema/SemaStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaStmt.cpp?rev=310449=310448=310449=diff
==
--- cfe/trunk/lib/Sema/SemaStmt.cpp (original)
+++ cfe/trunk/lib/Sema/SemaStmt.cpp Wed Aug  9 01:57:09 2017
@@ -602,14 +602,14 @@ static bool EqEnumVals(const std::pair(expr))
-expr = cleanups->getSubExpr();
-  while (ImplicitCastExpr *impcast = dyn_cast(expr)) {
-if (impcast->getCastKind() != CK_IntegralCast) break;
-expr = impcast->getSubExpr();
+static QualType GetTypeBeforeIntegralPromotion(const Expr *) {
+  if (const auto *CleanUps = dyn_cast(E))
+E = CleanUps->getSubExpr();
+  while (const auto *ImpCast = dyn_cast(E)) {
+if (ImpCast->getCastKind() != CK_IntegralCast) break;
+E = ImpCast->getSubExpr();
   }
-  return expr->getType();
+  return E->getType();
 }
 
 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
@@ -743,6 +743,24 @@ static bool ShouldDiagnoseSwitchCaseNotI
   return true;
 }
 
+static void checkEnumTypesInSwitchStmt(Sema , const Expr *Cond,
+   const Expr *Case) {
+  QualType CondType = GetTypeBeforeIntegralPromotion(Cond);
+  QualType CaseType = Case->getType();
+
+  const EnumType *CondEnumType = CondType->getAs();
+  const EnumType *CaseEnumType = CaseType->getAs();
+  if (!CondEnumType || !CaseEnumType)
+return;
+
+  if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
+return;
+
+  S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types)
+  << CondType << CaseType << Cond->getSourceRange()
+  << Case->getSourceRange();
+}
+
 StmtResult
 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
 Stmt *BodyStmt) {
@@ -760,7 +778,7 @@ Sema::ActOnFinishSwitchStmt(SourceLocati
 
   QualType CondType = CondExpr->getType();
 
-  Expr *CondExprBeforePromotion = CondExpr;
+  const Expr *CondExprBeforePromotion = CondExpr;
   QualType CondTypeBeforePromotion =
   GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
 
@@ -843,6 +861,8 @@ Sema::ActOnFinishSwitchStmt(SourceLocati
 break;
   }
 
+  checkEnumTypesInSwitchStmt(*this, CondExpr, Lo);
+
   llvm::APSInt LoVal;
 
   if (getLangOpts().CPlusPlus11) {

Modified: cfe/trunk/test/Sema/switch.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/switch.c?rev=310449=310448=310449=diff
==
--- cfe/trunk/test/Sema/switch.c (original)
+++ cfe/trunk/test/Sema/switch.c Wed Aug  9 01:57:09 2017
@@ -372,6 +372,7 @@ void switch_on_ExtendedEnum1(enum Extend
   case EE1_b: break;
   case EE1_c: break; // no-warning
   case EE1_d: break; // expected-warning {{case value not in enumerated type 
'enum ExtendedEnum1'}}
+  // expected-warning@-1 {{comparison of two values with different enumeration 
types ('enum ExtendedEnum1' and 'const enum ExtendedEnum1_unrelated')}}
   }
 }
 

Modified: cfe/trunk/test/SemaCXX/warn-enum-compare.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-enum-compare.cpp?rev=310449=310448=310449=diff
==
--- cfe/trunk/test/SemaCXX/warn-enum-compare.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-enum-compare.cpp Wed Aug  9 01:57:09 2017
@@ -209,4 +209,21 @@ void test () {
   while (getBar() > x); // expected-warning  {{comparison of two values with 
different enumeration types ('Bar' and 'Foo')}}
   while (getBar() < x); // expected-warning  {{comparison of two values with 
different enumeration types ('Bar' and 'Foo')}}
 
+  switch (a) {
+case name1::F1: break;
+case name1::F3: break;
+case name2::B2: break; // expected-warning {{comparison of two values with 
different enumeration types ('name1::Foo' and 'name2::Baz')}}
+  }
+
+  switch (x) {
+case FooB: break;
+case FooC: break;
+case BarD: break; // expected-warning {{comparison of two values with 
different enumeration types ('Foo' and 'Bar')}}
+  }
+
+  switch(getBar()) {
+case BarE: break;
+case BarF: break;
+case FooA: break; // expected-warning {{comparison of two values with 
different enumeration types ('Bar' and 'Foo')}}
+  }
 }


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


[clang-tools-extra] r310371 - [clang-tidy] Add new readability non-idiomatic static access check

2017-08-08 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Tue Aug  8 08:33:48 2017
New Revision: 310371

URL: http://llvm.org/viewvc/llvm-project?rev=310371=rev
Log:
[clang-tidy] Add new readability non-idiomatic static access check

Patch by: Lilla Barancsuk

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

Added:

clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp

clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/readability-static-accessed-through-instance.rst

clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance-nesting-threshold.cpp

clang-tools-extra/trunk/test/clang-tidy/readability-static-accessed-through-instance.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt?rev=310371=310370=310371=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt Tue Aug  8 
08:33:48 2017
@@ -25,6 +25,7 @@ add_clang_library(clangTidyReadabilityMo
   RedundantSmartptrGetCheck.cpp
   RedundantStringInitCheck.cpp
   SimplifyBooleanExprCheck.cpp
+  StaticAccessedThroughInstanceCheck.cpp
   StaticDefinitionInAnonymousNamespaceCheck.cpp
   UniqueptrDeleteReleaseCheck.cpp
 

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp?rev=310371=310370=310371=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp 
Tue Aug  8 08:33:48 2017
@@ -32,6 +32,7 @@
 #include "RedundantStringCStrCheck.h"
 #include "RedundantStringInitCheck.h"
 #include "SimplifyBooleanExprCheck.h"
+#include "StaticAccessedThroughInstanceCheck.h"
 #include "StaticDefinitionInAnonymousNamespaceCheck.h"
 #include "UniqueptrDeleteReleaseCheck.h"
 
@@ -70,6 +71,8 @@ public:
 "readability-redundant-function-ptr-dereference");
 CheckFactories.registerCheck(
 "readability-redundant-member-init");
+CheckFactories.registerCheck(
+"readability-static-accessed-through-instance");
 CheckFactories.registerCheck(
 "readability-static-definition-in-anonymous-namespace");
 CheckFactories.registerCheck(

Added: 
clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp?rev=310371=auto
==
--- 
clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 (added)
+++ 
clang-tools-extra/trunk/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 Tue Aug  8 08:33:48 2017
@@ -0,0 +1,90 @@
+//===--- StaticAccessedThroughInstanceCheck.cpp - 
clang-tidy---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "StaticAccessedThroughInstanceCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace readability {
+
+static unsigned getNameSpecifierNestingLevel(const QualType ) {
+  if (const ElaboratedType *ElType = QType->getAs()) {
+const NestedNameSpecifier *NestedSpecifiers = ElType->getQualifier();
+unsigned NameSpecifierNestingLevel = 1;
+do {
+  NameSpecifierNestingLevel++;
+  NestedSpecifiers = NestedSpecifiers->getPrefix();
+} while (NestedSpecifiers);
+
+return NameSpecifierNestingLevel;
+  }
+  return 0;
+}
+
+void StaticAccessedThroughInstanceCheck::storeOptions(
+ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "NameSpecifierNestingThreshold",
+NameSpecifierNestingThreshold);
+}
+
+void StaticAccessedThroughInstanceCheck::registerMatchers(MatchFinder *Finder) 
{
+  Finder->addMatcher(
+  memberExpr(hasDeclaration(anyOf(cxxMethodDecl(isStaticStorageClass()),
+  

r309948 - Fix some typos in the documentation.

2017-08-03 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Thu Aug  3 08:38:14 2017
New Revision: 309948

URL: http://llvm.org/viewvc/llvm-project?rev=309948=rev
Log:
Fix some typos in the documentation.

Patch by: Reka Nikolett Kovacs

Modified:
cfe/trunk/docs/InternalsManual.rst

Modified: cfe/trunk/docs/InternalsManual.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/InternalsManual.rst?rev=309948=309947=309948=diff
==
--- cfe/trunk/docs/InternalsManual.rst (original)
+++ cfe/trunk/docs/InternalsManual.rst Thu Aug  3 08:38:14 2017
@@ -49,7 +49,7 @@ when the code is incorrect or dubious.
 (at the minimum) a unique ID, an English translation associated with it, a
 :ref:`SourceLocation ` to "put the caret", and a severity
 (e.g., ``WARNING`` or ``ERROR``).  They can also optionally include a number of
-arguments to the dianostic (which fill in "%0"'s in the string) as well as a
+arguments to the diagnostic (which fill in "%0"'s in the string) as well as a
 number of source ranges that related to the diagnostic.
 
 In this section, we'll be giving examples produced by the Clang command line
@@ -795,7 +795,7 @@ preprocessor and notifies a client of th
 Historically, the parser used to talk to an abstract ``Action`` interface that
 had virtual methods for parse events, for example ``ActOnBinOp()``.  When Clang
 grew C++ support, the parser stopped supporting general ``Action`` clients --
-it now always talks to the :ref:`Sema libray `.  However, the Parser
+it now always talks to the :ref:`Sema library `.  However, the Parser
 still accesses AST objects only through opaque types like ``ExprResult`` and
 ``StmtResult``.  Only :ref:`Sema ` looks at the AST node contents of 
these
 wrappers.
@@ -1324,9 +1324,9 @@ range of iterators over declarations of
 function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
 a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
 maintaining the lookup table used for the semantics-centric view.  Given a
-DeclContext, one can obtain the set of declaration contexts that are 
semanticaly
-connected to this declaration context, in source order, including this context
-(which will be the only result, for non-namespace contexts) via
+DeclContext, one can obtain the set of declaration contexts that are
+semantically connected to this declaration context, in source order, including
+this context (which will be the only result, for non-namespace contexts) via
 ``DeclContext::collectAllContexts``. Note that these functions are used
 internally within the lookup and insertion methods of the ``DeclContext``, so
 the vast majority of clients can ignore them.
@@ -1514,7 +1514,7 @@ use an i-c-e where one is required, but
 Things get a little bit more tricky when it comes to compatibility with
 real-world source code.  Specifically, GCC has historically accepted a huge
 superset of expressions as i-c-e's, and a lot of real world code depends on
-this unfortuate accident of history (including, e.g., the glibc system
+this unfortunate accident of history (including, e.g., the glibc system
 headers).  GCC accepts anything its "fold" optimizer is capable of reducing to
 an integer constant, which means that the definition of what it accepts changes
 as its optimizer does.  One example is that GCC accepts things like "``case


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


[clang-tools-extra] r308954 - [clang-tidy] Handle incomplete types in bugprone-undefined-memory-manipulation

2017-07-25 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Jul 24 23:52:08 2017
New Revision: 308954

URL: http://llvm.org/viewvc/llvm-project?rev=308954=rev
Log:
[clang-tidy] Handle incomplete types in bugprone-undefined-memory-manipulation
check

Patch by: Reka Nikolett Kovacs

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

Modified:

clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp

clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp?rev=308954=308953=308954=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
 (original)
+++ 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
 Mon Jul 24 23:52:08 2017
@@ -19,7 +19,8 @@ namespace bugprone {
 
 namespace {
 AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
-  return !Node.isTriviallyCopyable();
+  // For incomplete types, assume they are TriviallyCopyable.
+  return Node.hasDefinition() ? !Node.isTriviallyCopyable() : false;
 }
 } // namespace
 

Modified: 
clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp?rev=308954=308953=308954=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
 Mon Jul 24 23:52:08 2017
@@ -52,6 +52,13 @@ struct VirtualBase : virtual Base {
   int vb;
 };
 
+// Incomplete type, assume it is TriviallyCopyable.
+struct NoDef;
+
+void f(NoDef *s) {
+  memset(s, 0, 5);
+}
+
 template 
 void memset_temp(T *b) {
   memset(b, 0, sizeof(T));


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


[clang-tools-extra] r308022 - [clang-tidy] Minor documentation fix. NFC.

2017-07-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Jul 14 05:31:21 2017
New Revision: 308022

URL: http://llvm.org/viewvc/llvm-project?rev=308022=rev
Log:
[clang-tidy] Minor documentation fix. NFC.

Modified:

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst?rev=308022=308021=308022=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst
 Fri Jul 14 05:31:21 2017
@@ -1,7 +1,7 @@
 .. title:: clang-tidy - bugprone-undefined-memory-manipulation
 
 bugprone-undefined-memory-manipulation
-==
+==
 
 Finds calls of memory manipulation functions ``memset()``, ``memcpy()`` and
 ``memmove()`` on not TriviallyCopyable objects resulting in undefined behavior.


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


[clang-tools-extra] r308021 - [clang-tidy] Add bugprone-undefined-memory-manipulation check

2017-07-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Jul 14 05:20:19 2017
New Revision: 308021

URL: http://llvm.org/viewvc/llvm-project?rev=308021=rev
Log:
[clang-tidy] Add bugprone-undefined-memory-manipulation check

Patch by: Reka Nikolett Kovacs

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

Added:

clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp

clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst

clang-tools-extra/trunk/test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=308021=308020=308021=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Fri Jul 
14 05:20:19 2017
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "SuspiciousMemsetUsageCheck.h"
+#include "UndefinedMemoryManipulationCheck.h"
 
 namespace clang {
 namespace tidy {
@@ -21,6 +22,8 @@ public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
 "bugprone-suspicious-memset-usage");
+CheckFactories.registerCheck(
+"bugprone-undefined-memory-manipulation");
   }
 };
 

Modified: clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt?rev=308021=308020=308021=diff
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt Fri Jul 14 
05:20:19 2017
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS support)
 add_clang_library(clangTidyBugproneModule
   BugproneTidyModule.cpp
   SuspiciousMemsetUsageCheck.cpp
+  UndefinedMemoryManipulationCheck.cpp
 
   LINK_LIBS
   clangAnalysis

Added: 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp?rev=308021=auto
==
--- 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
 (added)
+++ 
clang-tools-extra/trunk/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
 Fri Jul 14 05:20:19 2017
@@ -0,0 +1,61 @@
+//===--- UndefinedMemoryManipulationCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "UndefinedMemoryManipulationCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+namespace {
+AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
+  return !Node.isTriviallyCopyable();
+}
+} // namespace
+
+void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
+  const auto NotTriviallyCopyableObject =
+  hasType(pointsTo(cxxRecordDecl(isNotTriviallyCopyable(;
+
+  // Check whether destination object is not TriviallyCopyable.
+  // Applicable to all three memory manipulation functions.
+  Finder->addMatcher(callExpr(callee(functionDecl(hasAnyName(
+  "::memset", "::memcpy", "::memmove"))),
+  hasArgument(0, NotTriviallyCopyableObject))
+ .bind("dest"),
+ this);
+
+  // Check whether source object is not TriviallyCopyable.
+  // Only applicable to memcpy() and memmove().
+  Finder->addMatcher(
+  callExpr(callee(functionDecl(hasAnyName("::memcpy", "::memmove"))),
+   hasArgument(1, NotTriviallyCopyableObject))
+  .bind("src"),
+  this);
+}
+
+void UndefinedMemoryManipulationCheck::check(
+const MatchFinder::MatchResult ) {
+  if (const auto *Destination = Result.Nodes.getNodeAs("dest")) {
+diag(Destination->getLocStart(), "undefined behavior, destination "
+ "object is not TriviallyCopyable");
+  }
+  if 

[clang-tools-extra] r308020 - [clang-tidy] Add bugprone-suspicious-memset-usage check

2017-07-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Fri Jul 14 05:15:55 2017
New Revision: 308020

URL: http://llvm.org/viewvc/llvm-project?rev=308020=rev
Log:
[clang-tidy] Add bugprone-suspicious-memset-usage check

Created new module bugprone and placed the check in that.

Finds memset() calls with potential mistakes in their arguments.
Replaces and extends the existing google-runtime-memset-zero-length check.

Cases covered:
* Fill value is a character '0'. Integer 0 might have been intended.
* Fill value is out of char range and gets truncated.
* Byte count is zero. Potentially swapped with the fill value argument.

Patch by: Reka Nikolett Kovacs

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

Added:
clang-tools-extra/trunk/clang-tidy/bugprone/
clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
clang-tools-extra/trunk/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/bugprone-suspicious-memset-usage.rst
clang-tools-extra/trunk/test/clang-tidy/bugprone-suspicious-memset-usage.cpp
Removed:
clang-tools-extra/trunk/clang-tidy/google/MemsetZeroLengthCheck.cpp
clang-tools-extra/trunk/clang-tidy/google/MemsetZeroLengthCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/google-runtime-memset.rst

clang-tools-extra/trunk/test/clang-tidy/google-runtime-memset-zero-length.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/google/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/google/GoogleTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/tool/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
clang-tools-extra/trunk/docs/clang-tidy/index.rst

Modified: clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/CMakeLists.txt?rev=308020=308019=308020=diff
==
--- clang-tools-extra/trunk/clang-tidy/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/CMakeLists.txt Fri Jul 14 05:15:55 2017
@@ -28,6 +28,7 @@ add_clang_library(clangTidy
 
 add_subdirectory(android)
 add_subdirectory(boost)
+add_subdirectory(bugprone)
 add_subdirectory(cert)
 add_subdirectory(cppcoreguidelines)
 add_subdirectory(google)

Added: clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp?rev=308020=auto
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/BugproneTidyModule.cpp Fri Jul 
14 05:15:55 2017
@@ -0,0 +1,38 @@
+//===--- BugproneTidyModule.cpp - clang-tidy 
--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "../ClangTidy.h"
+#include "../ClangTidyModule.h"
+#include "../ClangTidyModuleRegistry.h"
+#include "SuspiciousMemsetUsageCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+class BugproneModule : public ClangTidyModule {
+public:
+  void addCheckFactories(ClangTidyCheckFactories ) override {
+CheckFactories.registerCheck(
+"bugprone-suspicious-memset-usage");
+  }
+};
+
+} // namespace bugprone
+
+// Register the BugproneTidyModule using this statically initialized variable.
+static ClangTidyModuleRegistry::Add
+X("bugprone-module", "Adds checks for bugprone code constructs.");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the BugproneModule.
+volatile int BugproneModuleAnchorSource = 0;
+
+} // namespace tidy
+} // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt?rev=308020=auto
==
--- clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt (added)
+++ clang-tools-extra/trunk/clang-tidy/bugprone/CMakeLists.txt Fri Jul 14 
05:15:55 2017
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(clangTidyBugproneModule
+  BugproneTidyModule.cpp
+  SuspiciousMemsetUsageCheck.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  clangASTMatchers
+  clangBasic
+  clangLex
+  clangTidy
+  clangTidyUtils
+  

  1   2   >