r307759 - CFG: Add CFGElement for automatic variables that leave the scope

2017-07-12 Thread Matthias Gehre via cfe-commits
Author: mgehre
Date: Wed Jul 12 00:04:19 2017
New Revision: 307759

URL: http://llvm.org/viewvc/llvm-project?rev=307759&view=rev
Log:
CFG: Add CFGElement for automatic variables that leave the scope

Summary:
This mimics the implementation for the implicit destructors. The
generation of this scope leaving elements is hidden behind
a flag to the CFGBuilder, thus it should not affect existing code.

Currently, I'm missing a test (it's implicitly tested by the clang-tidy
lifetime checker that I'm proposing).
I though about a test using debug.DumpCFG, but then I would
have to add an option to StaticAnalyzer/Core/AnalyzerOptions
to enable the scope leaving CFGElement,
which would only be useful to that particular test.

Any other ideas how I could make a test for this feature?

Reviewers: krememek, jordan_rose

Subscribers: cfe-commits

Differential Revision: http://reviews.llvm.org/D15031

Added:
cfe/trunk/test/Analysis/lifetime-cfg-output.cpp
Modified:
cfe/trunk/include/clang/Analysis/AnalysisContext.h
cfe/trunk/include/clang/Analysis/CFG.h
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
cfe/trunk/lib/Analysis/CFG.cpp
cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp
cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
cfe/trunk/test/Analysis/analyzer-config.c
cfe/trunk/test/Analysis/analyzer-config.cpp

Modified: cfe/trunk/include/clang/Analysis/AnalysisContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/AnalysisContext.h?rev=307759&r1=307758&r2=307759&view=diff
==
--- cfe/trunk/include/clang/Analysis/AnalysisContext.h (original)
+++ cfe/trunk/include/clang/Analysis/AnalysisContext.h Wed Jul 12 00:04:19 2017
@@ -426,6 +426,7 @@ public:
  bool addImplicitDtors = false,
  bool addInitializers = false,
  bool addTemporaryDtors = false,
+ bool addLifetime = false,
  bool synthesizeBodies = false,
  bool addStaticInitBranches = false,
  bool addCXXNewAllocator = true,

Modified: cfe/trunk/include/clang/Analysis/CFG.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CFG.h?rev=307759&r1=307758&r2=307759&view=diff
==
--- cfe/trunk/include/clang/Analysis/CFG.h (original)
+++ cfe/trunk/include/clang/Analysis/CFG.h Wed Jul 12 00:04:19 2017
@@ -58,6 +58,7 @@ public:
 Statement,
 Initializer,
 NewAllocator,
+LifetimeEnds,
 // dtor kind
 AutomaticObjectDtor,
 DeleteDtor,
@@ -167,6 +168,28 @@ private:
   }
 };
 
+/// Represents the point where the lifetime of an automatic object ends
+class CFGLifetimeEnds : public CFGElement {
+public:
+  explicit CFGLifetimeEnds(const VarDecl *var, const Stmt *stmt)
+  : CFGElement(LifetimeEnds, var, stmt) {}
+
+  const VarDecl *getVarDecl() const {
+return static_cast(Data1.getPointer());
+  }
+
+  const Stmt *getTriggerStmt() const {
+return static_cast(Data2.getPointer());
+  }
+
+private:
+  friend class CFGElement;
+  CFGLifetimeEnds() {}
+  static bool isKind(const CFGElement &elem) {
+return elem.getKind() == LifetimeEnds;
+  }
+};
+
 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
 /// by compiler on various occasions.
 class CFGImplicitDtor : public CFGElement {
@@ -701,6 +724,10 @@ public:
 Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
   }
 
+  void appendLifetimeEnds(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
+Elements.push_back(CFGLifetimeEnds(VD, S), C);
+  }
+
   void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, 
BumpVectorContext &C) {
 Elements.push_back(CFGDeleteDtor(RD, DE), C);
   }
@@ -717,6 +744,19 @@ public:
 *I = CFGAutomaticObjDtor(VD, S);
 return ++I;
   }
+
+  // Scope leaving must be performed in reversed order. So insertion is in two
+  // steps. First we prepare space for some number of elements, then we insert
+  // the elements beginning at the last position in prepared space.
+  iterator beginLifetimeEndsInsert(iterator I, size_t Cnt,
+   BumpVectorContext &C) {
+return iterator(
+Elements.insert(I.base(), Cnt, CFGLifetimeEnds(nullptr, nullptr), C));
+  }
+  iterator insertLifetimeEnds(iterator I, VarDecl *VD, Stmt *S) {
+*I = CFGLifetimeEnds(VD, S);
+return ++I;
+  }
 };
 
 /// \brief CFGCallback defines methods that should be called when a logical
@@ -753,6 +793,7 @@ public:
 bool AddEHEdges;
 bool AddInitializers;
 bool AddImplicitDtors;
+bool AddLifetime;
 bool 

[PATCH] D15031: CFG: Add CFGElement for automatic variables that leave the scope

2017-07-12 Thread Matthias Gehre via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307759: CFG: Add CFGElement for automatic variables that 
leave the scope (authored by mgehre).

Changed prior to commit:
  https://reviews.llvm.org/D15031?vs=91378&id=106146#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D15031

Files:
  cfe/trunk/include/clang/Analysis/AnalysisContext.h
  cfe/trunk/include/clang/Analysis/CFG.h
  cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  cfe/trunk/lib/Analysis/AnalysisDeclContext.cpp
  cfe/trunk/lib/Analysis/CFG.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/AnalysisManager.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  cfe/trunk/test/Analysis/analyzer-config.c
  cfe/trunk/test/Analysis/analyzer-config.cpp
  cfe/trunk/test/Analysis/lifetime-cfg-output.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
@@ -205,9 +205,15 @@
   /// Controls which C++ member functions will be considered for inlining.
   CXXInlineableMemberKind CXXMemberInliningMode;
   
+  /// \sa includeImplicitDtorsInCFG
+  Optional IncludeImplicitDtorsInCFG;
+
   /// \sa includeTemporaryDtorsInCFG
   Optional IncludeTemporaryDtorsInCFG;
-  
+
+  /// \sa IncludeLifetimeInCFG
+  Optional IncludeLifetimeInCFG;
+
   /// \sa mayInlineCXXStandardLibrary
   Optional InlineCXXStandardLibrary;
   
@@ -395,6 +401,20 @@
   /// accepts the values "true" and "false".
   bool includeTemporaryDtorsInCFG();
 
+  /// Returns whether or not implicit destructors for C++ objects should
+  /// be included in the CFG.
+  ///
+  /// This is controlled by the 'cfg-implicit-dtors' config option, which
+  /// accepts the values "true" and "false".
+  bool includeImplicitDtorsInCFG();
+
+  /// Returns whether or not end-of-lifetime information should be included in
+  /// the CFG.
+  ///
+  /// This is controlled by the 'cfg-lifetime' config option, which accepts
+  /// the values "true" and "false".
+  bool includeLifetimeInCFG();
+
   /// Returns whether or not C++ standard library functions may be considered
   /// for inlining.
   ///
Index: cfe/trunk/include/clang/Analysis/CFG.h
===
--- cfe/trunk/include/clang/Analysis/CFG.h
+++ cfe/trunk/include/clang/Analysis/CFG.h
@@ -58,6 +58,7 @@
 Statement,
 Initializer,
 NewAllocator,
+LifetimeEnds,
 // dtor kind
 AutomaticObjectDtor,
 DeleteDtor,
@@ -167,6 +168,28 @@
   }
 };
 
+/// Represents the point where the lifetime of an automatic object ends
+class CFGLifetimeEnds : public CFGElement {
+public:
+  explicit CFGLifetimeEnds(const VarDecl *var, const Stmt *stmt)
+  : CFGElement(LifetimeEnds, var, stmt) {}
+
+  const VarDecl *getVarDecl() const {
+return static_cast(Data1.getPointer());
+  }
+
+  const Stmt *getTriggerStmt() const {
+return static_cast(Data2.getPointer());
+  }
+
+private:
+  friend class CFGElement;
+  CFGLifetimeEnds() {}
+  static bool isKind(const CFGElement &elem) {
+return elem.getKind() == LifetimeEnds;
+  }
+};
+
 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
 /// by compiler on various occasions.
 class CFGImplicitDtor : public CFGElement {
@@ -701,6 +724,10 @@
 Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
   }
 
+  void appendLifetimeEnds(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
+Elements.push_back(CFGLifetimeEnds(VD, S), C);
+  }
+
   void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
 Elements.push_back(CFGDeleteDtor(RD, DE), C);
   }
@@ -717,6 +744,19 @@
 *I = CFGAutomaticObjDtor(VD, S);
 return ++I;
   }
+
+  // Scope leaving must be performed in reversed order. So insertion is in two
+  // steps. First we prepare space for some number of elements, then we insert
+  // the elements beginning at the last position in prepared space.
+  iterator beginLifetimeEndsInsert(iterator I, size_t Cnt,
+   BumpVectorContext &C) {
+return iterator(
+Elements.insert(I.base(), Cnt, CFGLifetimeEnds(nullptr, nullptr), C));
+  }
+  iterator insertLifetimeEnds(iterator I, VarDecl *VD, Stmt *S) {
+*I = CFGLifetimeEnds(VD, S);
+return ++I;
+  }
 };
 
 /// \brief CFGCallback defines methods that should be called when a logical
@@ -753,6 +793,7 @@
 bool AddEHEdges;
 bool AddInitializers;
 bool AddImplicitDtors;
+bool AddLifetime;
 bool AddTemporaryDtors;
 bool AddStaticInitBranches;
 bool AddCXXNewAllocator;
@@ -774,8 +815,10 @@
 
 BuildOptions()
   : forcedBlkExprs(nullptr), Observer(nullptr),
-PruneTriviallyFalseEdges(true), AddEHEd

[PATCH] D34301: [Sema] Make sure the definition of a referenced virtual function is emitted when it is final

2017-07-12 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak marked 2 inline comments as done.
ahatanak added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:14715
+if (Method->isVirtual() && !(Method->hasAttr() ||
+ Method->getParent()->hasAttr()))
   OdrUse = false;

vsk wrote:
> Do you think it makes sense to eliminate all candidate virtual methods which 
> can be devirtualized? If so, you could make 
> "CanDevirtualizeMemberFunctionCall" a shared utility between Sema and 
> CodeGen, and use it here. That function should give "the truth" about whether 
> or not a call can be devirtualized.
I moved CanDevirtualizeMemberFunctionCall to DeclCXX.cpp and added overloaded 
functions of canDevirtualizeCall and used one of them here. This caused changes 
in the generated IR in two test cases (no-devirt.cpp and 
vtable-available-externally.cpp). Both changes look correct to me.



Comment at: test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp:271
+// Derived::operator() is not emitted, there will be a linker error.
+(*ptr)();
+  }

vsk wrote:
> Have you looked into why "ptr->operator()();" compiles? We are either missing 
> a devirtualization opportunity, or we have inconsistent logic for setting 
> MightBeOdrUse for member calls. Either way, I think this patch is the right 
> vehicle to address the issue.
"ptr->operator()();"  creates a MemberExpr, which MarkMemberReferenced handles. 
The difference between MarkMemberReferenced and MarkDeclRefReferenced is that 
the former sets OdrUse to false when the method is pure while the latter does 
so when the method is virtual.  Prior to r174341, MarkDeclRefReferenced was 
setting OdrUse to false for pure methods too (see r174242).


https://reviews.llvm.org/D34301



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


[PATCH] D34301: [Sema] Make sure the definition of a referenced virtual function is emitted when it is final

2017-07-12 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 106149.
ahatanak marked an inline comment as done.
ahatanak added a comment.

Address review comments.


https://reviews.llvm.org/D34301

Files:
  include/clang/AST/DeclCXX.h
  include/clang/Sema/Sema.h
  lib/AST/DeclCXX.cpp
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaOverload.cpp
  test/CodeGen/no-devirt.cpp
  test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
  test/CodeGenCXX/vtable-available-externally.cpp

Index: test/CodeGenCXX/vtable-available-externally.cpp
===
--- test/CodeGenCXX/vtable-available-externally.cpp
+++ test/CodeGenCXX/vtable-available-externally.cpp
@@ -275,9 +275,8 @@
   virtual D& operator=(const D&);
 };
 
-// Cannot emit D's vtable available_externally, because we cannot create
-// a reference to the inline virtual D::operator= function.
-// CHECK-TEST11: @_ZTVN6Test111DE = external unnamed_addr constant
+// Can emit D's vtable available_externally.
+// CHECK-TEST11: @_ZTVN6Test111DE = available_externally unnamed_addr constant
 struct D : C {
   virtual void key();
 };
Index: test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
===
--- test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
+++ test/CodeGenCXX/devirtualize-virtual-function-calls-final.cpp
@@ -241,3 +241,53 @@
 return static_cast(b)->f();
   }
 }
+
+namespace Test11 {
+  // Check that the definition of Derived::operator() is emitted.
+
+  // CHECK-LABEL: define linkonce_odr void @_ZN6Test111SIiE4foo1Ev(
+  // CHECK: call void @_ZN6Test111SIiE7DerivedclEv(
+  // CHECK: call zeroext i1 @_ZN6Test111SIiE7DerivedeqERKNS_4BaseE(
+  // CHECK: call zeroext i1 @_ZN6Test111SIiE7DerivedntEv(
+  // CHECK: call dereferenceable(4) %"class.Test11::Base"* @_ZN6Test111SIiE7DerivedixEi(
+  // CHECK: define linkonce_odr void @_ZN6Test111SIiE7DerivedclEv(
+  // CHECK: define linkonce_odr zeroext i1 @_ZN6Test111SIiE7DerivedeqERKNS_4BaseE(
+  // CHECK: define linkonce_odr zeroext i1 @_ZN6Test111SIiE7DerivedntEv(
+  // CHECK: define linkonce_odr dereferenceable(4) %"class.Test11::Base"* @_ZN6Test111SIiE7DerivedixEi(
+  class Base {
+  public:
+virtual void operator()() {}
+virtual bool operator==(const Base &other) { return false; }
+virtual bool operator!() { return false; }
+virtual Base &operator[](int i) { return *this; }
+  };
+
+  template
+  struct S {
+class Derived final : public Base {
+public:
+  void operator()() override {}
+  bool operator==(const Base &other) override { return true; }
+  bool operator!() override { return true; }
+  Base &operator[](int i) override { return *this; }
+};
+
+Derived *ptr = nullptr, *ptr2 = nullptr;
+
+void foo1() {
+  if (ptr && ptr2) {
+// These calls get devirtualized. Linkage fails if the definitions of
+// the called functions are not emitted.
+(*ptr)();
+(void)(*ptr == *ptr2);
+(void)(!(*ptr));
+(void)((*ptr)[1]);
+  }
+}
+  };
+
+  void foo2() {
+S *s = new S;
+s->foo1();
+  }
+}
Index: test/CodeGen/no-devirt.cpp
===
--- test/CodeGen/no-devirt.cpp
+++ test/CodeGen/no-devirt.cpp
@@ -21,7 +21,7 @@
 struct Wrapper {
   TmplWithArray data;
   bool indexIt(int a) {
-if (a > 6) return data[a] ;  // Should not devirtualize
+if (a > 6) return data[a] ;  // Should devirtualize
 if (a > 4) return data.func1(a); // Should devirtualize
 return data.func2(a);// Should devirtualize
   }
@@ -53,7 +53,7 @@
 }
 #endif
 
-// CHECK-NOT: call {{.*}} @_ZN13TmplWithArrayIbLi10EEixEi
+// CHECK-DAG: call {{.*}} @_ZN13TmplWithArrayIbLi10EEixEi
 // CHECK-DAG: call {{.*}} @_ZN13TmplWithArrayIbLi10EE5func1Ei
 // CHECK-DAG: call {{.*}} @_ZN13TmplWithArrayIbLi10EE5func2Ei
 
Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -48,7 +48,7 @@
 /// A convenience routine for creating a decayed reference to a function.
 static ExprResult
 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
-  bool HadMultipleCandidates,
+  const Expr *Base, bool HadMultipleCandidates,
   SourceLocation Loc = SourceLocation(),
   const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
@@ -68,7 +68,7 @@
   if (HadMultipleCandidates)
 DRE->setHadMultipleCandidates(true);
 
-  S.MarkDeclRefReferenced(DRE);
+  S.MarkDeclRefReferenced(DRE, Base);
   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
  CK_FunctionToPointerDecay);
 }
@@ -11946,6 +11

[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk updated this revision to Diff 106148.
barancsuk marked 2 inline comments as done.
barancsuk added a comment.

- Further reviews addressed


https://reviews.llvm.org/D35257

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tidy/modernize/UnaryStaticAssertCheck.cpp
  clang-tidy/modernize/UnaryStaticAssertCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-unary-static-assert.rst
  test/clang-tidy/modernize-unary-static-assert.cpp

Index: test/clang-tidy/modernize-unary-static-assert.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-unary-static-assert.cpp
@@ -0,0 +1,27 @@
+// RUN: %check_clang_tidy %s modernize-unary-static-assert %t -- -- -std=c++1z
+
+#define FOO static_assert(sizeof(a) <= 15, "");
+#define MSG ""
+
+void f_textless(int a) {
+  static_assert(sizeof(a) <= 10, "");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when the string literal is an empty string [modernize-unary-static-assert]
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 10 );{{$}}
+  static_assert(sizeof(a) <= 12, L"");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 12 );{{$}}
+  FOO
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when
+  // CHECK-FIXES: {{^}}  FOO{{$}}
+  static_assert(sizeof(a) <= 17, MSG);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 17, MSG);{{$}}
+}
+
+void f_with_tex(int a) {
+  static_assert(sizeof(a) <= 10, "Size of variable a is out of range!");
+}
+
+void f_unary(int a) { static_assert(sizeof(a) <= 10); }
+
+void f_incorrect_assert() { static_assert(""); }
Index: docs/clang-tidy/checks/modernize-unary-static-assert.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/modernize-unary-static-assert.rst
@@ -0,0 +1,25 @@
+.. title:: clang-tidy - modernize-unary-static-assert
+
+modernize-unary-static-assert
+=
+
+The check diagnoses any ``static_assert`` declaration with an empty string literal
+and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
+
+The check is only applicable for C++17 and later code.
+
+The following code:
+
+.. code-block:: c++
+
+  void f_textless(int a) {
+static_assert(sizeof(a) <= 10, "");
+  }
+
+is replaced by:
+
+.. code-block:: c++
+
+  void f_textless(int a) {
+static_assert(sizeof(a) <= 10);
+  }
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -132,6 +132,7 @@
modernize-replace-random-shuffle
modernize-return-braced-init-list
modernize-shrink-to-fit
+   modernize-unary-static-assert
modernize-use-auto
modernize-use-bool-literals
modernize-use-default-member-init
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -108,6 +108,12 @@
   Finds and replaces explicit calls to the constructor in a return statement by
   a braced initializer list so that the return type is not needlessly repeated.
 
+- New `modernize-unary-static-assert-check
+  `_ check
+
+  The check diagnoses any ``static_assert`` declaration with an empty string literal
+  and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
+
 - Improved `modernize-use-emplace
   `_ check
 
Index: clang-tidy/modernize/UnaryStaticAssertCheck.h
===
--- /dev/null
+++ clang-tidy/modernize/UnaryStaticAssertCheck.h
@@ -0,0 +1,36 @@
+//===--- UnaryStaticAssertCheck.h - clang-tidy---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+/// Replaces a static_assert declaration with an empty message
+/// with the unary version.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-unary-static-assert.html
+class UnaryStaticAssertCheck : public Cla

[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk added inline comments.



Comment at: clang-tidy/modernize/UnaryStaticAssertCheck.cpp:32
+
+  if (!AssertMessage || AssertMessage->getLength())
+return;

aaron.ballman wrote:
> I think this should be `!AssertMessage->getLength()`
It works correctly without the negation, otherwise the tests fail. 


https://reviews.llvm.org/D35257



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


r307760 - Expose some type-conversion functions as part of the IRGen ABI.

2017-07-12 Thread John McCall via cfe-commits
Author: rjmccall
Date: Wed Jul 12 00:44:17 2017
New Revision: 307760

URL: http://llvm.org/viewvc/llvm-project?rev=307760&view=rev
Log:
Expose some type-conversion functions as part of the IRGen ABI.

Patch by Benoit Vey!

Modified:
cfe/trunk/include/clang/CodeGen/CodeGenABITypes.h
cfe/trunk/lib/CodeGen/CodeGenABITypes.cpp

Modified: cfe/trunk/include/clang/CodeGen/CodeGenABITypes.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CodeGen/CodeGenABITypes.h?rev=307760&r1=307759&r2=307760&view=diff
==
--- cfe/trunk/include/clang/CodeGen/CodeGenABITypes.h (original)
+++ cfe/trunk/include/clang/CodeGen/CodeGenABITypes.h Wed Jul 12 00:44:17 2017
@@ -31,6 +31,8 @@
 namespace llvm {
   class DataLayout;
   class Module;
+  class FunctionType;
+  class Type;
 }
 
 namespace clang {
@@ -70,6 +72,12 @@ const CGFunctionInfo &arrangeFreeFunctio
   FunctionType::ExtInfo info,
   RequiredArgs args);
 
+// Returns null if the function type is incomplete and can't be lowered.
+llvm::FunctionType *convertFreeFunctionType(CodeGenModule &CGM,
+const FunctionDecl *FD);
+
+llvm::Type *convertTypeForMemory(CodeGenModule &CGM, QualType T);
+
 }  // end namespace CodeGen
 }  // end namespace clang
 

Modified: cfe/trunk/lib/CodeGen/CodeGenABITypes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenABITypes.cpp?rev=307760&r1=307759&r2=307760&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenABITypes.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenABITypes.cpp Wed Jul 12 00:44:17 2017
@@ -64,3 +64,19 @@ CodeGen::arrangeFreeFunctionCall(CodeGen
   returnType, /*IsInstanceMethod=*/false, /*IsChainCall=*/false, argTypes,
   info, {}, args);
 }
+
+llvm::FunctionType *
+CodeGen::convertFreeFunctionType(CodeGenModule &CGM, const FunctionDecl *FD) {
+  assert(FD != nullptr && "Expected a non-null function declaration!");
+  llvm::Type *T = CGM.getTypes().ConvertFunctionType(FD->getType(), FD);
+
+  if (auto FT = dyn_cast(T))
+return FT;
+
+  return nullptr;
+}
+
+llvm::Type *
+CodeGen::convertTypeForMemory(CodeGenModule &CGM, QualType T) {
+  return CGM.getTypes().ConvertTypeForMem(T);
+}


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


[PATCH] D35180: Expose the Clang::QualType to llvm::Type conversion functions

2017-07-12 Thread John McCall via Phabricator via cfe-commits
rjmccall closed this revision.
rjmccall added a comment.

Committed.


https://reviews.llvm.org/D35180



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


[PATCH] D35109: [Analyzer] SValBuilder Comparison Rearrangement

2017-07-12 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

I think you might also need to convert `APSInt`s to an appropriate type, as 
done above. Type of right-hand-side `APSInt`s do not necessarily coincide with 
the type of the left-hand-side symbol or of the whole expression. `APSInt` 
operations crash when signedness doesn't match (and in a few other cases).

In https://reviews.llvm.org/D35109#802123, @baloghadamsoftware wrote:

> In https://reviews.llvm.org/D35109#801921, @NoQ wrote:
>
> > Because integer promotion rules are tricky, could we, for now, avoid 
> > dealing with the situation when left-hand side and right-hand side and the 
> > result (all three) are not all of the same type? Or maybe we'd like to 
> > support substraction of unsigned values into a signed value of the same 
> > size, but still avoid the rest of the cases. Because it'd take an 
> > overwhelming amount of testing to ensure that we get all the promotion 
> > cases correctly.
>
>
> I think the best place to add and test integer promotion rules is the type 
> system.


Currently we have broken symbolic casts, which means that we significantly 
ignore the type system, because symbolic expressions involving casts are much 
harder to simplify or deal with, while overflow cases are too often implicitly 
contracted out to make the analyzer good at understanding them. Which leads to 
everything having different type.




Comment at: lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:397-403
   // We're looking for a type big enough to compare the two values.
   // FIXME: This is not correct. char + short will result in a 
promotion
   // to int. Unfortunately we have lost types by this point.
   APSIntType CompareType = std::max(APSIntType(LHSValue),
 APSIntType(RHSValue));
   CompareType.apply(LHSValue);
   CompareType.apply(RHSValue);

An example of how `APSInt` types are handled.



Comment at: lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:521-522
   APSIntType IntType = BasicVals.getAPSIntType(resultTy);
   const llvm::APSInt &first = 
IntType.convert(symIntExpr->getRHS());
   const llvm::APSInt &second = IntType.convert(*RHSValue);
 

An example of how `APSInt` types are handled.


https://reviews.llvm.org/D35109



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


[PATCH] D35110: [Analyzer] Constraint Manager Negates Difference

2017-07-12 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:496
 
+  if (const SymSymExpr *SSE = dyn_cast(Sym)) {
+if (SSE->getOpcode() == BO_Sub) {

With this, it sounds as if we're half-way into finally supporting the unary 
minus operator (:

Could you add a FIXME here: "Once SValBuilder supports unary minus, we should 
use SValBuilder to obtain the negated symbolic expression instead of 
constructing the symbol manually. This will allow us to support finding ranges 
of not only negated SymSymExpr-type expressions, but also of other, simpler 
expressions which we currently do not know how to negate."



Comment at: lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:499-504
+  // If the type of A - B is the same as the type of A, then use the type 
of
+  // B as the type of B - A. Otherwise keep the type of A - B.
+  SymbolRef negSym = SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub,
+  SSE->getLHS(),
+  (T == SSE->getLHS()->getType()) ?
+  SSE->getRHS()->getType() : T);

I'm quite sure that types of `A - B` and `B - A` are always equal when it comes 
to integer promotion rules.

Also, due to our broken `SymbolCast` (which is often missing where it ideally 
should be), the type of the `A - B` symbol may not necessarily be the same as 
the type that you obtain by applying integer promotion rules to types of `A` 
and `B`.

So i think you should always take the type of `A - B` and expect to find `B - 
A` of the same type in the range map, otherwise give up.



Comment at: lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:511
+   SSE->getLHS()->getType()->isSignedIntegerOrEnumerationType() ||
+   SSE->getLHS()->getType()->isPointerType()) {
+  return negV->Negate(BV, F);

Pointer types are currently treated as unsigned, so i'm not sure you want them 
here.



Comment at: test/Analysis/ptr-arith.c:268-270
 //---
 // False positives
 //---

The tests that are now supported should be moved above this comment.


https://reviews.llvm.org/D35110



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


[PATCH] D34367: CodeGen: Fix address space of indirect function argument

2017-07-12 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGCall.cpp:3832
+ "indirect-arg-temp");
+IRCallArgs[FirstIRArg] = CastToAllocaAddrSpace(Addr.getPointer());
 

Isn't the original code here correct?  You're basically just adding unnecessary 
casts.



Comment at: lib/CodeGen/CGCall.cpp:3851
+ ->getType()
+ ->getPointerAddressSpace();
 const unsigned ArgAddrSpace =

Hmm.  Is there actually a test case where Addr.getType()->getAddressSpace() is 
not the lowering of LangAS::Default?  The correctness of the 
performAddrSpaceCast call you make depends on that.

If there isn't, I think it would be better to add a target hook to attempt to 
peephole an addrspace cast:
  llvm::Value *tryPeepholeAddrSpaceCast(llvm::Value*, unsigned valueAS, 
unsigned targetAS);

And then you can just do
  bool HasAddrSpaceMismatch = CGM.getASTAllocaAddrSpace() != LangAS::Default);
  if (HasAddrSpaceMismatch) {
if (llvm::Value *ptr = tryPeepholeAddrSpaceCast(Addr.getPointer(), 
LangAS::Default, getASTAllocAddrSpace())) {
  Addr = Address(ptr, Addr.getAlignment()); // might need to cast the 
element type for this
  HasAddrSpaceMismatch = false;
}
  }



Comment at: lib/CodeGen/CGCall.cpp:3861
< Align.getQuantity()) ||
 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
   // Create an aligned temporary, and copy to it.

This should be comparing AST address spaces.



Comment at: lib/CodeGen/CGCall.cpp:3865
+ "byval-temp");
+  IRCallArgs[FirstIRArg] = CastToAllocaAddrSpace(AI.getPointer());
   EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());

Same thing, no reason to do the casts here.



Comment at: lib/CodeGen/CGDecl.cpp:1828
+auto DestAS = getContext().getTargetAddressSpace(LangAS::Default);
+if (SrcAS != DestAS) {
+  assert(SrcAS == CGM.getDataLayout().getAllocaAddrSpace());

This should be comparing AST address spaces.


https://reviews.llvm.org/D34367



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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

To me, features that only serve to help compiler development need to meet a 
higher bar than this.  This just seems really marginal.

Like Alex said, you should be able to pretty easily write a debugger script 
that breaks when it sees a specific diagnostic, or a diagnostic at a specific 
line and column.  That would be quite welcome in utils/.


https://reviews.llvm.org/D35175



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


[PATCH] D35295: [docs] Add section 'Half-Precision Floating Point'

2017-07-12 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer created this revision.

This documents the differences and interactions between _Float16 and __fp16.


https://reviews.llvm.org/D35295

Files:
  docs/LanguageExtensions.rst


Index: docs/LanguageExtensions.rst
===
--- docs/LanguageExtensions.rst
+++ docs/LanguageExtensions.rst
@@ -436,6 +436,37 @@
 
 See also :ref:`langext-__builtin_shufflevector`, 
:ref:`langext-__builtin_convertvector`.
 
+Half-Precision Floating Point
+=
+
+Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
+``_Float16``. ``__fp16`` is defined in the ARM C Language Extensions (`ACLE
+`_
+and ``_Float16`` in ISO/IEC TS 18661-3:2015.
+
+``__fp16`` is a storage and interchange format only. This means that values of
+``__fp16`` promote to (at least) float when used in artimethic operations. 
There are
+two ``__fp16`` formats. Clang supports the IEEE 754-2008 format and not the
+ARM alternative format.
+
+ISO/IEC TS 18661-3:2015 defines C support for additional floating point types.
+``_FloatN`` is defined as a binary floating type, where the N suffix denotes
+the number of bits and is 16, 32, 64, or greater and egual to 128 and a
+multiple of 32. Clang supports ``_Float16``.  The difference with ``__fp16`` is
+that arithmetic is performed in half-precision, thus it is not a storage-only
+format. It is recommended that portable code use the ``_Float16`` type.
+
+In an arithmetic operation where one operand is of ``__fp16`` type and the
+other is of ``_Float16`` type, the ``_Float16`` type is first converted to
+``__fp16`` type and then the operation is completed as if both operands were of
+``__fp16`` type.
+
+To define a ``_Float16`` literal, suffix ``f16`` can be appended to the 
compile-time
+constant declaration. There is no default argument promotion for ``_Float16``; 
this
+applies to the standard floating types only. As a consequence, for example, an
+explicit cast is required for printing a ``_Float16`` value (there is no string
+format specifier for ``_Float16``).
+
 Messages on ``deprecated`` and ``unavailable`` Attributes
 =
 


Index: docs/LanguageExtensions.rst
===
--- docs/LanguageExtensions.rst
+++ docs/LanguageExtensions.rst
@@ -436,6 +436,37 @@
 
 See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
 
+Half-Precision Floating Point
+=
+
+Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
+``_Float16``. ``__fp16`` is defined in the ARM C Language Extensions (`ACLE
+`_
+and ``_Float16`` in ISO/IEC TS 18661-3:2015.
+
+``__fp16`` is a storage and interchange format only. This means that values of
+``__fp16`` promote to (at least) float when used in artimethic operations. There are
+two ``__fp16`` formats. Clang supports the IEEE 754-2008 format and not the
+ARM alternative format.
+
+ISO/IEC TS 18661-3:2015 defines C support for additional floating point types.
+``_FloatN`` is defined as a binary floating type, where the N suffix denotes
+the number of bits and is 16, 32, 64, or greater and egual to 128 and a
+multiple of 32. Clang supports ``_Float16``.  The difference with ``__fp16`` is
+that arithmetic is performed in half-precision, thus it is not a storage-only
+format. It is recommended that portable code use the ``_Float16`` type.
+
+In an arithmetic operation where one operand is of ``__fp16`` type and the
+other is of ``_Float16`` type, the ``_Float16`` type is first converted to
+``__fp16`` type and then the operation is completed as if both operands were of
+``__fp16`` type.
+
+To define a ``_Float16`` literal, suffix ``f16`` can be appended to the compile-time
+constant declaration. There is no default argument promotion for ``_Float16``; this
+applies to the standard floating types only. As a consequence, for example, an
+explicit cast is required for printing a ``_Float16`` value (there is no string
+format specifier for ``_Float16``).
+
 Messages on ``deprecated`` and ``unavailable`` Attributes
 =
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-07-12 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added a comment.

I've created revision https://reviews.llvm.org/D35295 for the documentation 
update.


https://reviews.llvm.org/D33719



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


[PATCH] D33644: Add default values for function parameter chunks

2017-07-12 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Ping! Comments are added :)


https://reviews.llvm.org/D33644



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


[PATCH] D35200: Don't use mmap on Windows

2017-07-12 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

What do you think about that change?


https://reviews.llvm.org/D35200



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


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
Herald added a subscriber: klimek.

This patch fixes bug https://bugs.llvm.org/show_bug.cgi?id=3313: a comment line
was aligned with the next #ifdef even in the presence of an empty line between
them.


https://reviews.llvm.org/D35296

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestComments.cpp


Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,23 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   EXPECT_EQ("/* This is a long\n"
 " * comment that\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,21 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  bool UpdateLevel = NextNonCommentLine->First->NewlinesBefore <= 1;
+  if (UpdateLevel)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }


Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,23 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   EXPECT_EQ("/* This is a long\n"
 " * comment that\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,21 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  bool UpdateLevel = NextNonCommentLine->First->NewlinesBefore <= 1;
+  if (UpdateLevel)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35295: [docs] Add section 'Half-Precision Floating Point'

2017-07-12 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: docs/LanguageExtensions.rst:448
+``__fp16`` is a storage and interchange format only. This means that values of
+``__fp16`` promote to (at least) float when used in artimethic operations. 
There are
+two ``__fp16`` formats. Clang supports the IEEE 754-2008 format and not the

typo: artimethic -> arithmetic



Comment at: docs/LanguageExtensions.rst:454
+``_FloatN`` is defined as a binary floating type, where the N suffix denotes
+the number of bits and is 16, 32, 64, or greater and egual to 128 and a
+multiple of 32. Clang supports ``_Float16``.  The difference with ``__fp16`` is

typo: egual -> equal



Comment at: docs/LanguageExtensions.rst:455
+the number of bits and is 16, 32, 64, or greater and egual to 128 and a
+multiple of 32. Clang supports ``_Float16``.  The difference with ``__fp16`` is
+that arithmetic is performed in half-precision, thus it is not a storage-only

Wording nit: "The difference with `__fp16` is that ..." suggests that you're 
about to describe how __fp16 does things. Or at least it could be read as 
suggesting that.

Using "from" instead of "with" clarifies that you're saying how something is 
//unlike// fp16. I think I would also clarify by restating the type name in the 
subclause, along the lines of

  The difference from ``__fp16`` is that arithmetic on ``_Float16`` is 
performed in half-precision, ...


https://reviews.llvm.org/D35295



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


[PATCH] D35297: [Sema] Fix operator lookup to consider local extern declarations.

2017-07-12 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF created this revision.

Previously Clang was not considering operator declarations that occur at 
function scope. This is incorrect according to [over.match.oper]p3

> The set of non-member candidates is the result of the unqualified lookup of 
> operator@ in the context of the expression according to the usual rules for 
> name lookup in unqualified function calls.

This patch fixes operator name lookup to consider block scope declarations.

I think there might be existing open bugs for this but I can't find them.


https://reviews.llvm.org/D35297

Files:
  lib/Sema/SemaLookup.cpp
  test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp


Index: test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
===
--- test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
+++ test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
@@ -2,6 +2,21 @@
 
 namespace bullet2 {
 
+// The set of non-member candidates is the result of the unqualified lookup of
+// operator@ in the context of the expression according to the usual rules for
+// name lookup in unqualified function calls.
+
+// Test that local extern declarations are allowed.
+struct A {};
+void test_local_lookup() {
+  A a;
+  +a; // expected-error {{invalid argument type 'bullet2::A' to unary 
expression}}
+  a + a; // expected-error {{invalid operands to binary expression 
('bullet2::A' and 'bullet2::A')}}
+  void operator+(A);
+  void operator+(A, A);
+  +a; // OK
+  a + a;
+}
 // For non-member candidates, if no operand has a class type, only those
 // non-member functions that have a matching enumeration parameter are
 // candidates.
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:


Index: test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
===
--- test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
+++ test/CXX/over/over.match/over.match.funcs/over.match.oper/p3.cpp
@@ -2,6 +2,21 @@
 
 namespace bullet2 {
 
+// The set of non-member candidates is the result of the unqualified lookup of
+// operator@ in the context of the expression according to the usual rules for
+// name lookup in unqualified function calls.
+
+// Test that local extern declarations are allowed.
+struct A {};
+void test_local_lookup() {
+  A a;
+  +a; // expected-error {{invalid argument type 'bullet2::A' to unary expression}}
+  a + a; // expected-error {{invalid operands to binary expression ('bullet2::A' and 'bullet2::A')}}
+  void operator+(A);
+  void operator+(A, A);
+  +a; // OK
+  a + a;
+}
 // For non-member candidates, if no operand has a class type, only those
 // non-member functions that have a matching enumeration parameter are
 // candidates.
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34404: [Clang-Tidy] Preserve Message, FileOffset, FilePath in Clang-Tidy YAML output

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

I tried landing the patch for you, but it doesn't apply cleanly. One reason is 
that it contains changes to both cfe and clang-tools-extra repos. But even when 
I apply the patch to the two directories it breaks a bunch of 
clang-apply-replacements tests:

  Failing Tests (4):
  Clang Tools :: clang-apply-replacements/basic.cpp
  Clang Tools :: clang-apply-replacements/conflict.cpp
  Clang Tools :: clang-apply-replacements/crlf.cpp
  Clang Tools :: clang-apply-replacements/format.cpp

Please rebase the patch and split it in two (upload a second differential 
revision for the clang-tools-extra part).


Repository:
  rL LLVM

https://reviews.llvm.org/D34404



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


[PATCH] D35297: [Sema] Fix operator lookup to consider local extern declarations.

2017-07-12 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF updated this revision to Diff 106166.
EricWF added a comment.

Add more appropriate test.


https://reviews.llvm.org/D35297

Files:
  lib/Sema/SemaLookup.cpp
  test/SemaCXX/overloaded-operator.cpp


Index: test/SemaCXX/overloaded-operator.cpp
===
--- test/SemaCXX/overloaded-operator.cpp
+++ test/SemaCXX/overloaded-operator.cpp
@@ -531,3 +531,20 @@
 b3 / 0; // expected-note {{in instantiation of}} expected-error {{invalid 
operands to}}
   }
 }
+
+
+namespace TestLookupFindsBlockScopeDecls {
+  template  void operator+(T, T) = delete; // expected-note 2 
{{candidate}}
+  template  void operator+(T) = delete; // expected-note 2 
{{candidate}}
+
+  struct A {};
+  void f() {
+A a;
++a; // expected-error {{overload resolution selected deleted operator '+'}}
+a + a; // expected-error {{overload resolution selected deleted operator 
'+'}}
+void operator+(A);
+void operator+(A, A);
++a; // OK
+a + a;
+  }
+}
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:


Index: test/SemaCXX/overloaded-operator.cpp
===
--- test/SemaCXX/overloaded-operator.cpp
+++ test/SemaCXX/overloaded-operator.cpp
@@ -531,3 +531,20 @@
 b3 / 0; // expected-note {{in instantiation of}} expected-error {{invalid operands to}}
   }
 }
+
+
+namespace TestLookupFindsBlockScopeDecls {
+  template  void operator+(T, T) = delete; // expected-note 2 {{candidate}}
+  template  void operator+(T) = delete; // expected-note 2 {{candidate}}
+
+  struct A {};
+  void f() {
+A a;
++a; // expected-error {{overload resolution selected deleted operator '+'}}
+a + a; // expected-error {{overload resolution selected deleted operator '+'}}
+void operator+(A);
+void operator+(A, A);
++a; // OK
+a + a;
+  }
+}
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35297: [Sema] Fix operator lookup to consider local extern declarations.

2017-07-12 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF updated this revision to Diff 106168.
EricWF edited the summary of this revision.

https://reviews.llvm.org/D35297

Files:
  lib/Sema/SemaLookup.cpp
  test/SemaCXX/overloaded-operator.cpp


Index: test/SemaCXX/overloaded-operator.cpp
===
--- test/SemaCXX/overloaded-operator.cpp
+++ test/SemaCXX/overloaded-operator.cpp
@@ -531,3 +531,20 @@
 b3 / 0; // expected-note {{in instantiation of}} expected-error {{invalid 
operands to}}
   }
 }
+
+
+namespace PR27027 {
+  template  void operator+(T, T) = delete; // expected-note 2 
{{candidate}}
+  template  void operator+(T) = delete; // expected-note 2 
{{candidate}}
+
+  struct A {};
+  void f() {
+A a;
++a; // expected-error {{overload resolution selected deleted operator '+'}}
+a + a; // expected-error {{overload resolution selected deleted operator 
'+'}}
+void operator+(A);
+void operator+(A, A);
++a; // OK
+a + a;
+  }
+}
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:


Index: test/SemaCXX/overloaded-operator.cpp
===
--- test/SemaCXX/overloaded-operator.cpp
+++ test/SemaCXX/overloaded-operator.cpp
@@ -531,3 +531,20 @@
 b3 / 0; // expected-note {{in instantiation of}} expected-error {{invalid operands to}}
   }
 }
+
+
+namespace PR27027 {
+  template  void operator+(T, T) = delete; // expected-note 2 {{candidate}}
+  template  void operator+(T) = delete; // expected-note 2 {{candidate}}
+
+  struct A {};
+  void f() {
+A a;
++a; // expected-error {{overload resolution selected deleted operator '+'}}
+a + a; // expected-error {{overload resolution selected deleted operator '+'}}
+void operator+(A);
+void operator+(A, A);
++a; // OK
+a + a;
+  }
+}
Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -226,7 +226,7 @@
 // Operator lookup is its own crazy thing;  it is not the same
 // as (e.g.) looking up an operator name for redeclaration.
 assert(!Redeclaration && "cannot do redeclaration operator lookup");
-IDNS = Decl::IDNS_NonMemberOperator;
+IDNS = Decl::IDNS_NonMemberOperator | Decl::IDNS_LocalExtern;
 break;
 
   case Sema::LookupTagName:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35295: [docs] Add section 'Half-Precision Floating Point'

2017-07-12 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer updated this revision to Diff 106167.
SjoerdMeijer added a comment.

Thanks for review! Feedback addressed.


https://reviews.llvm.org/D35295

Files:
  docs/LanguageExtensions.rst


Index: docs/LanguageExtensions.rst
===
--- docs/LanguageExtensions.rst
+++ docs/LanguageExtensions.rst
@@ -436,6 +436,38 @@
 
 See also :ref:`langext-__builtin_shufflevector`, 
:ref:`langext-__builtin_convertvector`.
 
+Half-Precision Floating Point
+=
+
+Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
+``_Float16``. ``__fp16`` is defined in the ARM C Language Extensions (`ACLE
+`_
+and ``_Float16`` in ISO/IEC TS 18661-3:2015.
+
+``__fp16`` is a storage and interchange format only. This means that values of
+``__fp16`` promote to (at least) float when used in arithmetic operations.
+There are two ``__fp16`` formats. Clang supports the IEEE 754-2008 format and
+not the ARM alternative format.
+
+ISO/IEC TS 18661-3:2015 defines C support for additional floating point types.
+``_FloatN`` is defined as a binary floating type, where the N suffix denotes
+the number of bits and is 16, 32, 64, or greater and equal to 128 and a
+multiple of 32. Clang supports ``_Float16``. The difference from ``__fp16`` is
+that arithmetic on ``_Float16`` is performed in half-precision, thus it is not
+a storage-only format. It is recommended that portable code use the
+``_Float16`` type.
+
+In an arithmetic operation where one operand is of ``__fp16`` type and the
+other is of ``_Float16`` type, the ``_Float16`` type is first converted to
+``__fp16`` type and then the operation is completed as if both operands were of
+``__fp16`` type.
+
+To define a ``_Float16`` literal, suffix ``f16`` can be appended to the 
compile-time
+constant declaration. There is no default argument promotion for ``_Float16``; 
this
+applies to the standard floating types only. As a consequence, for example, an
+explicit cast is required for printing a ``_Float16`` value (there is no string
+format specifier for ``_Float16``).
+
 Messages on ``deprecated`` and ``unavailable`` Attributes
 =
 


Index: docs/LanguageExtensions.rst
===
--- docs/LanguageExtensions.rst
+++ docs/LanguageExtensions.rst
@@ -436,6 +436,38 @@
 
 See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
 
+Half-Precision Floating Point
+=
+
+Clang supports two half-precision (16-bit) floating point types: ``__fp16`` and
+``_Float16``. ``__fp16`` is defined in the ARM C Language Extensions (`ACLE
+`_
+and ``_Float16`` in ISO/IEC TS 18661-3:2015.
+
+``__fp16`` is a storage and interchange format only. This means that values of
+``__fp16`` promote to (at least) float when used in arithmetic operations.
+There are two ``__fp16`` formats. Clang supports the IEEE 754-2008 format and
+not the ARM alternative format.
+
+ISO/IEC TS 18661-3:2015 defines C support for additional floating point types.
+``_FloatN`` is defined as a binary floating type, where the N suffix denotes
+the number of bits and is 16, 32, 64, or greater and equal to 128 and a
+multiple of 32. Clang supports ``_Float16``. The difference from ``__fp16`` is
+that arithmetic on ``_Float16`` is performed in half-precision, thus it is not
+a storage-only format. It is recommended that portable code use the
+``_Float16`` type.
+
+In an arithmetic operation where one operand is of ``__fp16`` type and the
+other is of ``_Float16`` type, the ``_Float16`` type is first converted to
+``__fp16`` type and then the operation is completed as if both operands were of
+``__fp16`` type.
+
+To define a ``_Float16`` literal, suffix ``f16`` can be appended to the compile-time
+constant declaration. There is no default argument promotion for ``_Float16``; this
+applies to the standard floating types only. As a consequence, for example, an
+explicit cast is required for printing a ``_Float16`` value (there is no string
+format specifier for ``_Float16``).
+
 Messages on ``deprecated`` and ``unavailable`` Attributes
 =
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

I still think we should make this dependent on the current indentation. Why do 
you think this is better?


https://reviews.llvm.org/D35296



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


[PATCH] D35295: [docs] Add section 'Half-Precision Floating Point'

2017-07-12 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: docs/LanguageExtensions.rst:457
+that arithmetic on ``_Float16`` is performed in half-precision, thus it is not
+a storage-only format. It is recommended that portable code use the
+``_Float16`` type.

I think the use of "portable" here doesn't really give enough detail.

From an ARM-specific perspective, source code using `_Float16` will be compiled 
into code that uses the hardware FP instructions for arithmetic on 16-bit FP 
values which were introduced in ARMv8.2, whereas `__fp16` will be compiled into 
code that only uses the instructions to convert 16-bit to and from 32-bit, from 
a much earlier architecture revision. So from that perspective, using 
`_Float16` will //reduce// portability, because it will make your code run (or 
at least run at full hardware-FP speed) on a smaller set of CPUs.

On the other hand, from a source language perspective, `__fp16` is defined in 
an ARM-specific language extension, whereas `_Float16` is defined by the C 
standards committee. So if your portability concern is between entire 
architectures, rather than between versions of the ARM architecture, then using 
`_Float16` probably does help.

So I think it would probably be better to make some of this explicit – don't 
just say one or the other type is "more portable", but say something more 
specific about the circumstances in which each one can be expected to work.


https://reviews.llvm.org/D35295



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


[PATCH] D35187: [libclang] Support for querying whether an enum is scoped

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Sure, I'll commit it today.


https://reviews.llvm.org/D35187



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


[PATCH] D33644: Add default values for function parameter chunks

2017-07-12 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 106170.
yvvan added a comment.

Add more checks into GetDefaultValueString to make it safe


https://reviews.llvm.org/D33644

Files:
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/functions.cpp
  test/Index/code-completion.cpp
  test/Index/complete-optional-params.cpp

Index: test/Index/complete-optional-params.cpp
===
--- test/Index/complete-optional-params.cpp
+++ test/Index/complete-optional-params.cpp
@@ -6,15 +6,19 @@
 void baz(int a = 42, ...);
 struct S{ S(int a = 42, int = 42) {} };
 
+class Bar1 { public: Bar1() {} }; class Bar2;
+void foo_2(Bar1 b1 = Bar1(), Bar2 b2 = Bar2());
+
 int main() {
 foo(42, 42);
 bar(42, 42, 42);
 baz(42, 42, 42);
 S s(42, 42);
+foo_2();
 }
 
-// RUN: c-index-test -code-completion-at=%s:10:9 %s | FileCheck -check-prefix=CHECK-CC1 %s
-// CHECK-CC1: OverloadCandidate:{ResultType void}{Text foo}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
+// RUN: c-index-test -code-completion-at=%s:13:9 %s | FileCheck -check-prefix=CHECK-CC1 %s
+// CHECK-CC1: OverloadCandidate:{ResultType void}{Text foo}{LeftParen (}{Optional {CurrentParameter int a = 42}{Optional {Comma , }{Placeholder int = 42}}}{RightParen )} (1)
 // CHECK-CC1: Completion contexts:
 // CHECK-CC1-NEXT: Any type
 // CHECK-CC1-NEXT: Any value
@@ -25,8 +29,8 @@
 // CHECK-CC1-NEXT: Nested name specifier
 // CHECK-CC1-NEXT: Objective-C interface
 
-// RUN: c-index-test -code-completion-at=%s:11:9 %s | FileCheck -check-prefix=CHECK-CC2 %s
-// CHECK-CC2: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{CurrentParameter int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{Placeholder int c}}}{RightParen )} (1)
+// RUN: c-index-test -code-completion-at=%s:14:9 %s | FileCheck -check-prefix=CHECK-CC2 %s
+// CHECK-CC2: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{CurrentParameter int a}{Optional {Comma , }{Placeholder int b = 42}{Optional {Comma , }{Placeholder int c = 42}}}{RightParen )} (1)
 // CHECK-CC2: Completion contexts:
 // CHECK-CC2-NEXT: Any type
 // CHECK-CC2-NEXT: Any value
@@ -37,8 +41,8 @@
 // CHECK-CC2-NEXT: Nested name specifier
 // CHECK-CC2-NEXT: Objective-C interface
 
-// RUN: c-index-test -code-completion-at=%s:11:16 %s | FileCheck -check-prefix=CHECK-CC3 %s
-// CHECK-CC3: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{Placeholder int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{CurrentParameter int c}}}{RightParen )} (1)
+// RUN: c-index-test -code-completion-at=%s:14:16 %s | FileCheck -check-prefix=CHECK-CC3 %s
+// CHECK-CC3: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{Placeholder int a}{Optional {Comma , }{Placeholder int b = 42}{Optional {Comma , }{CurrentParameter int c = 42}}}{RightParen )} (1)
 // CHECK-CC3: Completion contexts:
 // CHECK-CC3-NEXT: Any type
 // CHECK-CC3-NEXT: Any value
@@ -49,8 +53,8 @@
 // CHECK-CC3-NEXT: Nested name specifier
 // CHECK-CC3-NEXT: Objective-C interface
 
-// RUN: c-index-test -code-completion-at=%s:12:16 %s | FileCheck -check-prefix=CHECK-CC4 %s
-// CHECK-CC4: OverloadCandidate:{ResultType void}{Text baz}{LeftParen (}{Optional {Placeholder int a}{Optional {Comma , }{CurrentParameter ...}}}{RightParen )} (1)
+// RUN: c-index-test -code-completion-at=%s:15:16 %s | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: OverloadCandidate:{ResultType void}{Text baz}{LeftParen (}{Optional {Placeholder int a = 42}{Optional {Comma , }{CurrentParameter ...}}}{RightParen )} (1)
 // CHECK-CC4: Completion contexts:
 // CHECK-CC4-NEXT: Any type
 // CHECK-CC4-NEXT: Any value
@@ -61,8 +65,8 @@
 // CHECK-CC4-NEXT: Nested name specifier
 // CHECK-CC4-NEXT: Objective-C interface
 
-// RUN: c-index-test -code-completion-at=%s:13:9 %s | FileCheck -check-prefix=CHECK-CC5 %s
-// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
+// RUN: c-index-test -code-completion-at=%s:16:9 %s | FileCheck -check-prefix=CHECK-CC5 %s
+// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{Optional {CurrentParameter int a = 42}{Optional {Comma , }{Placeholder int = 42}}}{RightParen )} (1)
 // CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S &}{RightParen )} (1)
 // CHECK-CC5: Completion contexts:
 // CHECK-CC5-NEXT: Any type
@@ -73,3 +77,15 @@
 // CHECK-CC5-NEXT: Class name
 // CHECK-CC5-NEXT: Nested name specifier
 // CHECK-CC5-NEXT: Objective-C interface
+
+// RUN: c-index-test -code-completion-at=%s:17:11 %s | FileCheck -check-prefix=CHECK-CC6 %s
+// CHECK-CC6: FunctionDecl:{ResultType void}{TypedText foo_2}{LeftParen (}{Optional {Placeholder Bar1 b1 = Bar1()}{Optional {Comma , }{Placeholder Bar2 b2}}}{RightParen )} (50)
+// CHECK-CC6: Completion contexts:
+// CHECK-CC6-NEXT: Any type
+// CHECK-CC6-NEXT: Any value
+// CHECK-CC6-

r307769 - [libclang] Support for querying whether an enum is scoped

2017-07-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Jul 12 04:31:37 2017
New Revision: 307769

URL: http://llvm.org/viewvc/llvm-project?rev=307769&view=rev
Log:
[libclang] Support for querying whether an enum is scoped

This commit allows checking whether an enum declaration is scoped
through libclang and clang.cindex (Python).

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

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/print-type-declaration.cpp
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CIndex.cpp
cfe/trunk/tools/libclang/libclang.exports

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=307769&r1=307768&r2=307769&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Jul 12 04:31:37 2017
@@ -1478,6 +1478,11 @@ class Cursor(Structure):
 """
 return conf.lib.clang_CXXMethod_isVirtual(self)
 
+def is_scoped_enum(self):
+"""Returns True if the cursor refers to a scoped enum declaration.
+"""
+return conf.lib.clang_EnumDecl_isScoped(self)
+
 def get_definition(self):
 """
 If the cursor is a reference to a declaration or a declaration of
@@ -3314,6 +3319,10 @@ functionList = [
[Cursor],
bool),
 
+  ("clang_EnumDecl_isScoped",
+   [Cursor],
+   bool),
+
   ("clang_defaultDiagnosticDisplayOptions",
[],
c_uint),

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=307769&r1=307768&r2=307769&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Wed Jul 12 04:31:37 
2017
@@ -255,6 +255,22 @@ def test_is_virtual_method():
 assert foo.is_virtual_method()
 assert not bar.is_virtual_method()
 
+def test_is_scoped_enum():
+"""Ensure Cursor.is_scoped_enum works."""
+source = 'class X {}; enum RegularEnum {}; enum class ScopedEnum {};'
+tu = get_tu(source, lang='cpp')
+
+cls = get_cursor(tu, 'X')
+regular_enum = get_cursor(tu, 'RegularEnum')
+scoped_enum = get_cursor(tu, 'ScopedEnum')
+assert cls is not None
+assert regular_enum is not None
+assert scoped_enum is not None
+
+assert not cls.is_scoped_enum()
+assert not regular_enum.is_scoped_enum()
+assert scoped_enum.is_scoped_enum()
+
 def test_underlying_type():
 tu = get_tu('typedef int foo;')
 typedef = get_cursor(tu, 'foo')

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=307769&r1=307768&r2=307769&view=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Wed Jul 12 04:31:37 2017
@@ -4417,6 +4417,11 @@ CINDEX_LINKAGE unsigned clang_CXXMethod_
 CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C);
 
 /**
+ * \brief Determine if an enum declaration refers to a scoped enum.
+ */
+CINDEX_LINKAGE unsigned clang_EnumDecl_isScoped(CXCursor C);
+
+/**
  * \brief Determine if a C++ member function or member function template is
  * declared 'const'.
  */

Modified: cfe/trunk/test/Index/print-type-declaration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/print-type-declaration.cpp?rev=307769&r1=307768&r2=307769&view=diff
==
--- cfe/trunk/test/Index/print-type-declaration.cpp (original)
+++ cfe/trunk/test/Index/print-type-declaration.cpp Wed Jul 12 04:31:37 2017
@@ -7,6 +7,13 @@ int main()
   auto b = a;
 }
 
+enum RegularEnum {};
+
+enum class ScopedEnum {};
+
 // RUN: c-index-test -test-print-type-declaration -std=c++11 %s | FileCheck %s
 // CHECK: VarDecl=a:6:8 (Definition) [typedeclaration=Test] [typekind=Record]
 // CHECK: VarDecl=b:7:8 (Definition) [typedeclaration=Test] [typekind=Record]
+// CHECK: EnumDecl=RegularEnum:10:6 (Definition) [typedeclaration=RegularEnum] 
[typekind=Enum]
+// CHECK: EnumDecl=ScopedEnum:12:12 (Definition) (scoped) 
[typedeclaration=ScopedEnum] [typekind=Enum]
+

Modified: cfe/trunk/tools/c-index-test/c-index-test.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/c-index-test/c-index-test.c?rev=307769&r1=307768&r2=307769&view=diff
==
--- cfe/trunk/tools/c-index-test/c-index-test.c (original)
+++ cfe/trunk/tools/c-index-test/c-index-test.c Wed Jul 12 04:31:37 2017
@@ -804,6 +804

[PATCH] D35187: [libclang] Support for querying whether an enum is scoped

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307769: [libclang] Support for querying whether an enum is 
scoped (authored by arphaman).

Changed prior to commit:
  https://reviews.llvm.org/D35187?vs=106066&id=106173#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35187

Files:
  cfe/trunk/bindings/python/clang/cindex.py
  cfe/trunk/bindings/python/tests/cindex/test_cursor.py
  cfe/trunk/include/clang-c/Index.h
  cfe/trunk/test/Index/print-type-declaration.cpp
  cfe/trunk/tools/c-index-test/c-index-test.c
  cfe/trunk/tools/libclang/CIndex.cpp
  cfe/trunk/tools/libclang/libclang.exports

Index: cfe/trunk/tools/libclang/CIndex.cpp
===
--- cfe/trunk/tools/libclang/CIndex.cpp
+++ cfe/trunk/tools/libclang/CIndex.cpp
@@ -7807,6 +7807,15 @@
   return (Method && Method->isVirtual()) ? 1 : 0;
 }
 
+unsigned clang_EnumDecl_isScoped(CXCursor C) {
+  if (!clang_isDeclaration(C.kind))
+return 0;
+
+  const Decl *D = cxcursor::getCursorDecl(C);
+  auto *Enum = dyn_cast_or_null(D);
+  return (Enum && Enum->isScoped()) ? 1 : 0;
+}
+
 //===--===//
 // Attribute introspection.
 //===--===//
Index: cfe/trunk/tools/libclang/libclang.exports
===
--- cfe/trunk/tools/libclang/libclang.exports
+++ cfe/trunk/tools/libclang/libclang.exports
@@ -12,6 +12,7 @@
 clang_CXXMethod_isPureVirtual
 clang_CXXMethod_isStatic
 clang_CXXMethod_isVirtual
+clang_EnumDecl_isScoped
 clang_Cursor_getArgument
 clang_Cursor_getNumTemplateArguments
 clang_Cursor_getTemplateArgumentKind
Index: cfe/trunk/tools/c-index-test/c-index-test.c
===
--- cfe/trunk/tools/c-index-test/c-index-test.c
+++ cfe/trunk/tools/c-index-test/c-index-test.c
@@ -804,6 +804,8 @@
   printf(" (const)");
 if (clang_CXXMethod_isPureVirtual(Cursor))
   printf(" (pure)");
+if (clang_EnumDecl_isScoped(Cursor))
+  printf(" (scoped)");
 if (clang_Cursor_isVariadic(Cursor))
   printf(" (variadic)");
 if (clang_Cursor_isObjCOptional(Cursor))
Index: cfe/trunk/bindings/python/clang/cindex.py
===
--- cfe/trunk/bindings/python/clang/cindex.py
+++ cfe/trunk/bindings/python/clang/cindex.py
@@ -1478,6 +1478,11 @@
 """
 return conf.lib.clang_CXXMethod_isVirtual(self)
 
+def is_scoped_enum(self):
+"""Returns True if the cursor refers to a scoped enum declaration.
+"""
+return conf.lib.clang_EnumDecl_isScoped(self)
+
 def get_definition(self):
 """
 If the cursor is a reference to a declaration or a declaration of
@@ -3314,6 +3319,10 @@
[Cursor],
bool),
 
+  ("clang_EnumDecl_isScoped",
+   [Cursor],
+   bool),
+
   ("clang_defaultDiagnosticDisplayOptions",
[],
c_uint),
Index: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
===
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py
@@ -255,6 +255,22 @@
 assert foo.is_virtual_method()
 assert not bar.is_virtual_method()
 
+def test_is_scoped_enum():
+"""Ensure Cursor.is_scoped_enum works."""
+source = 'class X {}; enum RegularEnum {}; enum class ScopedEnum {};'
+tu = get_tu(source, lang='cpp')
+
+cls = get_cursor(tu, 'X')
+regular_enum = get_cursor(tu, 'RegularEnum')
+scoped_enum = get_cursor(tu, 'ScopedEnum')
+assert cls is not None
+assert regular_enum is not None
+assert scoped_enum is not None
+
+assert not cls.is_scoped_enum()
+assert not regular_enum.is_scoped_enum()
+assert scoped_enum.is_scoped_enum()
+
 def test_underlying_type():
 tu = get_tu('typedef int foo;')
 typedef = get_cursor(tu, 'foo')
Index: cfe/trunk/include/clang-c/Index.h
===
--- cfe/trunk/include/clang-c/Index.h
+++ cfe/trunk/include/clang-c/Index.h
@@ -4417,6 +4417,11 @@
 CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C);
 
 /**
+ * \brief Determine if an enum declaration refers to a scoped enum.
+ */
+CINDEX_LINKAGE unsigned clang_EnumDecl_isScoped(CXCursor C);
+
+/**
  * \brief Determine if a C++ member function or member function template is
  * declared 'const'.
  */
Index: cfe/trunk/test/Index/print-type-declaration.cpp
===
--- cfe/trunk/test/Index/print-type-declaration.cpp
+++ cfe/trunk/test/Index/print-type-declaration.cpp
@@ -7,6 +7,13 @@
   auto b = a;
 }
 
+enum RegularEnum {};
+
+enum class ScopedEnum {};
+
 // RUN: c-index-test -test-print-type-declaration -std=c++11 %s | FileCheck %s

r307770 - Revert r307769 (Forgot to mention the name of the contributor).

2017-07-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Jul 12 04:34:14 2017
New Revision: 307770

URL: http://llvm.org/viewvc/llvm-project?rev=307770&view=rev
Log:
Revert r307769 (Forgot to mention the name of the contributor).

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/print-type-declaration.cpp
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CIndex.cpp
cfe/trunk/tools/libclang/libclang.exports

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=307770&r1=307769&r2=307770&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Jul 12 04:34:14 2017
@@ -1478,11 +1478,6 @@ class Cursor(Structure):
 """
 return conf.lib.clang_CXXMethod_isVirtual(self)
 
-def is_scoped_enum(self):
-"""Returns True if the cursor refers to a scoped enum declaration.
-"""
-return conf.lib.clang_EnumDecl_isScoped(self)
-
 def get_definition(self):
 """
 If the cursor is a reference to a declaration or a declaration of
@@ -3319,10 +3314,6 @@ functionList = [
[Cursor],
bool),
 
-  ("clang_EnumDecl_isScoped",
-   [Cursor],
-   bool),
-
   ("clang_defaultDiagnosticDisplayOptions",
[],
c_uint),

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=307770&r1=307769&r2=307770&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Wed Jul 12 04:34:14 
2017
@@ -255,22 +255,6 @@ def test_is_virtual_method():
 assert foo.is_virtual_method()
 assert not bar.is_virtual_method()
 
-def test_is_scoped_enum():
-"""Ensure Cursor.is_scoped_enum works."""
-source = 'class X {}; enum RegularEnum {}; enum class ScopedEnum {};'
-tu = get_tu(source, lang='cpp')
-
-cls = get_cursor(tu, 'X')
-regular_enum = get_cursor(tu, 'RegularEnum')
-scoped_enum = get_cursor(tu, 'ScopedEnum')
-assert cls is not None
-assert regular_enum is not None
-assert scoped_enum is not None
-
-assert not cls.is_scoped_enum()
-assert not regular_enum.is_scoped_enum()
-assert scoped_enum.is_scoped_enum()
-
 def test_underlying_type():
 tu = get_tu('typedef int foo;')
 typedef = get_cursor(tu, 'foo')

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=307770&r1=307769&r2=307770&view=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Wed Jul 12 04:34:14 2017
@@ -4417,11 +4417,6 @@ CINDEX_LINKAGE unsigned clang_CXXMethod_
 CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C);
 
 /**
- * \brief Determine if an enum declaration refers to a scoped enum.
- */
-CINDEX_LINKAGE unsigned clang_EnumDecl_isScoped(CXCursor C);
-
-/**
  * \brief Determine if a C++ member function or member function template is
  * declared 'const'.
  */

Modified: cfe/trunk/test/Index/print-type-declaration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/print-type-declaration.cpp?rev=307770&r1=307769&r2=307770&view=diff
==
--- cfe/trunk/test/Index/print-type-declaration.cpp (original)
+++ cfe/trunk/test/Index/print-type-declaration.cpp Wed Jul 12 04:34:14 2017
@@ -7,13 +7,6 @@ int main()
   auto b = a;
 }
 
-enum RegularEnum {};
-
-enum class ScopedEnum {};
-
 // RUN: c-index-test -test-print-type-declaration -std=c++11 %s | FileCheck %s
 // CHECK: VarDecl=a:6:8 (Definition) [typedeclaration=Test] [typekind=Record]
 // CHECK: VarDecl=b:7:8 (Definition) [typedeclaration=Test] [typekind=Record]
-// CHECK: EnumDecl=RegularEnum:10:6 (Definition) [typedeclaration=RegularEnum] 
[typekind=Enum]
-// CHECK: EnumDecl=ScopedEnum:12:12 (Definition) (scoped) 
[typedeclaration=ScopedEnum] [typekind=Enum]
-

Modified: cfe/trunk/tools/c-index-test/c-index-test.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/c-index-test/c-index-test.c?rev=307770&r1=307769&r2=307770&view=diff
==
--- cfe/trunk/tools/c-index-test/c-index-test.c (original)
+++ cfe/trunk/tools/c-index-test/c-index-test.c Wed Jul 12 04:34:14 2017
@@ -804,8 +804,6 @@ static void PrintCursor(CXCursor Cursor,
   printf(" (const)");
 if (clang_CXXMethod_isPureVirtual(Cursor))
   printf(" (pure)");
-if (clan

r307771 - [libclang] Support for querying whether an enum is scoped

2017-07-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Jul 12 04:35:11 2017
New Revision: 307771

URL: http://llvm.org/viewvc/llvm-project?rev=307771&view=rev
Log:
[libclang] Support for querying whether an enum is scoped

This commit allows checking whether an enum declaration is scoped
through libclang and clang.cindex (Python).

Patch by Johann Klähn!

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

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/print-type-declaration.cpp
cfe/trunk/tools/c-index-test/c-index-test.c
cfe/trunk/tools/libclang/CIndex.cpp
cfe/trunk/tools/libclang/libclang.exports

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=307771&r1=307770&r2=307771&view=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Jul 12 04:35:11 2017
@@ -1478,6 +1478,11 @@ class Cursor(Structure):
 """
 return conf.lib.clang_CXXMethod_isVirtual(self)
 
+def is_scoped_enum(self):
+"""Returns True if the cursor refers to a scoped enum declaration.
+"""
+return conf.lib.clang_EnumDecl_isScoped(self)
+
 def get_definition(self):
 """
 If the cursor is a reference to a declaration or a declaration of
@@ -3314,6 +3319,10 @@ functionList = [
[Cursor],
bool),
 
+  ("clang_EnumDecl_isScoped",
+   [Cursor],
+   bool),
+
   ("clang_defaultDiagnosticDisplayOptions",
[],
c_uint),

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=307771&r1=307770&r2=307771&view=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Wed Jul 12 04:35:11 
2017
@@ -255,6 +255,22 @@ def test_is_virtual_method():
 assert foo.is_virtual_method()
 assert not bar.is_virtual_method()
 
+def test_is_scoped_enum():
+"""Ensure Cursor.is_scoped_enum works."""
+source = 'class X {}; enum RegularEnum {}; enum class ScopedEnum {};'
+tu = get_tu(source, lang='cpp')
+
+cls = get_cursor(tu, 'X')
+regular_enum = get_cursor(tu, 'RegularEnum')
+scoped_enum = get_cursor(tu, 'ScopedEnum')
+assert cls is not None
+assert regular_enum is not None
+assert scoped_enum is not None
+
+assert not cls.is_scoped_enum()
+assert not regular_enum.is_scoped_enum()
+assert scoped_enum.is_scoped_enum()
+
 def test_underlying_type():
 tu = get_tu('typedef int foo;')
 typedef = get_cursor(tu, 'foo')

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=307771&r1=307770&r2=307771&view=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Wed Jul 12 04:35:11 2017
@@ -4417,6 +4417,11 @@ CINDEX_LINKAGE unsigned clang_CXXMethod_
 CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C);
 
 /**
+ * \brief Determine if an enum declaration refers to a scoped enum.
+ */
+CINDEX_LINKAGE unsigned clang_EnumDecl_isScoped(CXCursor C);
+
+/**
  * \brief Determine if a C++ member function or member function template is
  * declared 'const'.
  */

Modified: cfe/trunk/test/Index/print-type-declaration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/print-type-declaration.cpp?rev=307771&r1=307770&r2=307771&view=diff
==
--- cfe/trunk/test/Index/print-type-declaration.cpp (original)
+++ cfe/trunk/test/Index/print-type-declaration.cpp Wed Jul 12 04:35:11 2017
@@ -7,6 +7,13 @@ int main()
   auto b = a;
 }
 
+enum RegularEnum {};
+
+enum class ScopedEnum {};
+
 // RUN: c-index-test -test-print-type-declaration -std=c++11 %s | FileCheck %s
 // CHECK: VarDecl=a:6:8 (Definition) [typedeclaration=Test] [typekind=Record]
 // CHECK: VarDecl=b:7:8 (Definition) [typedeclaration=Test] [typekind=Record]
+// CHECK: EnumDecl=RegularEnum:10:6 (Definition) [typedeclaration=RegularEnum] 
[typekind=Enum]
+// CHECK: EnumDecl=ScopedEnum:12:12 (Definition) (scoped) 
[typedeclaration=ScopedEnum] [typekind=Enum]
+

Modified: cfe/trunk/tools/c-index-test/c-index-test.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/c-index-test/c-index-test.c?rev=307771&r1=307770&r2=307771&view=diff
==
--- cfe/trunk/tools/c-index-test/c-index-test.c (original)
+++ cfe/trunk/tools/c-index-test/c-index-test.c Wed Jul 12 04:3

[PATCH] D32700: [clang-tidy] Add bugprone-suspicious-memset-usage check.

2017-07-12 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs updated this revision to Diff 106172.
rnkovacs retitled this revision from "[clang-tidy] Add 
misc-suspicious-memset-usage check." to "[clang-tidy] Add 
bugprone-suspicious-memset-usage check.".
rnkovacs edited the summary of this revision.
rnkovacs added a comment.

- Created new module `bugprone` and moved the check into that.
- Included summary of hits on LLVM in the description.


https://reviews.llvm.org/D32700

Files:
  clang-tidy/CMakeLists.txt
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
  clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
  clang-tidy/google/CMakeLists.txt
  clang-tidy/google/GoogleTidyModule.cpp
  clang-tidy/google/MemsetZeroLengthCheck.cpp
  clang-tidy/google/MemsetZeroLengthCheck.h
  clang-tidy/tool/CMakeLists.txt
  clang-tidy/tool/ClangTidyMain.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-suspicious-memset-usage.rst
  docs/clang-tidy/checks/google-runtime-memset.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/bugprone-suspicious-memset-usage.cpp
  test/clang-tidy/google-runtime-memset-zero-length.cpp

Index: test/clang-tidy/google-runtime-memset-zero-length.cpp
===
--- test/clang-tidy/google-runtime-memset-zero-length.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-// RUN: %check_clang_tidy %s google-runtime-memset %t
-
-void *memset(void *, int, __SIZE_TYPE__);
-
-namespace std {
-  using ::memset;
-}
-
-template 
-void memtmpl() {
-  memset(0, sizeof(int), i);
-  memset(0, sizeof(T), sizeof(T));
-  memset(0, sizeof(T), 0);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: memset(0, 0, sizeof(T));
-  memset(0, sizeof(int), 0);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: memset(0, 0, sizeof(int));
-}
-
-void foo(void *a, int xsize, int ysize) {
-  memset(a, sizeof(int), 0);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: memset(a, 0, sizeof(int));
-#define M memset(a, sizeof(int), 0);
-  M
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: #define M memset(a, sizeof(int), 0);
-  ::memset(a, xsize *
-   ysize, 0);
-// CHECK-MESSAGES: :[[@LINE-2]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: ::memset(a, 0, xsize *
-// CHECK-FIXES-NEXT: ysize);
-  std::memset(a, sizeof(int), 0x00);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: std::memset(a, 0x00, sizeof(int));
-
-  const int v = 0;
-  memset(a, sizeof(int), v);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: memset(a, v, sizeof(int));
-
-  memset(a, sizeof(int), v + v);
-// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument
-// CHECK-FIXES: memset(a, v + v, sizeof(int));
-
-  memset(a, sizeof(int), v + 1);
-
-  memset(a, -1, sizeof(int));
-  memset(a, 0xcd, 1);
-
-  // Don't warn when the fill char and the length are both known to be
-  // zero.  No bug is possible.
-  memset(a, 0, v);
-  memset(a, v, 0);
-
-  // -1 is clearly not a length by virtue of being negative, so no warning
-  // despite v == 0.
-  memset(a, -1, v);
-
-  memtmpl<0, int>();
-}
Index: test/clang-tidy/bugprone-suspicious-memset-usage.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-suspicious-memset-usage.cpp
@@ -0,0 +1,75 @@
+// RUN: %check_clang_tidy %s bugprone-suspicious-memset-usage %t
+
+void *memset(void *, int, __SIZE_TYPE__);
+
+namespace std {
+  using ::memset;
+}
+
+template 
+void mtempl(int *ptr) {
+  memset(ptr, '0', sizeof(T));
+// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: memset fill value is char '0', potentially mistaken for int 0 [bugprone-suspicious-memset-usage]
+// CHECK-FIXES: memset(ptr, 0, sizeof(T));
+  memset(ptr, 256, sizeof(T));
+// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: memset fill value is out of unsigned character range, gets truncated [bugprone-suspicious-memset-usage]
+  memset(0, sizeof(T), 0);
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped arguments [bugprone-suspicious-memset-usage]
+// CHECK-FIXES: memset(0, 0, sizeof(T));
+  memset(0, sizeof(int), 0);
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped arguments [bugprone-suspicious-memset-usage]
+// CHECK-FIXES: memset(0, 0, sizeof(int));
+}
+
+void foo(int xsize, int ysize) {
+  int i[5] = {1, 2, 3, 4, 5};
+  int *p = i;
+  int l = 5;
+  char z = '1';
+  char *c = &z;
+  int v = 0;
+
+  memset(p, '0', l);
+// CHECK-MESSAGES: :[[@LINE-1]]:13: warning: memset fill value is

[PATCH] D35187: [libclang] Support for querying whether an enum is scoped

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Committed r307771 with correct attribution.


Repository:
  rL LLVM

https://reviews.llvm.org/D35187



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


[PATCH] D32700: [clang-tidy] Add bugprone-suspicious-memset-usage check.

2017-07-12 Thread Whisperity via Phabricator via cfe-commits
whisperity requested changes to this revision.
whisperity added a comment.
This revision now requires changes to proceed.

Considering the results published in the opening description:

/home/reka/codechecker_dev_env/llvm/lib/Support/NativeFormatting.cpp:55:29: 

 `warning: memset fill value is char '0', potentially mistaken for int 0 
[bugprone-suspicious-memset-usage]`

  std::memset(NumberBuffer, '0', sizeof(NumberBuffer));
^~~~
0

/home/reka/codechecker_dev_env/llvm/lib/Support/NativeFormatting.cpp:148:26: 

 `warning: memset fill value is char '0', potentially mistaken for int 0 
[bugprone-suspicious-memset-usage]`

  ::memset(NumberBuffer, '0', llvm::array_lengthof(NumberBuffer));
 ^~~~
 0

In these case, the buffer is of `char[]` type. This `memset` call initialises 
the array with the character literal ASCII `0`, which is, in this context, the 
expected behaviour. Maybe you should add an exemption from the checker for 
these cases, i.e. where we **do** know that the buffer is a `char[]`.

Tests should be extended with a case for this addition.


https://reviews.llvm.org/D32700



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


[PATCH] D33645: [analyzer] Add missing documentation for static analyzer checkers

2017-07-12 Thread Dominik Szabó via Phabricator via cfe-commits
szdominik added a comment.

In https://reviews.llvm.org/D33645#805920, @dcoughlin wrote:

> Who is the target of this documentation? Is it developers of the analyzer or 
> is it end users of the analyzer? If it is end users, it is unfortunate that 
> we've been just grabbing examples from the regression tests. These tests are 
> usually not idiomatic and, since they're designed for testing, they typically 
> won't explain the check well to an end user.
>
> I've suggested some more idiomatic examples inline for for some of the 
> Objective-C targeted checkers -- but it is probably worth thinking about the 
> remaining examples from the perspective of an end user.


Thank you for the examples, I'll update the patch.
I think the target is the end users, so you're right, probably more idiomatic 
examples would be better. (And @NoQ is right with warning messages too - but it 
should be reconsider the whole documentation, because it doesn't have really 
recognizable convention for that.)
However I'm not very good with Objective-C, so probably I'm not the best for 
this task :)


https://reviews.llvm.org/D33645



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


[PATCH] D33645: [analyzer] Add missing documentation for static analyzer checkers

2017-07-12 Thread Dominik Szabó via Phabricator via cfe-commits
szdominik updated this revision to Diff 106184.
szdominik marked 9 inline comments as done.
szdominik added a comment.

Update with more idiomatic examples (from @dcoughlin).


https://reviews.llvm.org/D33645

Files:
  www/analyzer/alpha_checks.html
  www/analyzer/available_checks.html
  www/analyzer/implicit_checks.html

Index: www/analyzer/implicit_checks.html
===
--- www/analyzer/implicit_checks.html
+++ www/analyzer/implicit_checks.html
@@ -27,7 +27,7 @@
 OS X Implicit Checkers
 
 
-
+
 Core Implicit Checkers
 
 
@@ -124,7 +124,7 @@
 
 
 
-
+
 OS X Implicit Checkers
 
 
Index: www/analyzer/available_checks.html
===
--- www/analyzer/available_checks.html
+++ www/analyzer/available_checks.html
@@ -38,12 +38,14 @@
 Core Checkers model core language features and perform general-purpose checks such as division by zero, null pointer dereference, usage of uninitialized values, etc.
 C++ Checkers perform C++-specific checks
 Dead Code Checkers check for unused code
+Nullability Checkers 
+Optin Checkers 
 OS X Checkers perform Objective-C-specific checks and check the use of Apple's SDKs (OS X and iOS)
 Security Checkers check for insecure API usage and perform checks based on the CERT Secure Coding Standards
 Unix Checkers check the use of Unix and POSIX APIs
 
 
-
+
 Core Checkers
 
 
@@ -360,7 +362,7 @@
 
 
 
-
+
 C++ Checkers
 
 
@@ -421,9 +423,21 @@
 }
 
 
+
+cplusplus.NewDeleteLeaks
+(C++)
+Check for memory leaks. Traces memory managed by new/
+delete.
+
+
+void test() {
+  int *p = new int;
+} // warn
+
+
 
 
-
+
 Dead Code Checkers
 
 
@@ -444,7 +458,161 @@
 
 
 
-
+
+Nullability Checkers
+
+
+Name, DescriptionExample
+
+
+
+nullability.NullPassedToNonnull
+(ObjC)
+Warns when a null pointer is passed to a pointer which has a 
+_Nonnull type.
+
+
+if (name != nil)
+  return;
+// Warning: nil passed to a callee that requires a non-null 1st parameter
+NSString *greeting = [@"Hello " stringByAppendingString:name];
+
+
+
+
+nullability.NullReturnedFromNonnull
+(ObjC)
+Warns when a null pointer is returned from a function that has 
+_Nonnull return type.
+
+
+- (nonnull id)firstChild {
+  id result = nil;
+  if ([_children count] > 0)
+result = _children[0];
+
+  // Warning: nil returned from a method that is expected 
+  // to return a non-null value
+  return result;
+}
+
+
+
+
+nullability.NullableDereferenced
+(ObjC)
+Warns when a nullable pointer is dereferenced.
+
+
+struct LinkedList {
+  int data;
+  struct LinkedList *next;
+};
+
+struct LinkedList * _Nullable getNext(struct LinkedList *l);
+
+void updateNextData(struct LinkedList *list, int newData) {
+  struct LinkedList *next = getNext(list);
+  // Warning: Nullable pointer is dereferenced
+  next->data = 7;
+}
+
+
+
+
+nullability.NullablePassedToNonnull
+(ObjC)
+Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.
+
+
+typedef struct Dummy { int val; } Dummy;
+Dummy *_Nullable returnsNullable();
+void takesNonnull(Dummy *_Nonnull);
+
+void test() {
+  Dummy *p = returnsNullable();
+  takesNonnull(p); // warn
+}
+
+
+
+
+
+Optin Checkers
+
+
+Name, DescriptionExample
+
+
+
+optin.mpi.MPI-Checker
+(C)
+Checks MPI code
+
+
+void test() {
+  double buf = 0;
+  MPI_Request sendReq1;
+  MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM, 
+  0, MPI_COMM_WORLD, &sendReq1);
+} // warn: request 'sendReq1' has no matching wait.
+
+
+void test() {
+  double buf = 0;
+  MPI_Request sendReq;
+  MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq);
+  MPI_Irecv(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
+  MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
+  MPI_Wait(&sendReq, MPI_STATUS_IGNORE);
+}
+
+
+void missingNonBlocking() {
+  int rank = 0;
+  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
+  MPI_Request sendReq1[10][10][10];
+  MPI_Wait(&sendReq1[1][7][9], MPI_STATUS_IGNORE); // warn
+}
+
+
+
+
+optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
+(ObjC)
+Check that NSLocalizedString macros include a comment for context.
+
+
+- (void)test {
+  NSString *string = NSLocalizedString(@"LocalizedString", nil); // warn
+  NSString *string2 = NSLocalizedString(@"LocalizedString", @" "); // warn
+  NSString *string3 = NSLocalizedStringWithDefaultValue(
+@"LocalizedString", nil, [[NSBundle alloc] init], nil,@""); // warn
+}
+
+
+
+
+optin.osx.cocoa.localizability.NonLocalizedStringChecker
+(ObjC)
+Warns about uses of non-localized NSStrings passed to UI methods 
+expecting localized NSStrings
+
+
+NSString *alarmText = 
+  NSLocalizedString(@"Enabled", @"Indicates alarm is turned on");
+if (!isEnabled) {
+  alarmText = @"Disabled";
+}
+UILabel *alarmStateLabel = [[UILabel alloc] init];
+
+// Warning: User-facing text should use localized string macro
+[alarmStateLabel setText:alarmText];
+
+
+
+
+
 OS X Checkers
 
 
@@ -466,6 +634,22 @@
 

[PATCH] D35051: [clang-tidy] Add bugprone-undefined-memory-manipulation check.

2017-07-12 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs updated this revision to Diff 106185.
rnkovacs retitled this revision from "[clang-tidy] Add 
misc-undefined-memory-manipulation check." to "[clang-tidy] Add 
bugprone-undefined-memory-manipulation check.".
rnkovacs edited the summary of this revision.
rnkovacs added a comment.

- Moved to module `bugprone`.
- Added summary of hits on LLVM in the description.


https://reviews.llvm.org/D35051

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
  clang-tidy/bugprone/UndefinedMemoryManipulationCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-undefined-memory-manipulation.cpp

Index: test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
@@ -0,0 +1,178 @@
+// RUN: %check_clang_tidy %s bugprone-undefined-memory-manipulation %t
+
+void *memset(void *, int, __SIZE_TYPE__);
+void *memcpy(void *, const void *, __SIZE_TYPE__);
+void *memmove(void *, const void *, __SIZE_TYPE__);
+
+namespace std {
+using ::memcpy;
+using ::memmove;
+using ::memset;
+}
+
+// TriviallyCopyable types:
+struct Plain {
+  int n;
+};
+
+enum E {
+  X,
+  Y,
+  Z
+};
+
+struct Base {
+  float b;
+};
+
+struct Derived : Base {
+  bool d;
+};
+
+// not TriviallyCopyable types:
+struct Destruct {
+  ~Destruct() {};
+};
+
+struct Copy {
+  Copy() {};
+  Copy(const Copy &) {};
+};
+
+struct Move {
+  Move() {};
+  Move(Move &&) {};
+};
+
+struct VirtualFunc {
+  virtual void f() {};
+};
+
+struct VirtualBase : virtual Base {
+  int vb;
+};
+
+template 
+void memset_temp(T *b) {
+  memset(b, 0, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+template 
+void memcpy_temp(S *a, T *b) {
+  memcpy(a, b, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+template 
+void memmove_temp(S *a, T *b) {
+  memmove(a, b, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+void notTriviallyCopyable() {
+  Plain p; // TriviallyCopyable for variety
+  Destruct d;
+  Copy c;
+  Move m;
+  VirtualFunc vf;
+  VirtualBase vb;
+
+  memset(&vf, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memset(&d, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memset(&c, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  std::memset(&m, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  ::memset(&vb, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+
+  memcpy(&p, &vf, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memcpy(&p, &d, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memcpy(&c, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  std::memcpy(&m, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  ::memcpy(&vb, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+
+  memmove(&vf, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memmove(&d, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memmove(&p, &c, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memo

[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/UnaryStaticAssertCheck.cpp:32
+
+  if (!AssertMessage || AssertMessage->getLength())
+return;

barancsuk wrote:
> aaron.ballman wrote:
> > I think this should be `!AssertMessage->getLength()`
> It works correctly without the negation, otherwise the tests fail. 
Sorry about the brain hiccup, you're correct.



Comment at: test/clang-tidy/modernize-unary-static-assert.cpp:16
+  // CHECK-FIXES: {{^}}  FOO{{$}}
+  static_assert(sizeof(a) <= 17, MSG);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when

This probably should not diagnose, but definitely should not provide a fixit -- 
just because the macro is empty doesn't mean it will *always* be empty. 
Consider:
```
#if FOO
#define MSG ""
#else
#define MSG "Not empty"
#endif
```
I think diagnosing this case is just as likely to be a false-positive as not 
diagnosing, so my preference is to be silent instead of chatty. However, maybe 
there are other opinions.


https://reviews.llvm.org/D35257



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


[PATCH] D35295: [docs] Add section 'Half-Precision Floating Point'

2017-07-12 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added a comment.

Good points. I am thinking about how to write this down.
I am not yet sure that `_Float16` can reduce portability. I think the behaviour 
will depend on FLT_EVAL_METHOD. I.e., if your architecture supports 
half-precision instructions, you would like to set FLT_EVAL_METHOD = 16, which 
would avoid evaluation in float and thus promotions/truncations. If your 
architecture does not support half-precision arithmetic, this will be 
FLT_EVAL_METHOD = 0 so that `_Float16` is evaluated in float. So, from that 
point of view `_Float16` can achieve the same things as '__fp16`, and it is 
more efficient when the hardware supports it and is indeed also more portable 
between entire architectures.


https://reviews.llvm.org/D35295



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


[clang-tools-extra] r307787 - [clang-tidy] add_new_check.py updates ReleaseNotes.rst now

2017-07-12 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Wed Jul 12 06:13:41 2017
New Revision: 307787

URL: http://llvm.org/viewvc/llvm-project?rev=307787&view=rev
Log:
[clang-tidy] add_new_check.py updates ReleaseNotes.rst now

Modified:
clang-tools-extra/trunk/clang-tidy/add_new_check.py

Modified: clang-tools-extra/trunk/clang-tidy/add_new_check.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/add_new_check.py?rev=307787&r1=307786&r2=307787&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/add_new_check.py (original)
+++ clang-tools-extra/trunk/clang-tidy/add_new_check.py Wed Jul 12 06:13:41 2017
@@ -189,6 +189,37 @@ def adapt_module(module_path, module, ch
   f.write(line)
 
 
+# Adds a release notes entry.
+def add_release_notes(module_path, module, check_name):
+  check_name_dashes = module + '-' + check_name
+  filename = os.path.normpath(os.path.join(module_path,
+   '../../docs/ReleaseNotes.rst'))
+  with open(filename, 'r') as f:
+lines = f.readlines()
+
+  print('Updating %s...' % filename)
+  with open(filename, 'wb') as f:
+note_added = False
+header_found = False
+
+for line in lines:
+  if not note_added:
+match = re.search('Improvements to clang-tidy', line)
+if match:
+  header_found = True
+elif header_found:
+  if not line.startswith(''):
+f.write("""
+- New `%s
+  `_ check
+
+  FIXME: add release notes.
+""" % (check_name_dashes, check_name_dashes))
+note_added = True
+
+  f.write(line)
+
+
 # Adds a test for the check.
 def write_test(module_path, module, check_name):
   check_name_dashes = module + '-' + check_name
@@ -300,6 +331,7 @@ documentation files."""
   write_header(module_path, module, check_name, check_name_camel)
   write_implementation(module_path, module, check_name_camel)
   adapt_module(module_path, module, check_name, check_name_camel)
+  add_release_notes(module_path, module, check_name)
   write_test(module_path, module, check_name)
   write_docs(module_path, module, check_name)
   update_checks_list(clang_tidy_path)


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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread don hinton via Phabricator via cfe-commits
hintonda abandoned this revision.
hintonda added a comment.

Okay, sounds good.  Look forward to seeing Alex's script...


https://reviews.llvm.org/D35175



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


[PATCH] D31805: [clang-tidy] Mention "add the check to release note" in add_new_check.py.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In https://reviews.llvm.org/D31805#721433, @Eugene.Zelenko wrote:

> I don't know how hard it'll be to implement, but will be great to add
>
> - New ` .html>`_ check
>
>   Please add short description here.


Good idea. Implemented in r307787. No alphabetic order though. Feel free to fix 
;)

> into "Improvements to clang-tidy" section. Ideally according to alphabetic 
> order.




Repository:
  rL LLVM

https://reviews.llvm.org/D31805



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


[PATCH] D31700: [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

You might want to commit this at some point ;]


https://reviews.llvm.org/D31700



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


[PATCH] D30170: Function definition may have uninstantiated body

2017-07-12 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 106192.
sepavloff added a comment.

Rebased patch


https://reviews.llvm.org/D30170

Files:
  include/clang/AST/Decl.h
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaTemplateInstantiateDecl.cpp
  test/SemaCXX/friend2.cpp

Index: test/SemaCXX/friend2.cpp
===
--- test/SemaCXX/friend2.cpp
+++ test/SemaCXX/friend2.cpp
@@ -101,6 +101,34 @@
   friend void func_12(int x = 0);  // expected-error{{friend declaration specifying a default argument must be the only declaration}}
 };
 
+// Friend function with uninstantiated body is still a definition.
+
+template struct C20 {
+  friend void func_20() {} // expected-note{{previous definition is here}}
+};
+C20 c20i;
+void func_20() {} // expected-error{{redefinition of 'func_20'}}
+
+template struct C21a {
+  friend void func_21() {} // expected-note{{previous definition is here}}
+};
+template struct C21b {
+  friend void func_21() {} // expected-error{{redefinition of 'func_21'}}
+};
+C21a c21ai;
+C21b c21bi; // expected-note{{in instantiation of template class 'C21b' requested here}}
+
+template struct C22a {
+  friend void func_22() {} // expected-note{{previous definition is here}}
+};
+template struct C22b {
+  friend void func_22();
+};
+C22a c22ai;
+C22b c22bi;
+void func_22() {} // expected-error{{redefinition of 'func_22'}}
+
+
 
 namespace pr22307 {
 
Index: lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1807,45 +1807,24 @@
 //   apply to non-template function declarations and definitions also apply
 //   to these implicit definitions.
 if (D->isThisDeclarationADefinition()) {
-  // Check for a function body.
-  const FunctionDecl *Definition = nullptr;
-  if (Function->isDefined(Definition) &&
-  Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
-SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
-<< Function->getDeclName();
-SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
-  }
-  // Check for redefinitions due to other instantiations of this or
-  // a similar friend function.
-  else for (auto R : Function->redecls()) {
-if (R == Function)
-  continue;
-
-// If some prior declaration of this function has been used, we need
-// to instantiate its definition.
-if (!QueuedInstantiation && R->isUsed(false)) {
-  if (MemberSpecializationInfo *MSInfo =
-  Function->getMemberSpecializationInfo()) {
-if (MSInfo->getPointOfInstantiation().isInvalid()) {
-  SourceLocation Loc = R->getLocation(); // FIXME
-  MSInfo->setPointOfInstantiation(Loc);
-  SemaRef.PendingLocalImplicitInstantiations.push_back(
-   std::make_pair(Function, Loc));
-  QueuedInstantiation = true;
-}
-  }
-}
-
-// If some prior declaration of this function was a friend with an
-// uninstantiated definition, reject it.
-if (R->getFriendObjectKind()) {
-  if (const FunctionDecl *RPattern =
-  R->getTemplateInstantiationPattern()) {
-if (RPattern->isDefined(RPattern)) {
-  SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
-<< Function->getDeclName();
-  SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
-  break;
+  SemaRef.CheckForFunctionRedefinition(Function);
+  if (!Function->isInvalidDecl()) {
+for (auto R : Function->redecls()) {
+  if (R == Function)
+continue;
+
+  // If some prior declaration of this function has been used, we need
+  // to instantiate its definition.
+  if (!QueuedInstantiation && R->isUsed(false)) {
+if (MemberSpecializationInfo *MSInfo =
+Function->getMemberSpecializationInfo()) {
+  if (MSInfo->getPointOfInstantiation().isInvalid()) {
+SourceLocation Loc = R->getLocation(); // FIXME
+MSInfo->setPointOfInstantiation(Loc);
+SemaRef.PendingLocalImplicitInstantiations.push_back(
+std::make_pair(Function, Loc));
+QueuedInstantiation = true;
+  }
 }
   }
 }
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -11967,9 +11967,31 @@
const FunctionDecl *EffectiveDefinition,
SkipBodyInfo *SkipBody) {
   const FunctionDecl *Definition = EffectiveDefinition;
+  if (!Definition &&
+  !FD->isD

[PATCH] D35225: [clang-tidy] add regression test to performance-unnecessary-value-param

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

LG. Thanks!


https://reviews.llvm.org/D35225



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


[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk updated this revision to Diff 106195.
barancsuk marked 4 inline comments as done.
barancsuk added a comment.

- No longer warn when the message is from a macro expansion


https://reviews.llvm.org/D35257

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tidy/modernize/UnaryStaticAssertCheck.cpp
  clang-tidy/modernize/UnaryStaticAssertCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-unary-static-assert.rst
  test/clang-tidy/modernize-unary-static-assert.cpp

Index: test/clang-tidy/modernize-unary-static-assert.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-unary-static-assert.cpp
@@ -0,0 +1,25 @@
+// RUN: %check_clang_tidy %s modernize-unary-static-assert %t -- -- -std=c++1z
+
+#define FOO static_assert(sizeof(a) <= 15, "");
+#define MSG ""
+
+void f_textless(int a) {
+  static_assert(sizeof(a) <= 10, "");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when the string literal is an empty string [modernize-unary-static-assert]
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 10 );{{$}}
+  static_assert(sizeof(a) <= 12, L"");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 12 );{{$}}
+  FOO
+  // CHECK-FIXES: {{^}}  FOO{{$}}
+  static_assert(sizeof(a) <= 17, MSG);
+  // CHECK-FIXES: {{^}}  static_assert(sizeof(a) <= 17, MSG);{{$}}
+}
+
+void f_with_tex(int a) {
+  static_assert(sizeof(a) <= 10, "Size of variable a is out of range!");
+}
+
+void f_unary(int a) { static_assert(sizeof(a) <= 10); }
+
+void f_incorrect_assert() { static_assert(""); }
Index: docs/clang-tidy/checks/modernize-unary-static-assert.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/modernize-unary-static-assert.rst
@@ -0,0 +1,25 @@
+.. title:: clang-tidy - modernize-unary-static-assert
+
+modernize-unary-static-assert
+=
+
+The check diagnoses any ``static_assert`` declaration with an empty string literal
+and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
+
+The check is only applicable for C++17 and later code.
+
+The following code:
+
+.. code-block:: c++
+
+  void f_textless(int a) {
+static_assert(sizeof(a) <= 10, "");
+  }
+
+is replaced by:
+
+.. code-block:: c++
+
+  void f_textless(int a) {
+static_assert(sizeof(a) <= 10);
+  }
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -132,6 +132,7 @@
modernize-replace-random-shuffle
modernize-return-braced-init-list
modernize-shrink-to-fit
+   modernize-unary-static-assert
modernize-use-auto
modernize-use-bool-literals
modernize-use-default-member-init
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -108,6 +108,12 @@
   Finds and replaces explicit calls to the constructor in a return statement by
   a braced initializer list so that the return type is not needlessly repeated.
 
+- New `modernize-unary-static-assert-check
+  `_ check
+
+  The check diagnoses any ``static_assert`` declaration with an empty string literal
+  and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
+
 - Improved `modernize-use-emplace
   `_ check
 
Index: clang-tidy/modernize/UnaryStaticAssertCheck.h
===
--- /dev/null
+++ clang-tidy/modernize/UnaryStaticAssertCheck.h
@@ -0,0 +1,36 @@
+//===--- UnaryStaticAssertCheck.h - clang-tidy---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+/// Replaces a static_assert declaration with an empty message
+/// with the unary version.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-unary-static-assert.html
+class UnaryStaticAssertCheck : public ClangTidyCheck {
+public:
+  UnaryStaticAssertCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Co

[PATCH] D34913: [clang-tidy] Add a new Android check "android-cloexec-socket"

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.

LG


https://reviews.llvm.org/D34913



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


[PATCH] D35190: __builtin_constant_p should consider the parameter of a constexpr function as constant

2017-07-12 Thread Joerg Sonnenberger via Phabricator via cfe-commits
joerg added a comment.

What if the constexpr function is called with in a non-constexpr context, e.g. 
with a random global variable as argument?


https://reviews.llvm.org/D35190



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


[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk added inline comments.



Comment at: test/clang-tidy/modernize-unary-static-assert.cpp:16
+  // CHECK-FIXES: {{^}}  FOO{{$}}
+  static_assert(sizeof(a) <= 17, MSG);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use unary 'static_assert' when

aaron.ballman wrote:
> This probably should not diagnose, but definitely should not provide a fixit 
> -- just because the macro is empty doesn't mean it will *always* be empty. 
> Consider:
> ```
> #if FOO
> #define MSG ""
> #else
> #define MSG "Not empty"
> #endif
> ```
> I think diagnosing this case is just as likely to be a false-positive as not 
> diagnosing, so my preference is to be silent instead of chatty. However, 
> maybe there are other opinions.
You are right. Unfortunately, the message is also from a macro expansion when 
the whole static assert is from a macro expansion. Maybe it is possible to 
check whether they are from the same macro, but I think it might better be 
addressed in a separate patch if there is a need to support that case. 


https://reviews.llvm.org/D35257



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


[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D35257



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


[PATCH] D35230: [clang] buildFixItInsertionLine should use Hints of the same FID and LineNo

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

LG. Thank you for the fix!


https://reviews.llvm.org/D35230



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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

My script relies on a hack to map the name of the diagnostic to the enum value. 
We need to come up with a better to map the diagnostic name to the enum value. 
I propose a new utility tool that would take the name of the   diagnostic and 
map it back to the enum value.


https://reviews.llvm.org/D35175



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


[PATCH] D35109: [Analyzer] SValBuilder Comparison Rearrangement

2017-07-12 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

In https://reviews.llvm.org/D35109#806156, @NoQ wrote:

> I think you might also need to convert `APSInt`s to an appropriate type, as 
> done above. Type of right-hand-side `APSInt`s do not necessarily coincide 
> with the type of the left-hand-side symbol or of the whole expression. 
> `APSInt` operations crash when signedness doesn't match (and in a few other 
> cases).


Could you please help me by constructing an example for this scenario? I tried 
multiple options, but I always failed since I check the type of the two sides, 
as you proposed. So I need an example where `typeof(A+n) == typeof(B+m)` but 
`typeof(n) != typeof(m)`.


https://reviews.llvm.org/D35109



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


[PATCH] D35257: [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307791: [clang-tidy] Add new modernize use unary assert 
check (authored by xazax).

Changed prior to commit:
  https://reviews.llvm.org/D35257?vs=106195&id=106197#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35257

Files:
  clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h
  clang-tools-extra/trunk/docs/ReleaseNotes.rst
  clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-unary-static-assert.rst
  clang-tools-extra/trunk/test/clang-tidy/modernize-unary-static-assert.cpp

Index: clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -22,6 +22,7 @@
 #include "ReplaceRandomShuffleCheck.h"
 #include "ReturnBracedInitListCheck.h"
 #include "ShrinkToFitCheck.h"
+#include "UnaryStaticAssertCheck.h"
 #include "UseAutoCheck.h"
 #include "UseBoolLiteralsCheck.h"
 #include "UseDefaultMemberInitCheck.h"
@@ -61,6 +62,8 @@
 CheckFactories.registerCheck(
 "modernize-return-braced-init-list");
 CheckFactories.registerCheck("modernize-shrink-to-fit");
+CheckFactories.registerCheck(
+"modernize-unary-static-assert");
 CheckFactories.registerCheck("modernize-use-auto");
 CheckFactories.registerCheck(
 "modernize-use-bool-literals");
Index: clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h
===
--- clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h
+++ clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h
@@ -0,0 +1,36 @@
+//===--- UnaryStaticAssertCheck.h - clang-tidy---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+/// Replaces a static_assert declaration with an empty message
+/// with the unary version.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-unary-static-assert.html
+class UnaryStaticAssertCheck : public ClangTidyCheck {
+public:
+  UnaryStaticAssertCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};
+
+} // namespace modernize
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARY_STATIC_ASSERT_H
Index: clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
===
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@
   ReplaceRandomShuffleCheck.cpp
   ReturnBracedInitListCheck.cpp
   ShrinkToFitCheck.cpp
+  UnaryStaticAssertCheck.cpp
   UseAutoCheck.cpp
   UseBoolLiteralsCheck.cpp
   UseDefaultMemberInitCheck.cpp
Index: clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp
@@ -0,0 +1,45 @@
+//===--- UnaryStaticAssertCheck.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 "UnaryStaticAssertCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus1z)
+return;
+
+  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
+}
+
+void UnaryStaticAs

[clang-tools-extra] r307791 - [clang-tidy] Add new modernize use unary assert check

2017-07-12 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Jul 12 06:43:35 2017
New Revision: 307791

URL: http://llvm.org/viewvc/llvm-project?rev=307791&view=rev
Log:
[clang-tidy] Add new modernize use unary assert check

Patch by: Lilla Barancsuk

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

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

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-unary-static-assert.rst
clang-tools-extra/trunk/test/clang-tidy/modernize-unary-static-assert.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=307791&r1=307790&r2=307791&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt Wed Jul 12 
06:43:35 2017
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModu
   ReplaceRandomShuffleCheck.cpp
   ReturnBracedInitListCheck.cpp
   ShrinkToFitCheck.cpp
+  UnaryStaticAssertCheck.cpp
   UseAutoCheck.cpp
   UseBoolLiteralsCheck.cpp
   UseDefaultMemberInitCheck.cpp

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=307791&r1=307790&r2=307791&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp Wed 
Jul 12 06:43:35 2017
@@ -22,6 +22,7 @@
 #include "ReplaceRandomShuffleCheck.h"
 #include "ReturnBracedInitListCheck.h"
 #include "ShrinkToFitCheck.h"
+#include "UnaryStaticAssertCheck.h"
 #include "UseAutoCheck.h"
 #include "UseBoolLiteralsCheck.h"
 #include "UseDefaultMemberInitCheck.h"
@@ -61,6 +62,8 @@ public:
 CheckFactories.registerCheck(
 "modernize-return-braced-init-list");
 CheckFactories.registerCheck("modernize-shrink-to-fit");
+CheckFactories.registerCheck(
+"modernize-unary-static-assert");
 CheckFactories.registerCheck("modernize-use-auto");
 CheckFactories.registerCheck(
 "modernize-use-bool-literals");

Added: clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp?rev=307791&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.cpp Wed 
Jul 12 06:43:35 2017
@@ -0,0 +1,45 @@
+//===--- UnaryStaticAssertCheck.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 "UnaryStaticAssertCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus1z)
+return;
+
+  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
+}
+
+void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *MatchedDecl =
+  Result.Nodes.getNodeAs("static_assert");
+  const StringLiteral *AssertMessage = MatchedDecl->getMessage();
+
+  SourceLocation Loc = MatchedDecl->getLocation();
+
+  if (!AssertMessage || AssertMessage->getLength() ||
+  AssertMessage->getLocStart().isMacroID() || Loc.isMacroID())
+return;
+
+  diag(Loc,
+   "use unary 'static_assert' when the string literal is an empty string")
+  << FixItHint::CreateRemoval(AssertMessage->getSourceRange());
+}
+
+} // namespace modernize
+} // namespace tidy
+} // namespace clang

Added: clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h?rev=307791&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UnaryStaticAssertCheck.h 
(a

[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread don hinton via Phabricator via cfe-commits
hintonda added a comment.

Not sure how to do this all in a script, but perhaps we could enhance diagtool 
to generate this mapping for you.   It currently only lists warnings, but I 
don't think it would be difficult to extend it and generate a mapping you could 
use in your script.


https://reviews.llvm.org/D35175



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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Right. I was aware of the `diagtool` before, but didn't really look into what 
it did. TIL! It would make sense to add this kind of mapping functionality to 
that tool then.


https://reviews.llvm.org/D35175



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


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 106202.
krasimir added a comment.

- Switch to original column-based detection


https://reviews.llvm.org/D35296

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestComments.cpp

Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,70 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  // Keep the current level if the comment was originally not aligned with
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Keep the current level if there is an empty line between the comment and
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Align with the preprocessor directive if the comment was originally aligned
+  // with the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"/* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   EXPECT_EQ("/* This is a long\n"
 " * comment that\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,23 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  bool UpdateLevel = NextNonCommentLine->First->NewlinesBefore <= 1 &&
+ NextNonCommentLine->First->OriginalColumn ==
+ (*I)->First->OriginalColumn;
+  if (UpdateLevel)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-07-12 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

In https://reviews.llvm.org/D34512#803724, @klimek wrote:

> Specifically, ping Richard for new top-level lib in clang.


Richard proposed pulling this out into a separate library in the first place. 
Do we need his approval for the name? Or we want him to consider if this patch 
justifies the existence of a separate library?


https://reviews.llvm.org/D34512



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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-07-12 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

Yep, I want Richard's approval for the name. I think he already expressed a 
pro-pulling-out stance.


https://reviews.llvm.org/D34512



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


[PATCH] D34949: [refactor][rename] Use a single base class for class that finds a declaration at location and for class that searches for all occurrences of a specific declaration

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Ping.


Repository:
  rL LLVM

https://reviews.llvm.org/D34949



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


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 106205.
krasimir added a comment.

- Update switch tests


https://reviews.llvm.org/D35296

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestComments.cpp

Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,70 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  // Keep the current level if the comment was originally not aligned with
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Keep the current level if there is an empty line between the comment and
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Align with the preprocessor directive if the comment was originally aligned
+  // with the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"/* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   EXPECT_EQ("/* This is a long\n"
 " * comment that\n"
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -825,12 +825,34 @@
"  case A:\n"
"f();\n"
"break;\n"
-   "  // On B:\n"
+   "// fallthrough\n"
"  case B:\n"
"g();\n"
"break;\n"
"  }\n"
"});");
+  EXPECT_EQ("DEBUG({\n"
+"  switch (x) {\n"
+"  case A:\n"
+"f();\n"
+"break;\n"
+"  // On B:\n"
+"  case B:\n"
+"g();\n"
+"break;\n"
+"  }\n"
+"});",
+  format("DEBUG({\n"
+"  switch (x) {\n"
+"  case A:\n"
+"f();\n"
+"break;\n"
+"  // On B:\n"
+"  case B:\n"
+"g();\n"
+"break;\n"
+"  }\n"
+"});", getLLVMStyle()));
   verifyFormat("switch (a) {\n"
"case (b):\n"
"  return;\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,23 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  bool UpdateLevel = NextNonCommentLine->First->NewlinesBefore <= 1 &&
+ NextNonCommentLine->First->OriginalColumn ==
+ (*I)->First->OriginalColumn;
+  if (UpdateLevel)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }
_

[PATCH] D33644: Add default values for function parameter chunks

2017-07-12 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a reviewer: rsmith.
klimek added a comment.

+Richard, as apparently we get the source ranges for default values of built-in 
types without the preceding "=", but for user-defined types including the 
preceding "=" - is that intentional?




Comment at: lib/Sema/SemaCodeComplete.cpp:2424
+// If we don't have '=' in front of value.
+// Lexer returns built-in types values without '=' and user-defined types 
values with it.
+return " = " + DefValue;

"The Lexer returns default-values of built-in types without '=', and 
default-value of user-defined types with it."

But apart from that: that seems like a bug in the range of the default value? 
I'm now really confused :)


https://reviews.llvm.org/D33644



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


[PATCH] D31805: [clang-tidy] Mention "add the check to release note" in add_new_check.py.

2017-07-12 Thread Haojian Wu via Phabricator via cfe-commits
hokein abandoned this revision.
hokein added a comment.

> Good idea. Implemented in r307787. No alphabetic order though. Feel free to 
> fix ;)

Looks good. Thanks!

Closing this revision.


Repository:
  rL LLVM

https://reviews.llvm.org/D31805



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


[PATCH] D34949: [refactor][rename] Use a single base class for class that finds a declaration at location and for class that searches for all occurrences of a specific declaration

2017-07-12 Thread Manuel Klimek via Phabricator via cfe-commits
klimek accepted this revision.
klimek added a comment.
This revision is now accepted and ready to land.

lg


Repository:
  rL LLVM

https://reviews.llvm.org/D34949



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


[PATCH] D35190: __builtin_constant_p should consider the parameter of a constexpr function as constant

2017-07-12 Thread Olivier Goffart via Phabricator via cfe-commits
ogoffart added a comment.

>   What if the constexpr function is called with in a non-constexpr context, 
> e.g. with a random global variable as argument?

__builtin_constant_p will still return false in this case, contrary to gcc 
(whose behavior actually depends on the optimization level).

I think if we really want to get the exact gcc behavior, we need to mix it with 
the optimizer and generate some LLVM intrinsics. But what I was interested on 
with this patch is at least get  a closer behavior as GCC in a constexpr context


https://reviews.llvm.org/D35190



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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread don hinton via Phabricator via cfe-commits
hintonda added a comment.

I'd be happy to do that if it would help.  If so, should I do it here create a 
new diff?

Perhaps we might even make sense add the ability to pass in a message and find 
the matching name/index.


https://reviews.llvm.org/D35175



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


[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I was impatient, so I already started on a patch for diagtool. I'll post it 
soon.


https://reviews.llvm.org/D35175



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


[PATCH] D34275: [analyzer] Re-implemente current virtual calls checker in a path-sensitive way

2017-07-12 Thread wangxin via Phabricator via cfe-commits
wangxindsb updated this revision to Diff 106204.
wangxindsb added a comment.

- Change IsVirtualCall(const CallExpr *CE) to be a free static function.
- Rename some variables.
- Improve the BugReporterVisitor, enclose the declaration names in single 
quotes.
- Hoist getSValBuilder() from the if statements.
- Fix some code duplications.
- Use the CXXMemberCall instead CXXInstanceCall in the CheckPreCall.
- Remove IsVirtualCall(CE) from if statements.
- Fix the error of the visitnode() method which may throw a wrong call graph 
for the code blow.

  class Y {
  public:
virtual void foobar();
Y() {
  F f1;
  foobar();
}
  };

Previous visitnode() will issue the virtual function called from the F(); 
Current visitnode() fix this bug.


https://reviews.llvm.org/D34275

Files:
  lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
  test/Analysis/virtualcall.cpp

Index: test/Analysis/virtualcall.cpp
===
--- test/Analysis/virtualcall.cpp
+++ test/Analysis/virtualcall.cpp
@@ -1,79 +1,43 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=optin.cplusplus.VirtualCall -analyzer-store region -verify -std=c++11 %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=optin.cplusplus.VirtualCall -analyzer-store region -analyzer-config optin.cplusplus.VirtualCall:Interprocedural=true -DINTERPROCEDURAL=1 -verify -std=c++11 %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=optin.cplusplus.VirtualCall -analyzer-store region -analyzer-config optin.cplusplus.VirtualCall:PureOnly=true -DPUREONLY=1 -verify -std=c++11 %s
 
-/* When INTERPROCEDURAL is set, we expect diagnostics in all functions reachable
-   from a constructor or destructor. If it is not set, we expect diagnostics
-   only in the constructor or destructor.
-
-   When PUREONLY is set, we expect diagnostics only for calls to pure virtual
-   functions not to non-pure virtual functions.
-*/
+// RUN: %clang_analyze_cc1 -analyzer-checker=optin.cplusplus.VirtualCall -analyzer-store region -analyzer-config optin.cplusplus.VirtualCall:PureOnly=true -DPUREONLY=1 -verify -std=c++11 %s
 
 class A {
 public:
   A();
-  A(int i);
 
   ~A() {};
   
-  virtual int foo() = 0; // from Sema: expected-note {{'foo' declared here}}
-  virtual void bar() = 0;
+  virtual int foo()=0;
+  virtual void bar()=0;
   void f() {
 foo();
-#if INTERPROCEDURAL
-// expected-warning-re@-2 ^}}Call Path : foo <-- fCall to pure virtual function during construction has undefined behavior}}
-#endif
+// expected-warning:Call to virtual function during construction
   }
 };
 
 class B : public A {
 public:
   B() {
 foo();
-#if !PUREONLY
-#if INTERPROCEDURAL
-// expected-warning-re@-3 ^}}Call Path : fooCall to virtual function during construction will not dispatch to derived class}}
-#else
-// expected-warning-re@-5 ^}}Call to virtual function during construction will not dispatch to derived class}}
-#endif
-#endif
-
+// expected-warning:Call to virtual function during construction
   }
   ~B();
   
   virtual int foo();
   virtual void bar() { foo(); }
-#if INTERPROCEDURAL
-  // expected-warning-re@-2 ^}}Call Path : foo <-- barCall to virtual function during destruction will not dispatch to derived class}}
-#endif
+  // expected-warning:Call to virtual function during destruction
 };
 
 A::A() {
   f();
 }
 
-A::A(int i) {
-  foo(); // From Sema: expected-warning {{call to pure virtual member function 'foo' has undefined behavior}}
-#if INTERPROCEDURAL
-  // expected-warning-re@-2 ^}}Call Path : fooCall to pure virtual function during construction has undefined behavior}}
-#else
-  // expected-warning-re@-4 ^}}Call to pure virtual function during construction has undefined behavior}}
-#endif
-}
-
 B::~B() {
   this->B::foo(); // no-warning
   this->B::bar();
   this->foo();
-#if !PUREONLY
-#if INTERPROCEDURAL
-  // expected-warning-re@-3 ^}}Call Path : fooCall to virtual function during destruction will not dispatch to derived class}}
-#else
-  // expected-warning-re@-5 ^}}Call to virtual function during destruction will not dispatch to derived class}}
-#endif
-#endif
-
+  // expected-warning:Call to virtual function during destruction
 }
 
 class C : public B {
@@ -87,13 +51,7 @@
 
 C::C() {
   f(foo());
-#if !PUREONLY
-#if INTERPROCEDURAL
-  // expected-warning-re@-3 ^}}Call Path : fooCall to virtual function during construction will not dispatch to derived class}}
-#else
-  // expected-warning-re@-5 ^}}Call to virtual function during construction will not dispatch to derived class}}
-#endif
-#endif
+  // expected-warning:Call to virtual function during construction
 }
 
 class D : public B {
@@ -103,7 +61,8 @@
   }
   ~D() { bar(); }
   int foo() final;
-  void bar() final { foo(); } // no-warning
+  void bar() final { foo(); } 
+  // no-warning
 };
 
 class E final : public B {
@@ -115,7 +74,6 @@
   int f

[PATCH] D35175: New option that adds the DiagID enum name and index to Diagnostic output.

2017-07-12 Thread don hinton via Phabricator via cfe-commits
hintonda added a comment.

Great, thanks...


https://reviews.llvm.org/D35175



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


Re: [clang-tools-extra] r303735 - Modify test so that it looks for patterns in stderr as well

2017-07-12 Thread Alexander Kornienko via cfe-commits
Done in r307661.

On Mon, Jul 10, 2017 at 2:08 PM, Alexander Kornienko 
wrote:

> Benjamin has actually fixed the issue by reverting to the old behavior in 
> r306822.
> I'll add a test for this behavior anyway.
>
> On Mon, Jul 10, 2017 at 11:47 AM, Alexander Kornienko 
> wrote:
>
>> Sorry, missed this thread somehow. So, the behavior itself seems
>> incorrect. Clang tools should not be trying to find a compilation database
>> in case the command line has a `--`, but the driver fails to parse it. It
>> should be a hard failure. We also need a reliable test for this behavior
>> (with a compile_commands.json being put into a test directory or generated
>> during a test).
>>
>>
>> On Tue, Jun 27, 2017 at 3:33 AM, David Blaikie 
>> wrote:
>>
>>>
>>>
>>> On Mon, Jun 26, 2017 at 5:31 AM Serge Pavlov 
>>> wrote:
>>>
 2017-06-26 4:05 GMT+07:00 David Blaikie :

> Ah, I see now then.
>
> I have a symlink from the root of my source directory pointing to the
> compile_commands.json in my build directory.
>
> I have this so that the vim YouCompleteMe plugin (& any other clang
> tools) can find it, as they usually should, for using tools with the
> llvm/clang project...
>
> Sounds like this test is incompatible with using the tooling
> infrastructure in the llvm/clang project?
>
 Any test that relies on compilation database search can fail in such
 case. Maybe the root of the tools test could contain some special
 compile_commands.json so that the search will always end up in definite
 state?

>>>
>>> Perhaps - or maybe tools could have a parameter limiting how many parent
>>> directories to recurse up through? But yeah, dunno what the best solution
>>> would be.
>>>
>>>


>
> On Sun, Jun 25, 2017, 10:24 AM Serge Pavlov 
> wrote:
>
>> 2017-06-25 0:52 GMT+07:00 David Blaikie :
>>
>>>
>>>
>>> On Sat, Jun 24, 2017 at 10:08 AM Serge Pavlov 
>>> wrote:
>>>
 With CMAKE_EXPORT_COMPILE_COMMANDS the file compile_commands.json
 is created in the directory 
 /tools/clang/tools/extra/test/clang-tidy/Output,


>>>
>>> I'd be really surprised if this is the case - why would
>>> cmake/ninja/makefiles put the compile commands for the whole LLVM
>>> project/build in that somewhat random subdirectory?
>>>
>>
>> I was wrong, these json files were not created by cmake run but
>> appear during test run. The file created by cmake is in the build root.
>>
>>
>>>
>>>
 but the tests from 
 /llvm/tools/clang/tools/extra/test/clang-tidy
 run in the directory /tools/cl
 ang/tools/extra/test/clang-tidy, which does not contain json
 files. So the test passes successfully. Ubuntu 16.04, cmake 3.5.1.

>>>
>>> Ah, perhaps you found a compile_commands for one of the test cases,
>>> not the one generated by CMake. CMake 3.5.1 doesn't support
>>> CMAKE_EXPORT_COMPILE_COMMANDS.
>>>
>>> It was added in 3.5.2, according to the documentation:
>>> https://cmake.org/cmake/help/v3.5/variable/CM
>>> AKE_EXPORT_COMPILE_COMMANDS.html
>>>
>>>
>>
>> It was added in 2.8.5 according to documentation (
>> http://clang.llvm.org/docs/JSONCompilationDatabase.html#sup
>> ported-systems), at least the version 3.5.1 creates compilation
>> databases.
>>
>> clang-tidy tries to create compilation database from source path,
>> looking for compile_commands.json in the directory where provided source
>> file resides and in all its parent directories. If source tree is in a
>> subdirectory of build tree, then compile_commands.json in the build
>> directory would be found and the test would fail. Is it your case?
>>
>>
 Thanks,
 --Serge

 2017-06-24 9:42 GMT+07:00 David Blaikie :

> Ping (+Manuel, perhaps he's got some ideas about this, given
> background in the tooling & compilation database work, or could point 
> this
> to someone who does?)
>
>
> On Thu, Jun 15, 2017 at 10:40 AM David Blaikie 
> wrote:
>
>> https://sarcasm.github.io/notes/dev/compilation-database.htm
>> l#cmake
>>
>> If you enable the CMAKE_EXPORT_COMPILE_COMMANDS option in cmake
>> (& have a sufficiently recent cmake), then CMake will generate a
>> compile_commands.json in the root of the build tree. The test finds 
>> this &
>> fails, instead of finding no compilation database & succeeding.
>>
>> (to use this, you can then symlink from the root of the source
>> tree to point to this in your build tree - this is how I get YCM to 
>> work
>> for my LLVM builds & could work for other clang tools as well)
>>
>> On Thu, Jun 15, 2017 at 7:5

[PATCH] D34949: [refactor][rename] Use a single base class for class that finds a declaration at location and for class that searches for all occurrences of a specific declaration

2017-07-12 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.

LGTM.




Comment at: include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h:33
+: public RecursiveASTVisitor> {
+  using BaseType = RecursiveASTVisitor>;
+  const SourceManager &SM;

nit: I'd add a `private` specifier for these private members, and put it after 
the `public` section.


Repository:
  rL LLVM

https://reviews.llvm.org/D34949



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


Re: [clang-tools-extra] r303735 - Modify test so that it looks for patterns in stderr as well

2017-07-12 Thread David Blaikie via cfe-commits
Thanks all!

On Wed, Jul 12, 2017 at 7:46 AM Alexander Kornienko 
wrote:

> Done in r307661.
>
> On Mon, Jul 10, 2017 at 2:08 PM, Alexander Kornienko 
> wrote:
>
>> Benjamin has actually fixed the issue by reverting to the old behavior in 
>> r306822.
>> I'll add a test for this behavior anyway.
>>
>> On Mon, Jul 10, 2017 at 11:47 AM, Alexander Kornienko 
>> wrote:
>>
>>> Sorry, missed this thread somehow. So, the behavior itself seems
>>> incorrect. Clang tools should not be trying to find a compilation database
>>> in case the command line has a `--`, but the driver fails to parse it. It
>>> should be a hard failure. We also need a reliable test for this behavior
>>> (with a compile_commands.json being put into a test directory or generated
>>> during a test).
>>>
>>>
>>> On Tue, Jun 27, 2017 at 3:33 AM, David Blaikie 
>>> wrote:
>>>


 On Mon, Jun 26, 2017 at 5:31 AM Serge Pavlov 
 wrote:

> 2017-06-26 4:05 GMT+07:00 David Blaikie :
>
>> Ah, I see now then.
>>
>> I have a symlink from the root of my source directory pointing to the
>> compile_commands.json in my build directory.
>>
>> I have this so that the vim YouCompleteMe plugin (& any other clang
>> tools) can find it, as they usually should, for using tools with the
>> llvm/clang project...
>>
>> Sounds like this test is incompatible with using the tooling
>> infrastructure in the llvm/clang project?
>>
> Any test that relies on compilation database search can fail in such
> case. Maybe the root of the tools test could contain some special
> compile_commands.json so that the search will always end up in definite
> state?
>

 Perhaps - or maybe tools could have a parameter limiting how many
 parent directories to recurse up through? But yeah, dunno what the best
 solution would be.


>
>
>>
>> On Sun, Jun 25, 2017, 10:24 AM Serge Pavlov 
>> wrote:
>>
>>> 2017-06-25 0:52 GMT+07:00 David Blaikie :
>>>


 On Sat, Jun 24, 2017 at 10:08 AM Serge Pavlov 
 wrote:

> With CMAKE_EXPORT_COMPILE_COMMANDS the file compile_commands.json
> is created in the directory
> /tools/clang/tools/extra/test/clang-tidy/Output,
>

 I'd be really surprised if this is the case - why would
 cmake/ninja/makefiles put the compile commands for the whole LLVM
 project/build in that somewhat random subdirectory?

>>>
>>> I was wrong, these json files were not created by cmake run but
>>> appear during test run. The file created by cmake is in the build root.
>>>
>>>


> but the tests from
> /llvm/tools/clang/tools/extra/test/clang-tidy run in the
> directory /tools/clang/tools/extra/test/clang-tidy, which 
> does
> not contain json files. So the test passes successfully. Ubuntu 16.04,
> cmake 3.5.1.
>

 Ah, perhaps you found a compile_commands for one of the test cases,
 not the one generated by CMake. CMake 3.5.1 doesn't support
 CMAKE_EXPORT_COMPILE_COMMANDS.

 It was added in 3.5.2, according to the documentation:
 https://cmake.org/cmake/help/v3.5/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html


>>>
>>> It was added in 2.8.5 according to documentation (
>>> http://clang.llvm.org/docs/JSONCompilationDatabase.html#supported-systems),
>>> at least the version 3.5.1 creates compilation databases.
>>>
>>> clang-tidy tries to create compilation database from source path,
>>> looking for compile_commands.json in the directory where provided source
>>> file resides and in all its parent directories. If source tree is in a
>>> subdirectory of build tree, then compile_commands.json in the build
>>> directory would be found and the test would fail. Is it your case?
>>>
>>>
> Thanks,
> --Serge
>
> 2017-06-24 9:42 GMT+07:00 David Blaikie :
>
>> Ping (+Manuel, perhaps he's got some ideas about this, given
>> background in the tooling & compilation database work, or could 
>> point this
>> to someone who does?)
>>
>>
>> On Thu, Jun 15, 2017 at 10:40 AM David Blaikie <
>> dblai...@gmail.com> wrote:
>>
>>>
>>> https://sarcasm.github.io/notes/dev/compilation-database.html#cmake
>>>
>>> If you enable the CMAKE_EXPORT_COMPILE_COMMANDS option in cmake
>>> (& have a sufficiently recent cmake), then CMake will generate a
>>> compile_commands.json in the root of the build tree. The test finds 
>>> this &
>>> fails, instead of finding no compilation database & succeeding.
>>>
>>> (to use this, you can then symlink from the root of the source
>>>

[PATCH] D35306: [diagtool] Add the 'find-diagnostic-id' subcommand that converts a name of the diagnostic to its enum value

2017-07-12 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
Herald added a subscriber: mgorny.

The new subcommand prints out the enum value of the diagnostic. This will be 
used in a utility script that invokes clang and forces it to stop when some 
specific diagnostic is emitted (see https://reviews.llvm.org/D35175 for 
discussion).

@hintonda 
My current script only deals with one specific diagnostic (i.e. the enum name). 
I was thinking that it could be extended to support diagnostic groups (i.e. -W 
options), where it would stop at any warning from that group. This extension 
will require an addition to this patch (i.e. if you supply -Wgroupname, we will 
print out a list of diagnostic ids instead of just one id that corresponds to 
the specific diagnostic). Do you think this will be useful?


Repository:
  rL LLVM

https://reviews.llvm.org/D35306

Files:
  test/Misc/find-diagnostic-id.c
  tools/diagtool/CMakeLists.txt
  tools/diagtool/FindDiagnosticID.cpp


Index: tools/diagtool/FindDiagnosticID.cpp
===
--- /dev/null
+++ tools/diagtool/FindDiagnosticID.cpp
@@ -0,0 +1,58 @@
+//===- FindDiagnosticID.cpp - diagtool tool for finding diagnostic id 
-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "DiagTool.h"
+#include "DiagnosticNames.h"
+#include "clang/Basic/AllDiagnostics.h"
+#include "llvm/Support/CommandLine.h"
+
+DEF_DIAGTOOL("find-diagnostic-id", "Print the id of the given diagnostic",
+ FindDiagnosticID)
+
+using namespace clang;
+using namespace diagtool;
+
+static Optional
+findDiagnostic(ArrayRef Diagnostics, StringRef Name) {
+  for (const auto &Diag : Diagnostics) {
+StringRef DiagName = Diag.getName();
+if (DiagName == Name)
+  return Diag;
+  }
+  return None;
+}
+
+int FindDiagnosticID::run(unsigned int argc, char **argv,
+  llvm::raw_ostream &OS) {
+  static llvm::cl::OptionCategory FindDiagnosticIDOptions(
+  "diagtool find-diagnostic-id options");
+
+  static llvm::cl::opt DiagnosticName(
+  llvm::cl::Positional, llvm::cl::desc(""),
+  llvm::cl::Required, llvm::cl::cat(FindDiagnosticIDOptions));
+
+  std::vector Args;
+  Args.push_back("find-diagnostic-id");
+  for (const char *A : llvm::makeArrayRef(argv, argc))
+Args.push_back(A);
+
+  llvm::cl::HideUnrelatedOptions(FindDiagnosticIDOptions);
+  llvm::cl::ParseCommandLineOptions((int)Args.size(), Args.data(),
+"Diagnostic ID mapping utility");
+
+  ArrayRef AllDiagnostics = getBuiltinDiagnosticsByName();
+  Optional Diag =
+  findDiagnostic(AllDiagnostics, DiagnosticName);
+  if (!Diag) {
+llvm::errs() << "error: invalid diagnostic '" << DiagnosticName << "'\n";
+return 1;
+  }
+  OS << Diag->DiagID << "\n";
+  return 0;
+}
Index: tools/diagtool/CMakeLists.txt
===
--- tools/diagtool/CMakeLists.txt
+++ tools/diagtool/CMakeLists.txt
@@ -6,6 +6,7 @@
   diagtool_main.cpp
   DiagTool.cpp
   DiagnosticNames.cpp
+  FindDiagnosticID.cpp
   ListWarnings.cpp
   ShowEnabledWarnings.cpp
   TreeView.cpp
Index: test/Misc/find-diagnostic-id.c
===
--- /dev/null
+++ test/Misc/find-diagnostic-id.c
@@ -0,0 +1,5 @@
+// RUN: diagtool find-diagnostic-id warn_unused_variable | FileCheck %s
+// RUN: not diagtool find-diagnostic-id warn_unused_vars 2>&1 | FileCheck 
--check-prefix=ERROR %s
+
+// CHECK: {{^[0-9]+$}}
+// ERROR: error: invalid diagnostic 'warn_unused_vars'


Index: tools/diagtool/FindDiagnosticID.cpp
===
--- /dev/null
+++ tools/diagtool/FindDiagnosticID.cpp
@@ -0,0 +1,58 @@
+//===- FindDiagnosticID.cpp - diagtool tool for finding diagnostic id -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "DiagTool.h"
+#include "DiagnosticNames.h"
+#include "clang/Basic/AllDiagnostics.h"
+#include "llvm/Support/CommandLine.h"
+
+DEF_DIAGTOOL("find-diagnostic-id", "Print the id of the given diagnostic",
+ FindDiagnosticID)
+
+using namespace clang;
+using namespace diagtool;
+
+static Optional
+findDiagnostic(ArrayRef Diagnostics, StringRef Name) {
+  for (const auto &Diag : Diagnostics) {
+StringRef DiagName = Diag.getName();
+if (DiagName == Name)
+  return Diag;
+  }
+  return None;
+}
+
+int FindDiagnosticID::run(unsigned int argc, char **argv,
+  llvm::raw_ostream &OS) {
+  static llvm::cl::OptionCateg

[PATCH] D34275: [analyzer] Re-implemente current virtual calls checker in a path-sensitive way

2017-07-12 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Thank you! I think we can start to run this check on real world code bases and 
evaluate the results.




Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:41
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+  void ChangeMaps(bool IsBeginFunction, CheckerContext &C) const;
+  void ReportBug(const char *Msg, bool PureError, const MemRegion *Reg,

Function names should start with a lower case letter. These two could be 
private. I'd prefer another name for this function like 
`registerCtorDtorCallInState`.



Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:42
+  void ChangeMaps(bool IsBeginFunction, CheckerContext &C) const;
+  void ReportBug(const char *Msg, bool PureError, const MemRegion *Reg,
+ CheckerContext &C) const;

Use `StringRef` instead of `const char *`.  It is more idiomatic in LLVM code. 



Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:179
+} else {
+  const char *Msg = "Call to virtual function during construction";
+  ReportBug(Msg, false, Reg, C);

I'd omit the `Msg` local variable. After that, we do not need to use braces for 
single statement blocks.



Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:210
+const MemRegion *Reg = ThiSVal.getAsRegion();
+if (IsBeginFunction) {
+  State = State->set(Reg, true);

Braces for single statement blocks. 



Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:224
+const MemRegion *Reg = ThiSVal.getAsRegion();
+if (IsBeginFunction) {
+  State = State->set(Reg, true);

Braces for single statement blocks. 



Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:238
+  ExplodedNode *N;
+  if (PureError) {
+N = C.generateErrorNode();

Do not use braces for single statement blocks. 


https://reviews.llvm.org/D34275



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


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Some small comments, otherwise looks good.




Comment at: lib/Format/TokenAnnotator.cpp:1706
+if (NextNonCommentLine && CommentLine) {
+  bool UpdateLevel = NextNonCommentLine->First->NewlinesBefore <= 1 &&
+ NextNonCommentLine->First->OriginalColumn ==

Add a comment a long the lines of:

  // If the comment is currently aligned with the line immediately following it,
  // that's probably intentional and we should keep it.

And maybe rename s/UpdateLevel/AlignedWithNextLine/



Comment at: unittests/Format/FormatTest.cpp:855
+"  }\n"
+"});", getLLVMStyle()));
   verifyFormat("switch (a) {\n"

Please format this with clang-format.


https://reviews.llvm.org/D35296



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


[PATCH] D31700: [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 106219.
hokein marked an inline comment as done.
hokein added a comment.
Herald added subscribers: xazax.hun, JDevlieghere.

Support more cases.


https://reviews.llvm.org/D31700

Files:
  clang-tidy/google/AvoidCStyleCastsCheck.cpp
  test/clang-tidy/google-readability-casting.cpp


Index: test/clang-tidy/google-readability-casting.cpp
===
--- test/clang-tidy/google-readability-casting.cpp
+++ test/clang-tidy/google-readability-casting.cpp
@@ -85,6 +85,22 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   // CHECK-FIXES: b1 = (const int&)b;
 
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
   Y *pB = (Y*)pX;
   // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   Y &rB = (Y&)*pX;
@@ -114,6 +130,14 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  e = e;
 
+  e = (Enum)   e;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = e;
+
+  e = (Enum)   (e);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = (e);
+
   static const int kZero = 0;
   (int)kZero;
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type
Index: clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -58,10 +58,9 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
-  auto ParenRange = CharSourceRange::getTokenRange(CastExpr->getLParenLoc(),
-   CastExpr->getRParenLoc());
+
   // Ignore casts in macros.
-  if (ParenRange.getBegin().isMacroID() || ParenRange.getEnd().isMacroID())
+  if (CastExpr->getExprLoc().isMacroID())
 return;
 
   // Casting to void is an idiomatic way to mute "unused variable" and similar
@@ -82,6 +81,9 @@
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
+  auto ReplaceRange = CharSourceRange::getCharRange(
+  CastExpr->getLParenLoc(), 
CastExpr->getSubExprAsWritten()->getLocStart());
+
   bool FnToFnCast =
   isFunction(SourceTypeAsWritten) && isFunction(DestTypeAsWritten);
 
@@ -92,7 +94,7 @@
 // pointer/reference types.
 if (SourceTypeAsWritten == DestTypeAsWritten) {
   diag(CastExpr->getLocStart(), "redundant cast to the same type")
-  << FixItHint::CreateRemoval(ParenRange);
+  << FixItHint::CreateRemoval(ReplaceRange);
   return;
 }
   }
@@ -136,7 +138,7 @@
  getLangOpts()),
   ")");
 }
-Diag << FixItHint::CreateReplacement(ParenRange, CastText);
+Diag << FixItHint::CreateReplacement(ReplaceRange, CastText);
   };
   auto ReplaceWithNamedCast = [&](StringRef CastType) {
 Diag << CastType;


Index: test/clang-tidy/google-readability-casting.cpp
===
--- test/clang-tidy/google-readability-casting.cpp
+++ test/clang-tidy/google-readability-casting.cpp
@@ -85,6 +85,22 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast/const_cast/reinterpret_cast [
   // CHECK-FIXES: b1 = (const int&)b;
 
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
   Y *pB = (Y*)pX;
   // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use static_cast/const_cast/reinterpret_cast [
   Y &rB = (Y&)*pX;
@@ -114,6 +130,14 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  e = e;
 
+  e = (Enum

[PATCH] D31700: [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

> You might want to commit this at some point ;]

I somewhat forgot this minor patch.




Comment at: clang-tidy/google/AvoidCStyleCastsCheck.cpp:139
   ")");
+  ReplaceRange = CharSourceRange::getCharRange(CastExpr->getLParenLoc(),
+   SubExpr->getLocStart());

alexfh wrote:
> Why is this only done on non-parenthesized expressions? Will `(int)  (b)` 
> turn into `static_cast  (b)` as well?
Good point, I have updated the patch to cover more cases. Please take a look 
again.


https://reviews.llvm.org/D31700



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


[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 106220.
krasimir marked 2 inline comments as done.
krasimir added a comment.

- Address review comments


https://reviews.llvm.org/D35296

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestComments.cpp

Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,70 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  // Keep the current level if the comment was originally not aligned with
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Keep the current level if there is an empty line between the comment and
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Align with the preprocessor directive if the comment was originally aligned
+  // with the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"/* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   EXPECT_EQ("/* This is a long\n"
 " * comment that\n"
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -825,12 +825,35 @@
"  case A:\n"
"f();\n"
"break;\n"
-   "  // On B:\n"
+   "// fallthrough\n"
"  case B:\n"
"g();\n"
"break;\n"
"  }\n"
"});");
+  EXPECT_EQ("DEBUG({\n"
+"  switch (x) {\n"
+"  case A:\n"
+"f();\n"
+"break;\n"
+"  // On B:\n"
+"  case B:\n"
+"g();\n"
+"break;\n"
+"  }\n"
+"});",
+format("DEBUG({\n"
+   "  switch (x) {\n"
+   "  case A:\n"
+   "f();\n"
+   "break;\n"
+   "  // On B:\n"
+   "  case B:\n"
+   "g();\n"
+   "break;\n"
+   "  }\n"
+   "});",
+   getLLVMStyle()));
   verifyFormat("switch (a) {\n"
"case (b):\n"
"  return;\n"
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,26 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  // If the comment is currently aligned with the line immediately following
+  // it, that's probably intentional and we should keep it.
+  bool AlignedWithNextLine =
+  NextNonCommentLine->First->NewlinesBefore <= 1 &&
+  NextNonCommentLine->First->OriginalColumn ==
+  (*I)->F

[PATCH] D32478: [clang-format] Fix AlignOperands when BreakBeforeBinaryOperators is set

2017-07-12 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 106221.
Typz marked 3 inline comments as done.
Typz added a comment.

Rename option to AlignAfterOperator


https://reviews.llvm.org/D32478

Files:
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  lib/Format/Format.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestJS.cpp

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -102,7 +102,7 @@
   verifyFormat("var x = a() in\n"
".aa.aa;");
   FormatStyle Style = getGoogleJSStyleWithColumns(80);
-  Style.AlignOperands = true;
+  Style.AlignOperands = FormatStyle::OAS_Align;
   verifyFormat("var x = a() in\n"
".aa.aa;",
Style);
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -2702,6 +2702,9 @@
"  > c) {\n"
"}",
Style);
+  verifyFormat("return a\n"
+   "   && bbb;",
+   Style);
   verifyFormat("return (a)\n"
"   // comment\n"
"   + b;",
@@ -2730,11 +2733,103 @@
 
   Style.ColumnLimit = 60;
   verifyFormat("zz\n"
-   "= b\n"
+   "= \n"
"  >> (aa);",
Style);
 }
 
+TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+  Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
+
+  verifyFormat("bool value = a\n"
+   "   + a\n"
+   "   + a\n"
+   "  == a\n"
+   " * b\n"
+   " + b\n"
+   "  && a\n"
+   " * a\n"
+   " > c;",
+   Style);
+  verifyFormat("if (a\n"
+   "* \n"
+   "+ aa\n"
+   "== bbb) {\n}",
+   Style);
+  verifyFormat("if (a\n"
+   "+ \n"
+   "  * aa\n"
+   "== bbb) {\n}",
+   Style);
+  verifyFormat("if (a\n"
+   "== \n"
+   "   * aa\n"
+   "   + bbb) {\n}",
+   Style);
+  verifyFormat("if () {\n"
+   "} else if (a\n"
+   "   && b // break\n"
+   "  > c) {\n"
+   "}",
+   Style);
+  verifyFormat("return a\n"
+   "&& bbb;",
+   Style);
+  verifyFormat("return (a)\n"
+   " // comment\n"
+   " + b;",
+   Style);
+  verifyFormat(
+  "int aa = aa\n"
+  "   * bbb\n"
+  "   + cc;",
+  Style);
+
+  verifyFormat("a\n"
+   "=  + ;",
+   Style);
+
+  verifyFormat("return boost::fusion::at_c<0>().second\n"
+   "== boost::fusion::at_c<1>().second;",
+   Style);
+
+  Style.ColumnLimit = 60;
+  verifyFormat("z\n"
+   "= \n"
+   "   >> aaa

[PATCH] D35296: [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307795: [clang-format] Keep level of comment before an empty 
line (authored by krasimir).

Repository:
  rL LLVM

https://reviews.llvm.org/D35296

Files:
  cfe/trunk/lib/Format/TokenAnnotator.cpp
  cfe/trunk/unittests/Format/FormatTest.cpp
  cfe/trunk/unittests/Format/FormatTestComments.cpp

Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -1694,17 +1694,26 @@
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  // If the comment is currently aligned with the line immediately following
+  // it, that's probably intentional and we should keep it.
+  bool AlignedWithNextLine =
+  NextNonCommentLine->First->NewlinesBefore <= 1 &&
+  NextNonCommentLine->First->OriginalColumn ==
+  (*I)->First->OriginalColumn;
+  if (AlignedWithNextLine)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -825,12 +825,35 @@
"  case A:\n"
"f();\n"
"break;\n"
-   "  // On B:\n"
+   "// fallthrough\n"
"  case B:\n"
"g();\n"
"break;\n"
"  }\n"
"});");
+  EXPECT_EQ("DEBUG({\n"
+"  switch (x) {\n"
+"  case A:\n"
+"f();\n"
+"break;\n"
+"  // On B:\n"
+"  case B:\n"
+"g();\n"
+"break;\n"
+"  }\n"
+"});",
+format("DEBUG({\n"
+   "  switch (x) {\n"
+   "  case A:\n"
+   "f();\n"
+   "break;\n"
+   "  // On B:\n"
+   "  case B:\n"
+   "g();\n"
+   "break;\n"
+   "  }\n"
+   "});",
+   getLLVMStyle()));
   verifyFormat("switch (a) {\n"
"case (b):\n"
"  return;\n"
Index: cfe/trunk/unittests/Format/FormatTestComments.cpp
===
--- cfe/trunk/unittests/Format/FormatTestComments.cpp
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp
@@ -805,6 +805,70 @@
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  // Keep the current level if the comment was originally not aligned with
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Keep the current level if there is an empty line between the comment and
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "/* comment */\n"
+   "\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  // Align with the preprocessor directive if the comment was originally aligned
+  // with the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int

r307795 - [clang-format] Keep level of comment before an empty line

2017-07-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Jul 12 08:21:43 2017
New Revision: 307795

URL: http://llvm.org/viewvc/llvm-project?rev=307795&view=rev
Log:
[clang-format] Keep level of comment before an empty line

Summary:
This patch fixes bug https://bugs.llvm.org/show_bug.cgi?id=3313: a comment line
was aligned with the next #ifdef even in the presence of an empty line between
them.

Reviewers: djasper, klimek

Reviewed By: djasper

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=307795&r1=307794&r2=307795&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Jul 12 08:21:43 2017
@@ -1694,17 +1694,26 @@ void TokenAnnotator::setCommentLineLevel
   for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(),
   E = Lines.rend();
I != E; ++I) {
-bool CommentLine = (*I)->First;
+bool CommentLine = true;
 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
   if (!Tok->is(tok::comment)) {
 CommentLine = false;
 break;
   }
 }
-if (NextNonCommentLine && CommentLine)
-  (*I)->Level = NextNonCommentLine->Level;
-else
+
+if (NextNonCommentLine && CommentLine) {
+  // If the comment is currently aligned with the line immediately 
following
+  // it, that's probably intentional and we should keep it.
+  bool AlignedWithNextLine =
+  NextNonCommentLine->First->NewlinesBefore <= 1 &&
+  NextNonCommentLine->First->OriginalColumn ==
+  (*I)->First->OriginalColumn;
+  if (AlignedWithNextLine)
+(*I)->Level = NextNonCommentLine->Level;
+} else {
   NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
+}
 
 setCommentLineLevels((*I)->Children);
   }

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=307795&r1=307794&r2=307795&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Jul 12 08:21:43 2017
@@ -825,12 +825,35 @@ TEST_F(FormatTest, FormatsSwitchStatemen
"  case A:\n"
"f();\n"
"break;\n"
-   "  // On B:\n"
+   "// fallthrough\n"
"  case B:\n"
"g();\n"
"break;\n"
"  }\n"
"});");
+  EXPECT_EQ("DEBUG({\n"
+"  switch (x) {\n"
+"  case A:\n"
+"f();\n"
+"break;\n"
+"  // On B:\n"
+"  case B:\n"
+"g();\n"
+"break;\n"
+"  }\n"
+"});",
+format("DEBUG({\n"
+   "  switch (x) {\n"
+   "  case A:\n"
+   "f();\n"
+   "break;\n"
+   "  // On B:\n"
+   "  case B:\n"
+   "g();\n"
+   "break;\n"
+   "  }\n"
+   "});",
+   getLLVMStyle()));
   verifyFormat("switch (a) {\n"
"case (b):\n"
"  return;\n"

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=307795&r1=307794&r2=307795&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp Wed Jul 12 08:21:43 2017
@@ -805,6 +805,70 @@ TEST_F(FormatTestComments, ParsesComment
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, KeepsLevelOfCommentBeforePPDirective) {
+  // Keep the current level if the comment was originally not aligned with
+  // the preprocessor directive.
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"#ifdef A\n"
+"  int j;\n"
+"}",
+format("void f() {\n"
+   "  int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "}"));
+
+  EXPECT_EQ("void f() {\n"
+"  int i;\n"
+"  /* comment */\n"
+"\n"
+"#ifdef A\n"
+"  int

[PATCH] D35051: [clang-tidy] Add bugprone-undefined-memory-manipulation check.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh requested changes to this revision.
alexfh added inline comments.
This revision now requires changes to proceed.



Comment at: clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp:22
+AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
+  return !(Node.isTriviallyCopyable());
+}

nit: No need for the parentheses.



Comment at: clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp:39
+  // Check whether source object is not TriviallyCopyable.
+  // Only applicable to memcpy() and memmove().
+  Finder->addMatcher(

What about `memset`?



Comment at: test/clang-tidy/bugprone-undefined-memory-manipulation.cpp:34
+struct Destruct {
+  ~Destruct() {};
+};

Remove stray semicolons after closing braces of function bodies.


https://reviews.llvm.org/D35051



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


[PATCH] D32700: [clang-tidy] Add bugprone-suspicious-memset-usage check.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp:127-130
+SourceRange LHSRange = FillChar->getSourceRange();
+SourceRange RHSRange = ByteCount->getSourceRange();
+StringRef RHSString = getAsString(Result, RHSRange);
+StringRef LHSString = getAsString(Result, LHSRange);

It looks like this can be replaced with `clang::tooling::fixit::getText()` or 
even `createReplacement`.


https://reviews.llvm.org/D32700



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


Re: [clang-tools-extra] r307701 - Fix clang-tidy diagnostic.cpp test on Windows

2017-07-12 Thread Alexander Kornienko via cfe-commits
Thank you!

On Tue, Jul 11, 2017 at 10:22 PM, Reid Kleckner via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: rnk
> Date: Tue Jul 11 13:22:17 2017
> New Revision: 307701
>
> URL: http://llvm.org/viewvc/llvm-project?rev=307701&view=rev
> Log:
> Fix clang-tidy diagnostic.cpp test on Windows
>
> Modified:
> clang-tools-extra/trunk/test/clang-tidy/diagnostic.cpp
>
> Modified: clang-tools-extra/trunk/test/clang-tidy/diagnostic.cpp
> URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/
> trunk/test/clang-tidy/diagnostic.cpp?rev=307701&r1=
> 307700&r2=307701&view=diff
> 
> ==
> --- clang-tools-extra/trunk/test/clang-tidy/diagnostic.cpp (original)
> +++ clang-tools-extra/trunk/test/clang-tidy/diagnostic.cpp Tue Jul 11
> 13:22:17 2017
> @@ -13,7 +13,7 @@
>  // use it after failing to parse commands from the command line:
>  //
>  // RUN: mkdir -p %T/diagnostics/
> -// RUN: echo '[{"directory": "%T/diagnostics/","command": "clang++
> -fan-option-from-compilation-database -c %T/diagnostics/input.cpp",
> "file": "%T/diagnostics/input.cpp"}]' > %T/diagnostics/compile_
> commands.json
> +// RUN: echo '[{"directory": "%/T/diagnostics/","command": "clang++
> -fan-option-from-compilation-database -c %/T/diagnostics/input.cpp",
> "file": "%/T/diagnostics/input.cpp"}]' > %T/diagnostics/compile_
> commands.json
>  // RUN: cat %s > %T/diagnostics/input.cpp
>  // RUN: clang-tidy -checks='-*,modernize-use-override'
> %T/diagnostics/nonexistent.cpp -- 2>&1 | FileCheck -check-prefix=CHECK1
> -implicit-check-not='{{warning:|error:}}' %s
>  // RUN: clang-tidy 
> -checks='-*,clang-diagnostic-*,google-explicit-constructor'
> %T/diagnostics/input.cpp -- -fan-unknown-option 2>&1 | FileCheck
> -check-prefix=CHECK2 -implicit-check-not='{{warning:|error:}}' %s
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D35306: [diagtool] Add the 'find-diagnostic-id' subcommand that converts a name of the diagnostic to its enum value

2017-07-12 Thread don hinton via Phabricator via cfe-commits
hintonda accepted this revision.
hintonda added a comment.
This revision is now accepted and ready to land.

LGTM.

Category ids' might be useful, but I'd wait until someone actually needs them.


Repository:
  rL LLVM

https://reviews.llvm.org/D35306



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


[PATCH] D35051: [clang-tidy] Add bugprone-undefined-memory-manipulation check.

2017-07-12 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs updated this revision to Diff 106234.
rnkovacs added a comment.
Herald added a subscriber: baloghadamsoftware.

Removed redundant parens and stray semicolons.


https://reviews.llvm.org/D35051

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp
  clang-tidy/bugprone/UndefinedMemoryManipulationCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-undefined-memory-manipulation.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-undefined-memory-manipulation.cpp

Index: test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-undefined-memory-manipulation.cpp
@@ -0,0 +1,178 @@
+// RUN: %check_clang_tidy %s bugprone-undefined-memory-manipulation %t
+
+void *memset(void *, int, __SIZE_TYPE__);
+void *memcpy(void *, const void *, __SIZE_TYPE__);
+void *memmove(void *, const void *, __SIZE_TYPE__);
+
+namespace std {
+using ::memcpy;
+using ::memmove;
+using ::memset;
+}
+
+// TriviallyCopyable types:
+struct Plain {
+  int n;
+};
+
+enum E {
+  X,
+  Y,
+  Z
+};
+
+struct Base {
+  float b;
+};
+
+struct Derived : Base {
+  bool d;
+};
+
+// not TriviallyCopyable types:
+struct Destruct {
+  ~Destruct() {}
+};
+
+struct Copy {
+  Copy() {}
+  Copy(const Copy &) {}
+};
+
+struct Move {
+  Move() {}
+  Move(Move &&) {}
+};
+
+struct VirtualFunc {
+  virtual void f() {}
+};
+
+struct VirtualBase : virtual Base {
+  int vb;
+};
+
+template 
+void memset_temp(T *b) {
+  memset(b, 0, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+template 
+void memcpy_temp(S *a, T *b) {
+  memcpy(a, b, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+template 
+void memmove_temp(S *a, T *b) {
+  memmove(a, b, sizeof(T));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+}
+
+void notTriviallyCopyable() {
+  Plain p; // TriviallyCopyable for variety
+  Destruct d;
+  Copy c;
+  Move m;
+  VirtualFunc vf;
+  VirtualBase vb;
+
+  memset(&vf, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memset(&d, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memset(&c, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  std::memset(&m, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  ::memset(&vb, 0, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+
+  memcpy(&p, &vf, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memcpy(&p, &d, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memcpy(&c, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  std::memcpy(&m, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  ::memcpy(&vb, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+
+  memmove(&vf, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memmove(&d, &p, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, destination object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  memmove(&p, &c, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  std::memmove(&p, &m, sizeof(int));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: undefined behavior, source object is not TriviallyCopyable [bugprone-undefined-memory-manipulation]
+  ::me

[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-07-12 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer updated this revision to Diff 106228.
SjoerdMeijer added a comment.

This fixes:

- type mangling for `_Float16` (approved here: 
https://github.com/itanium-cxx-abi/cxx-abi/pull/22, but not yet committed. )
- removed the argument promotion for `_Float16` that I added because it turns 
out that it does not apply to `_Float16` but only to the standard float types.
- the nit in the comments of the literal parser.


https://reviews.llvm.org/D33719

Files:
  include/clang-c/Index.h
  include/clang/AST/ASTContext.h
  include/clang/AST/BuiltinTypes.def
  include/clang/Basic/Specifiers.h
  include/clang/Basic/TokenKinds.def
  include/clang/Lex/LiteralSupport.h
  include/clang/Sema/DeclSpec.h
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/ASTContext.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/MicrosoftMangle.cpp
  lib/AST/NSAPI.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/Type.cpp
  lib/AST/TypeLoc.cpp
  lib/Analysis/PrintfFormatString.cpp
  lib/CodeGen/CGDebugInfo.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenTypes.cpp
  lib/CodeGen/ItaniumCXXABI.cpp
  lib/Format/FormatToken.cpp
  lib/Index/USRGeneration.cpp
  lib/Lex/LiteralSupport.cpp
  lib/Parse/ParseDecl.cpp
  lib/Parse/ParseExpr.cpp
  lib/Parse/ParseExprCXX.cpp
  lib/Parse/ParseTentative.cpp
  lib/Sema/DeclSpec.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaTemplateVariadic.cpp
  lib/Sema/SemaType.cpp
  lib/Serialization/ASTCommon.cpp
  lib/Serialization/ASTReader.cpp
  test/CodeGenCXX/float16-declarations.cpp
  test/Frontend/float16.cpp
  test/Lexer/half-literal.cpp
  tools/libclang/CXType.cpp

Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -53,6 +53,7 @@
 BTCASE(Float);
 BTCASE(Double);
 BTCASE(LongDouble);
+BTCASE(Float16);
 BTCASE(Float128);
 BTCASE(NullPtr);
 BTCASE(Overload);
@@ -520,7 +521,7 @@
 TKIND(Char_U);
 TKIND(UChar);
 TKIND(Char16);
-TKIND(Char32);  
+TKIND(Char32);
 TKIND(UShort);
 TKIND(UInt);
 TKIND(ULong);
@@ -538,6 +539,7 @@
 TKIND(Float);
 TKIND(Double);
 TKIND(LongDouble);
+TKIND(Float16);
 TKIND(Float128);
 TKIND(NullPtr);
 TKIND(Overload);
Index: test/Lexer/half-literal.cpp
===
--- test/Lexer/half-literal.cpp
+++ test/Lexer/half-literal.cpp
@@ -1,3 +1,6 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -pedantic %s
 float a = 1.0h; // expected-error{{invalid suffix 'h' on floating constant}}
 float b = 1.0H; // expected-error{{invalid suffix 'H' on floating constant}}
+
+_Float16 c = 1.f166; // expected-error{{invalid suffix 'f166' on floating constant}}
+_Float16 d = 1.f1;   // expected-error{{invalid suffix 'f1' on floating constant}}
Index: test/Frontend/float16.cpp
===
--- /dev/null
+++ test/Frontend/float16.cpp
@@ -0,0 +1,299 @@
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -ast-dump -fnative-half-type %s | FileCheck %s --check-prefix=CHECK-NATIVE
+
+/*  Various contexts where type _Float16 can appear. */
+
+/*  Namespace */
+namespace {
+  _Float16 f1n;
+  _Float16 f2n = 33.f16;
+  _Float16 arr1n[10];
+  _Float16 arr2n[] = { 1.2, 3.0, 3.e4 };
+  const volatile _Float16 func1n(const _Float16 &arg) {
+return arg + f2n + arr1n[4] - arr2n[1];
+  }
+}
+
+//CHECK: |-NamespaceDecl
+//CHECK: | |-VarDecl {{.*}} f1n '_Float16'
+//CHECK: | |-VarDecl {{.*}} f2n '_Float16' cinit
+//CHECK: | | `-FloatingLiteral {{.*}} '_Float16' 3.30e+01
+//CHECK: | |-VarDecl {{.*}} arr1n '_Float16 [10]'
+//CHECK: | |-VarDecl {{.*}} arr2n '_Float16 [3]' cinit
+//CHECK: | | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 3.00e+00
+//CHECK: | |   `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | | `-FloatingLiteral {{.*}} 'double' 3.00e+04
+//CHECK: | `-FunctionDecl {{.*}} func1n 'const volatile _Float16 (const _Float16 &)'
+
+/* File */
+_Float16 f1f;
+_Float16 f2f = 32.4;
+_Float16 arr1f[10];
+_Float16 arr2f[] = { -1.2, -3.0, -3.e4 };
+_Float16 func1f(_Float16 arg);
+
+//CHECK: |-VarDecl {{.*}} f1f '_Float16'
+//CHECK: |-VarDecl {{.*}} f2f '_Float16' cinit
+//CHECK: | `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   `-FloatingLiteral {{.*}} 'double' 3.24e+01
+//CHECK: |-VarDecl {{.*}} arr1f '_Float16 [10]'
+//CHECK: |-VarDecl {{.*}} arr2f '_Float16 [3]' cinit
+//CHECK: | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   | `-UnaryOperator {{.*}} 'double' prefix '-'
+//CHECK: |   |   `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: |   |-ImplicitCastExpr {{.*

[PATCH] D35051: [clang-tidy] Add bugprone-undefined-memory-manipulation check.

2017-07-12 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs marked 2 inline comments as done.
rnkovacs added inline comments.



Comment at: clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp:39
+  // Check whether source object is not TriviallyCopyable.
+  // Only applicable to memcpy() and memmove().
+  Finder->addMatcher(

alexfh wrote:
> What about `memset`?
`memset` has a bit different signature than the other two. It has a fill value 
as its second argument instead of a source object.


https://reviews.llvm.org/D35051



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


[PATCH] D35051: [clang-tidy] Add bugprone-undefined-memory-manipulation check.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

LG




Comment at: clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp:39
+  // Check whether source object is not TriviallyCopyable.
+  // Only applicable to memcpy() and memmove().
+  Finder->addMatcher(

rnkovacs wrote:
> alexfh wrote:
> > What about `memset`?
> `memset` has a bit different signature than the other two. It has a fill 
> value as its second argument instead of a source object.
Ah, now I get it. We're inspecting the second argument here.


https://reviews.llvm.org/D35051



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


[PATCH] D31700: [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.

LG. Thanks!


https://reviews.llvm.org/D31700



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


[PATCH] D35118: [AArch64] Add support for handling the +sve target feature

2017-07-12 Thread Renato Golin via Phabricator via cfe-commits
rengolin added a reviewer: jmolloy.
rengolin added a subscriber: jmolloy.
rengolin added a comment.

@jmolloy Can you check this change, please?




Comment at: lib/Basic/Targets.cpp:6245
   enum FPUModeEnum {
-FPUMode,
-NeonMode
+NeonMode = (1 << 0),
+SveMode = (1 << 1)

aemerson wrote:
> rengolin wrote:
> > Is there any AArch64 arch without SIMD?
> > 
> > Anyway, that seems deliberate, @t.p.northover any idea?
> SIMD support can be disabled with +nosimd. This change doesn't affect how 
> that works.
The commit that introduced this (by James) states: "Allow the disabling of NEON 
and crypto instructions."

I wouldn't remove the FPUMode as is.

It's also surprising that this passes the test that James updated on the same 
commit. Maybe the tests weren't good enough?


Repository:
  rL LLVM

https://reviews.llvm.org/D35118



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


[PATCH] D35230: [clang] buildFixItInsertionLine should use Hints of the same FID and LineNo

2017-07-12 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307809: [clang] buildFixItInsertionLine should use Hints of 
the same FID and LineNo (authored by chh).

Changed prior to commit:
  https://reviews.llvm.org/D35230?vs=105937&id=106240#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35230

Files:
  cfe/trunk/lib/Frontend/TextDiagnostic.cpp


Index: cfe/trunk/lib/Frontend/TextDiagnostic.cpp
===
--- cfe/trunk/lib/Frontend/TextDiagnostic.cpp
+++ cfe/trunk/lib/Frontend/TextDiagnostic.cpp
@@ -1052,7 +1052,8 @@
   std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
 }
 
-static std::string buildFixItInsertionLine(unsigned LineNo,
+static std::string buildFixItInsertionLine(FileID FID,
+   unsigned LineNo,
const SourceColumnMap &map,
ArrayRef Hints,
const SourceManager &SM,
@@ -1069,7 +1070,8 @@
   // code contains no newlines and is on the same line as the caret.
   std::pair HintLocInfo
 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
-  if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
+  if (FID == HintLocInfo.first &&
+  LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
   StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) 
{
 // Insert the new code into the line just below the code
 // that the user wrote.
@@ -1105,9 +1107,6 @@
 
 PrevHintEndCol =
   HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
-  } else {
-FixItInsertionLine.clear();
-break;
   }
 }
   }
@@ -1222,7 +1221,7 @@
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
-LineNo, sourceColMap, Hints, SM, DiagOpts.get());
+FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
 
 // If the source line is too long for our terminal, select only the
 // "interesting" source region within that line.


Index: cfe/trunk/lib/Frontend/TextDiagnostic.cpp
===
--- cfe/trunk/lib/Frontend/TextDiagnostic.cpp
+++ cfe/trunk/lib/Frontend/TextDiagnostic.cpp
@@ -1052,7 +1052,8 @@
   std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
 }
 
-static std::string buildFixItInsertionLine(unsigned LineNo,
+static std::string buildFixItInsertionLine(FileID FID,
+   unsigned LineNo,
const SourceColumnMap &map,
ArrayRef Hints,
const SourceManager &SM,
@@ -1069,7 +1070,8 @@
   // code contains no newlines and is on the same line as the caret.
   std::pair HintLocInfo
 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
-  if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
+  if (FID == HintLocInfo.first &&
+  LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
   StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
 // Insert the new code into the line just below the code
 // that the user wrote.
@@ -1105,9 +1107,6 @@
 
 PrevHintEndCol =
   HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
-  } else {
-FixItInsertionLine.clear();
-break;
   }
 }
   }
@@ -1222,7 +1221,7 @@
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
-LineNo, sourceColMap, Hints, SM, DiagOpts.get());
+FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
 
 // If the source line is too long for our terminal, select only the
 // "interesting" source region within that line.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r307809 - [clang] buildFixItInsertionLine should use Hints of the same FID and LineNo

2017-07-12 Thread Chih-Hung Hsieh via cfe-commits
Author: chh
Date: Wed Jul 12 09:25:40 2017
New Revision: 307809

URL: http://llvm.org/viewvc/llvm-project?rev=307809&view=rev
Log:
[clang] buildFixItInsertionLine should use Hints of the same FID and LineNo

Fix bug https://bugs.llvm.org/show_bug.cgi?id=33734

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

Modified:
cfe/trunk/lib/Frontend/TextDiagnostic.cpp

Modified: cfe/trunk/lib/Frontend/TextDiagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/TextDiagnostic.cpp?rev=307809&r1=307808&r2=307809&view=diff
==
--- cfe/trunk/lib/Frontend/TextDiagnostic.cpp (original)
+++ cfe/trunk/lib/Frontend/TextDiagnostic.cpp Wed Jul 12 09:25:40 2017
@@ -1052,7 +1052,8 @@ static void highlightRange(const CharSou
   std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
 }
 
-static std::string buildFixItInsertionLine(unsigned LineNo,
+static std::string buildFixItInsertionLine(FileID FID,
+   unsigned LineNo,
const SourceColumnMap &map,
ArrayRef Hints,
const SourceManager &SM,
@@ -1069,7 +1070,8 @@ static std::string buildFixItInsertionLi
   // code contains no newlines and is on the same line as the caret.
   std::pair HintLocInfo
 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
-  if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
+  if (FID == HintLocInfo.first &&
+  LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
   StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) 
{
 // Insert the new code into the line just below the code
 // that the user wrote.
@@ -1105,9 +1107,6 @@ static std::string buildFixItInsertionLi
 
 PrevHintEndCol =
   HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
-  } else {
-FixItInsertionLine.clear();
-break;
   }
 }
   }
@@ -1222,7 +1221,7 @@ void TextDiagnostic::emitSnippetAndCaret
 }
 
 std::string FixItInsertionLine = buildFixItInsertionLine(
-LineNo, sourceColMap, Hints, SM, DiagOpts.get());
+FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
 
 // If the source line is too long for our terminal, select only the
 // "interesting" source region within that line.


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


[clang-tools-extra] r307810 - [clang-tidy] add regression test to performance-unnecessary-value-param

2017-07-12 Thread Chih-Hung Hsieh via cfe-commits
Author: chh
Date: Wed Jul 12 09:27:00 2017
New Revision: 307810

URL: http://llvm.org/viewvc/llvm-project?rev=307810&view=rev
Log:
[clang-tidy] add regression test to performance-unnecessary-value-param

This test shows the problem in https://bugs.llvm.org/show_bug.cgi?id=33734

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

Added:

clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/

clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h

clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h

clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp

Added: 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h?rev=307810&view=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
 Wed Jul 12 09:27:00 2017
@@ -0,0 +1,15 @@
+// struct ABC is expensive to copy and should be
+// passed as a const referece.
+struct ABC {
+  ABC(const ABC&);
+  int get(int) const;
+};
+
+
+int f1(int n,  const ABC& v1,   const ABC& v2); // line 9
+
+int f1(int n, ABC v1); // line 11
+
+
+
+int f2(int n,   const ABC& v2); // line 15

Added: 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h?rev=307810&view=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
 Wed Jul 12 09:27:00 2017
@@ -0,0 +1,15 @@
+// struct ABC is expensive to copy and should be
+// passed as a const referece.
+struct ABC {
+  ABC(const ABC&);
+  int get(int) const;
+};
+
+
+int f1(int n,  ABC v1,   ABC v2); // line 9
+
+int f1(int n, ABC v1); // line 11
+
+
+
+int f2(int n,   ABC v2); // line 15

Added: 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp?rev=307810&view=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
 Wed Jul 12 09:27:00 2017
@@ -0,0 +1,18 @@
+// RUN: cp %S/Inputs/performance-unnecessary-value-param/header.h %T/header.h
+// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t -- -- 
-std=c++11 -I %T
+// RUN: diff %T/header.h 
%S/Inputs/performance-unnecessary-value-param/header-fixed.h
+
+#include "header.h"
+
+
+
+int f1(int n, ABC v1, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v1' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-MESSAGES: [[@LINE-2]]:27: warning: the parameter 'v2' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f1(int n, const ABC& v1, const ABC& v2) {
+  return v1.get(n) + v2.get(n);
+}
+int f2(int n, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v2' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f2(int n, const ABC& v2) {
+}


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


[PATCH] D35225: [clang-tidy] add regression test to performance-unnecessary-value-param

2017-07-12 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307810: [clang-tidy] add regression test to 
performance-unnecessary-value-param (authored by chh).

Changed prior to commit:
  https://reviews.llvm.org/D35225?vs=106064&id=106241#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35225

Files:
  
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
  
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
  
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp


Index: 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
===
--- 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
+++ 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
@@ -0,0 +1,18 @@
+// RUN: cp %S/Inputs/performance-unnecessary-value-param/header.h %T/header.h
+// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t -- -- 
-std=c++11 -I %T
+// RUN: diff %T/header.h 
%S/Inputs/performance-unnecessary-value-param/header-fixed.h
+
+#include "header.h"
+
+
+
+int f1(int n, ABC v1, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v1' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-MESSAGES: [[@LINE-2]]:27: warning: the parameter 'v2' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f1(int n, const ABC& v1, const ABC& v2) {
+  return v1.get(n) + v2.get(n);
+}
+int f2(int n, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v2' is copied for 
each invocation but only used as a const reference; consider making it a const 
reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f2(int n, const ABC& v2) {
+}
Index: 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
===
--- 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
+++ 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header-fixed.h
@@ -0,0 +1,15 @@
+// struct ABC is expensive to copy and should be
+// passed as a const referece.
+struct ABC {
+  ABC(const ABC&);
+  int get(int) const;
+};
+
+
+int f1(int n,  const ABC& v1,   const ABC& v2); // line 9
+
+int f1(int n, ABC v1); // line 11
+
+
+
+int f2(int n,   const ABC& v2); // line 15
Index: 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
===
--- 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
+++ 
clang-tools-extra/trunk/test/clang-tidy/Inputs/performance-unnecessary-value-param/header.h
@@ -0,0 +1,15 @@
+// struct ABC is expensive to copy and should be
+// passed as a const referece.
+struct ABC {
+  ABC(const ABC&);
+  int get(int) const;
+};
+
+
+int f1(int n,  ABC v1,   ABC v2); // line 9
+
+int f1(int n, ABC v1); // line 11
+
+
+
+int f2(int n,   ABC v2); // line 15


Index: clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-header.cpp
@@ -0,0 +1,18 @@
+// RUN: cp %S/Inputs/performance-unnecessary-value-param/header.h %T/header.h
+// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t -- -- -std=c++11 -I %T
+// RUN: diff %T/header.h %S/Inputs/performance-unnecessary-value-param/header-fixed.h
+
+#include "header.h"
+
+
+
+int f1(int n, ABC v1, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v1' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
+  // CHECK-MESSAGES: [[@LINE-2]]:27: warning: the parameter 'v2' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f1(int n, const ABC& v1, const ABC& v2) {
+  return v1.get(n) + v2.get(n);
+}
+int f2(int n, ABC v2) {
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the parameter 'v2' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
+  // CHECK-FIXES: int f2(int n, const ABC& v2) {
+}
Index:

[PATCH] D32478: [clang-format] Fix AlignOperands when BreakBeforeBinaryOperators is set

2017-07-12 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

I renamed the option to `AlignAfterOperator`, is it acceptable now?
(I also thought of `UnindentOperator`, but I think it is better to keep the 
notion of alignment)

Note that this style is used in multiple open-source projects: Skia 
, parts of QtCreator 
 code base 
(e.g. in multiple plugins: clang, cpptools, android...), the OpenEXR 
 library...


https://reviews.llvm.org/D32478



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


[clang-tools-extra] r307812 - [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Jul 12 09:38:59 2017
New Revision: 307812

URL: http://llvm.org/viewvc/llvm-project?rev=307812&view=rev
Log:
[clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

Summary:
Before the change:

`auto i = (Enum) 5;` => `auto i = static_cast( 5);`

After the change:

`auto i = (Enum) 5;` => `auto i = static_cast(5);`

Reviewers: alexfh

Reviewed By: alexfh

Subscribers: JDevlieghere, xazax.hun, cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp

Modified: clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp?rev=307812&r1=307811&r2=307812&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp Wed Jul 
12 09:38:59 2017
@@ -58,10 +58,9 @@ static bool pointedUnqualifiedTypesAreEq
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
-  auto ParenRange = CharSourceRange::getTokenRange(CastExpr->getLParenLoc(),
-   CastExpr->getRParenLoc());
+
   // Ignore casts in macros.
-  if (ParenRange.getBegin().isMacroID() || ParenRange.getEnd().isMacroID())
+  if (CastExpr->getExprLoc().isMacroID())
 return;
 
   // Casting to void is an idiomatic way to mute "unused variable" and similar
@@ -82,6 +81,9 @@ void AvoidCStyleCastsCheck::check(const
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
+  auto ReplaceRange = CharSourceRange::getCharRange(
+  CastExpr->getLParenLoc(), 
CastExpr->getSubExprAsWritten()->getLocStart());
+
   bool FnToFnCast =
   isFunction(SourceTypeAsWritten) && isFunction(DestTypeAsWritten);
 
@@ -92,7 +94,7 @@ void AvoidCStyleCastsCheck::check(const
 // pointer/reference types.
 if (SourceTypeAsWritten == DestTypeAsWritten) {
   diag(CastExpr->getLocStart(), "redundant cast to the same type")
-  << FixItHint::CreateRemoval(ParenRange);
+  << FixItHint::CreateRemoval(ReplaceRange);
   return;
 }
   }
@@ -136,7 +138,7 @@ void AvoidCStyleCastsCheck::check(const
  getLangOpts()),
   ")");
 }
-Diag << FixItHint::CreateReplacement(ParenRange, CastText);
+Diag << FixItHint::CreateReplacement(ReplaceRange, CastText);
   };
   auto ReplaceWithNamedCast = [&](StringRef CastType) {
 Diag << CastType;

Modified: clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp?rev=307812&r1=307811&r2=307812&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp Wed 
Jul 12 09:38:59 2017
@@ -85,6 +85,22 @@ void f(int a, double b, const char *cpc,
   // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   // CHECK-FIXES: b1 = (const int&)b;
 
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
   Y *pB = (Y*)pX;
   // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   Y &rB = (Y&)*pX;
@@ -114,6 +130,14 @@ void f(int a, double b, const char *cpc,
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  e = e;
 
+  e = (Enum)   e;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = e;
+
+  e = (Enum)   (e);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = (e);
+
   static const int kZero = 0;
   (int)kZero;
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
ht

[PATCH] D31700: [clang-tidy] Ignore blank spaces between cast's ")" and its sub expr.

2017-07-12 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL307812: [clang-tidy] Ignore blank spaces between cast's ")" 
and its sub expr. (authored by hokein).

Repository:
  rL LLVM

https://reviews.llvm.org/D31700

Files:
  clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
  clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp


Index: clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -58,10 +58,9 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
-  auto ParenRange = CharSourceRange::getTokenRange(CastExpr->getLParenLoc(),
-   CastExpr->getRParenLoc());
+
   // Ignore casts in macros.
-  if (ParenRange.getBegin().isMacroID() || ParenRange.getEnd().isMacroID())
+  if (CastExpr->getExprLoc().isMacroID())
 return;
 
   // Casting to void is an idiomatic way to mute "unused variable" and similar
@@ -82,6 +81,9 @@
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
+  auto ReplaceRange = CharSourceRange::getCharRange(
+  CastExpr->getLParenLoc(), 
CastExpr->getSubExprAsWritten()->getLocStart());
+
   bool FnToFnCast =
   isFunction(SourceTypeAsWritten) && isFunction(DestTypeAsWritten);
 
@@ -92,7 +94,7 @@
 // pointer/reference types.
 if (SourceTypeAsWritten == DestTypeAsWritten) {
   diag(CastExpr->getLocStart(), "redundant cast to the same type")
-  << FixItHint::CreateRemoval(ParenRange);
+  << FixItHint::CreateRemoval(ReplaceRange);
   return;
 }
   }
@@ -136,7 +138,7 @@
  getLangOpts()),
   ")");
 }
-Diag << FixItHint::CreateReplacement(ParenRange, CastText);
+Diag << FixItHint::CreateReplacement(ReplaceRange, CastText);
   };
   auto ReplaceWithNamedCast = [&](StringRef CastType) {
 Diag << CastType;
Index: clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
@@ -85,6 +85,22 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   // CHECK-FIXES: b1 = (const int&)b;
 
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
+  b1 = (int) (b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: {{.*}}; use static_cast {{.*}}
+  // CHECK-FIXES: b1 = static_cast(b);
+
   Y *pB = (Y*)pX;
   // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use 
static_cast/const_cast/reinterpret_cast [
   Y &rB = (Y&)*pX;
@@ -114,6 +130,14 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
   // CHECK-FIXES: {{^}}  e = e;
 
+  e = (Enum)   e;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = e;
+
+  e = (Enum)   (e);
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: redundant cast to the same type
+  // CHECK-FIXES: {{^}}  e = (e);
+
   static const int kZero = 0;
   (int)kZero;
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type


Index: clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
@@ -58,10 +58,9 @@
 
 void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *CastExpr = Result.Nodes.getNodeAs("cast");
-  auto ParenRange = CharSourceRange::getTokenRange(CastExpr->getLParenLoc(),
-   CastExpr->getRParenLoc());
+
   // Ignore casts in macros.
-  if (ParenRange.getBegin().isMacroID() || ParenRange.getEnd().isMacroID())
+  if (CastExpr->getExprLoc().isMacroID())
 return;
 
   // Casting to void is an idiomatic way to mute "unused variable" and similar
@@ -82,6 +81,9 @@
   const QualType SourceType = SourceTypeAsWritten.getCanonicalType();
   const QualType DestType = DestTypeAsWritten.getCanonicalType();
 
+  auto Re

r307813 - [diagtool] Add a 'find-diagnostic-id' subcommand that converts a name of

2017-07-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Jul 12 09:41:49 2017
New Revision: 307813

URL: http://llvm.org/viewvc/llvm-project?rev=307813&view=rev
Log:
[diagtool] Add a 'find-diagnostic-id' subcommand that converts a name of
the diagnostic to its enum value

This will be used by a script that invokes clang in a debugger and forces it
to stop when it reports a particular diagnostic.

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

Added:
cfe/trunk/test/Misc/find-diagnostic-id.c
cfe/trunk/tools/diagtool/FindDiagnosticID.cpp
Modified:
cfe/trunk/tools/diagtool/CMakeLists.txt

Added: cfe/trunk/test/Misc/find-diagnostic-id.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Misc/find-diagnostic-id.c?rev=307813&view=auto
==
--- cfe/trunk/test/Misc/find-diagnostic-id.c (added)
+++ cfe/trunk/test/Misc/find-diagnostic-id.c Wed Jul 12 09:41:49 2017
@@ -0,0 +1,5 @@
+// RUN: diagtool find-diagnostic-id warn_unused_variable | FileCheck %s
+// RUN: not diagtool find-diagnostic-id warn_unused_vars 2>&1 | FileCheck 
--check-prefix=ERROR %s
+
+// CHECK: {{^[0-9]+$}}
+// ERROR: error: invalid diagnostic 'warn_unused_vars'

Modified: cfe/trunk/tools/diagtool/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/diagtool/CMakeLists.txt?rev=307813&r1=307812&r2=307813&view=diff
==
--- cfe/trunk/tools/diagtool/CMakeLists.txt (original)
+++ cfe/trunk/tools/diagtool/CMakeLists.txt Wed Jul 12 09:41:49 2017
@@ -6,6 +6,7 @@ add_clang_executable(diagtool
   diagtool_main.cpp
   DiagTool.cpp
   DiagnosticNames.cpp
+  FindDiagnosticID.cpp
   ListWarnings.cpp
   ShowEnabledWarnings.cpp
   TreeView.cpp

Added: cfe/trunk/tools/diagtool/FindDiagnosticID.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/diagtool/FindDiagnosticID.cpp?rev=307813&view=auto
==
--- cfe/trunk/tools/diagtool/FindDiagnosticID.cpp (added)
+++ cfe/trunk/tools/diagtool/FindDiagnosticID.cpp Wed Jul 12 09:41:49 2017
@@ -0,0 +1,58 @@
+//===- FindDiagnosticID.cpp - diagtool tool for finding diagnostic id 
-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "DiagTool.h"
+#include "DiagnosticNames.h"
+#include "clang/Basic/AllDiagnostics.h"
+#include "llvm/Support/CommandLine.h"
+
+DEF_DIAGTOOL("find-diagnostic-id", "Print the id of the given diagnostic",
+ FindDiagnosticID)
+
+using namespace clang;
+using namespace diagtool;
+
+static Optional
+findDiagnostic(ArrayRef Diagnostics, StringRef Name) {
+  for (const auto &Diag : Diagnostics) {
+StringRef DiagName = Diag.getName();
+if (DiagName == Name)
+  return Diag;
+  }
+  return None;
+}
+
+int FindDiagnosticID::run(unsigned int argc, char **argv,
+  llvm::raw_ostream &OS) {
+  static llvm::cl::OptionCategory FindDiagnosticIDOptions(
+  "diagtool find-diagnostic-id options");
+
+  static llvm::cl::opt DiagnosticName(
+  llvm::cl::Positional, llvm::cl::desc(""),
+  llvm::cl::Required, llvm::cl::cat(FindDiagnosticIDOptions));
+
+  std::vector Args;
+  Args.push_back("find-diagnostic-id");
+  for (const char *A : llvm::makeArrayRef(argv, argc))
+Args.push_back(A);
+
+  llvm::cl::HideUnrelatedOptions(FindDiagnosticIDOptions);
+  llvm::cl::ParseCommandLineOptions((int)Args.size(), Args.data(),
+"Diagnostic ID mapping utility");
+
+  ArrayRef AllDiagnostics = getBuiltinDiagnosticsByName();
+  Optional Diag =
+  findDiagnostic(AllDiagnostics, DiagnosticName);
+  if (!Diag) {
+llvm::errs() << "error: invalid diagnostic '" << DiagnosticName << "'\n";
+return 1;
+  }
+  OS << Diag->DiagID << "\n";
+  return 0;
+}


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


  1   2   >