[PATCH] D64276: [ItaniumMangle] Replace useFloat128ManglingForLongDouble() with getManglingForLongDouble() and getManglingForFloat128()

2019-07-05 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: awilfox, echristo, erichkeane, hfinkel, majnemer, rnk, 
rsmith.
Herald added subscribers: cfe-commits, erik.pilkington, jdoerfert, jsji, 
kbarton, nemanjai.
Herald added a project: clang.

On PowerPC, long double has 3 mangling schemes:

-mlong-double-64: "e"
-mlong-double-128 -mabi=ibmlongdouble: "g"
-mlong-double-128 -mabi=ieeelongdouble: "U10__float128"

The current bisection is not suitable when we add -mlong-double-128.
Replace useFloat128ManglingForLongDouble() with
getManglingForLongDouble() and getManglingForFloat128() to allow 3
mangling schemes.

This change is a no-op on X86 and SystemZ.
I deleted `getTriple().isOSBinFormatELF()` because the Darwin support
has gone: https://reviews.llvm.org/D50988


Repository:
  rC Clang

https://reviews.llvm.org/D64276

Files:
  include/clang/Basic/TargetInfo.h
  lib/AST/ItaniumMangle.cpp
  lib/Basic/Targets/PPC.h
  lib/Basic/Targets/SystemZ.h
  lib/Basic/Targets/X86.h

Index: lib/Basic/Targets/X86.h
===
--- lib/Basic/Targets/X86.h
+++ lib/Basic/Targets/X86.h
@@ -848,7 +848,12 @@
 LongDoubleFormat = ::APFloat::IEEEquad();
   }
 
-  bool useFloat128ManglingForLongDouble() const override { return true; }
+  const char *getManglingForLongDouble() const override {
+return LongDoubleWidth == 128 ? "g" : "e";
+  }
+  const char *getManglingForFloat128() const override {
+return "U10__float128";
+  }
 };
 } // namespace targets
 } // namespace clang
Index: lib/Basic/Targets/SystemZ.h
===
--- lib/Basic/Targets/SystemZ.h
+++ lib/Basic/Targets/SystemZ.h
@@ -141,7 +141,7 @@
 return "";
   }
 
-  bool useFloat128ManglingForLongDouble() const override { return true; }
+  const char *getManglingForLongDouble() const override { return "g"; }
 };
 } // namespace targets
 } // namespace clang
Index: lib/Basic/Targets/PPC.h
===
--- lib/Basic/Targets/PPC.h
+++ lib/Basic/Targets/PPC.h
@@ -314,10 +314,15 @@
 
   bool hasSjLjLowering() const override { return true; }
 
-  bool useFloat128ManglingForLongDouble() const override {
-return LongDoubleWidth == 128 &&
-   LongDoubleFormat == ::APFloat::PPCDoubleDouble() &&
-   getTriple().isOSBinFormatELF();
+  const char *getManglingForLongDouble() const override {
+if (LongDoubleWidth == 64)
+  return "e";
+return LongDoubleFormat == ::APFloat::PPCDoubleDouble()
+   ? "g"
+   : "U10__float128";
+  }
+  const char *getManglingForFloat128() const override {
+return "U10__float128";
   }
 };
 
Index: lib/AST/ItaniumMangle.cpp
===
--- lib/AST/ItaniumMangle.cpp
+++ lib/AST/ItaniumMangle.cpp
@@ -2608,30 +2608,19 @@
 Out << 'd';
 break;
   case BuiltinType::LongDouble: {
-bool UseFloat128Mangling =
-getASTContext().getTargetInfo().useFloat128ManglingForLongDouble();
-if (getASTContext().getLangOpts().OpenMP &&
-getASTContext().getLangOpts().OpenMPIsDevice) {
-  UseFloat128Mangling = getASTContext()
-.getAuxTargetInfo()
-->useFloat128ManglingForLongDouble();
-}
-Out << (UseFloat128Mangling ? 'g' : 'e');
+const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
+   getASTContext().getLangOpts().OpenMPIsDevice
+   ? getASTContext().getAuxTargetInfo()
+   : ().getTargetInfo();
+Out << TI->getManglingForLongDouble();
 break;
   }
   case BuiltinType::Float128: {
-bool UseFloat128Mangling =
-getASTContext().getTargetInfo().useFloat128ManglingForLongDouble();
-if (getASTContext().getLangOpts().OpenMP &&
-getASTContext().getLangOpts().OpenMPIsDevice) {
-  UseFloat128Mangling = getASTContext()
-.getAuxTargetInfo()
-->useFloat128ManglingForLongDouble();
-}
-if (UseFloat128Mangling)
-  Out << "U10__float128"; // Match the GCC mangling
-else
-  Out << 'g';
+const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
+   getASTContext().getLangOpts().OpenMPIsDevice
+   ? getASTContext().getAuxTargetInfo()
+   : ().getTargetInfo();
+Out << TI->getManglingForFloat128();
 break;
   }
   case BuiltinType::NullPtr:
Index: include/clang/Basic/TargetInfo.h
===
--- include/clang/Basic/TargetInfo.h
+++ include/clang/Basic/TargetInfo.h
@@ -599,9 +599,11 @@
 return *Float128Format;
   }
 
-  /// Return true if the 'long double' type should be mangled like
-  /// __float128.
-  virtual bool 

[PATCH] D64271: [analyzer] Don't track the right hand side of the last store for conditions

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Consider:

  int flag;
  bool coin();
  
  void foo() {
flag = coin();
  }
  
  void test() {
int *x = 0;
int local_flag;
flag = 1;
  
foo();
local_flag = flag;
if (local_flag)
  x = new int;
  
foo();
local_flag = flag;
if (local_flag)
  *x = 5;
  }

I'd rather track `flag` when i reach `local_flag`. I believe that we must track 
the RHS, but only as long as it's an overwrite on its own (or it's the value 
that participated in the collapse).

This is why the heuristic that i suggested was "track normally until the *last* 
out-of-frame overwrite point or until the collapse point".


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64271/new/

https://reviews.llvm.org/D64271



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


[PATCH] D64270: [analyzer][NFC] Prepare visitors for different tracking kinds

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Approve!

> null pointer dereference

...should in my opinion be tracked in a mild manner, as if it's a condition, 
because D62978 . I think the definition we're 
looking for is "when we care only about why it's null, regardless of what it is 
or where it comes from".

Say, in case of MallocChecker the malloc() call is the "origin" of the tracked 
pointer; we need to track it back to its original malloc. Similarly, in case of 
null dereference, the collapse point should be treated as an "origin" of the 
null pointer. The same for condition.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64270/new/

https://reviews.llvm.org/D64270



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


[PATCH] D63756: [AMDGPU] Increased the number of implicit argument bytes for both OpenCL and HIP (CLANG).

2019-07-05 Thread Christudasan Devadasan via Phabricator via cfe-commits
cdevadas added a comment.

The backend changes, D63886  are in the 
upstream now with revision rL365217 .
Please review this patch.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63756/new/

https://reviews.llvm.org/D63756



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


[PATCH] D59919: [Attributor] Deduce "returned" argument attribute

2019-07-05 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel accepted this revision.
hfinkel added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/test/CodeGenOpenCL/as_type.cl:3
+// Once the attributor is on by default remove the following run line and 
change the prefixes below.
+// RUN: %clang_cc1 %s -emit-llvm -mllvm -attributor-disable=false -triple 
spir-unknown-unknown -o - | FileCheck %s --check-prefix=ATTRIBUTOR
 

I recommend leaving the Clang tests along. Clang tests that run the optimizer 
don't follow out best practices and, while end-to-end testing is valuable, I 
don't think that we should encourage general optimizer testing here.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59919/new/

https://reviews.llvm.org/D59919



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


r365258 - [Rewrite] Extend to further accept CharSourceRange

2019-07-05 Thread Joel E. Denny via cfe-commits
Author: jdenny
Date: Fri Jul  5 19:55:06 2019
New Revision: 365258

URL: http://llvm.org/viewvc/llvm-project?rev=365258=rev
Log:
[Rewrite] Extend to further accept CharSourceRange

Some Rewrite functions are already overloaded to accept
CharSourceRange, and this extends others in the same manner.  I'm
calling these in code that's not ready to upstream, but I figure they
might be useful to others in the meantime.

Reviewed By: jdoerfert

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

Added:
cfe/trunk/unittests/Rewrite/RewriterTest.cpp
Modified:
cfe/trunk/include/clang/Rewrite/Core/Rewriter.h
cfe/trunk/lib/Rewrite/Rewriter.cpp
cfe/trunk/unittests/Rewrite/CMakeLists.txt

Modified: cfe/trunk/include/clang/Rewrite/Core/Rewriter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Rewrite/Core/Rewriter.h?rev=365258=365257=365258=diff
==
--- cfe/trunk/include/clang/Rewrite/Core/Rewriter.h (original)
+++ cfe/trunk/include/clang/Rewrite/Core/Rewriter.h Fri Jul  5 19:55:06 2019
@@ -84,7 +84,16 @@ public:
   /// in different buffers, this returns an empty string.
   ///
   /// Note that this method is not particularly efficient.
-  std::string getRewrittenText(SourceRange Range) const;
+  std::string getRewrittenText(CharSourceRange Range) const;
+
+  /// getRewrittenText - Return the rewritten form of the text in the specified
+  /// range.  If the start or end of the range was unrewritable or if they are
+  /// in different buffers, this returns an empty string.
+  ///
+  /// Note that this method is not particularly efficient.
+  std::string getRewrittenText(SourceRange Range) const {
+return getRewrittenText(CharSourceRange::getTokenRange(Range));
+  }
 
   /// InsertText - Insert the specified string at the specified location in the
   /// original buffer.  This method returns true (and does nothing) if the 
input
@@ -140,6 +149,13 @@ public:
 
   /// ReplaceText - This method replaces a range of characters in the input
   /// buffer with a new string.  This is effectively a combined "remove/insert"
+  /// operation.
+  bool ReplaceText(CharSourceRange range, StringRef NewStr) {
+return ReplaceText(range.getBegin(), getRangeSize(range), NewStr);
+  }
+
+  /// ReplaceText - This method replaces a range of characters in the input
+  /// buffer with a new string.  This is effectively a combined "remove/insert"
   /// operation.
   bool ReplaceText(SourceRange range, StringRef NewStr) {
 return ReplaceText(range.getBegin(), getRangeSize(range), NewStr);

Modified: cfe/trunk/lib/Rewrite/Rewriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Rewrite/Rewriter.cpp?rev=365258=365257=365258=diff
==
--- cfe/trunk/lib/Rewrite/Rewriter.cpp (original)
+++ cfe/trunk/lib/Rewrite/Rewriter.cpp Fri Jul  5 19:55:06 2019
@@ -170,7 +170,7 @@ int Rewriter::getRangeSize(SourceRange R
 /// in different buffers, this returns an empty string.
 ///
 /// Note that this method is not particularly efficient.
-std::string Rewriter::getRewrittenText(SourceRange Range) const {
+std::string Rewriter::getRewrittenText(CharSourceRange Range) const {
   if (!isRewritable(Range.getBegin()) ||
   !isRewritable(Range.getEnd()))
 return {};
@@ -193,7 +193,9 @@ std::string Rewriter::getRewrittenText(S
 
 // Adjust the end offset to the end of the last token, instead of being the
 // start of the last token.
-EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
+if (Range.isTokenRange())
+  EndOff +=
+  Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
 return std::string(Ptr, Ptr+EndOff-StartOff);
   }
 
@@ -203,7 +205,8 @@ std::string Rewriter::getRewrittenText(S
 
   // Adjust the end offset to the end of the last token, instead of being the
   // start of the last token.
-  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
+  if (Range.isTokenRange())
+EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
 
   // Advance the iterators to the right spot, yay for linear time algorithms.
   RewriteBuffer::iterator Start = RB.begin();

Modified: cfe/trunk/unittests/Rewrite/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Rewrite/CMakeLists.txt?rev=365258=365257=365258=diff
==
--- cfe/trunk/unittests/Rewrite/CMakeLists.txt (original)
+++ cfe/trunk/unittests/Rewrite/CMakeLists.txt Fri Jul  5 19:55:06 2019
@@ -4,8 +4,10 @@ set(LLVM_LINK_COMPONENTS
 
 add_clang_unittest(RewriteTests
   RewriteBufferTest.cpp
+  RewriterTest.cpp
   )
 clang_target_link_libraries(RewriteTests
   PRIVATE
   clangRewrite
+  clangTooling
   )

Added: cfe/trunk/unittests/Rewrite/RewriterTest.cpp
URL: 

[PATCH] D61467: [Rewrite] Extend to further accept CharSourceRange

2019-07-05 Thread Joel E. Denny via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365258: [Rewrite] Extend to further accept CharSourceRange 
(authored by jdenny, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D61467?vs=208247=208250#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61467/new/

https://reviews.llvm.org/D61467

Files:
  cfe/trunk/include/clang/Rewrite/Core/Rewriter.h
  cfe/trunk/lib/Rewrite/Rewriter.cpp
  cfe/trunk/unittests/Rewrite/CMakeLists.txt
  cfe/trunk/unittests/Rewrite/RewriterTest.cpp

Index: cfe/trunk/lib/Rewrite/Rewriter.cpp
===
--- cfe/trunk/lib/Rewrite/Rewriter.cpp
+++ cfe/trunk/lib/Rewrite/Rewriter.cpp
@@ -170,7 +170,7 @@
 /// in different buffers, this returns an empty string.
 ///
 /// Note that this method is not particularly efficient.
-std::string Rewriter::getRewrittenText(SourceRange Range) const {
+std::string Rewriter::getRewrittenText(CharSourceRange Range) const {
   if (!isRewritable(Range.getBegin()) ||
   !isRewritable(Range.getEnd()))
 return {};
@@ -193,7 +193,9 @@
 
 // Adjust the end offset to the end of the last token, instead of being the
 // start of the last token.
-EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
+if (Range.isTokenRange())
+  EndOff +=
+  Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
 return std::string(Ptr, Ptr+EndOff-StartOff);
   }
 
@@ -203,7 +205,8 @@
 
   // Adjust the end offset to the end of the last token, instead of being the
   // start of the last token.
-  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
+  if (Range.isTokenRange())
+EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
 
   // Advance the iterators to the right spot, yay for linear time algorithms.
   RewriteBuffer::iterator Start = RB.begin();
Index: cfe/trunk/unittests/Rewrite/RewriterTest.cpp
===
--- cfe/trunk/unittests/Rewrite/RewriterTest.cpp
+++ cfe/trunk/unittests/Rewrite/RewriterTest.cpp
@@ -0,0 +1,80 @@
+//===- unittests/Rewrite/RewriterTest.cpp - Rewriter tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Rewrite/Core/Rewriter.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+struct RangeTypeTest {
+  std::unique_ptr AST;
+  Rewriter Rewrite;
+  SourceLocation FileStart;
+  CharSourceRange CRange; // covers exact char range
+  CharSourceRange TRange; // extends CRange to whole tokens
+  SourceRange SRange; // different type but behaves like TRange
+  SourceLocation makeLoc(int Off) { return FileStart.getLocWithOffset(Off); }
+  CharSourceRange makeCharRange(int StartOff, int EndOff) {
+return CharSourceRange::getCharRange(makeLoc(StartOff), makeLoc(EndOff));
+  }
+  RangeTypeTest(StringRef Code, int StartOff, int EndOff) {
+AST = tooling::buildASTFromCode(Code);
+ASTContext  = AST->getASTContext();
+Rewrite = Rewriter(C.getSourceManager(), C.getLangOpts());
+FileStart = AST->getStartOfMainFileID();
+CRange = makeCharRange(StartOff, EndOff);
+SRange = CRange.getAsRange();
+TRange = CharSourceRange::getTokenRange(SRange);
+  }
+};
+
+TEST(Rewriter, GetRewrittenTextRangeTypes) {
+  // Check that correct text is retrieved for each range type.  Check again
+  // after a modification.  Ranges remain in terms of the original text but
+  // include the new text.
+  StringRef Code = "int main() { return 0; }";
+  //  get char range ^~~= "ret"
+  // get token range ^~~+++ = "return"
+  //get source range ^~~+++ = "return"
+  //  insert "x" ^
+  //  get char range ^~~= "xret"
+  // get token range ^~~+++ = "xreturn"
+  //get source range ^~~+++ = "xreturn"
+  RangeTypeTest T(Code, 13, 16);
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.CRange), "ret");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.TRange), "return");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.SRange), "return");
+  T.Rewrite.InsertText(T.makeLoc(13), "x");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.CRange), "xret");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.TRange), "xreturn");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.SRange), "xreturn");
+}
+
+TEST(Rewriter, ReplaceTextRangeTypes) {
+  // Check that correct text is replaced for each range type.  Ranges remain in
+  // terms of the original text but include the new text.
+  

[PATCH] D64274: [analyzer] VirtualCallChecker overhaul.

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: dcoughlin, xazax.hun, a_sidorin, rnkovacs, Szelethus, 
baloghadamsoftware, Charusso.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, szepet.
Herald added a project: clang.

This is slightly controversial, please hold me back / bikeshed if you don't 
like it.

The `optin.cplusplus.VirtualCall` checker in its current shape was implemented 
by @wangxindsb during his GSoC'2017 project - see D34275 
. It is a path-sensitive checker that finds 
calls to virtual functions during construction and destruction. This is a 
problem because virtual dispatch won't occur during construction or 
destruction. In particular, if the function is pure virtual, it is outright 
undefined behavior; in other cases it is simply an unexpected behavior. The 
checker has an option `PureOnly` to control whether the user is only interested 
in calls to pure virtual functions. It defaults to false, i.e. warn on 
non-pure-virtual calls as well.

I propose the following changes:

- Remove the option.
- Instead, split the checker in two:
  - `cplusplus.PureVirtualCall` will only check pure virtual calls and it 
//will be on by default//.
  - `optin.cplusplus.VirtualCall` will check all calls and will remain opt-in 
under the old name. It would automatically load `cplusplus.PureVirtualCall`.
- Additionally, remove the bug visitor. The reasons for that have been 
described in D34275 ?id=111862#inline-321253: 
essentially, the visitor doesn't add any new interesting information to the 
report. It's also currently broken: it places its note in a really weird spot.

I'd like to point out that it breaks backwards compatibility. I'm not going to 
be hurt by this and i haven't heard a lot about users of this opt-in check but 
if you know them, please let me know. If we agree to break backwards 
compatibility, we should make sure that the result is the best, so i'd like to 
hear @Szelethus's opinion, as he usually has strong opinions on checker options 
and dependencies :)

See also http://lists.llvm.org/pipermail/cfe-dev/2018-December/060558.html (the 
thread was bumped recently)


Repository:
  rC Clang

https://reviews.llvm.org/D64274

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/virtualcall.cpp
  clang/test/Analysis/virtualcall.h

Index: clang/test/Analysis/virtualcall.h
===
--- clang/test/Analysis/virtualcall.h
+++ clang/test/Analysis/virtualcall.h
@@ -2,12 +2,7 @@
   class Z {
   public:
 Z() {
-  foo();
-#if !PUREONLY
-	// expected-warning-re@-2 ^}}Call to virtual function during construction}}
-	// expected-note-re@-3 ^}}This constructor of an object of type 'Z' has not returned when the virtual method was called}}
-	// expected-note-re@-4 ^}}Call to virtual function during construction}}	
-#endif
+  foo(); // impure-warning {{Call to virtual function during construction}}
 }
 virtual int foo();
   };
Index: clang/test/Analysis/virtualcall.cpp
===
--- clang/test/Analysis/virtualcall.cpp
+++ clang/test/Analysis/virtualcall.cpp
@@ -1,6 +1,8 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=optin.cplusplus.VirtualCall -analyzer-store region -analyzer-output=text -verify -std=c++11 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,optin.cplusplus.VirtualCall \
+// RUN:  -verify=expected,impure -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 -analyzer-output=text -verify -std=c++11 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.PureVirtualCall \
+// RUN:  -verify=expected -std=c++11 %s
 
 #include "virtualcall.h"
 
@@ -13,54 +15,31 @@
   virtual int foo() = 0;
   virtual void bar() = 0;
   void f() {
-foo();
-	// expected-warning-re@-1 ^}}Call to pure virtual function during construction}}
-	// expected-note-re@-2 ^}}Call to pure virtual function during construction}}
+foo(); // expected-warning{{Call to pure virtual function during construction}}
   }
 };
 
 class B : public A {
 public:
-  B() { // expected-note {{Calling default constructor for 'A'}}
-foo(); 
-#if !PUREONLY
-  	// expected-warning-re@-2 ^}}Call to virtual function during construction}}
-	// expected-note-re@-3 ^}}This constructor of an object of type 'B' has not returned when the virtual method was called}}
-  	// expected-note-re@-4 ^}}Call to virtual function during construction}}
-#endif
+  B() {
+foo(); // impure-warning {{Call to virtual function during construction}}
   }
   ~B();
 
   virtual int foo();
   virtual void bar() {
-

[PATCH] D64128: [CodeGen] Generate llvm.ptrmask instead of inttoptr(and(ptrtoint, C)) if possible.

2019-07-05 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel added a comment.

In D64128#1570609 , @rjmccall wrote:

> In D64128#1569836 , @hfinkel wrote:
>
> > In D64128#1569817 , @rjmccall 
> > wrote:
> >
> > > The pointer/integer conversion is "implementation-defined", but it's not 
> > > totally unconstrained.  C notes that "The mapping functions for 
> > > converting a pointer to an integer or an integer to a pointer are 
> > > intended to be consistent with the addressing structure of the execution 
> > > environment.", and we do have to honor that.  The standard allows that 
> > > "the result ... might not point to an entity of the referenced type", but 
> > > when in fact it's guaranteed to do so (i.e. it's not just a coincidental 
> > > result of an implementation decision like the exact address of a global 
> > > variable — no "guessing"), I do think we have an obligation to make it 
> > > work.  And on a practical level, there has to be *some* way of playing 
> > > clever address tricks in the language in order to implement things like 
> > > allocators and so forth.  So this makes me very antsy.
> >
> >
> > I don't disagree. But I believe the question is if we have:
> >
> >   int *x = malloc(4);
> >   int *y = malloc(4);
> >   if (x & ~15 == y) {
> > *(x & ~15) = 5; // Is this allowed, and if so, must the compiler assume 
> > that it might set the value of *y?
> >   }
> >   
> >
> > I certainly agree that we must allow the implementation of allocators, etc. 
> > But allocators, I think, have the opposite problem. They actually have some 
> > large underlying objects (from mmap or whatever), and we want the rest of 
> > the system to treat some subobjects of these larger objects as though they 
> > were independent objects of some given types. From the point of view of the 
> > allocator, we have x, and we have `void *memory_pool`, and we need to allow 
> > `x & N` to point into `memory_pool`, but because, from the allocator's 
> > perspective, we never knew that x didn't point into memory_pool (as, in 
> > fact, it likely does), that should be fine (*).
> >
> > There might be more of an issue, for example, if for a given object, I 
> > happen to know that there's some interesting structure at the beginning of 
> > its page (or some other boundary).
>
>
> This is what I was thinking about for allocators; this is a common 
> implementation technique for `free` / `realloc` / `malloc_size`.
>
> > If I also have a pointer to this structure via some other means, then maybe 
> > this will cause a problem. This kind of thing certainly falls outside of 
> > the C/C++ abstract machine, and I'd lean toward a flag for supporting it 
> > (not on by default).
>
> If you mean a theoretical minimal C abstract machine that does not correspond 
> to an actual target and is therefore not bound by any of the statements in 
> the C standard that say things like "this is expected to have its obvious 
> translation on the target", then yes, I completely agree.  If you're talking 
> about the actual C programming language that does correspond to actual 
> targets, then it's not clear at all that it's outside the C abstract machine, 
> because AFAICT integer-pointer conversions are (1) well-specified on specific 
> targets by this de facto requirement of corresponding directly to pointer 
> representations and (2) well-behaved as long as the integer does correspond 
> to the address of an actual object of that type.
>
> Also, please understand that compiler writers have been telling our users for 
> decades that (1) pointer arithmetic is subject to some restrictions on 
> penalty of UB and (2) they can avoid those restrictions by using 
> pointer-integer conversions and doing integer arithmetic instead.


Indeed, we have.

>   So any proposal to weaken the latter as a workaround makes me very worried, 
> especially if it's also enforcing alignment restrictions that we've generally 
> chosen not to enforce when separated from actual memory accesses.

I *think* that what @fhahn points out about the masking restrictions addresses 
the concerns that we were discussing: My understanding of the 
potentially-problematic cases here are when the masking could get you from one 
variable from one underlying object (that you might access) to another variable 
in a different underlying object (that you might also access), and given the 
masking restrictions, this is impossible (*): because the high bits can't be 
used for addressing, and for the lower bits, these fall within the alignment of 
the type, and so in order for that to move you between underlying objects, the 
objects would need to be smaller than the type alignment.

(*) I suppose one can arrange for this to break something given some 
system-specific setup:

  // note: the linker script ensures that these are packed and adjacent.
  short a;
  struct {
short b, c;
  } s;
  
  ...
  int *ib = 

[PATCH] D61467: [Rewrite] Extend to further accept CharSourceRange

2019-07-05 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

The comments help a lot. LGTM.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61467/new/

https://reviews.llvm.org/D61467



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


[PATCH] D61467: [Rewrite] Extend to further accept CharSourceRange

2019-07-05 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny updated this revision to Diff 208247.
jdenny added a comment.

@jdoerfert Thanks for your reply.  I added some comments to the tests.  Let me 
know whether that's what you're looking for.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61467/new/

https://reviews.llvm.org/D61467

Files:
  clang/include/clang/Rewrite/Core/Rewriter.h
  clang/lib/Rewrite/Rewriter.cpp
  clang/unittests/Rewrite/CMakeLists.txt
  clang/unittests/Rewrite/RewriterTest.cpp

Index: clang/unittests/Rewrite/RewriterTest.cpp
===
--- /dev/null
+++ clang/unittests/Rewrite/RewriterTest.cpp
@@ -0,0 +1,80 @@
+//===- unittests/Rewrite/RewriterTest.cpp - Rewriter tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Rewrite/Core/Rewriter.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+struct RangeTypeTest {
+  std::unique_ptr AST;
+  Rewriter Rewrite;
+  SourceLocation FileStart;
+  CharSourceRange CRange; // covers exact char range
+  CharSourceRange TRange; // extends CRange to whole tokens
+  SourceRange SRange; // different type but behaves like TRange
+  SourceLocation makeLoc(int Off) { return FileStart.getLocWithOffset(Off); }
+  CharSourceRange makeCharRange(int StartOff, int EndOff) {
+return CharSourceRange::getCharRange(makeLoc(StartOff), makeLoc(EndOff));
+  }
+  RangeTypeTest(StringRef Code, int StartOff, int EndOff) {
+AST = tooling::buildASTFromCode(Code);
+ASTContext  = AST->getASTContext();
+Rewrite = Rewriter(C.getSourceManager(), C.getLangOpts());
+FileStart = AST->getStartOfMainFileID();
+CRange = makeCharRange(StartOff, EndOff);
+SRange = CRange.getAsRange();
+TRange = CharSourceRange::getTokenRange(SRange);
+  }
+};
+
+TEST(Rewriter, GetRewrittenTextRangeTypes) {
+  // Check that correct text is retrieved for each range type.  Check again
+  // after a modification.  Ranges remaing in terms of the original text but
+  // include the new text.
+  StringRef Code = "int main() { return 0; }";
+  //  get char range ^~~= "ret"
+  // get token range ^~~+++ = "return"
+  //get source range ^~~+++ = "return"
+  //  insert "x" ^
+  //  get char range ^~~= "xret"
+  // get token range ^~~+++ = "xreturn"
+  //get source range ^~~+++ = "xreturn"
+  RangeTypeTest T(Code, 13, 16);
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.CRange), "ret");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.TRange), "return");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.SRange), "return");
+  T.Rewrite.InsertText(T.makeLoc(13), "x");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.CRange), "xret");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.TRange), "xreturn");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.SRange), "xreturn");
+}
+
+TEST(Rewriter, ReplaceTextRangeTypes) {
+  // Check that correct text is replaced for each range type.  Ranges remain in
+  // terms of the original text but include the new text.
+  StringRef Code = "int main(int argc, char *argv[]) { return argc; }";
+  //replace char range with "foo" ^~
+  //  get ^ = "foogc;"
+  //   replace token range with "bar" ^~++
+  //  get ^ = "bar;"
+  //replace source range with "0" ^~++
+  //  get ^ = "0;"
+  RangeTypeTest T(Code, 42, 44);
+  T.Rewrite.ReplaceText(T.CRange, "foo");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.makeCharRange(42, 47)), "foogc;");
+  T.Rewrite.ReplaceText(T.TRange, "bar");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.makeCharRange(42, 47)), "bar;");
+  T.Rewrite.ReplaceText(T.SRange, "0");
+  EXPECT_EQ(T.Rewrite.getRewrittenText(T.makeCharRange(42, 47)), "0;");
+}
+
+} // anonymous namespace
Index: clang/unittests/Rewrite/CMakeLists.txt
===
--- clang/unittests/Rewrite/CMakeLists.txt
+++ clang/unittests/Rewrite/CMakeLists.txt
@@ -4,8 +4,10 @@
 
 add_clang_unittest(RewriteTests
   RewriteBufferTest.cpp
+  RewriterTest.cpp
   )
 target_link_libraries(RewriteTests
   PRIVATE
   clangRewrite
+  clangTooling
   )
Index: clang/lib/Rewrite/Rewriter.cpp
===
--- clang/lib/Rewrite/Rewriter.cpp
+++ clang/lib/Rewrite/Rewriter.cpp
@@ -170,7 +170,7 @@
 /// in different buffers, this returns an empty string.
 ///
 /// Note that this method is not particularly efficient.
-std::string 

[PATCH] D64272: [analyzer] Note last writes to a condition only in a nested stackframe

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: NoQ, xazax.hun, rnkovacs, dcoughlin, Charusso, 
baloghadamsoftware.
Szelethus added a project: clang.
Herald added subscribers: cfe-commits, gamesh411, dkrupp, donat.nagy, 
mikhail.ramalho, a.sidorin, szepet, whisperity.
Szelethus added a parent revision: D64271: [analyzer] Don't track the right 
hand side of the last store for conditions.

Exactly what it says on the tin! The comments in the code detail this a little 
more too.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64272

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/test/Analysis/track-control-dependency-conditions.cpp

Index: clang/test/Analysis/track-control-dependency-conditions.cpp
===
--- clang/test/Analysis/track-control-dependency-conditions.cpp
+++ clang/test/Analysis/track-control-dependency-conditions.cpp
@@ -127,10 +127,9 @@
 void test() {
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
 
-  if (int flag = foo()) // tracking-note{{'flag' initialized here}}
-// debug-note@-1{{Tracking condition 'flag'}}
-// expected-note@-2{{Assuming 'flag' is not equal to 0}}
-// expected-note@-3{{Taking true branch}}
+  if (int flag = foo()) // debug-note{{Tracking condition 'flag'}}
+// expected-note@-1{{Assuming 'flag' is not equal to 0}}
+// expected-note@-2{{Taking true branch}}
 
 *x = 5; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1{{Dereference of null pointer}}
@@ -209,7 +208,7 @@
 int getInt();
 
 void f() {
-  int flag = getInt(); // tracking-note{{'flag' initialized here}}
+  int flag = getInt();
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
   if (flag) // expected-note{{Assuming 'flag' is not equal to 0}}
 // expected-note@-1{{Taking true branch}}
@@ -225,7 +224,7 @@
 
 void f(int y) {
   y = 1;
-  flag = y; // tracking-note{{The value 1 is assigned to 'flag'}}
+  flag = y;
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
   if (flag) // expected-note{{'flag' is 1}}
 // expected-note@-1{{Taking true branch}}
@@ -298,7 +297,7 @@
 void f(int flag) {
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
 
-  flag = getInt(); // tracking-note{{Value assigned to 'flag'}}
+  flag = getInt();
   assert(flag); // tracking-note{{Calling 'assert'}}
 // tracking-note@-1{{Returning from 'assert'}}
 
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1421,6 +1421,11 @@
 
   if (!StoreSite)
 return nullptr;
+
+  if (TKind != TrackingKind::ThoroughTracking &&
+  StoreSite->getStackFrame() == OriginSFC)
+return nullptr;
+
   Satisfied = true;
 
   // If we have an expression that provided the value, try to track where it
@@ -1466,7 +1471,7 @@
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
   BR.addVisitor(llvm::make_unique(
-  *KV, OriginalR, EnableNullFPSuppression, TKind));
+  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
   }
 }
   }
@@ -1898,6 +1903,7 @@
 return false;
 
   ProgramStateRef LVState = LVNode->getState();
+  const StackFrameContext *SFC = LVNode->getStackFrame();
 
   // We only track expressions if we believe that they are important. Chances
   // are good that control dependencies to the tracking point are also improtant
@@ -1933,7 +1939,7 @@
 if (RR && !LVIsNull)
   if (auto KV = LVal.getAs())
 report.addVisitor(llvm::make_unique(
-  *KV, RR, EnableNullFPSuppression, TKind));
+  *KV, RR, EnableNullFPSuppression, TKind, SFC));
 
 // In case of C++ references, we want to differentiate between a null
 // reference and reference to null pointer.
@@ -1970,7 +1976,7 @@
 
   if (auto KV = V.getAs())
 report.addVisitor(llvm::make_unique(
-  *KV, R, EnableNullFPSuppression, TKind));
+  *KV, R, EnableNullFPSuppression, TKind, SFC));
   return true;
 }
   }
@@ -2008,7 +2014,7 @@
 if (CanDereference)
   if (auto KV = RVal.getAs())
 report.addVisitor(llvm::make_unique(
-*KV, L->getRegion(), EnableNullFPSuppression, TKind));
+*KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC));
 
 const MemRegion *RegionRVal = RVal.getAsRegion();
 if (RegionRVal && isa(RegionRVal)) {
Index: 

[PATCH] D64271: [analyzer] Don't track the right hand side of the last store for conditions

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: NoQ, xazax.hun, baloghadamsoftware, rnkovacs, 
Charusso, dcoughlin.
Szelethus added a project: clang.
Herald added subscribers: cfe-commits, gamesh411, dkrupp, donat.nagy, 
mikhail.ramalho, a.sidorin, szepet, whisperity.
Szelethus added a parent revision: D64270: [analyzer][NFC] Prepare visitors for 
different tracking kinds.

Exactly what it says on the tin!


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64271

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/test/Analysis/track-control-dependency-conditions.cpp


Index: clang/test/Analysis/track-control-dependency-conditions.cpp
===
--- clang/test/Analysis/track-control-dependency-conditions.cpp
+++ clang/test/Analysis/track-control-dependency-conditions.cpp
@@ -119,7 +119,7 @@
 bool coin();
 
 bool foo() {
-  return coin(); // tracking-note{{Returning value}}
+  return coin();
 }
 
 int bar;
@@ -127,12 +127,10 @@
 void test() {
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
 
-  if (int flag = foo()) // tracking-note{{Calling 'foo'}}
-// tracking-note@-1{{Returning from 'foo'}}
-// tracking-note@-2{{'flag' initialized here}}
-// debug-note@-3{{Tracking condition 'flag'}}
-// expected-note@-4{{Assuming 'flag' is not equal to 
0}}
-// expected-note@-5{{Taking true branch}}
+  if (int flag = foo()) // tracking-note{{'flag' initialized here}}
+// debug-note@-1{{Tracking condition 'flag'}}
+// expected-note@-2{{Assuming 'flag' is not equal to 
0}}
+// expected-note@-3{{Taking true branch}}
 
 *x = 5; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1{{Dereference of null pointer}}
@@ -226,9 +224,8 @@
 int getInt();
 
 void f(int y) {
-  y = 1; // tracking-note{{The value 1 is assigned to 'y'}}
+  y = 1;
   flag = y; // tracking-note{{The value 1 is assigned to 'flag'}}
-
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
   if (flag) // expected-note{{'flag' is 1}}
 // expected-note@-1{{Taking true branch}}
@@ -244,9 +241,8 @@
 
 void foo() {
   int y;
-  y = 1; // tracking-note{{The value 1 is assigned to 'y'}}
+  y = 1;
   flag = y; // tracking-note{{The value 1 is assigned to 'flag'}}
-
 }
 
 void f(int y) {
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1425,16 +1425,20 @@
 
   // If we have an expression that provided the value, try to track where it
   // came from.
-  if (InitE) {
-if (V.isUndef() ||
-V.getAs() || V.getAs()) {
-  if (!IsParam)
-InitE = InitE->IgnoreParenCasts();
-  bugreporter::trackExpressionValue(StoreSite, InitE, BR,
-   EnableNullFPSuppression);
+  // For tracked conditions, this isn't really important, it would pollute the
+  // bug report far too much.
+  if (TKind != TrackingKind::ConditionTracking) {
+if (InitE) {
+  if (V.isUndef() ||
+  V.getAs() || V.getAs()) {
+if (!IsParam)
+  InitE = InitE->IgnoreParenCasts();
+bugreporter::trackExpressionValue(StoreSite, InitE, BR,
+ EnableNullFPSuppression);
+  }
+  ReturnVisitor::addVisitorIfNecessary(StoreSite, 
InitE->IgnoreParenCasts(),
+   BR, EnableNullFPSuppression);
 }
-ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
- BR, EnableNullFPSuppression);
   }
 
   // Okay, we've found the binding. Emit an appropriate message.
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -138,7 +138,8 @@
   /// \param R The region we're tracking.
   /// \param EnableNullFPSuppression Whether we should employ false positive
   /// suppression (inlined defensive checks, returned null).
-  /// \param TKind May limit the amount of notes added to the bug report.
+  /// \param TKind May limit the amount of notes added to the bug report. For
+  ///conditions, ignores the initialization point.
   FindLastStoreBRVisitor(KnownSVal V, const MemRegion *R,
  bool InEnableNullFPSuppression,
  TrackingKind TKind)



[PATCH] D64270: [analyzer][NFC] Prepare visitors for different tracking kinds

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: NoQ, xazax.hun, rnkovacs, Charusso, 
baloghadamsoftware, dcoughlin.
Szelethus added a project: clang.
Herald added subscribers: cfe-commits, gamesh411, dkrupp, donat.nagy, 
mikhail.ramalho, a.sidorin, szepet, whisperity.

When we're tracking a variable that is responsible for a null pointer 
dereference or some other sinister programming error, we of course would like 
to gather as much information why we think that the variable has that specific 
value as possible. However, the newly introduced condition tracking shows that 
tracking all values this thoroughly could easily cause an intolerable growth in 
the bug report's length.

Take, for instance the following report as an example: BEFORE condition 
tracking 
,
 AFTER condition tracking 
.
 Having an already lengthy, bug report with 18 events grew to 45 is inexcusable.

There are a variety of heuristics we discussed on the mailing list 
 to combat this, 
all of them requiring to differentiate in between tracking a "regular value" 
and a "condition".

This patch introduces the new `bugreporter::TrackingKind` enum, adds it to 
`FindLastStoreBRVisitor` as a non-optional argument, and moves some functions 
around to make the code a little more coherent.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64270

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -71,6 +71,20 @@
 // Utility functions.
 //===--===//
 
+/// Implementation function for trackExpressionValue().
+static bool trackExpressionValue(
+const ExplodedNode *InputNode,
+const Expr *E, BugReport ,
+bool EnableNullFPSuppression,
+bugreporter::TrackingKind TKind);
+
+bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
+   const Expr *E, BugReport ,
+   bool EnableNullFPSuppression) {
+  return ::trackExpressionValue(InputNode, E, report, EnableNullFPSuppression,
+TrackingKind::ThoroughTracking);
+}
+
 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
   if (B->isAdditiveOp() && B->getType()->isPointerType()) {
 if (B->getLHS()->getType()->isPointerType()) {
@@ -1141,9 +1155,45 @@
   ID.AddPointer();
   ID.AddPointer(R);
   ID.Add(V);
+  ID.AddInteger(static_cast(TKind));
   ID.AddBoolean(EnableNullFPSuppression);
 }
 
+void FindLastStoreBRVisitor::registerStatementVarDecls(
+BugReport , const Stmt *S, bool EnableNullFPSuppression,
+TrackingKind TKind) {
+
+  const ExplodedNode *N = BR.getErrorNode();
+  std::deque WorkList;
+  WorkList.push_back(S);
+
+  while (!WorkList.empty()) {
+const Stmt *Head = WorkList.front();
+WorkList.pop_front();
+
+ProgramStateManager  = N->getState()->getStateManager();
+
+if (const auto *DR = dyn_cast(Head)) {
+  if (const auto *VD = dyn_cast(DR->getDecl())) {
+const VarRegion *R =
+StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
+
+// What did we load?
+SVal V = N->getSVal(S);
+
+if (V.getAs() || V.getAs()) {
+  // Register a new visitor with the BugReport.
+  BR.addVisitor(llvm::make_unique(
+  V.castAs(), R, EnableNullFPSuppression, TKind));
+}
+  }
+}
+
+for (const Stmt *SubStmt : Head->children())
+  WorkList.push_back(SubStmt);
+  }
+}
+
 /// Returns true if \p N represents the DeclStmt declaring and initializing
 /// \p VR.
 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
@@ -1314,7 +1364,7 @@
   // should track the initializer expression.
   if (Optional PIP = Pred->getLocationAs()) {
 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
-if (FieldReg && FieldReg == R) {
+if 

r365248 - Improve MSVC visualization of annot_template_id tokens

2019-07-05 Thread Mike Spertus via cfe-commits
Author: mps
Date: Fri Jul  5 14:41:30 2019
New Revision: 365248

URL: http://llvm.org/viewvc/llvm-project?rev=365248=rev
Log:
Improve MSVC visualization of annot_template_id tokens

Now shows the actual annotated template. E.g.,
{annot_template_id (A)}

Also a few miscellaneous fixes to visualizers of other types

Modified:
cfe/trunk/utils/ClangVisualizers/clang.natvis

Modified: cfe/trunk/utils/ClangVisualizers/clang.natvis
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/ClangVisualizers/clang.natvis?rev=365248=365247=365248=diff
==
--- cfe/trunk/utils/ClangVisualizers/clang.natvis (original)
+++ cfe/trunk/utils/ClangVisualizers/clang.natvis Fri Jul  5 14:41:30 2019
@@ -52,8 +52,9 @@ For later versions of Visual Studio, no
 {*(clang::InjectedClassNameType *)this}
 {*(clang::DependentNameType *)this}
 {*(clang::PackExpansionType *)this}
-{*(clang::LocInfoType *)this}
-{*this,view(poly)}
+{(clang::LocInfoType *)this,na}
+{(clang::LocInfoType *)this,view(cpp)na}
+{this,view(poly)na}
 {*this,view(cpp)}
 
 No visualizer yet for 
{(clang::Type::TypeClass)TypeBits.TC,en}Type 
@@ -222,7 +223,31 @@ For later versions of Visual Studio, no
 {(TypedefNameDecl 
*)this,view(name)nand}
 using {(TypedefNameDecl *)this,view(name)nand} = 
{(TypedefNameDecl *)this,view(type)nand}
   
-
+  
+{Name}
+  
+  
+Kind={(UncommonTemplateNameStorage::Kind)Kind,en}, 
Size={Size}
+
+  (UncommonTemplateNameStorage::Kind)Kind
+  Size
+
+  
+  
+{Bits},
+{this,view(cmn)na},{(OverloadedTemplateStorage*)this,na}
+{this,view(cmn)na},{(AssumedTemplateStorage*)this,na}
+{this,view(cmn)na},{(SubstTemplateTemplateParmStorage*)this,na}
+{this,view(cmn)na},{(SubstTemplateTemplateParmPackStorage*)this,na}
+{this,view(cmn)na}
+
+  Bits
+  (OverloadedTemplateStorage*)this
+  (AssumedTemplateStorage*)this
+  (SubstTemplateTemplateParmStorage*)this
+  (SubstTemplateTemplateParmPackStorage*)this
+
+  
   
 {Storage,na}
 
@@ -290,7 +315,7 @@ For later versions of Visual Studio, no
 ({*this,view(parm0)})
 {this,view(left)na}{this,view(right)na}
 
-  ResultType
+  ResultType
   
 {*this,view(parm0)}
 
@@ -324,10 +349,11 @@ For later versions of Visual Studio, no
 Non-canonical: {*TTPDecl}
 Canonical: {CanTTPTInfo}
 
+  *(clang::Type *)this, view(cmn)
 
   
   
-{*Decl,view(cpp)}
+{InjectedType,view(cpp)}
 
   Decl
   InjectedType
@@ -384,7 +410,8 @@ For later versions of Visual Studio, no
 
   
   
-{*DeclInfo}
+{DeclInfo,view(cpp)na}
+{DeclInfo,na}
 
   DeclInfo
   *(clang::Type *)this, view(cmn)
@@ -420,9 +447,11 @@ For later versions of Visual Studio, no
 , {Args.Args[2],view(cpp)}, 
...
 {*this,view(arg0cpp)}
 {*this,view(arg0)}
+{(clang::Expr 
*)TypeOrValue.V,view(cpp)na}
 
{(clang::TemplateArgument::ArgKind)TypeOrValue.Kind,en}
 
   *(clang::QualType 
*)TypeOrValue.V
+  (clang::Expr 
*)TypeOrValue.V
   
 Args.NumArgs
 Args.Args
@@ -468,6 +497,7 @@ For later versions of Visual Studio, no
 
   
   
+{(clang::QualType *)Arg,view(cpp)na}
 Type 
template argument: {*(clang::QualType *)Arg}
 Non-type template 
argument: {*(clang::Expr *)Arg}
 Template template 
argument: {*(clang::TemplateName *)Arg
@@ -604,7 +634,7 @@ For later versions of Visual Studio, no
   
   
 {Template->TemplatedDecl,view(cpp)}
-C++ Deduction guide for 
{Template->TemplatedDecl,view(cpp)}
+C++ Deduction guide for 
{Template->TemplatedDecl,view(cpp)na}
   
   
 {Type,view(cpp)}
@@ -613,9 +643,32 @@ For later versions of Visual Studio, no
   
 {Name}
   
+  
+
+{(ParsedTemplateArgument 
*)(this+1),view(cpp)na}{this,view(arg1)na}
+
+, {((ParsedTemplateArgument 
*)(this+1))+1,view(cpp)na}{this,view(arg2)na}
+
+, ...
+{Name,na}{this,view(arg0)na}
+
+  Name
+  
+{this,view(arg0)na}
+
+  
+NumArgs
+(ParsedTemplateArgument *)(this+1)
+  
+
+  
+  Operator
+
+  
   
-{(clang::tok::TokenKind)Kind,en}
-{{Identifier 
({*(clang::IdentifierInfo *)(PtrData)})}}
+{{annot_template_id 
({(clang::TemplateIdAnnotation *)(PtrData),na})}}
+{{Identifier 
({(clang::IdentifierInfo *)(PtrData),na})}}
+{(clang::tok::TokenKind)Kind,en}
   
   
 [{(clang::DeclSpec::SCS)StorageClassSpec}], 
[{(clang::TypeSpecifierType)TypeSpecType}]


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


[PATCH] D64264: [analyzer] exploded-graph-rewriter: Implement a topology-only mode.

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 208236.
NoQ added a comment.

Fxd!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64264/new/

https://reviews.llvm.org/D64264

Files:
  test/Analysis/exploded-graph-rewriter/topology.dot
  utils/analyzer/exploded-graph-rewriter.py


Index: utils/analyzer/exploded-graph-rewriter.py
===
--- utils/analyzer/exploded-graph-rewriter.py
+++ utils/analyzer/exploded-graph-rewriter.py
@@ -384,11 +384,12 @@
 # A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
 # syntax highlighing.
 class DotDumpVisitor(object):
-def __init__(self, do_diffs, dark_mode, gray_mode):
+def __init__(self, do_diffs, dark_mode, gray_mode, topo_mode):
 super(DotDumpVisitor, self).__init__()
 self._do_diffs = do_diffs
 self._dark_mode = dark_mode
 self._gray_mode = gray_mode
+self._topo_mode = topo_mode
 
 @staticmethod
 def _dump_raw(s):
@@ -766,18 +767,19 @@
 if node.is_sink:
 self._dump('Sink Node'
'')
-self._dump('')
-if len(node.points) > 1:
-self._dump('Program points:')
-else:
-self._dump('Program point:')
+if not self._topo_mode:
+self._dump('')
+if len(node.points) > 1:
+self._dump('Program points:')
+else:
+self._dump('Program point:')
 self._dump(''
'')
 for p in node.points:
 self.visit_program_point(p)
 self._dump('')
 
-if node.state is not None:
+if node.state is not None and not self._topo_mode:
 prev_s = None
 # Do diffs only when we have a unique predecessor.
 # Don't do diffs on the leaf nodes because they're
@@ -868,6 +870,9 @@
 parser.add_argument('-d', '--diff', action='store_const', dest='diff',
 const=True, default=False,
 help='display differences between states')
+parser.add_argument('-t', '--topology', action='store_const',
+dest='topology', const=True, default=False,
+help='only display program points, omit states')
 parser.add_argument('-s', '--single-path', action='store_const',
 dest='single_path', const=True, default=False,
 help='only display the leftmost path in the graph '
@@ -889,7 +894,7 @@
 graph.add_raw_line(raw_line)
 
 explorer = SinglePathExplorer() if args.single_path else BasicExplorer()
-visitor = DotDumpVisitor(args.diff, args.dark, args.gray)
+visitor = DotDumpVisitor(args.diff, args.dark, args.gray, args.topology)
 
 explorer.explore(graph, visitor)
 
Index: test/Analysis/exploded-graph-rewriter/topology.dot
===
--- /dev/null
+++ test/Analysis/exploded-graph-rewriter/topology.dot
@@ -0,0 +1,32 @@
+// RUN: %exploded_graph_rewriter %s \
+// RUN: | FileCheck -check-prefixes=NORMAL %s
+// RUN: %exploded_graph_rewriter -t %s \
+// RUN: | FileCheck -check-prefixes=TOPOLOGY %s
+
+// FIXME: Substitution doesn't seem to work on Windows.
+// UNSUPPORTED: system-windows
+
+// NORMAL: Program point
+// TOPOLOGY-NOT: Program point
+// NORMAL: Checker State
+// TOPOLOGY-NOT: Checker State
+Node0x1 [shape=record,label=
+ "{
+{ "node_id": 1,
+  "pointer": "0x1",
+  "has_report": false,
+  "is_sink": false,
+  "state_id": 2,
+  "program_points": [],
+  "program_state": {
+"environment": null,
+"constraints": null,
+"dynamic_types": null,
+"constructing_objects": null,
+"checker_messages": [
+  { "checker": "foo", "messages": ["bar"] }
+],
+"store": null
+  }
+}
+\l}"];


Index: utils/analyzer/exploded-graph-rewriter.py
===
--- utils/analyzer/exploded-graph-rewriter.py
+++ utils/analyzer/exploded-graph-rewriter.py
@@ -384,11 +384,12 @@
 # A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
 # syntax highlighing.
 class DotDumpVisitor(object):
-def __init__(self, do_diffs, dark_mode, gray_mode):
+def __init__(self, do_diffs, dark_mode, gray_mode, topo_mode):
 super(DotDumpVisitor, self).__init__()
 self._do_diffs = do_diffs
 self._dark_mode = dark_mode
 self._gray_mode = gray_mode
+self._topo_mode = topo_mode
 
 @staticmethod
 def _dump_raw(s):
@@ -766,18 +767,19 @@
 if node.is_sink:
 self._dump('Sink Node'
'')
-self._dump('')
-if len(node.points) > 1:
-self._dump('Program points:')
-else:
-self._dump('Program point:')
+if not self._topo_mode:
+

[PATCH] D64264: [analyzer] exploded-graph-rewriter: Implement a topology-only mode.

2019-07-05 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso accepted this revision.
Charusso added a comment.
This revision is now accepted and ready to land.

May you would remove the "Program points:" part as we only have that, but I 
think we have enough space for that tiny note. Thanks!


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64264/new/

https://reviews.llvm.org/D64264



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


[PATCH] D64263: [analyzer] exploded-graph-rewriter: Implement a single-path mode.

2019-07-05 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso accepted this revision.
Charusso added a comment.
This revision is now accepted and ready to land.

Smart move! The left-most usually the shortest path, but what if not? I would 
calculate the length, other than that, cool. Thanks!


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64263/new/

https://reviews.llvm.org/D64263



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


[PATCH] D64263: [analyzer] exploded-graph-rewriter: Implement a single-path mode.

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added a reviewer: Charusso.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: clang.

Instead of rewriting the whole graph, rewrite the leftmost path in the graph. 
Useful for trimmed graphs that are still too large to display due to multiple 
equivalent reports mixed into them.


Repository:
  rC Clang

https://reviews.llvm.org/D64263

Files:
  clang/test/Analysis/exploded-graph-rewriter/explorers.dot
  clang/utils/analyzer/exploded-graph-rewriter.py

Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -804,8 +804,7 @@
 #===---===#
 
 
-# A class that encapsulates traversal of the ExplodedGraph. Different explorer
-# kinds could potentially traverse specific sub-graphs.
+# BasicExplorer explores the whole graph in no particular order.
 class BasicExplorer(object):
 def __init__(self):
 super(BasicExplorer, self).__init__()
@@ -821,6 +820,39 @@
 visitor.visit_end_of_graph()
 
 
+# SinglePathExplorer traverses only a single path - the leftmost path
+# from the root. Useful when the trimmed graph is still too large
+# due to a large amount of equivalent reports.
+class SinglePathExplorer(object):
+def __init__(self):
+super(SinglePathExplorer, self).__init__()
+
+def explore(self, graph, visitor):
+visitor.visit_begin_graph(graph)
+
+# Keep track of visited nodes in order to avoid loops.
+visited = set()
+node_id = graph.root_id
+while True:
+visited.add(node_id)
+node = graph.nodes[node_id]
+logging.debug('Visiting ' + node_id)
+visitor.visit_node(node)
+if len(node.successors) == 0:
+break
+
+succ_id = node.successors[0]
+succ = graph.nodes[succ_id]
+logging.debug('Visiting edge: %s -> %s ' % (node_id, succ_id))
+visitor.visit_edge(node, succ)
+if succ_id in visited:
+break
+
+node_id = succ_id
+
+visitor.visit_end_of_graph()
+
+
 #===---===#
 # The entry point to the script.
 #===---===#
@@ -836,6 +868,11 @@
 parser.add_argument('-d', '--diff', action='store_const', dest='diff',
 const=True, default=False,
 help='display differences between states')
+parser.add_argument('-s', '--single-path', action='store_const',
+dest='single_path', const=True, default=False,
+help='only display the leftmost path in the graph '
+ '(useful for trimmed graphs that still '
+ 'branch too much)')
 parser.add_argument('--dark', action='store_const', dest='dark',
 const=True, default=False,
 help='dark mode')
@@ -851,8 +888,9 @@
 raw_line = raw_line.strip()
 graph.add_raw_line(raw_line)
 
-explorer = BasicExplorer()
+explorer = SinglePathExplorer() if args.single_path else BasicExplorer()
 visitor = DotDumpVisitor(args.diff, args.dark, args.gray)
+
 explorer.explore(graph, visitor)
 
 
Index: clang/test/Analysis/exploded-graph-rewriter/explorers.dot
===
--- /dev/null
+++ clang/test/Analysis/exploded-graph-rewriter/explorers.dot
@@ -0,0 +1,37 @@
+// RUN: %exploded_graph_rewriter %s \
+// RUN: | FileCheck %s -check-prefixes=CHECK,BASIC
+// RUN: %exploded_graph_rewriter -s %s \
+// RUN: | FileCheck %s -check-prefixes=CHECK,SINGLE
+
+// FIXME: Substitution doesn't seem to work on Windows.
+// UNSUPPORTED: system-windows
+
+Node0x1 [shape=record,label=
+ "{{ "node_id": 1, "pointer": "0x1", "has_report": false, "is_sink": false,
+  "program_state": null, "program_points": []}\l}"];
+
+Node0x2 [shape=record,label=
+ "{{ "node_id": 2, "pointer": "0x2", "has_report": false, "is_sink": false,
+  "program_state": null, "program_points": []}\l}"];
+
+Node0x3 [shape=record,label=
+ "{{ "node_id": 3, "pointer": "0x3", "has_report": false, "is_sink": false,
+  "program_state": null, "program_points": []}\l}"];
+
+Node0x4 [shape=record,label=
+ "{{ "node_id": 4, "pointer": "0x4", "has_report": false, "is_sink": false,
+  "program_state": null, "program_points": []}\l}"];
+
+// CHECK: Node0x1 -> Node0x2;
+Node0x1 -> Node0x2;
+
+// BASIC: Node0x1 -> Node0x3;
+// SINGLE-NOT: Node0x1 -> Node0x3;
+Node0x1 -> Node0x3;
+
+// CHECK: Node0x2 -> Node0x4;

[PATCH] D64262: Bitstream reader: Fix undefined behavior seen after rL364464

2019-07-05 Thread Bjorn Pettersson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365239: Bitstream reader: Fix undefined behavior seen after 
rL364464 (authored by bjope, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64262?vs=208222=208226#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64262/new/

https://reviews.llvm.org/D64262

Files:
  cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
  clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp


Index: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
===
--- clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
+++ clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
@@ -615,10 +615,12 @@
   return Cursor::BadBlock;
 }
 
-// FIXME check that the enum is in range.
-auto Code = static_cast(MaybeCode.get());
-
-switch (Code) {
+unsigned Code = MaybeCode.get();
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected MaybeID = Stream.ReadSubBlockID())
 BlockOrRecordID = MaybeID.get();
@@ -639,9 +641,8 @@
   continue;
 case llvm::bitc::UNABBREV_RECORD:
   return Cursor::BadBlock;
-default:
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
   llvm_unreachable("Premature stream end.");
Index: cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
===
--- cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
+++ cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
@@ -124,7 +124,12 @@
 else
   return llvm::errorToErrorCode(Res.takeError());
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  // We found a record.
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected Res = Stream.ReadSubBlockID())
 BlockOrRecordID = Res.get();
@@ -145,10 +150,8 @@
 case llvm::bitc::UNABBREV_RECORD:
   return SDError::UnsupportedConstruct;
 
-default:
-  // We found a record.
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
 


Index: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
===
--- clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
+++ clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
@@ -615,10 +615,12 @@
   return Cursor::BadBlock;
 }
 
-// FIXME check that the enum is in range.
-auto Code = static_cast(MaybeCode.get());
-
-switch (Code) {
+unsigned Code = MaybeCode.get();
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected MaybeID = Stream.ReadSubBlockID())
 BlockOrRecordID = MaybeID.get();
@@ -639,9 +641,8 @@
   continue;
 case llvm::bitc::UNABBREV_RECORD:
   return Cursor::BadBlock;
-default:
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
   llvm_unreachable("Premature stream end.");
Index: cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
===
--- cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
+++ cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
@@ -124,7 +124,12 @@
 else
   return llvm::errorToErrorCode(Res.takeError());
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  // We found a record.
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected Res = Stream.ReadSubBlockID())
 BlockOrRecordID = Res.get();
@@ -145,10 +150,8 @@
 case llvm::bitc::UNABBREV_RECORD:
   return SDError::UnsupportedConstruct;
 
-default:
-  // We found a record.
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D64264: [analyzer] exploded-graph-rewriter: Implement a topology-only mode.

2019-07-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added a reviewer: Charusso.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: clang.

In this mode the rewriter will only rewrite program points and omit program 
states. Useful for understanding the rough topology of the graph.

F9470109: Screen Shot 2019-07-05 at 1.20.29 PM.png 



Repository:
  rC Clang

https://reviews.llvm.org/D64264

Files:
  clang/test/Analysis/exploded-graph-rewriter/topology.dot
  clang/utils/analyzer/exploded-graph-rewriter.py


Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -384,11 +384,12 @@
 # A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
 # syntax highlighing.
 class DotDumpVisitor(object):
-def __init__(self, do_diffs, dark_mode, gray_mode):
+def __init__(self, do_diffs, dark_mode, gray_mode, topo_mode):
 super(DotDumpVisitor, self).__init__()
 self._do_diffs = do_diffs
 self._dark_mode = dark_mode
 self._gray_mode = gray_mode
+self._topo_mode = topo_mode
 
 @staticmethod
 def _dump_raw(s):
@@ -777,7 +778,7 @@
 self.visit_program_point(p)
 self._dump('')
 
-if node.state is not None:
+if node.state is not None and not self._topo_mode:
 prev_s = None
 # Do diffs only when we have a unique predecessor.
 # Don't do diffs on the leaf nodes because they're
@@ -868,6 +869,9 @@
 parser.add_argument('-d', '--diff', action='store_const', dest='diff',
 const=True, default=False,
 help='display differences between states')
+parser.add_argument('-t', '--topology', action='store_const',
+dest='topology', const=True, default=False,
+help='only display program points, omit states')
 parser.add_argument('-s', '--single-path', action='store_const',
 dest='single_path', const=True, default=False,
 help='only display the leftmost path in the graph '
@@ -889,7 +893,7 @@
 graph.add_raw_line(raw_line)
 
 explorer = SinglePathExplorer() if args.single_path else BasicExplorer()
-visitor = DotDumpVisitor(args.diff, args.dark, args.gray)
+visitor = DotDumpVisitor(args.diff, args.dark, args.gray, args.topology)
 
 explorer.explore(graph, visitor)
 
Index: clang/test/Analysis/exploded-graph-rewriter/topology.dot
===
--- /dev/null
+++ clang/test/Analysis/exploded-graph-rewriter/topology.dot
@@ -0,0 +1,30 @@
+// RUN: %exploded_graph_rewriter %s \
+// RUN: | FileCheck -check-prefixes=NORMAL %s
+// RUN: %exploded_graph_rewriter -t %s \
+// RUN: | FileCheck -check-prefixes=TOPOLOGY %s
+
+// FIXME: Substitution doesn't seem to work on Windows.
+// UNSUPPORTED: system-windows
+
+// NORMAL: Checker State:
+// TOPOLOGY-NOT: Checker State:
+Node0x1 [shape=record,label=
+ "{
+{ "node_id": 1,
+  "pointer": "0x1",
+  "has_report": false,
+  "is_sink": false,
+  "state_id": 2,
+  "program_points": [],
+  "program_state": {
+"environment": null,
+"constraints": null,
+"dynamic_types": null,
+"constructing_objects": null,
+"checker_messages": [
+  { "checker": "foo", "messages": ["bar"] }
+],
+"store": null
+  }
+}
+\l}"];


Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -384,11 +384,12 @@
 # A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
 # syntax highlighing.
 class DotDumpVisitor(object):
-def __init__(self, do_diffs, dark_mode, gray_mode):
+def __init__(self, do_diffs, dark_mode, gray_mode, topo_mode):
 super(DotDumpVisitor, self).__init__()
 self._do_diffs = do_diffs
 self._dark_mode = dark_mode
 self._gray_mode = gray_mode
+self._topo_mode = topo_mode
 
 @staticmethod
 def _dump_raw(s):
@@ -777,7 +778,7 @@
 self.visit_program_point(p)
 self._dump('')
 
-if node.state is not None:
+if node.state is not None and not self._topo_mode:
 prev_s = None
 # Do diffs only when we have a unique predecessor.
 # Don't do diffs on the leaf nodes because they're
@@ -868,6 +869,9 @@
 parser.add_argument('-d', '--diff', action='store_const', dest='diff',
 const=True, default=False,
 

r365239 - Bitstream reader: Fix undefined behavior seen after rL364464

2019-07-05 Thread Bjorn Pettersson via cfe-commits
Author: bjope
Date: Fri Jul  5 13:22:40 2019
New Revision: 365239

URL: http://llvm.org/viewvc/llvm-project?rev=365239=rev
Log:
Bitstream reader: Fix undefined behavior seen after rL364464

Summary:
After rL364464 the following tests started to fail when
running the clang-doc tests with an ubsan instrumented
build of clang-doc:
Clang Tools :: clang-doc/single-file-public.cpp
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitEnumInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitRecordInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/SerializeTest.emitInfoWithCommentBitcode

We need to check that the read value is in range for being
casted to the llvm::bitc::FixedAbbrevIDs enum, before the
cast in ClangDocBitcodeReader::skipUntilRecordOrBlock.

SerializedDiagnosticReader::skipUntilRecordOrBlock was updated
in the same way.

Reviewers: jfb

Reviewed By: jfb

Subscribers: Bigcheese, vsapsai, bruno, ilya-biryukov, dexonsmith, kadircet, 
cfe-commits

Tags: #clang

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

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

Modified: cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp?rev=365239=365238=365239=diff
==
--- cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp (original)
+++ cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp Fri Jul  5 13:22:40 
2019
@@ -124,7 +124,12 @@ SerializedDiagnosticReader::skipUntilRec
 else
   return llvm::errorToErrorCode(Res.takeError());
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  // We found a record.
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected Res = Stream.ReadSubBlockID())
 BlockOrRecordID = Res.get();
@@ -145,10 +150,8 @@ SerializedDiagnosticReader::skipUntilRec
 case llvm::bitc::UNABBREV_RECORD:
   return SDError::UnsupportedConstruct;
 
-default:
-  // We found a record.
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
 


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


[clang-tools-extra] r365239 - Bitstream reader: Fix undefined behavior seen after rL364464

2019-07-05 Thread Bjorn Pettersson via cfe-commits
Author: bjope
Date: Fri Jul  5 13:22:40 2019
New Revision: 365239

URL: http://llvm.org/viewvc/llvm-project?rev=365239=rev
Log:
Bitstream reader: Fix undefined behavior seen after rL364464

Summary:
After rL364464 the following tests started to fail when
running the clang-doc tests with an ubsan instrumented
build of clang-doc:
Clang Tools :: clang-doc/single-file-public.cpp
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitEnumInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitRecordInfoBitcode
Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/SerializeTest.emitInfoWithCommentBitcode

We need to check that the read value is in range for being
casted to the llvm::bitc::FixedAbbrevIDs enum, before the
cast in ClangDocBitcodeReader::skipUntilRecordOrBlock.

SerializedDiagnosticReader::skipUntilRecordOrBlock was updated
in the same way.

Reviewers: jfb

Reviewed By: jfb

Subscribers: Bigcheese, vsapsai, bruno, ilya-biryukov, dexonsmith, kadircet, 
cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp

Modified: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp?rev=365239=365238=365239=diff
==
--- clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp (original)
+++ clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp Fri Jul  5 13:22:40 2019
@@ -615,10 +615,12 @@ ClangDocBitcodeReader::skipUntilRecordOr
   return Cursor::BadBlock;
 }
 
-// FIXME check that the enum is in range.
-auto Code = static_cast(MaybeCode.get());
-
-switch (Code) {
+unsigned Code = MaybeCode.get();
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected MaybeID = Stream.ReadSubBlockID())
 BlockOrRecordID = MaybeID.get();
@@ -639,9 +641,8 @@ ClangDocBitcodeReader::skipUntilRecordOr
   continue;
 case llvm::bitc::UNABBREV_RECORD:
   return Cursor::BadBlock;
-default:
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
   llvm_unreachable("Premature stream end.");


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


[PATCH] D63845: [WIP] Create a clang attribute that lets users specify LLVM attributes

2019-07-05 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

I think we should postpone a detailed discussion until we are ready to send an 
RFC on this. Nevertheless, I inlined some responses below.

In D63845#1570639 , @aaron.ballman 
wrote:

> In D63845#1566987 , @jdoerfert wrote:
>
> > In D63845#1561983 , @lebedev.ri 
> > wrote:
> >
> > > In D63845#1561793 , @jdoerfert 
> > > wrote:
> > >
> > > > In D63845#1560605 , 
> > > > @aaron.ballman wrote:
> > > >
> > > > > In D63845#1559995 , 
> > > > > @lebedev.ri wrote:
> > > > >
> > > > > > What's the target use-case here? What can't be solved with normal 
> > > > > > attributes?
> > > > >
> > > >
> > > >
> > > > With "normal" you mean something like `__attribute__((noescape))`? We 
> > > > don't have them for all attributes, I doubt we want to but I might be 
> > > > wrong.
> > >
> > >
> > > That is precisely the question.
> > >  What is the motivation for exposing such LLVM-specific low-level 
> > > unstable implementation detail?
> >
> >
> > I would disagree to the unstable part. Keeping LLVM-IR backward 
> > compatibility is always a priority and changing the meaning of an existing 
> > LLVM-IR attribute will break various things already.
> >  Why would you think it is unstable?
>
>
> Because, to date, we've never made blanket any stability guarantees about 
> LLVM attributes from within the context of Clang. Instead, LLVM attributes 
> are introduced into Clang on a case by case basis when they've been 
> determined to be stable enough to warrant exposing. This extra layer also 
> gives us more flexibility in translating frontend attributes into backend 
> attributes.


You still assume LLVM attributes are not stable while I tried to argue they 
are, they have to be already for backward compatibility, at least target 
agnostic ones.

Your example below was `thunk` and you mentioned other problems that can arise 
but I think we should step back for a moment and talk about the use case here 
because that should limit the potential problems. For me the use case is as 
follows: The user, or a tool, wants to encode additional information in the 
source to aide optimization. The basically only way to do this in IR is to add 
attributes to one of three locations, (1) function level, (2) return value 
level, or (3) argument level. For all three we have examples in Clang so we 
know how do interact with templates, and other potential hurdles. Now it is not 
the goal to allow all attributes as some of them encode not information but 
implementation details, e.g., `thunk`. I'm basically interested in attributes 
that can be safely derived and dropped in he IR today.

>> Also, we basically do expose the low-level parts one by one through "normal" 
>> attributes as soon as someone has enough motivation to write all the 
>> necessary boilerplate (see more below). Why not merge all the logic/code-gen 
>> into a single uniform framework that deals with LLVM-IR attributes?
> 
> Because that increases the chance of bad user experiences by lowering the bar 
> that ensures newly added attributes behave well for user code. That 
> boilerplate exists for a reason and forces a developer to make decisions 
> (like what number and kind of arguments are accepted, what spellings make 
> sense for the attribute, what subjects the attribute appertains to, etc).

We can still make all these decisions, this patch almost makes all of them 
explicit. We can whitelist arguments (through the switch that exists), we can 
rename them between the FE and IR if we want to (though I would prefer not to), 
and we do restrict the positions already to the three interesting ones.

>> In D63845#1564289 , @aaron.ballman 
>> wrote:
>> 
>>> > In D63845#1561983 , @lebedev.ri 
>>> > wrote:
>>> > 
>>> >> In D63845#1561793 , @jdoerfert 
>>> >> wrote:
>>> >>
>>> >> > In D63845#1560605 , 
>>> >> > @aaron.ballman wrote:
>>> >> >
>>> >> > > In D63845#1559995 , 
>>> >> > > @lebedev.ri wrote:
>>> >> > >
>>> >> > > > What's the target use-case here? What can't be solved with normal 
>>> >> > > > attributes?
>>> >> > >
>>> >> >
>>> >> >
>>> >> > With "normal" you mean something like `__attribute__((noescape))`? We 
>>> >> > don't have them for all attributes, I doubt we want to but I might be 
>>> >> > wrong.
>>> >>
>>> >>
>>> >> That is precisely the question.
>>> >>  What is the motivation for exposing such LLVM-specific low-level 
>>> >> unstable implementation detail?
>>> > 
>>> > 
>>> > There's a couple of potential use cases for this -- most of which are 
>>> > more for LLVM developers than end 

[PATCH] D63518: BitStream reader: propagate errors

2019-07-05 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp:619
+// FIXME check that the enum is in range.
+auto Code = static_cast(MaybeCode.get());
+

jfb wrote:
> jfb wrote:
> > bjope wrote:
> > > This has caused problem for our sanitizer tests the last couple of days:
> > > 
> > > ```
> > > FAIL: Extra Tools Unit Tests :: 
> > > clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode (20077 of 
> > > 48746)
> > >  TEST 'Extra Tools Unit Tests :: 
> > > clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode' FAILED 
> > > 
> > > Note: Google Test filter = BitcodeTest.emitMethodInfoBitcode
> > > [==] Running 1 test from 1 test case.
> > > [--] Global test environment set-up.
> > > [--] 1 test from BitcodeTest
> > > [ RUN  ] BitcodeTest.emitMethodInfoBitcode
> > > /local/repo/bbiswjenk/fem023-eiffel003/workspace/llvm/llvm-master-sanitize/clang-tools-extra/clang-doc/BitcodeReader.cpp:621:13:
> > >  runtime error: load of value 9, which is not a valid value for type 
> > > 'llvm::bitc::FixedAbbrevIDs'
> > > 
> > > ```
> > > 
> > > This was seen when building trunk with clang 6.0.0 and 
> > > LVM_USE_SANITIZER=Undefined
> > > 
> > > ```
> > > cmake -G Ninja '-DLLVM_ENABLE_PROJECTS='\''clang;clang-tools-extra'\''' 
> > > -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON 
> > > '-DCMAKE_CXX_FLAGS='\''-stdlib=libc++'\''' -DCMAKE_C_COMPILER=clang 
> > > -DCMAKE_CXX_COMPILER=clang++ -DLLVM_USE_LINKER=gold 
> > > -DLLVM_USE_SANITIZER=Undefined ../.
> > > -- The C compiler identification is Clang 6.0.0
> > > -- The CXX compiler identification is Clang 6.0.0
> > > ```
> > > 
> > > Afaict we can't cast the read value to FixedAbbrevIDs as we do not know 
> > > yet if it matches one of the values defined in the enum, or if we will 
> > > take the default case.
> > > 
> > > 
> > > A similar switch exist at 
> > > cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp:127, but it is 
> > > using a slightly different pattern:
> > > 
> > > ```
> > > unsigned Code;
> > > Code = Res.get();
> > > switch ((llvm::bitc::FixedAbbrevIDs)Code) 
> > > ```
> > > I haven't seen any failures for SerializedDiagnosticReader. So either we 
> > > lack test coverage for that function, or the sanitizer only introduce the 
> > > check when using the static_cast (and declaring Code as an enum) as done 
> > > here.
> > > 
> > That sounds like a pre-existing bug. We should check that the value is in 
> > range before casting. Can you send patches to fix both code locations, and 
> > add test coverage? This code is indeed poorly tested.
> > 
> > Why do the sanitizers catch `static_cast` but not C-style casts?
> To be clear: relying on the `default` case is still UB because there's a cast 
> to the enum type before it occurs.
I made a patch here (assuming the goal would be to keep the cast to the enum, 
and to let the switch cover all enum values): https://reviews.llvm.org/D64262


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63518/new/

https://reviews.llvm.org/D63518



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


[PATCH] D64262: Bitstream reader: Fix undefined behavior seen after rL364464

2019-07-05 Thread JF Bastien via Phabricator via cfe-commits
jfb accepted this revision.
jfb added a comment.
This revision is now accepted and ready to land.

Thanks for catching this!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64262/new/

https://reviews.llvm.org/D64262



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


[PATCH] D64262: Bitstream reader: Fix undefined behavior seen after rL364464

2019-07-05 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope created this revision.
bjope added a reviewer: jfb.
Herald added subscribers: kadircet, dexonsmith, ilya-biryukov.
Herald added a project: clang.

After rL364464  the following tests started 
to fail when
running the clang-doc tests with an ubsan instrumented
build of clang-doc:

  Clang Tools :: clang-doc/single-file-public.cpp
  Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitEnumInfoBitcode
  Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode
  Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitRecordInfoBitcode
  Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/SerializeTest.emitInfoWithCommentBitcode

We need to check that the read value is in range for being
casted to the llvm::bitc::FixedAbbrevIDs enum, before the
cast in ClangDocBitcodeReader::skipUntilRecordOrBlock.

SerializedDiagnosticReader::skipUntilRecordOrBlock was updated
in the same way.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64262

Files:
  clang-tools-extra/clang-doc/BitcodeReader.cpp
  clang/lib/Frontend/SerializedDiagnosticReader.cpp


Index: clang/lib/Frontend/SerializedDiagnosticReader.cpp
===
--- clang/lib/Frontend/SerializedDiagnosticReader.cpp
+++ clang/lib/Frontend/SerializedDiagnosticReader.cpp
@@ -124,7 +124,12 @@
 else
   return llvm::errorToErrorCode(Res.takeError());
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  // We found a record.
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected Res = Stream.ReadSubBlockID())
 BlockOrRecordID = Res.get();
@@ -145,10 +150,8 @@
 case llvm::bitc::UNABBREV_RECORD:
   return SDError::UnsupportedConstruct;
 
-default:
-  // We found a record.
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
 
Index: clang-tools-extra/clang-doc/BitcodeReader.cpp
===
--- clang-tools-extra/clang-doc/BitcodeReader.cpp
+++ clang-tools-extra/clang-doc/BitcodeReader.cpp
@@ -615,10 +615,12 @@
   return Cursor::BadBlock;
 }
 
-// FIXME check that the enum is in range.
-auto Code = static_cast(MaybeCode.get());
-
-switch (Code) {
+unsigned Code = MaybeCode.get();
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected MaybeID = Stream.ReadSubBlockID())
 BlockOrRecordID = MaybeID.get();
@@ -639,9 +641,8 @@
   continue;
 case llvm::bitc::UNABBREV_RECORD:
   return Cursor::BadBlock;
-default:
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
   llvm_unreachable("Premature stream end.");


Index: clang/lib/Frontend/SerializedDiagnosticReader.cpp
===
--- clang/lib/Frontend/SerializedDiagnosticReader.cpp
+++ clang/lib/Frontend/SerializedDiagnosticReader.cpp
@@ -124,7 +124,12 @@
 else
   return llvm::errorToErrorCode(Res.takeError());
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  // We found a record.
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected Res = Stream.ReadSubBlockID())
 BlockOrRecordID = Res.get();
@@ -145,10 +150,8 @@
 case llvm::bitc::UNABBREV_RECORD:
   return SDError::UnsupportedConstruct;
 
-default:
-  // We found a record.
-  BlockOrRecordID = Code;
-  return Cursor::Record;
+case llvm::bitc::FIRST_APPLICATION_ABBREV:
+  llvm_unreachable("Unexpected abbrev id.");
 }
   }
 
Index: clang-tools-extra/clang-doc/BitcodeReader.cpp
===
--- clang-tools-extra/clang-doc/BitcodeReader.cpp
+++ clang-tools-extra/clang-doc/BitcodeReader.cpp
@@ -615,10 +615,12 @@
   return Cursor::BadBlock;
 }
 
-// FIXME check that the enum is in range.
-auto Code = static_cast(MaybeCode.get());
-
-switch (Code) {
+unsigned Code = MaybeCode.get();
+if (Code >= static_cast(llvm::bitc::FIRST_APPLICATION_ABBREV)) {
+  BlockOrRecordID = Code;
+  return Cursor::Record;
+}
+switch (static_cast(Code)) {
 case llvm::bitc::ENTER_SUBBLOCK:
   if (Expected MaybeID = 

[PATCH] D61467: [Rewrite] Extend to further accept CharSourceRange

2019-07-05 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Could you describe the unit tests a little, what is tested and why.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61467/new/

https://reviews.llvm.org/D61467



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


[PATCH] D63518: BitStream reader: propagate errors

2019-07-05 Thread JF Bastien via Phabricator via cfe-commits
jfb marked an inline comment as done.
jfb added inline comments.



Comment at: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp:619
+// FIXME check that the enum is in range.
+auto Code = static_cast(MaybeCode.get());
+

jfb wrote:
> bjope wrote:
> > This has caused problem for our sanitizer tests the last couple of days:
> > 
> > ```
> > FAIL: Extra Tools Unit Tests :: 
> > clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode (20077 of 48746)
> >  TEST 'Extra Tools Unit Tests :: 
> > clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode' FAILED 
> > 
> > Note: Google Test filter = BitcodeTest.emitMethodInfoBitcode
> > [==] Running 1 test from 1 test case.
> > [--] Global test environment set-up.
> > [--] 1 test from BitcodeTest
> > [ RUN  ] BitcodeTest.emitMethodInfoBitcode
> > /local/repo/bbiswjenk/fem023-eiffel003/workspace/llvm/llvm-master-sanitize/clang-tools-extra/clang-doc/BitcodeReader.cpp:621:13:
> >  runtime error: load of value 9, which is not a valid value for type 
> > 'llvm::bitc::FixedAbbrevIDs'
> > 
> > ```
> > 
> > This was seen when building trunk with clang 6.0.0 and 
> > LVM_USE_SANITIZER=Undefined
> > 
> > ```
> > cmake -G Ninja '-DLLVM_ENABLE_PROJECTS='\''clang;clang-tools-extra'\''' 
> > -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON 
> > '-DCMAKE_CXX_FLAGS='\''-stdlib=libc++'\''' -DCMAKE_C_COMPILER=clang 
> > -DCMAKE_CXX_COMPILER=clang++ -DLLVM_USE_LINKER=gold 
> > -DLLVM_USE_SANITIZER=Undefined ../.
> > -- The C compiler identification is Clang 6.0.0
> > -- The CXX compiler identification is Clang 6.0.0
> > ```
> > 
> > Afaict we can't cast the read value to FixedAbbrevIDs as we do not know yet 
> > if it matches one of the values defined in the enum, or if we will take the 
> > default case.
> > 
> > 
> > A similar switch exist at 
> > cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp:127, but it is using 
> > a slightly different pattern:
> > 
> > ```
> > unsigned Code;
> > Code = Res.get();
> > switch ((llvm::bitc::FixedAbbrevIDs)Code) 
> > ```
> > I haven't seen any failures for SerializedDiagnosticReader. So either we 
> > lack test coverage for that function, or the sanitizer only introduce the 
> > check when using the static_cast (and declaring Code as an enum) as done 
> > here.
> > 
> That sounds like a pre-existing bug. We should check that the value is in 
> range before casting. Can you send patches to fix both code locations, and 
> add test coverage? This code is indeed poorly tested.
> 
> Why do the sanitizers catch `static_cast` but not C-style casts?
To be clear: relying on the `default` case is still UB because there's a cast 
to the enum type before it occurs.


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63518/new/

https://reviews.llvm.org/D63518



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


[PATCH] D63518: BitStream reader: propagate errors

2019-07-05 Thread JF Bastien via Phabricator via cfe-commits
jfb marked 2 inline comments as done.
jfb added inline comments.



Comment at: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp:619
+// FIXME check that the enum is in range.
+auto Code = static_cast(MaybeCode.get());
+

bjope wrote:
> This has caused problem for our sanitizer tests the last couple of days:
> 
> ```
> FAIL: Extra Tools Unit Tests :: 
> clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode (20077 of 48746)
>  TEST 'Extra Tools Unit Tests :: 
> clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode' FAILED 
> 
> Note: Google Test filter = BitcodeTest.emitMethodInfoBitcode
> [==] Running 1 test from 1 test case.
> [--] Global test environment set-up.
> [--] 1 test from BitcodeTest
> [ RUN  ] BitcodeTest.emitMethodInfoBitcode
> /local/repo/bbiswjenk/fem023-eiffel003/workspace/llvm/llvm-master-sanitize/clang-tools-extra/clang-doc/BitcodeReader.cpp:621:13:
>  runtime error: load of value 9, which is not a valid value for type 
> 'llvm::bitc::FixedAbbrevIDs'
> 
> ```
> 
> This was seen when building trunk with clang 6.0.0 and 
> LVM_USE_SANITIZER=Undefined
> 
> ```
> cmake -G Ninja '-DLLVM_ENABLE_PROJECTS='\''clang;clang-tools-extra'\''' 
> -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON 
> '-DCMAKE_CXX_FLAGS='\''-stdlib=libc++'\''' -DCMAKE_C_COMPILER=clang 
> -DCMAKE_CXX_COMPILER=clang++ -DLLVM_USE_LINKER=gold 
> -DLLVM_USE_SANITIZER=Undefined ../.
> -- The C compiler identification is Clang 6.0.0
> -- The CXX compiler identification is Clang 6.0.0
> ```
> 
> Afaict we can't cast the read value to FixedAbbrevIDs as we do not know yet 
> if it matches one of the values defined in the enum, or if we will take the 
> default case.
> 
> 
> A similar switch exist at 
> cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp:127, but it is using a 
> slightly different pattern:
> 
> ```
> unsigned Code;
> Code = Res.get();
> switch ((llvm::bitc::FixedAbbrevIDs)Code) 
> ```
> I haven't seen any failures for SerializedDiagnosticReader. So either we lack 
> test coverage for that function, or the sanitizer only introduce the check 
> when using the static_cast (and declaring Code as an enum) as done here.
> 
That sounds like a pre-existing bug. We should check that the value is in range 
before casting. Can you send patches to fix both code locations, and add test 
coverage? This code is indeed poorly tested.

Why do the sanitizers catch `static_cast` but not C-style casts?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63518/new/

https://reviews.llvm.org/D63518



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


[PATCH] D64257: [clangd] Added highlighting for non-builtin types

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, sammccall, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Added highlighting for non-builtin types using VisitTypeLoc. Ignoring namespace 
qualifiers as for now.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64257

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/test/semantic-highlighting.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -34,11 +34,12 @@
   auto AST = TestTU::withCode(Test.code()).build();
   static const std::map KindToString{
   {HighlightingKind::Variable, "Variable"},
-  {HighlightingKind::Function, "Function"}};
+  {HighlightingKind::Function, "Function"},
+  {HighlightingKind::Type, "Type"}};
   std::vector ExpectedTokens;
   for (const auto  : KindToString) {
-std::vector Toks =
-makeHighlightingTokens(Test.ranges(KindString.second), KindString.first);
+std::vector Toks = makeHighlightingTokens(
+Test.ranges(KindString.second), KindString.first);
 ExpectedTokens.insert(ExpectedTokens.end(), Toks.begin(), Toks.end());
   }
 
@@ -49,14 +50,14 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
 R"cpp(
-  struct AS {
+  struct $Type[[AS]] {
 double SomeMember;
   };
-  struct {
+  $Type[[struct]] {
   } $Variable[[S]];
-  void $Function[[foo]](int $Variable[[A]]) {
+  void $Function[[foo]](int $Variable[[A]], $Type[[AS]] $Variable[[As]]) {
 auto $Variable[[VeryLongVariableName]] = 12312;
-AS $Variable[[AA]];
+$Type[[AS]] $Variable[[AA]];
 auto $Variable[[L]] = $Variable[[AA]].SomeMember + $Variable[[A]];
 auto $Variable[[FN]] = [ $Variable[[AA]]](int $Variable[[A]]) -> void {};
 $Variable[[FN]](12312);
@@ -70,11 +71,18 @@
   }
 )cpp",
 R"cpp(
-  struct A {
+  namespace abc {
+template
+struct $Type[[A]] {};
+  }
+  abc::$Type[[A]] $Variable[[AA]];
+)cpp",
+R"cpp(
+  struct $Type[[A]] {
 A();
 ~A();
 void $Function[[abc]]();
-void operator<<(int);
+void operator<<($Type[[A]]);
   };
 )cpp"};
   for (const auto  : TestCases) {
Index: clang-tools-extra/clangd/test/semantic-highlighting.test
===
--- clang-tools-extra/clangd/test/semantic-highlighting.test
+++ clang-tools-extra/clangd/test/semantic-highlighting.test
@@ -10,6 +10,9 @@
 # CHECK-NEXT:  [
 # CHECK-NEXT:"entity.name.function.cpp"
 # CHECK-NEXT:  ]
+# CHECK-NEXT:  [
+# CHECK-NEXT:"entity.name.type.cpp"
+# CHECK-NEXT:  ]
 # CHECK-NEXT:]
 # CHECK-NEXT:  },
 ---
Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -26,6 +26,7 @@
 enum class HighlightingKind {
   Variable = 0,
   Function,
+  Type,
 
   NumKinds,
 };
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -56,6 +56,36 @@
 return true;
   }
 
+  bool VisitTypeLoc(TypeLoc ) {
+// The check for DependentName is so namespace qualifiers are not
+// highlighted. The check for elaborated type is for not getting two entries
+// whenever there is an anonymous struct.
+if (TL.getTypeLocClass() == TypeLoc::TypeLocClass::DependentName ||
+TL.getTypeLocClass() == TypeLoc::TypeLocClass::Elaborated) {
+  return true;
+}
+
+TagDecl *D = TL.getTypePtr()->getAsTagDecl();
+if (!D)
+  return true;
+
+if (auto RD = dyn_cast(D)) {
+  if (auto DC = RD->getDestructor()) {
+auto Range = DC->getSourceRange();
+// Destructors appear as a TagTypeLoc RecordDecl. To not highlight
+// destructors incorrectly the TagTypeLoc is skipped if it is wrapped
+// inside the actual destructor.
+if (Range.getBegin() < TL.getBeginLoc() &&
+TL.getBeginLoc() < Range.getEnd()) {
+  return true;
+}
+  }
+}
+
+addToken(TL.getBeginLoc(), D);
+return true;
+  }
+
 private:
   void addToken(SourceLocation Loc, const Decl *D) {
 if (isa(D)) {
@@ -66,6 +96,10 @@
   

[PATCH] D64256: Teach some warnings to respect gsd::Pointer and gsl::Owner attributes

2019-07-05 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun created this revision.
xazax.hun added reviewers: mgehre, rsmith, gribozavr.
Herald added subscribers: cfe-commits, Charusso, gamesh411, Szelethus, dkrupp, 
rnkovacs.
Herald added a project: clang.

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

The implicit assumption of this patch is that if a class annotated with 
gsl::Pointer is created from a gsl::Owner (through conversion operator or a 
constructor taking the owner as the first argument) the Pointer will point to 
the buffer of the Owner, so it will dangle after the lifetime of the Owner ends.


Repository:
  rC Clang

https://reviews.llvm.org/D64256

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Index: clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- /dev/null
+++ clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -0,0 +1,104 @@
+// RUN: %clang_cc1 -fsyntax-only -Wdangling -Wdangling-field -Wreturn-stack-address -verify %s
+struct [[gsl::Owner(int)]] MyOwner {
+  MyOwner();
+  int *();
+};
+
+struct T;
+
+struct [[gsl::Pointer(int)]] MyPointer {
+  MyPointer(int *p = 0);
+  MyPointer(const MyOwner &);
+  int *();
+  T toOwner();
+};
+
+struct [[gsl::Owner(int)]] T {
+  T();
+  operator MyPointer(); 
+  int *();
+  MyPointer release();
+  int *release2();
+  int *c_str() const;
+};
+
+void f() {
+  new MyPointer(T{}); // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
+  new MyPointer(MyOwner{}); // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
+}
+
+void g() {
+  int i;
+  MyPointer p{}; // ok
+  new MyPointer(MyPointer{p}); // ok
+}
+
+MyPointer g2() {
+  T t;
+  return t.release(); // ok
+}
+
+int *g3() {
+  T t;
+  return t.release2(); // ok
+}
+
+int *g4() {
+  T t;
+  return t.c_str(); // TODO
+}
+
+int *g5() {
+  MyPointer p;
+  return p.toOwner().c_str(); // TODO
+}
+
+struct Y {
+  int a[4];
+};
+
+void h() {
+  MyPointer p = Y{}.a; // expected-warning {{temporary whose address is used as value of local variable 'p' will be destroyed at the end of the full-expression}}
+  (void)p;
+}
+
+struct S {
+  MyPointer p; // expected-note 3{{pointer member declared here}}
+  S(int i) : p() {} // expected-warning {{initializing pointer member 'p' with the stack address of parameter 'i'}}
+  S() : p(T{}) {} // expected-warning {{initializing pointer member 'p' to point to a temporary object whose lifetime is shorter than the lifetime of the constructed object}}
+  S(double) : p(MyOwner{}) {} // expected-warning {{initializing pointer member 'p' to point to a temporary object whose lifetime is shorter than the lifetime of the constructed object}}
+};
+
+MyPointer i() {
+  int j;
+  return  // expected-warning {{address of stack memory associated with local variable 'j' returned}}
+}
+
+MyPointer i2() {
+  T t;
+  return t; // TODO
+}
+
+MyPointer i3() {
+  return T{}; // expected-warning {{returning address of local temporary object}}
+}
+
+MyPointer global;
+
+void j() {
+  MyPointer p = MyOwner{}; // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
+  p = MyOwner{}; // TODO ?
+  global = MyOwner{}; // TODO ?
+  p = T{}; // TODO ?
+  global = T{}; // TODO ?
+}
+
+struct IntVector {
+  int *begin();
+  int *end();
+};
+
+void future_work() {
+  int *it = IntVector{}.begin(); // TODO ?
+  (void)it;
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -6507,6 +6507,8 @@
 VarInit,
 LValToRVal,
 LifetimeBoundCall,
+LifetimePointerInit,
+LifetimeTempOwner
   } Kind;
   Expr *E;
   const Decl *D = nullptr;
@@ -6543,6 +6545,13 @@
   });
 }
 
+static bool
+pathInitializeLifetimePointer(llvm::ArrayRef Path) {
+  return Path.size() > 0 && llvm::all_of(Path, [=](IndirectLocalPathEntry E) {
+return E.Kind == IndirectLocalPathEntry::LifetimePointerInit;
+  });
+}
+
 static void visitLocalsRetainedByInitializer(IndirectLocalPath ,
  Expr *Init, LocalVisitor Visit,
  bool RevisitSubinits);
@@ -6568,32 +6577,53 @@
   return false;
 }
 
+template
+static bool recordHasAttr(QualType Type) {
+  if (auto *RD = Type->getAsCXXRecordDecl())
+return RD->getCanonicalDecl()->hasAttr();
+  return false;
+}
+
 static void visitLifetimeBoundArguments(IndirectLocalPath , Expr *Call,
 LocalVisitor Visit) {
   const FunctionDecl *Callee;
   ArrayRef Args;
+  bool CtorOfLifetimePointer = false;
 
   if (auto *CE = dyn_cast(Call)) {
 Callee = CE->getDirectCallee();
 Args = llvm::makeArrayRef(CE->getArgs(), 

[PATCH] D61809: [BPF] Preserve debuginfo array/union/struct type/access index

2019-07-05 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song added a comment.

@rsmith Ping again, do you have any comments on this patch? Thanks!


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61809/new/

https://reviews.llvm.org/D61809



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


[PATCH] D61879: WIP: Prototype of DSE optimizations for -ftrivial-auto-var-init

2019-07-05 Thread Alexander Potapenko via Phabricator via cfe-commits
glider added inline comments.



Comment at: llvm/lib/Transforms/Scalar/DeadStoreEliminationExp.cpp:556
+  LocationSize LS = MemoryLocation::getForDest(MSI).Size;
+  ConstantRange Range(PointerSizeInBits, false);
+  if (!LS.isPrecise() ||

An assertion fires here on the Android kernel:

```
aarch64-linux-android-ld.gold: 
/usr/local/google/src/llvm-git-monorepo/llvm/lib/IR/ConstantRange.cpp:54: 
llvm::ConstantRange::ConstantRange(llvm::APInt, llvm::APInt): Assertion `(Lower 
!= Upper || (Lower.isMaxValue() || Lower.isMinValue())) && "Lower == Upper, but 
they aren't min or max value!"' failed.
```

For some reason the (APInt, APInt) version of the constructor is being invoked.
Probably PointerSizeInBits should be declared as `int32_t` here and in 
`findDeadStores()`



Comment at: llvm/lib/Transforms/Scalar/DeadStoreEliminationExp.cpp:563
+assert(RR.getBitWidth() == Range.getBitWidth());
+ConstantRange RRR = {Range.getLower(),
+ Range.getLower() + LS.getValue()};

I'm seeing a case in which Range.getLower() is 20179 and LS.getValue() is 0.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61879/new/

https://reviews.llvm.org/D61879



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


[PATCH] D63773: [clangd] dummy variable extraction on a function scope

2019-07-05 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp:90
+bool isAFunctionRef(const clang::Expr *Expr) {
+  const clang::DeclRefExpr *DeclRef = dyn_cast_or_null(Expr);
+  if (DeclRef && isa(DeclRef->getDecl()))

sammccall wrote:
> sammccall wrote:
> > Extracting just a declrefexpr (and replacing it with another declrefexpr) 
> > doesn't seem useful. Any reason to only do this for functions, rather than 
> > all declrefexprs?
> a syntactically similar case is MemberExpr where isImplicitAccess() is true. 
> (This is referring to a method of the current class, without qualification)
Extracting
  int a = [[f]]();
yields
  auto dummy = f;
  int a = dummy();

I thought this should be prevented. But now I see there's no need to do that.
I'll add a triviality check if needed in the next patch.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63773/new/

https://reviews.llvm.org/D63773



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


[PATCH] D64253: Let unaliased Args track which Alias they were created from, and use that in Arg::getAsString() for diagnostics

2019-07-05 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: rnk.
Herald added subscribers: MaskRay, hiraditya, arichardson, javed.absar, emaste.
Herald added a reviewer: espindola.
Herald added a project: LLVM.

With this, `clang-cl /source-charset:utf-16 test.cc` now prints `invalid value 
'utf-16' in '/source-charset:utf-16'` instead of `invalid value 'utf-16' in 
'-finput-charset=utf-16'` before, and several other clang-cl flags produce much 
less confusing output as well.

Fixes PR29106.

Since an arg and its alias can have different arg types (joined vs not) and 
different values (because of AliasArgs<>), I chose to give the Alias its own 
Arg object. For convenience, I just store the alias directly in the unaliased 
arg – there aren't many arg objects at runtime, so that seems ok.

Finally, I changed Arg::getAsString() to use the alias's representation if it's 
present – that function was already documented as being the suitable function 
for diagnostics, and most callers already used it for diagnostics.

Implementation-wise, Arg::accept() previously used to parse things as the 
unaliased option. The core of that switch is now extracted into a new function 
acceptInternal() which parses as the _aliased_ option, and the 
previously-intermingled unaliasing is now done as an explicit step afterwards.

(This also changes one place in lld that didn't use getAsString() for 
diagnostics, so that that one place now also prints the flag as the user wrote 
it, not as it looks after it went through unaliasing.)


https://reviews.llvm.org/D64253

Files:
  clang/test/Driver/arm-execute-only.c
  clang/test/Driver/cl-options.c
  clang/test/Driver/darwin-version.c
  lld/Common/Reproduce.cpp
  lld/ELF/Driver.cpp
  lld/test/ELF/sectionstart.s
  llvm/include/llvm/Option/Arg.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/Option/Arg.cpp
  llvm/lib/Option/Option.cpp

Index: llvm/lib/Option/Option.cpp
===
--- llvm/lib/Option/Option.cpp
+++ llvm/lib/Option/Option.cpp
@@ -106,49 +106,23 @@
   return false;
 }
 
-Arg *Option::accept(const ArgList ,
-unsigned ,
-unsigned ArgSize) const {
-  const Option  = getUnaliasedOption();
-  StringRef Spelling;
-  // If the option was an alias, get the spelling from the unaliased one.
-  if (getID() == UnaliasedOption.getID()) {
-Spelling = StringRef(Args.getArgString(Index), ArgSize);
-  } else {
-Spelling = Args.MakeArgString(Twine(UnaliasedOption.getPrefix()) +
-  Twine(UnaliasedOption.getName()));
-  }
-
+Arg *Option::acceptInternal(const ArgList , unsigned ,
+unsigned ArgSize) const {
+  StringRef Spelling = StringRef(Args.getArgString(Index), ArgSize);
   switch (getKind()) {
   case FlagClass: {
 if (ArgSize != strlen(Args.getArgString(Index)))
   return nullptr;
-
-Arg *A = new Arg(UnaliasedOption, Spelling, Index++);
-if (getAliasArgs()) {
-  const char *Val = getAliasArgs();
-  while (*Val != '\0') {
-A->getValues().push_back(Val);
-
-// Move past the '\0' to the next argument.
-Val += strlen(Val) + 1;
-  }
-}
-
-if (UnaliasedOption.getKind() == JoinedClass && !getAliasArgs())
-  // A Flag alias for a Joined option must provide an argument.
-  A->getValues().push_back("");
-
-return A;
+return new Arg(*this, Spelling, Index++);
   }
   case JoinedClass: {
 const char *Value = Args.getArgString(Index) + ArgSize;
-return new Arg(UnaliasedOption, Spelling, Index++, Value);
+return new Arg(*this, Spelling, Index++, Value);
   }
   case CommaJoinedClass: {
 // Always matches.
 const char *Str = Args.getArgString(Index) + ArgSize;
-Arg *A = new Arg(UnaliasedOption, Spelling, Index++);
+Arg *A = new Arg(*this, Spelling, Index++);
 
 // Parse out the comma separated values.
 const char *Prev = Str;
@@ -184,8 +158,7 @@
 Args.getArgString(Index - 1) == nullptr)
   return nullptr;
 
-return new Arg(UnaliasedOption, Spelling,
-   Index - 2, Args.getArgString(Index - 1));
+return new Arg(*this, Spelling, Index - 2, Args.getArgString(Index - 1));
   case MultiArgClass: {
 // Matches iff this is an exact match.
 // FIXME: Avoid strlen.
@@ -196,8 +169,8 @@
 if (Index > Args.getNumInputArgStrings())
   return nullptr;
 
-Arg *A = new Arg(UnaliasedOption, Spelling, Index - 1 - getNumArgs(),
-  Args.getArgString(Index - getNumArgs()));
+Arg *A = new Arg(*this, Spelling, Index - 1 - getNumArgs(),
+ Args.getArgString(Index - getNumArgs()));
 for (unsigned i = 1; i != getNumArgs(); ++i)
   A->getValues().push_back(Args.getArgString(Index - getNumArgs() + i));
 return A;
@@ -207,7 +180,7 @@
 // FIXME: Avoid strlen.
 if (ArgSize != strlen(Args.getArgString(Index))) {
   const char *Value = 

[PATCH] D63518: BitStream reader: propagate errors

2019-07-05 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp:619
+// FIXME check that the enum is in range.
+auto Code = static_cast(MaybeCode.get());
+

This has caused problem for our sanitizer tests the last couple of days:

```
FAIL: Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode (20077 of 48746)
 TEST 'Extra Tools Unit Tests :: 
clang-doc/./ClangDocTests/BitcodeTest.emitMethodInfoBitcode' FAILED 

Note: Google Test filter = BitcodeTest.emitMethodInfoBitcode
[==] Running 1 test from 1 test case.
[--] Global test environment set-up.
[--] 1 test from BitcodeTest
[ RUN  ] BitcodeTest.emitMethodInfoBitcode
/local/repo/bbiswjenk/fem023-eiffel003/workspace/llvm/llvm-master-sanitize/clang-tools-extra/clang-doc/BitcodeReader.cpp:621:13:
 runtime error: load of value 9, which is not a valid value for type 
'llvm::bitc::FixedAbbrevIDs'

```

This was seen when building trunk with clang 6.0.0 and 
LVM_USE_SANITIZER=Undefined

```
cmake -G Ninja '-DLLVM_ENABLE_PROJECTS='\''clang;clang-tools-extra'\''' 
-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON 
'-DCMAKE_CXX_FLAGS='\''-stdlib=libc++'\''' -DCMAKE_C_COMPILER=clang 
-DCMAKE_CXX_COMPILER=clang++ -DLLVM_USE_LINKER=gold 
-DLLVM_USE_SANITIZER=Undefined ../.
-- The C compiler identification is Clang 6.0.0
-- The CXX compiler identification is Clang 6.0.0
```

Afaict we can't cast the read value to FixedAbbrevIDs as we do not know yet if 
it matches one of the values defined in the enum, or if we will take the 
default case.


A similar switch exist at 
cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp:127, but it is using a 
slightly different pattern:

```
unsigned Code;
Code = Res.get();
switch ((llvm::bitc::FixedAbbrevIDs)Code) 
```
I haven't seen any failures for SerializedDiagnosticReader. So either we lack 
test coverage for that function, or the sanitizer only introduce the check when 
using the static_cast (and declaring Code as an enum) as done here.



Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63518/new/

https://reviews.llvm.org/D63518



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


[PATCH] D63640: [clang] Improve Serialization/Imporing of APValues

2019-07-05 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:8503
 
+llvm::Expected ASTImporter::Import(const APValue ) {
+  APValue Result;

Tyker wrote:
> martong wrote:
> > Tyker wrote:
> > > martong wrote:
> > > > Looks okay, but could we have unit tests for this in 
> > > > ASTImporterTest.cpp?
> > > I tested importing using the same test file as serialization 
> > > `clang/test/PCH/APValue.cpp` with `-ast-merge` which uses importing. this 
> > > prevent duplicating the test code for importing and serializing. is the 
> > > unit-test in ASTImporterTest.cpp necessary anyway ?
> > Okay, that's fine I missed that previously, so there is no need for the 
> > unit-tests in this case.
> > Though maybe the `-ast-merge` part of the test should reside in the  
> > `clang/test/ASTMerge` directory, because that is where all the other 
> > `-ast-merge` tests are. 
> > I am not sure how to solve that nicely, because i see you use the same file 
> > for both the serialization and for the import.
> > Perhaps there should be a common header file which is included both in 
> > `test/PCH/APValue.cpp` and in `test/ASTMerge/apvalue/test.cpp`?
> > 
> > 
> we can have a common header,  but i don't know where to put it. having a in 
> `PCH` that includes a header form `ASTMerge` seems weird and vice versa. 
Yes, that is indeed not so good.

The point is that, we should execute the APValue tests as well when we invoke 
`ninja check-clang-astmerge`. (Some people do not execute the whole 
`check-clang` verification when they change only the ASTImporter, this way the 
edit-test cycle can be faster)

Can we have a symbolic link from `test/PCH/APValue.cpp` to 
`test/ASTMerge/APValue.cpp`? Probably that would work on *nix, but not on 
Windows (https://stackoverflow.com/questions/5917249/git-symlinks-in-windows).
If the symlink is really not an option then I am just fine with a real copy of 
the file.
If we have a link or a copy then the tests will run twice, that seems ok for 
me, but may disturb other devs.
Actually, this is an inconvenient problem, perhaps someone had this before, so 
maybe a mail to cfe-dev could help us out.



CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63640/new/

https://reviews.llvm.org/D63640



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


[PATCH] D63538: [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

In D63538#1571454 , @Szelethus wrote:

> In D63538#1571451 , @Szelethus wrote:
>
> > Since the followup patches test this roughly anyways, and the fact that the 
> > AST's lifetime ends right after the CFG's construction makes the remaining 
> > tests pretty much pointless, if I can't resolve this, I'll just remove the 
> > testfile.
>
>
> I mean, this is a good enough reason to just go through with it. Removed in 
> rL365209 . Sorry for the inconvenience!


Thanks!


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63538/new/

https://reviews.llvm.org/D63538



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


[PATCH] D64222: [sanitizers] Use covering ObjectFormatType switches

2019-07-05 Thread Sean Fertile via Phabricator via cfe-commits
sfertile accepted this revision.
sfertile added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64222/new/

https://reviews.llvm.org/D64222



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


r365212 - Add a comment explaining why a function exists

2019-07-05 Thread Nico Weber via cfe-commits
Author: nico
Date: Fri Jul  5 08:12:31 2019
New Revision: 365212

URL: http://llvm.org/viewvc/llvm-project?rev=365212=rev
Log:
Add a comment explaining why a function exists

Modified:
cfe/trunk/lib/Driver/Driver.cpp

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=365212=365211=365212=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Fri Jul  5 08:12:31 2019
@@ -966,6 +966,9 @@ Compilation *Driver::BuildCompilation(Ar
   InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
   : std::move(*CLOptions));
 
+  // The args for config files or /clang: flags belong to different 
InputArgList
+  // objects than Args. This copies an Arg from one of those other 
InputArgLists
+  // to the ownership of Args.
   auto appendOneArg = [](const Arg *Opt, const Arg *BaseArg) {
   unsigned Index = Args.MakeIndex(Opt->getSpelling());
   Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),


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


[PATCH] D64232: [analyzer] Prune calls to functions with linear CFGs that return a non-zero constrained value

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus marked 2 inline comments as done.
Szelethus added a comment.

In D64232#1570938 , @NoQ wrote:

> I'm slightly worried that we're fighting the symptoms rather than the root 
> cause here: why were these values tracked that far in the first place when we 
> already have no interest in tracking them at the end of the function?


Could you please elaborate? Which of the modified test cases (or any other) do 
you think falls under "being tracked too far" and why? Whenever the CFG where 
the value isn't linear, I think the information could be valuable, see the 
inline.

> I.e., i suspect that your "mild tracking mode" would get rid of a lot of 
> those automagically.

A lot of those, correct, all of them, nope. I've been slacking on publishing 
the moderate tracking I've been working on, I'll get that done during the day.




Comment at: clang/test/Analysis/track-control-dependency-conditions.cpp:185
 return true;
   return coin(); // tracking-note{{Returning value}}
 }

This note is meaningful, the bug would not have occurred if `coin()` wasn't 
assumed to be false.



Comment at: clang/test/Analysis/uninit-vals.c:181
 void testUseHalfPoint() {
-  struct Point p = getHalfPoint(); // expected-note{{Calling 'getHalfPoint'}}
-   // expected-note@-1{{Returning from 
'getHalfPoint'}}
-   // expected-note@-2{{'p' initialized here}}
+  struct Point p = getHalfPoint(); // expected-note{{'p' initialized here}}
   use(p); // expected-warning{{uninitialized}}

NoQ wrote:
> Huh, so there's not even a note in `getHalfPoint()`, just calling..returning? 
> This definitely needs some attention from `NoStoreFuncVisitor`.
> 
> Generally, i think this is probably the single place where we do really want 
> some info about what happens in `getHalfPoint()`. The report that consists 
> only of "p is initialized..." and "...p is uninitialized" is pretty weird. 
> Btw, could you write down the full warning text in this test? How bad this 
> actually is?
Wild idea: `UninitializedObjectChecker` exposes it's main logic through a 
header file, how about we use it when we find a read of an uninitialized region?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64232/new/

https://reviews.llvm.org/D64232



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


[PATCH] D55793: [clang-tidy] Add duplicated access specifier readability check (PR25403)

2019-07-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D55793#1535895 , @m4tx wrote:

> @JonasToth thanks for asking! Yes, since I do not have commit access, I need 
> someone to do the commit for me.


I'm sorry for the terribly long delay on getting this committed -- it fell off 
my radar for a bit. When I try to apply the branch to trunk, I get merge 
conflicts. Can you rebase it on ToT, please?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D55793/new/

https://reviews.llvm.org/D55793



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


[PATCH] D57086: Ignore trailing NullStmts in StmtExprs for GCC compatibility

2019-07-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D57086#1551354 , @domdom wrote:

> In D57086#1550514 , @aaron.ballman 
> wrote:
>
> > In D57086#1549632 , @domdom wrote:
> >
> > > clang-format the patch
> >
> >
> > Thanks! Do you need someone to commit on your behalf?
>
>
> You are very welcome; thank you both for your comments!
>
> I do need someone to commit on my behalf :)


I'm sorry for the incredibly long delay in committing this for you -- I managed 
to lose track of this thread. I went to apply the changes today and get the 
following test failures when trying on Windows 10 x64:

  FAIL: Clang :: AST/ast-dump-stmt.c (152 of 11055)
   TEST 'Clang :: AST/ast-dump-stmt.c' FAILED 

  Script:
  --
  : 'RUN: at line 1';   c:\cmakebuilds\build\x64-debug\bin\clang.exe -cc1 
-internal-isystem c:\cmakebuilds\build\x64-debug\lib\clang\9.0.0\include 
-nostdsysteminc -std=gnu11 -ast-dump 
C:\llvm\tools\clang\test\AST\ast-dump-stmt.c | 
c:\cmakebuilds\build\x64-debug\bin\filecheck.exe -strict-whitespace 
C:\llvm\tools\clang\test\AST\ast-dump-stmt.c
  --
  Exit Code: 1
  
  Command Output (stdout):
  --
  $ ":" "RUN: at line 1"
  $ "c:\cmakebuilds\build\x64-debug\bin\clang.exe" "-cc1" "-internal-isystem" 
"c:\cmakebuilds\build\x64-debug\lib\clang\9.0.0\include" "-nostdsysteminc" 
"-std=gnu11" "-ast-dump" "C:\llvm\tools\clang\test\AST\ast-dump-stmt.c"
  # command stderr:
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:48:3: warning: expression result 
unused
-T1;
^~~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:49:3: warning: expression result 
unused
-T2;
^~~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:58:3: warning: expression result 
unused
~T1;
^~~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:59:3: warning: expression result 
unused
~T2;
^~~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:70:21: warning: expression 
result unused
_Generic(i, int : 12);
  ^~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:79:21: warning: expression 
result unused
_Generic(i, int : 12, default : 0);
  ^~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:90:34: warning: expression 
result unused
_Generic(i, default : 0, int : 12);
   ^~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:101:21: warning: expression 
result unused
_Generic(i, int : 12, float : 10, default : 100);
  ^~
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:142:3: warning: expression 
result unused
0;
^
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:288:8: warning: expression 
result unused
for (b; b; b)
 ^
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:288:14: warning: expression 
result unused
for (b; b; b)
   ^
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:367:17: warning: expression 
result unused
({int a = 10; a;});
  ^
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:375:3: warning: expression 
result unused
({int a = 10; a;;; });
^
  13 warnings generated.
  
  $ "c:\cmakebuilds\build\x64-debug\bin\filecheck.exe" "-strict-whitespace" 
"C:\llvm\tools\clang\test\AST\ast-dump-stmt.c"
  # command stderr:
  C:\llvm\tools\clang\test\AST\ast-dump-stmt.c:376:18: error: CHECK-NEXT: 
expected string not found in input
// CHECK-NEXT: StmtExpr 0x{{[^ ]*}}  'int'
   ^
  :282:5: note: scanning from here
  `-StmtExpr 0x19f2d493d18  'int'
  ^
  :282:5: note: with "@LINE-1" equal to "375"
  `-StmtExpr 0x19f2d493d18  'int'
  ^
  :282:14: note: possible intended match here
  `-StmtExpr 0x19f2d493d18  'int'
   ^
  
  error: command failed with exit status: 1
  
  --

It looks like the column number is off by one, and I wasn't certain why. Can 
you look into that before I commit?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D57086/new/

https://reviews.llvm.org/D57086



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


r365210 - NFC: Add an explicit return for safety and consistency

2019-07-05 Thread Hamza Sood via cfe-commits
Author: hamzasood
Date: Fri Jul  5 07:36:08 2019
New Revision: 365210

URL: http://llvm.org/viewvc/llvm-project?rev=365210=rev
Log:
NFC: Add an explicit return for safety and consistency

This case implicitly falls-through, which is fine now as it's at the end of the
function, but it seems like an accident waiting to happen.

Modified:
cfe/trunk/lib/CodeGen/CGDecl.cpp

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=365210=365209=365210=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Fri Jul  5 07:36:08 2019
@@ -153,6 +153,8 @@ void CodeGenFunction::EmitDecl(const Dec
 
 if (Ty->isVariablyModifiedType())
   EmitVariablyModifiedType(Ty);
+
+return;
   }
   }
 }


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


[PATCH] D63538: [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D63538#1571451 , @Szelethus wrote:

> Since the followup patches test this roughly anyways, and the fact that the 
> AST's lifetime ends right after the CFG's construction makes the remaining 
> tests pretty much pointless, if I can't resolve this, I'll just remove the 
> testfile.


I mean, this is a good enough reason to just go through with it. Removed in 
rL365209 . Sorry for the inconvenience!


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63538/new/

https://reviews.llvm.org/D63538



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


[PATCH] D63538: [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D63538#1571418 , @RKSimon wrote:

> @Szelethus This is causing problems on windows buildbots 
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast
>  - revert?


Apologies, I thought my followup commit fixed the issue -- No other other 
platforms seem to suffer (not even sanitizer builds) -- what does SEH exception 
mean in this case? I did look up on it but found nothing concrete.

Since the followup patches test this roughly anyways, and the fact that the 
AST's lifetime ends right after the CFG's construction makes the remaining 
tests pretty much pointless, if I can't resolve this, I'll just remove the 
testfile. Would you like me to go ahead with that right away?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63538/new/

https://reviews.llvm.org/D63538



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


r365209 - Removed the test case added in D63538 due to windows buildbot failures

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 07:22:10 2019
New Revision: 365209

URL: http://llvm.org/viewvc/llvm-project?rev=365209=rev
Log:
Removed the test case added in D63538 due to windows buildbot failures

Modified:
cfe/trunk/unittests/Analysis/CFGTest.cpp

Modified: cfe/trunk/unittests/Analysis/CFGTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Analysis/CFGTest.cpp?rev=365209=365208=365209=diff
==
--- cfe/trunk/unittests/Analysis/CFGTest.cpp (original)
+++ cfe/trunk/unittests/Analysis/CFGTest.cpp Fri Jul  5 07:22:10 2019
@@ -67,44 +67,6 @@ TEST(CFG, IsLinear) {
   expectLinear(true,  "void foo() { foo(); }"); // Recursion is not our 
problem.
 }
 
-TEST(CFG, ConditionExpr) {
-  const char *Code = R"(void f(bool A, bool B, bool C) {
-  if (A && B && C)
-int x;
-})";
-  BuildResult Result = BuildCFG(Code);
-  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
-
-  // [B5 (ENTRY)] -> [B4] -> [B3] -> [B2] -> [B1] -> [B0 (EXIT)]
-  //   \  \   \ /
-  //--->
-
-  CFG *cfg = Result.getCFG();
-
-  auto GetBlock = [cfg] (unsigned Index) -> CFGBlock * {
-assert(Index < cfg->size());
-return *(cfg->begin() + Index);
-  };
-
-  EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
-  // Unfortunately, we can't check whether the correct Expr was returned by
-  // getLastCondition, because the lifetime of the AST ends by the time we
-  // retrieve the CFG.
-
-  
//======//
-
-  Code = R"(void foo(int x, int y) {
-  (void)(x + y);
-})";
-  Result = BuildCFG(Code);
-  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
-
-  // [B2 (ENTRY)] -> [B1] -> [B0 (EXIT)]
-
-  cfg = Result.getCFG();
-  EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
-}
-
 } // namespace
 } // namespace analysis
 } // namespace clang


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


[PATCH] D63773: [clangd] dummy variable extraction on a function scope

2019-07-05 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 208174.
SureYeaah marked 21 inline comments as done.
SureYeaah added a comment.

Added whitelist for computeInsertionPoint


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63773/new/

https://reviews.llvm.org/D63773

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -239,13 +239,13 @@
   checkNotAvailable(ID, "/*c^omment*/ int foo() return 2 ^ + 2; }");
 
   const char *Input = "int x = 2 ^+ 2;";
-  auto result = getMessage(ID, Input);
-  EXPECT_THAT(result, ::testing::HasSubstr("BinaryOperator"));
-  EXPECT_THAT(result, ::testing::HasSubstr("'+'"));
-  EXPECT_THAT(result, ::testing::HasSubstr("|-IntegerLiteral"));
-  EXPECT_THAT(result,
+  auto Result = getMessage(ID, Input);
+  EXPECT_THAT(Result, ::testing::HasSubstr("BinaryOperator"));
+  EXPECT_THAT(Result, ::testing::HasSubstr("'+'"));
+  EXPECT_THAT(Result, ::testing::HasSubstr("|-IntegerLiteral"));
+  EXPECT_THAT(Result,
   ::testing::HasSubstr(" 'int' 2\n`-IntegerLiteral"));
-  EXPECT_THAT(result, ::testing::HasSubstr(" 'int' 2"));
+  EXPECT_THAT(Result, ::testing::HasSubstr(" 'int' 2"));
 }
 
 TEST(TweakTest, ShowSelectionTree) {
@@ -277,6 +277,136 @@
   const char *Input = "struct ^X { int x; int y; }";
   EXPECT_THAT(getMessage(ID, Input), ::testing::HasSubstr("0 |   int x"));
 }
+TEST(TweakTest, ExtractVariable) {
+  llvm::StringLiteral ID = "ExtractVariable";
+  checkAvailable(ID, R"cpp(
+int xyz() {
+  // return statement
+  return ^1;
+}
+void f() {
+  int a = 5 + [[4 ^* ^xyz^()]];
+  // multivariable initialization
+  if(1)
+int x = ^1, y = ^a + 1, a = ^1, z = a + 1;
+  // if without else
+  if(^1) {}
+  // if with else
+  if(a < ^3)
+if(a == ^4)
+  a = ^5;
+else
+  a = ^6;
+  else if (a < ^4)
+a = ^4;
+  else
+a = ^5;
+  // for loop 
+  for(a = ^1; a > ^3^+^4; a++)
+a = ^2;
+  // while 
+  while(a < ^1)
+^a++;
+  // do while 
+  do
+a = ^1;
+  while(a < ^3);
+}
+  )cpp");
+  checkNotAvailable(ID, R"cpp(
+int xyz(int a = ^1) {
+  return 1;
+  class T {
+T(int a = ^1) {};
+int xyz = ^1;
+  };
+}
+// function default argument
+void f(int b = ^1) {
+  // invalid expression checking;
+  auto i = new int, j = new int;
+  de^lete i^, del^ete j;
+  // if
+  if(1)
+int x = 1, y = a + 1, a = 1, z = ^a + 1;
+  if(int a = 1)
+if(^a == 4)
+  a = ^a ^+ 1;
+  // for loop 
+  for(int a = 1, b = 2, c = 3; ^a > ^b ^+ ^c; ^a++)
+a = ^a ^+ 1;
+  // lambda 
+  auto lamb = [&^a, &^b](int r = ^1) {return 1;}
+}
+  )cpp");
+  // vector of pairs of input and output strings
+  const std::vector>
+  InputOutputs = {
+  // extraction from variable declaration/assignment
+  {R"cpp(void varDecl() {
+   int a = 5 * (4 + (3 [[- 1)]]);
+ })cpp",
+   R"cpp(void varDecl() {
+   auto dummy = (3 - 1); int a = 5 * (4 + dummy);
+ })cpp"},
+  // FIXME: extraction from switch case
+  /*{R"cpp(void f(int a) {
+   if(1)
+ while(a < 1)
+   switch (1) {
+   case 1:
+ a = [[1 + 2]];
+ break;
+   default:
+ break;
+   }
+ })cpp",
+   R"cpp(void f(int a) {
+   auto dummy = 1 + 2; if(1)
+ while(a < 1)
+   switch (1) {
+   case 1:
+ a = dummy;
+ break;
+   default:
+ break;
+   }
+ })cpp"},*/
+  // ensure InsertionPoint isn't inside a macro
+  {R"cpp(#define LOOP(x) {int a = x + 1;}
+ void f(int a) {
+   if(1)
+LOOP(5 + ^3)
+ })cpp",
+   R"cpp(#define LOOP(x) {int a = x + 1;}
+ void f(int a) {
+   auto dummy = 3; if(1)
+LOOP(5 + dummy)
+ })cpp"},
+  // label and attribute testing
+  {R"cpp(void f(int a) {
+label: [ [gsl::suppress("type")] ] for (;;) a = ^1;
+ })cpp",
+   

[PATCH] D64247: [clangd] Filter out non-governed files from broadcast

2019-07-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

This also turns off implicit discovery of additional compilation
databases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64247

Files:
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/QueryDriverDatabase.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
  clang-tools-extra/clangd/unittests/TestFS.cpp
  clang-tools-extra/clangd/unittests/TestFS.h

Index: clang-tools-extra/clangd/unittests/TestFS.h
===
--- clang-tools-extra/clangd/unittests/TestFS.h
+++ clang-tools-extra/clangd/unittests/TestFS.h
@@ -12,6 +12,8 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTFS_H
 #define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTFS_H
 #include "ClangdServer.h"
+#include "GlobalCompilationDatabase.h"
+#include "Path.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/VirtualFileSystem.h"
@@ -48,7 +50,9 @@
   StringRef RelPathPrefix = StringRef());
 
   llvm::Optional
-  getCompileCommand(PathRef File, ProjectInfo * = nullptr) const override;
+  getCompileCommand(PathRef File) const override;
+
+  llvm::Optional getProjectInfo(PathRef File) const override;
 
   std::vector ExtraClangFlags;
 
Index: clang-tools-extra/clangd/unittests/TestFS.cpp
===
--- clang-tools-extra/clangd/unittests/TestFS.cpp
+++ clang-tools-extra/clangd/unittests/TestFS.cpp
@@ -6,7 +6,11 @@
 //
 //===--===//
 #include "TestFS.h"
+#include "GlobalCompilationDatabase.h"
+#include "Path.h"
 #include "URI.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/Path.h"
@@ -36,9 +40,13 @@
   // -ffreestanding avoids implicit stdc-predef.h.
 }
 
+llvm::Optional
+MockCompilationDatabase::getProjectInfo(PathRef File) const {
+  return ProjectInfo{Directory};
+};
+
 llvm::Optional
-MockCompilationDatabase::getCompileCommand(PathRef File,
-   ProjectInfo *Project) const {
+MockCompilationDatabase::getCompileCommand(PathRef File) const {
   if (ExtraClangFlags.empty())
 return None;
 
@@ -57,8 +65,6 @@
 CommandLine.push_back(RelativeFilePath.str());
   }
 
-  if (Project)
-Project->SourceRoot = Directory;
   return {tooling::CompileCommand(Directory != llvm::StringRef()
   ? Directory
   : llvm::sys::path::parent_path(File),
Index: clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
===
--- clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -8,10 +8,21 @@
 
 #include "GlobalCompilationDatabase.h"
 
+#include "Path.h"
 #include "TestFS.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -20,8 +31,10 @@
 using ::testing::Contains;
 using ::testing::ElementsAre;
 using ::testing::EndsWith;
+using ::testing::IsEmpty;
 using ::testing::Not;
 using ::testing::StartsWith;
+using ::testing::UnorderedElementsAre;
 
 TEST(GlobalCompilationDatabaseTest, FallbackCommand) {
   DirectoryBasedGlobalCompilationDatabase DB(None);
@@ -50,13 +63,9 @@
   class BaseCDB : public GlobalCompilationDatabase {
   public:
 llvm::Optional
-getCompileCommand(llvm::StringRef File,
-  ProjectInfo *Project) const override {
-  if (File == testPath("foo.cc")) {
-if (Project)
-  Project->SourceRoot = testRoot();
+getCompileCommand(llvm::StringRef File) const override {
+  if (File == testPath("foo.cc"))
 return cmd(File, "-DA=1");
-  }
   return None;
 }
 
@@ -64,6 +73,10 @@
 getFallbackCommand(llvm::StringRef File) const override {
   return cmd(File, "-DA=2");
 }
+
+llvm::Optional getProjectInfo(PathRef File) const override {
+  return ProjectInfo{testRoot()};
+}
   };
 
 protected:
@@ -153,6 +166,109 @@
 

[PATCH] D63642: [analyzer] Add a debug analyzer config to place an event for each tracked condition

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb55745606fa6: [analyzer] Add a debug analyzer config to 
place an event for each tracked… (authored by Szelethus).

Changed prior to commit:
  https://reviews.llvm.org/D63642?vs=205966=208171#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63642/new/

https://reviews.llvm.org/D63642

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/track-control-dependency-conditions.cpp

Index: clang/test/Analysis/track-control-dependency-conditions.cpp
===
--- clang/test/Analysis/track-control-dependency-conditions.cpp
+++ clang/test/Analysis/track-control-dependency-conditions.cpp
@@ -3,7 +3,23 @@
 // RUN:   -analyzer-config track-conditions=true \
 // RUN:   -analyzer-output=text \
 // RUN:   -analyzer-checker=core
+
+// RUN: not %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-config track-conditions-debug=true \
+// RUN:   2>&1 | FileCheck %s -check-prefix=CHECK-INVALID-DEBUG
+
+// CHECK-INVALID-DEBUG: (frontend): invalid input for analyzer-config option
+// CHECK-INVALID-DEBUG-SAME:'track-conditions-debug', that expects
+// CHECK-INVALID-DEBUG-SAME:'track-conditions' to also be enabled
 //
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -verify=expected,tracking,debug \
+// RUN:   -analyzer-config track-conditions=true \
+// RUN:   -analyzer-config track-conditions-debug=true \
+// RUN:   -analyzer-output=text \
+// RUN:   -analyzer-checker=core
+
 // RUN: %clang_analyze_cc1 %s -verify \
 // RUN:   -analyzer-output=text \
 // RUN:   -analyzer-checker=core
@@ -30,6 +46,8 @@
 
   if (flag) // expected-note   {{Assuming 'flag' is not equal to 0}}
 // expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'flag'}}
+
 *x = 5; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1{{Dereference of null pointer}}
 }
@@ -59,6 +77,8 @@
 
   if (flag) // expected-note   {{Assuming 'flag' is not equal to 0}}
 // expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'flag'}}
+
 *x = 5; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1{{Dereference of null pointer}}
 }
@@ -85,8 +105,11 @@
 
   if (bar) // expected-note   {{Assuming 'bar' is not equal to 0}}
// expected-note@-1{{Taking true branch}}
+   // debug-note@-2{{Tracking condition 'bar'}}
 if (flag) // expected-note   {{Assuming 'flag' is not equal to 0}}
   // expected-note@-1{{Taking true branch}}
+  // debug-note@-2{{Tracking condition 'flag'}}
+
   *x = 5; // expected-warning{{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
@@ -107,7 +130,7 @@
   if (int flag = foo()) // tracking-note{{Calling 'foo'}}
 // tracking-note@-1{{Returning from 'foo'}}
 // tracking-note@-2{{'flag' initialized here}}
-
+// debug-note@-3{{Tracking condition 'flag'}}
 // expected-note@-4{{Assuming 'flag' is not equal to 0}}
 // expected-note@-5{{Taking true branch}}
 
@@ -129,7 +152,7 @@
   if (ConvertsToBool())
 // tracking-note@-1 {{Calling 'ConvertsToBool::operator bool'}}
 // tracking-note@-2{{Returning from 'ConvertsToBool::operator bool'}}
-
+// debug-note@-3{{Tracking condition 'ConvertsToBool()'}}
 // expected-note@-4{{Assuming the condition is true}}
 // expected-note@-5{{Taking true branch}}
 *x = 5; // expected-warning{{Dereference of null pointer}}
@@ -150,8 +173,9 @@
   if (!flipCoin())
 // tracking-note@-1{{Calling 'flipCoin'}}
 // tracking-note@-2{{Returning from 'flipCoin'}}
-// expected-note@-3{{Assuming the condition is true}}
-// expected-note@-4{{Taking true branch}}
+// debug-note@-3{{Tracking condition '!flipCoin()'}}
+// expected-note@-4{{Assuming the condition is true}}
+// expected-note@-5{{Taking true branch}}
 *ptr = 5; // expected-warning{{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
@@ -163,6 +187,7 @@
 bool flipCoin() {
   if (coin()) // tracking-note{{Assuming the condition is false}}
   // tracking-note@-1{{Taking false branch}}
+  // debug-note@-2{{Tracking condition 'coin()'}}
 return true;
   return coin(); // tracking-note{{Returning value}}
 }
@@ -174,8 +199,9 @@
   if (!flipCoin())
 // tracking-note@-1{{Calling 'flipCoin'}}
 // tracking-note@-2{{Returning from 'flipCoin'}}
-// 

[PATCH] D64242: [AArch64] Fix scalar vuqadd intrinsics operands

2019-07-05 Thread John Brawn via Phabricator via cfe-commits
john.brawn accepted this revision.
john.brawn added a comment.
This revision is now accepted and ready to land.

LGTM, with one nitpick.




Comment at: test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c:2
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone 
-emit-llvm -o - %s 2>&1 \
+// RUN: | FileCheck %s

I don't think the -fallow-half-arguments-and-returns here is necessary.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64242/new/

https://reviews.llvm.org/D64242



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


r365208 - [analyzer] Add a debug analyzer config to place an event for each tracked condition

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 07:00:08 2019
New Revision: 365208

URL: http://llvm.org/viewvc/llvm-project?rev=365208=rev
Log:
[analyzer] Add a debug analyzer config to place an event for each tracked 
condition

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/analyzer-config.c
cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def?rev=365208=365207=365208=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def Fri Jul  5 
07:00:08 2019
@@ -296,6 +296,10 @@ ANALYZER_OPTION(bool, ShouldTrackConditi
 "an already tracked variable.",
 false)
 
+ANALYZER_OPTION(bool, ShouldTrackConditionsDebug, "track-conditions-debug",
+"Whether to place an event at each tracked condition.",
+false)
+
 
//===--===//
 // Unsinged analyzer options.
 
//===--===//

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=365208=365207=365208=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Fri Jul  5 07:00:08 2019
@@ -467,6 +467,10 @@ static void parseAnalyzerConfigs(Analyze
   if (!Diags)
 return;
 
+  if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
+Diags->Report(diag::err_analyzer_config_invalid_input)
+<< "track-conditions-debug" << "'track-conditions' to also be enabled";
+
   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
<< "a filename";

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=365208=365207=365208=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Fri Jul  5 
07:00:08 2019
@@ -1667,6 +1667,26 @@ static CFGBlock *GetRelevantBlock(const
   return nullptr;
 }
 
+static std::shared_ptr
+constructDebugPieceForTrackedCondition(const Expr *Cond,
+   const ExplodedNode *N,
+   BugReporterContext ) {
+
+  if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
+  !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
+return nullptr;
+
+  std::string ConditionText = Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Cond->getSourceRange()),
+ BRC.getSourceManager(),
+ BRC.getASTContext().getLangOpts());
+
+  return std::make_shared(
+  PathDiagnosticLocation::createBegin(
+  Cond, BRC.getSourceManager(), N->getLocationContext()),
+  (Twine() + "Tracking condition '" + ConditionText + "'").str());
+}
+
 std::shared_ptr
 TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
BugReporterContext ,
@@ -1695,6 +1715,7 @@ TrackControlDependencyCondBRVisitor::Vis
   if (BR.addTrackedCondition(N)) {
 bugreporter::trackExpressionValue(
 N, Condition, BR, /*EnableNullFPSuppression=*/false);
+return constructDebugPieceForTrackedCondition(Condition, N, BRC);
   }
 }
   }

Modified: cfe/trunk/test/Analysis/analyzer-config.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer-config.c?rev=365208=365207=365208=diff
==
--- cfe/trunk/test/Analysis/analyzer-config.c (original)
+++ cfe/trunk/test/Analysis/analyzer-config.c Fri Jul  5 07:00:08 2019
@@ -85,8 +85,9 @@
 // CHECK-NEXT: suppress-inlined-defensive-checks = true
 // CHECK-NEXT: suppress-null-return-paths = true
 // CHECK-NEXT: track-conditions = false
+// CHECK-NEXT: track-conditions-debug = false
 // CHECK-NEXT: unix.DynamicMemoryModeling:Optimistic = false
 // CHECK-NEXT: unroll-loops = false
 // 

[PATCH] D63538: [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@Szelethus This is causing problems on windows buildbots 
http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast
 - revert?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63538/new/

https://reviews.llvm.org/D63538



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


[PATCH] D64239: [AArch64] Fix vsqadd scalar intrinsics operands

2019-07-05 Thread John Brawn via Phabricator via cfe-commits
john.brawn accepted this revision.
john.brawn added a comment.
This revision is now accepted and ready to land.

LGTM, with a couple of nitpicks.

> The existing unsigned argument can cause faulty code as float to unsigned 
> conversion is undefined,
>  which llvm/clang optimizes away.

It's specifically negative float to unsigned that's undefined.




Comment at: test/CodeGen/aarch64-neon-vsqadd-float-conversion.c:2
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone 
-emit-llvm -o - %s \
+// RUN: | opt -S -mem2reg -dce \

I don't think -fallow-half-arguments-and-returns is necessary.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64239/new/

https://reviews.llvm.org/D64239



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


[PATCH] D62883: [analyzer] Track terminator conditions on which a tracked expressions depends

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365207: [analyzer] Track terminator conditions on which a 
tracked expression depends (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D62883?vs=208084=208167#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62883/new/

https://reviews.llvm.org/D62883

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  cfe/trunk/test/Analysis/analyzer-config.c
  cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Index: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/Type.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Analysis/Analyses/Dominators.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -1619,6 +1620,89 @@
 }
 
 //===--===//
+// TrackControlDependencyCondBRVisitor.
+//===--===//
+
+namespace {
+/// Tracks the expressions that are a control dependency of the node that was
+/// supplied to the constructor.
+/// For example:
+///
+///   cond = 1;
+///   if (cond)
+/// 10 / 0;
+///
+/// An error is emitted at line 3. This visitor realizes that the branch
+/// on line 2 is a control dependency of line 3, and tracks it's condition via
+/// trackExpressionValue().
+class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
+  const ExplodedNode *Origin;
+  ControlDependencyCalculator ControlDeps;
+  llvm::SmallSet VisitedBlocks;
+
+public:
+  TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
+  : Origin(O), ControlDeps(>getCFG()) {}
+
+  void Profile(llvm::FoldingSetNodeID ) const override {
+static int x = 0;
+ID.AddPointer();
+  }
+
+  std::shared_ptr VisitNode(const ExplodedNode *N,
+ BugReporterContext ,
+ BugReport ) override;
+};
+} // end of anonymous namespace
+
+static CFGBlock *GetRelevantBlock(const ExplodedNode *Node) {
+  if (auto SP = Node->getLocationAs()) {
+const Stmt *S = SP->getStmt();
+assert(S);
+
+return const_cast(Node->getLocationContext()
+->getAnalysisDeclContext()->getCFGStmtMap()->getBlock(S));
+  }
+
+  return nullptr;
+}
+
+std::shared_ptr
+TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
+   BugReporterContext ,
+   BugReport ) {
+  // We can only reason about control dependencies within the same stack frame.
+  if (Origin->getStackFrame() != N->getStackFrame())
+return nullptr;
+
+  CFGBlock *NB = GetRelevantBlock(N);
+
+  // Skip if we already inspected this block.
+  if (!VisitedBlocks.insert(NB).second)
+return nullptr;
+
+  CFGBlock *OriginB = GetRelevantBlock(Origin);
+
+  // TODO: Cache CFGBlocks for each ExplodedNode.
+  if (!OriginB || !NB)
+return nullptr;
+
+  if (ControlDeps.isControlDependent(OriginB, NB)) {
+if (const Expr *Condition = NB->getLastCondition()) {
+  // Keeping track of the already tracked conditions on a visitor level
+  // isn't sufficient, because a new visitor is created for each tracked
+  // expression, hence the BugReport level set.
+  if (BR.addTrackedCondition(N)) {
+bugreporter::trackExpressionValue(
+N, Condition, BR, /*EnableNullFPSuppression=*/false);
+  }
+}
+  }
+
+  return nullptr;
+}
+
+//===--===//
 // Implementation of trackExpressionValue.
 //===--===//
 
@@ -1734,6 +1818,15 @@
 
   ProgramStateRef LVState = LVNode->getState();
 
+  // We only track expressions if we believe that they are important. Chances
+  // are good that control dependencies to the tracking point are also improtant
+  // because of this, let's explain why we believe control reached this point.
+  // TODO: Shouldn't we track control dependencies of every bug location, rather
+  // than only tracked expressions?
+  if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
+report.addVisitor(llvm::make_unique(
+  InputNode));
+
   // The message send could be nil due to the receiver being nil.

r365207 - [analyzer] Track terminator conditions on which a tracked expression depends

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 06:29:54 2019
New Revision: 365207

URL: http://llvm.org/viewvc/llvm-project?rev=365207=rev
Log:
[analyzer] Track terminator conditions on which a tracked expression depends

This patch is a major part of my GSoC project, aimed to improve the bug
reports of the analyzer.

TL;DR: Help the analyzer understand that some conditions are important,
and should be explained better. If an CFGBlock is a control dependency
of a block where an expression value is tracked, explain the condition
expression better by tracking it.

if (A) // let's explain why we believe A to be true
  10 / x; // division by zero

This is an experimental feature, and can be enabled by the
off-by-default analyzer configuration "track-conditions".

In detail:

This idea was inspired by the program slicing algorithm. Essentially,
two things are used to produce a program slice (a subset of the program
relevant to a (statement, variable) pair): data and control
dependencies. The bug path (the linear path in the ExplodedGraph that leads
from the beginning of the analysis to the error node) enables to
analyzer to argue about data dependencies with relative ease.

Control dependencies are a different slice of the cake entirely.

Just because we reached a branch during symbolic execution, it
doesn't mean that that particular branch has any effect on whether the
bug would've occured. This means that we can't simply rely on the bug
path to gather control dependencies.

In previous patches, LLVM's IDFCalculator, which works on a control flow
graph rather than the ExplodedGraph was generalized to solve this issue.
We use this information to heuristically guess that the value of a tracked
expression depends greatly on it's control dependencies, and start
tracking them as well.

After plenty of evaluations this was seen as great idea, but still
lacking refinements (we should have different descriptions about a
conditions value), hence it's off-by-default.

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

Added:
cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/analyzer-config.c

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def?rev=365207=365206=365207=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def Fri Jul  5 
06:29:54 2019
@@ -291,6 +291,11 @@ ANALYZER_OPTION(bool, DisplayCTUProgress
 "the analyzer's progress related to ctu.",
 false)
 
+ANALYZER_OPTION(bool, ShouldTrackConditions, "track-conditions",
+"Whether to track conditions that are a control dependency of "
+"an already tracked variable.",
+false)
+
 
//===--===//
 // Unsinged analyzer options.
 
//===--===//

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=365207=365206=365207=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Fri 
Jul  5 06:29:54 2019
@@ -153,6 +153,9 @@ protected:
   /// \sa removeInvalidation
   llvm::SmallSet Invalidations;
 
+  /// Conditions we're already tracking.
+  llvm::SmallSet TrackedConditions;
+
 private:
   // Used internally by BugReporter.
   Symbols ();
@@ -349,6 +352,13 @@ public:
   visitor_iterator visitor_begin() { return Callbacks.begin(); }
   visitor_iterator visitor_end() { return Callbacks.end(); }
 
+  /// Notes that the condition of the CFGBlock associated with \p Cond is
+  /// being tracked.
+  /// \returns false if the condition is already being tracked.
+  bool addTrackedCondition(const ExplodedNode *Cond) {
+return TrackedConditions.insert(Cond).second;
+  }
+
   /// Profile to identify equivalent bug reports for error report coalescing.
   /// Reports are uniqued to ensure that we do not emit multiple diagnostics
   /// for each bug.

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=365207=365206=365207=diff

[PATCH] D61879: WIP: Prototype of DSE optimizations for -ftrivial-auto-var-init

2019-07-05 Thread Alexander Potapenko via Phabricator via cfe-commits
glider added inline comments.



Comment at: llvm/lib/Transforms/Scalar/DeadStoreEliminationExp.cpp:709
+   size_t argN) {
+  const Function *F = cast(Callee);
+  if (argN >= F->arg_size())

This cast fails in the following case:

```
%21 = call i64 @probe_kernel_read(i8* nonnull %9, i8* %20, i64 8) #10, !dbg 
!7740
```
, where the callee is declared as:
```
@probe_kernel_read = weak hidden alias i64 (i8*, i8*, i64), i64 (i8*, i8*, 
i64)* @__probe_kernel_read
```

When building Android kernel with LTO enabled, the gold plugin crashes on an 
assertion.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61879/new/

https://reviews.llvm.org/D61879



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


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
jvikstrom marked an inline comment as done.
Closed by commit rL365205: [clangd] Added highlighting for variable references 
(declrefs) (authored by jvikstrom, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64199?vs=208143=208165#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199

Files:
  clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
  clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
@@ -34,26 +34,46 @@
 return Tokens;
   }
 
-  bool VisitVarDecl(VarDecl *Var) {
-addToken(Var, HighlightingKind::Variable);
+  bool VisitNamedDecl(NamedDecl *ND) {
+// FIXME: (De)Constructors/operator need to be highlighted some other way.
+if (ND->getDeclName().getNameKind() != DeclarationName::Identifier)
+  return true;
+
+if (ND->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return true;
+addToken(ND->getLocation(), ND);
 return true;
   }
-  bool VisitFunctionDecl(FunctionDecl *Func) {
-addToken(Func, HighlightingKind::Function);
+
+  bool VisitDeclRefExpr(DeclRefExpr *Ref) {
+if (Ref->getNameInfo().getName().getNameKind() !=
+DeclarationName::Identifier)
+  // Only want to highlight identifiers.
+  return true;
+
+addToken(Ref->getLocation(), Ref->getDecl());
 return true;
   }
 
 private:
-  void addToken(const NamedDecl *D, HighlightingKind Kind) {
-if (D->getLocation().isMacroID())
-  // FIXME: skip tokens inside macros for now.
+  void addToken(SourceLocation Loc, const Decl *D) {
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Variable);
   return;
+}
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Function);
+  return;
+}
+  }
 
-if (D->getDeclName().isEmpty())
-  // Don't add symbols that don't have any length.
+  void addToken(SourceLocation Loc, HighlightingKind Kind) {
+if (Loc.isMacroID())
+  // FIXME: skip tokens inside macros for now.
   return;
 
-auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+auto R = getTokenRange(SM, Ctx.getLangOpts(), Loc);
 if (!R) {
   // R should always have a value, if it doesn't something is very wrong.
   elog("Tried to add semantic token with an invalid range");
Index: clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp
@@ -48,20 +48,35 @@
 
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
-  R"cpp(
-struct A {
-  double SomeMember;
-};
-struct {
-}   $Variable[[HStruct]];
-void $Function[[foo]](int $Variable[[a]]) {
-  auto $Variable[[VeryLongVariableName]] = 12312;
-  A $Variable[[aa]];
-}
-  )cpp",
-  R"cpp(
-void $Function[[foo]](int);
-  )cpp"};
+R"cpp(
+  struct AS {
+double SomeMember;
+  };
+  struct {
+  } $Variable[[S]];
+  void $Function[[foo]](int $Variable[[A]]) {
+auto $Variable[[VeryLongVariableName]] = 12312;
+AS $Variable[[AA]];
+auto $Variable[[L]] = $Variable[[AA]].SomeMember + $Variable[[A]];
+auto $Variable[[FN]] = [ $Variable[[AA]]](int $Variable[[A]]) -> void {};
+$Variable[[FN]](12312);
+  }
+)cpp",
+R"cpp(
+  void $Function[[foo]](int);
+  void $Function[[Gah]]();
+  void $Function[[foo]]() {
+auto $Variable[[Bou]] = $Function[[Gah]];
+  }
+)cpp",
+R"cpp(
+  struct A {
+A();
+~A();
+void $Function[[abc]]();
+void operator<<(int);
+  };
+)cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r365205 - [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Fri Jul  5 06:06:03 2019
New Revision: 365205

URL: http://llvm.org/viewvc/llvm-project?rev=365205=rev
Log:
[clangd] Added highlighting for variable references (declrefs)

Summary: Added highlighting for variable references using VisitDeclRefExpr.

Reviewers: hokein, sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, kadircet, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp

Modified: clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp?rev=365205=365204=365205=diff
==
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp (original)
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp Fri Jul  5 06:06:03 
2019
@@ -34,26 +34,46 @@ public:
 return Tokens;
   }
 
-  bool VisitVarDecl(VarDecl *Var) {
-addToken(Var, HighlightingKind::Variable);
+  bool VisitNamedDecl(NamedDecl *ND) {
+// FIXME: (De)Constructors/operator need to be highlighted some other way.
+if (ND->getDeclName().getNameKind() != DeclarationName::Identifier)
+  return true;
+
+if (ND->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return true;
+addToken(ND->getLocation(), ND);
 return true;
   }
-  bool VisitFunctionDecl(FunctionDecl *Func) {
-addToken(Func, HighlightingKind::Function);
+
+  bool VisitDeclRefExpr(DeclRefExpr *Ref) {
+if (Ref->getNameInfo().getName().getNameKind() !=
+DeclarationName::Identifier)
+  // Only want to highlight identifiers.
+  return true;
+
+addToken(Ref->getLocation(), Ref->getDecl());
 return true;
   }
 
 private:
-  void addToken(const NamedDecl *D, HighlightingKind Kind) {
-if (D->getLocation().isMacroID())
-  // FIXME: skip tokens inside macros for now.
+  void addToken(SourceLocation Loc, const Decl *D) {
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Variable);
   return;
+}
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Function);
+  return;
+}
+  }
 
-if (D->getDeclName().isEmpty())
-  // Don't add symbols that don't have any length.
+  void addToken(SourceLocation Loc, HighlightingKind Kind) {
+if (Loc.isMacroID())
+  // FIXME: skip tokens inside macros for now.
   return;
 
-auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+auto R = getTokenRange(SM, Ctx.getLangOpts(), Loc);
 if (!R) {
   // R should always have a value, if it doesn't something is very wrong.
   elog("Tried to add semantic token with an invalid range");

Modified: clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp?rev=365205=365204=365205=diff
==
--- clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp 
(original)
+++ clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp Fri 
Jul  5 06:06:03 2019
@@ -48,20 +48,35 @@ void checkHighlightings(llvm::StringRef
 
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
-  R"cpp(
-struct A {
-  double SomeMember;
-};
-struct {
-}   $Variable[[HStruct]];
-void $Function[[foo]](int $Variable[[a]]) {
-  auto $Variable[[VeryLongVariableName]] = 12312;
-  A $Variable[[aa]];
-}
-  )cpp",
-  R"cpp(
-void $Function[[foo]](int);
-  )cpp"};
+R"cpp(
+  struct AS {
+double SomeMember;
+  };
+  struct {
+  } $Variable[[S]];
+  void $Function[[foo]](int $Variable[[A]]) {
+auto $Variable[[VeryLongVariableName]] = 12312;
+AS $Variable[[AA]];
+auto $Variable[[L]] = $Variable[[AA]].SomeMember + $Variable[[A]];
+auto $Variable[[FN]] = [ $Variable[[AA]]](int $Variable[[A]]) -> void 
{};
+$Variable[[FN]](12312);
+  }
+)cpp",
+R"cpp(
+  void $Function[[foo]](int);
+  void $Function[[Gah]]();
+  void $Function[[foo]]() {
+auto $Variable[[Bou]] = $Function[[Gah]];
+  }
+)cpp",
+R"cpp(
+  struct A {
+A();
+~A();
+void $Function[[abc]]();
+void operator<<(int);
+  };
+)cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
   }


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


[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/Diagnostics.cpp:427
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle

sammccall wrote:
> hokein wrote:
> > sammccall wrote:
> > > This sorting/partitioning seems a bit heavyweight... what about
> > > 
> > > ```
> > > DenseSet> SeenDiagnostics;
> > > llvm::erase_if([&](const Diag ) {
> > >   return !SeenDiagnostics.try_emplace(D.Range, D.Message).second;
> > > });
> > > ```
> > This is neat. DenseSet requires a hashvalue function of the value, which we 
> > don't have, switched to use `set`
> Can we add one instead? It'd be nice to get rid of the `operator<` on range, 
> use of `set` etc.
> I can do this is a followup if you prefer.
I'd leave it to a follow-up.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127



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


[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365204: [clangd] Deduplicate clang-tidy diagnostic messages. 
(authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64127?vs=208158=208164#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127

Files:
  clang-tools-extra/trunk/clangd/Diagnostics.cpp
  clang-tools-extra/trunk/clangd/Protocol.h
  clang-tools-extra/trunk/clangd/test/fixits-duplication.test
  clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/trunk/clangd/Diagnostics.cpp
===
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp
@@ -424,6 +424,13 @@
   }
 }
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle
+  // template instantiations well; clang-tidy alias checks).
+  std::set> SeenDiags;
+  llvm::erase_if(Output, [&](const Diag& D) {
+return !SeenDiags.emplace(D.Range, D.Message).second;
+  });
   return std::move(Output);
 }
 
Index: clang-tools-extra/trunk/clangd/Protocol.h
===
--- clang-tools-extra/trunk/clangd/Protocol.h
+++ clang-tools-extra/trunk/clangd/Protocol.h
@@ -668,17 +668,11 @@
 
 /// A LSP-specific comparator used to find diagnostic in a container like
 /// std:map.
-/// We only use as many fields of Diagnostic as is needed to make distinct
-/// diagnostics unique in practice, to avoid  regression issues from LSP clients
-/// (e.g. VScode), see https://git.io/vbr29
+/// We only use the required fields of Diagnostic to do the comparsion to avoid
+/// any regression issues from LSP clients (e.g. VScode), see
+/// https://git.io/vbr29
 struct LSPDiagnosticCompare {
   bool operator()(const Diagnostic , const Diagnostic ) const {
-if (!LHS.code.empty() && !RHS.code.empty()) {
-  // If the code is known for both, use the code to diambiguate, as e.g.
-  // two checkers could produce diagnostics with the same range and message.
-  return std::tie(LHS.range, LHS.message, LHS.code) <
- std::tie(RHS.range, RHS.message, RHS.code);
-}
 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
   }
 };
Index: clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp
@@ -179,6 +179,44 @@
   DiagSource(Diag::Clang), DiagName("pp_file_not_found";
 }
 
+TEST(DiagnosticsTest, DeduplicatedClangTidyDiagnostics) {
+  Annotations Test(R"cpp(
+float foo = [[0.1f]];
+  )cpp");
+  auto TU = TestTU::withCode(Test.code());
+  // Enable alias clang-tidy checks, these check emits the same diagnostics
+  // (except the check name).
+  TU.ClangTidyChecks = "-*, readability-uppercase-literal-suffix, "
+   "hicpp-uppercase-literal-suffix";
+  // Verify that we filter out the duplicated diagnostic message.
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(::testing::AllOf(
+  Diag(Test.range(),
+   "floating point literal has suffix 'f', which is not uppercase"),
+  DiagSource(Diag::ClangTidy;
+
+  Test = Annotations(R"cpp(
+template
+void func(T) {
+  float f = [[0.3f]];
+}
+void k() {
+  func(123);
+  func(2.0);
+}
+  )cpp");
+  TU.Code = Test.code();
+  // The check doesn't handle template instantiations which ends up emitting
+  // duplicated messages, verify that we deduplicate them.
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(::testing::AllOf(
+  Diag(Test.range(),
+   "floating point literal has suffix 'f', which is not uppercase"),
+  DiagSource(Diag::ClangTidy;
+}
+
 TEST(DiagnosticsTest, ClangTidy) {
   Annotations Test(R"cpp(
 #include $deprecated[["assert.h"]]
Index: clang-tools-extra/trunk/clangd/test/fixits-duplication.test
===
--- clang-tools-extra/trunk/clangd/test/fixits-duplication.test
+++ clang-tools-extra/trunk/clangd/test/fixits-duplication.test
@@ -1,221 +0,0 @@
-# RUN: clangd -lit-test -clang-tidy-checks=modernize-use-nullptr,hicpp-use-nullptr -tweaks="" < %s | FileCheck -strict-whitespace %s
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{"textDocument":{"codeAction":{"codeActionLiteralSupport":{,"trace":"off"}}


[clang-tools-extra] r365204 - [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Fri Jul  5 05:57:56 2019
New Revision: 365204

URL: http://llvm.org/viewvc/llvm-project?rev=365204=rev
Log:
[clangd] Deduplicate clang-tidy diagnostic messages.

Summary:
Clang-tidy checks may emit duplicated messages (clang-tidy tool
deduplicate them in its custom diagnostic consumer), and we may show
multiple duplicated diagnostics in the UI, which is really bad.

This patch makes clangd do the deduplication, and revert the change
rL363889.

Reviewers: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, mgrang, arphaman, kadircet, 
cfe-commits

Tags: #clang

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

Removed:
clang-tools-extra/trunk/clangd/test/fixits-duplication.test
Modified:
clang-tools-extra/trunk/clangd/Diagnostics.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=365204=365203=365204=diff
==
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Fri Jul  5 05:57:56 2019
@@ -424,6 +424,13 @@ std::vector StoreDiags::take(const
   }
 }
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle
+  // template instantiations well; clang-tidy alias checks).
+  std::set> SeenDiags;
+  llvm::erase_if(Output, [&](const Diag& D) {
+return !SeenDiags.emplace(D.Range, D.Message).second;
+  });
   return std::move(Output);
 }
 

Modified: clang-tools-extra/trunk/clangd/Protocol.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.h?rev=365204=365203=365204=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.h (original)
+++ clang-tools-extra/trunk/clangd/Protocol.h Fri Jul  5 05:57:56 2019
@@ -668,17 +668,11 @@ llvm::json::Value toJSON(const Diagnosti
 
 /// A LSP-specific comparator used to find diagnostic in a container like
 /// std:map.
-/// We only use as many fields of Diagnostic as is needed to make distinct
-/// diagnostics unique in practice, to avoid  regression issues from LSP 
clients
-/// (e.g. VScode), see https://git.io/vbr29
+/// We only use the required fields of Diagnostic to do the comparsion to avoid
+/// any regression issues from LSP clients (e.g. VScode), see
+/// https://git.io/vbr29
 struct LSPDiagnosticCompare {
   bool operator()(const Diagnostic , const Diagnostic ) const {
-if (!LHS.code.empty() && !RHS.code.empty()) {
-  // If the code is known for both, use the code to diambiguate, as e.g.
-  // two checkers could produce diagnostics with the same range and 
message.
-  return std::tie(LHS.range, LHS.message, LHS.code) <
- std::tie(RHS.range, RHS.message, RHS.code);
-}
 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
   }
 };

Removed: clang-tools-extra/trunk/clangd/test/fixits-duplication.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/test/fixits-duplication.test?rev=365203=auto
==
--- clang-tools-extra/trunk/clangd/test/fixits-duplication.test (original)
+++ clang-tools-extra/trunk/clangd/test/fixits-duplication.test (removed)
@@ -1,221 +0,0 @@
-# RUN: clangd -lit-test 
-clang-tidy-checks=modernize-use-nullptr,hicpp-use-nullptr -tweaks="" < %s | 
FileCheck -strict-whitespace %s
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{"textDocument":{"codeAction":{"codeActionLiteralSupport":{,"trace":"off"}}

-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.cpp","languageId":"cpp","version":1,"text":"void
 foo() { char* p = 0; }"}}}
-#  CHECK:"method": "textDocument/publishDiagnostics",
-# CHECK-NEXT:  "params": {
-# CHECK-NEXT:"diagnostics": [
-# CHECK-NEXT:  {
-# CHECK-NEXT:"code": "hicpp-use-nullptr",
-# CHECK-NEXT:"message": "Use nullptr (fix available)",
-# CHECK-NEXT:"range": {
-# CHECK-NEXT:  "end": {
-# CHECK-NEXT:"character": 24,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "start": {
-# CHECK-NEXT:"character": 23,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  }
-# CHECK-NEXT:},
-# CHECK-NEXT:"severity": 2,
-# CHECK-NEXT:"source": "clang-tidy"
-# CHECK-NEXT:  },
-# CHECK-NEXT:  {
-# CHECK-NEXT:"code": "modernize-use-nullptr",
-# CHECK-NEXT:"message": "Use nullptr (fix available)",
-# CHECK-NEXT:"range": {
-# 

[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Diagnostics.cpp:427
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle

hokein wrote:
> sammccall wrote:
> > This sorting/partitioning seems a bit heavyweight... what about
> > 
> > ```
> > DenseSet> SeenDiagnostics;
> > llvm::erase_if([&](const Diag ) {
> >   return !SeenDiagnostics.try_emplace(D.Range, D.Message).second;
> > });
> > ```
> This is neat. DenseSet requires a hashvalue function of the value, which we 
> don't have, switched to use `set`
Can we add one instead? It'd be nice to get rid of the `operator<` on range, 
use of `set` etc.
I can do this is a followup if you prefer.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127



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


[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 208158.
hokein marked 2 inline comments as done.
hokein added a comment.

Address comment.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/test/fixits-duplication.test
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -179,6 +179,44 @@
   DiagSource(Diag::Clang), DiagName("pp_file_not_found";
 }
 
+TEST(DiagnosticsTest, DeduplicatedClangTidyDiagnostics) {
+  Annotations Test(R"cpp(
+float foo = [[0.1f]];
+  )cpp");
+  auto TU = TestTU::withCode(Test.code());
+  // Enable alias clang-tidy checks, these check emits the same diagnostics
+  // (except the check name).
+  TU.ClangTidyChecks = "-*, readability-uppercase-literal-suffix, "
+   "hicpp-uppercase-literal-suffix";
+  // Verify that we filter out the duplicated diagnostic message.
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(::testing::AllOf(
+  Diag(Test.range(),
+   "floating point literal has suffix 'f', which is not uppercase"),
+  DiagSource(Diag::ClangTidy;
+
+  Test = Annotations(R"cpp(
+template
+void func(T) {
+  float f = [[0.3f]];
+}
+void k() {
+  func(123);
+  func(2.0);
+}
+  )cpp");
+  TU.Code = Test.code();
+  // The check doesn't handle template instantiations which ends up emitting
+  // duplicated messages, verify that we deduplicate them.
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(::testing::AllOf(
+  Diag(Test.range(),
+   "floating point literal has suffix 'f', which is not uppercase"),
+  DiagSource(Diag::ClangTidy;
+}
+
 TEST(DiagnosticsTest, ClangTidy) {
   Annotations Test(R"cpp(
 #include $deprecated[["assert.h"]]
Index: clang-tools-extra/clangd/test/fixits-duplication.test
===
--- clang-tools-extra/clangd/test/fixits-duplication.test
+++ /dev/null
@@ -1,221 +0,0 @@
-# RUN: clangd -lit-test -clang-tidy-checks=modernize-use-nullptr,hicpp-use-nullptr -tweaks="" < %s | FileCheck -strict-whitespace %s
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{"textDocument":{"codeAction":{"codeActionLiteralSupport":{,"trace":"off"}}

-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.cpp","languageId":"cpp","version":1,"text":"void foo() { char* p = 0; }"}}}
-#  CHECK:"method": "textDocument/publishDiagnostics",
-# CHECK-NEXT:  "params": {
-# CHECK-NEXT:"diagnostics": [
-# CHECK-NEXT:  {
-# CHECK-NEXT:"code": "hicpp-use-nullptr",
-# CHECK-NEXT:"message": "Use nullptr (fix available)",
-# CHECK-NEXT:"range": {
-# CHECK-NEXT:  "end": {
-# CHECK-NEXT:"character": 24,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "start": {
-# CHECK-NEXT:"character": 23,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  }
-# CHECK-NEXT:},
-# CHECK-NEXT:"severity": 2,
-# CHECK-NEXT:"source": "clang-tidy"
-# CHECK-NEXT:  },
-# CHECK-NEXT:  {
-# CHECK-NEXT:"code": "modernize-use-nullptr",
-# CHECK-NEXT:"message": "Use nullptr (fix available)",
-# CHECK-NEXT:"range": {
-# CHECK-NEXT:  "end": {
-# CHECK-NEXT:"character": 24,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "start": {
-# CHECK-NEXT:"character": 23,
-# CHECK-NEXT:"line": 0
-# CHECK-NEXT:  }
-# CHECK-NEXT:},
-# CHECK-NEXT:"severity": 2,
-# CHECK-NEXT:"source": "clang-tidy"
-# CHECK-NEXT:  }
-# CHECK-NEXT:],
-# CHECK-NEXT:"uri": "file:///{{.*}}/foo.cpp"
-# CHECK-NEXT:  }

-{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.cpp"},"range":{"start":{"line":0,"character":23},"end":{"line":0,"character":24}},"context":{"diagnostics":[{"range":{"start": {"line": 0, "character": 23}, "end": {"line": 0, "character": 24}},"severity":2,"message":"Use nullptr (fix available)", "code": "hicpp-use-nullptr", "source": "clang-tidy"},{"range":{"start": {"line": 0, "character": 23}, "end": {"line": 0, "character": 24}},"severity":2,"message":"Use nullptr (fix available)", "code": "modernize-use-nullptr", "source": "clang-tidy"}]}}}
-#  CHECK:  "id": 2,
-# CHECK-NEXT:  

[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/Diagnostics.cpp:427
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle

sammccall wrote:
> This sorting/partitioning seems a bit heavyweight... what about
> 
> ```
> DenseSet> SeenDiagnostics;
> llvm::erase_if([&](const Diag ) {
>   return !SeenDiagnostics.try_emplace(D.Range, D.Message).second;
> });
> ```
This is neat. DenseSet requires a hashvalue function of the value, which we 
don't have, switched to use `set`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127



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


[PATCH] D62619: [analyzer][IDF] Add a control dependency calculator + a new debug checker

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Szelethus marked 11 inline comments as done.
Closed by commit rL365197: [analyzer][IDF] Add a control dependency calculator 
+ a new debug checker (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D62619?vs=205917=208157#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62619/new/

https://reviews.llvm.org/D62619

Files:
  cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
  cfe/trunk/include/clang/Analysis/CFG.h
  cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
  cfe/trunk/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
  cfe/trunk/test/Analysis/domtest.c
  cfe/trunk/test/Analysis/domtest.cpp
  cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1237,6 +1237,10 @@
   HelpText<"Print the post dominance tree for a given CFG">,
   Documentation;
 
+def ControlDependencyTreeDumper : Checker<"DumpControlDependencies">,
+  HelpText<"Print the post control dependency tree for a given CFG">,
+  Documentation;
+
 def LiveVariablesDumper : Checker<"DumpLiveVars">,
   HelpText<"Print results of live variable analysis">,
   Documentation;
Index: cfe/trunk/include/clang/Analysis/CFG.h
===
--- cfe/trunk/include/clang/Analysis/CFG.h
+++ cfe/trunk/include/clang/Analysis/CFG.h
@@ -1285,6 +1285,9 @@
   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
 };
 
+template <> struct GraphTraits
+: GraphTraits {};
+
 template <> struct GraphTraits< const ::clang::CFGBlock *> {
   using NodeRef = const ::clang::CFGBlock *;
   using ChildIteratorType = ::clang::CFGBlock::const_succ_iterator;
@@ -1294,6 +1297,9 @@
   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
 };
 
+template <> struct GraphTraits
+: GraphTraits {};
+
 template <> struct GraphTraits> {
   using NodeRef = ::clang::CFGBlock *;
   using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
@@ -1306,6 +1312,9 @@
   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
 };
 
+template <> struct GraphTraits>
+: GraphTraits {};
+
 template <> struct GraphTraits> {
   using NodeRef = const ::clang::CFGBlock *;
   using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
@@ -1318,6 +1327,9 @@
   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
 };
 
+template <> struct GraphTraits>
+: GraphTraits {};
+
 // Traits for: CFG
 
 template <> struct GraphTraits< ::clang::CFG* >
Index: cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
===
--- cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
+++ cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
@@ -18,6 +18,7 @@
 #include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/GraphTraits.h"
 #include "llvm/ADT/iterator.h"
+#include "llvm/Support/GenericIteratedDominanceFrontier.h"
 #include "llvm/Support/GenericDomTree.h"
 #include "llvm/Support/GenericDomTreeConstruction.h"
 #include "llvm/Support/raw_ostream.h"
@@ -44,12 +45,17 @@
 public:
   using DominatorTreeBase = llvm::DominatorTreeBase;
 
-  DominatorTreeBase DT;
-
   CFGDominatorTreeImpl() = default;
+
+  CFGDominatorTreeImpl(CFG *cfg) {
+buildDominatorTree(cfg);
+  }
+
   ~CFGDominatorTreeImpl() override = default;
 
-  DominatorTreeBase& getBase() { return *DT; }
+  DominatorTreeBase () { return DT; }
+
+  CFG *getCFG() { return cfg; }
 
   /// \returns the root CFGBlock of the dominators tree.
   CFGBlock *getRoot() const {
@@ -172,11 +178,96 @@
 
 private:
   CFG *cfg;
+  DominatorTreeBase DT;
 };
 
 using CFGDomTree = CFGDominatorTreeImpl;
 using CFGPostDomTree = CFGDominatorTreeImpl;
 
+} // end of namespace clang
+
+namespace llvm {
+namespace IDFCalculatorDetail {
+
+/// Specialize ChildrenGetterTy to skip nullpointer successors.
+template 
+struct ChildrenGetterTy {
+  using NodeRef = typename GraphTraits::NodeRef;
+  using ChildrenTy = SmallVector;
+
+  ChildrenTy get(const NodeRef ) {
+using OrderedNodeTy =
+typename IDFCalculatorBase::OrderedNodeTy;
+
+auto Children = children(N);
+ChildrenTy Ret{Children.begin(), Children.end()};
+Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
+return Ret;
+  }
+};
+
+} // end of namespace IDFCalculatorDetail
+} // end of namespace llvm
+
+namespace clang {
+
+class ControlDependencyCalculator : public ManagedAnalysis {
+  using IDFCalculator = llvm::IDFCalculatorBase;
+  using CFGBlockVector = llvm::SmallVector;
+  using 

r365197 - [analyzer][IDF] Add a control dependency calculator + a new debug checker

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 05:17:44 2019
New Revision: 365197

URL: http://llvm.org/viewvc/llvm-project?rev=365197=rev
Log:
[analyzer][IDF] Add a control dependency calculator + a new debug checker

I intend to improve the analyzer's bug reports by tracking condition
expressions.

01 bool b = messyComputation();
02 int i = 0;
03 if (b) // control dependency of the bug site, let's explain why we assume val
04// to be true
05   10 / i; // warn: division by zero

I'll detail this heuristic in the followup patch, strictly related to this one
however:

* Create the new ControlDependencyCalculator class that uses llvm::IDFCalculator
  to (lazily) calculate control dependencies for Clang's CFG.
* A new debug checker debug.DumpControlDependencies is added for lit tests
* Add unittests

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

Modified:
cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
cfe/trunk/include/clang/Analysis/CFG.h
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/lib/StaticAnalyzer/Checkers/DebugCheckers.cpp
cfe/trunk/test/Analysis/domtest.c
cfe/trunk/test/Analysis/domtest.cpp
cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp

Modified: cfe/trunk/include/clang/Analysis/Analyses/Dominators.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/Analyses/Dominators.h?rev=365197=365196=365197=diff
==
--- cfe/trunk/include/clang/Analysis/Analyses/Dominators.h (original)
+++ cfe/trunk/include/clang/Analysis/Analyses/Dominators.h Fri Jul  5 05:17:44 
2019
@@ -18,6 +18,7 @@
 #include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/GraphTraits.h"
 #include "llvm/ADT/iterator.h"
+#include "llvm/Support/GenericIteratedDominanceFrontier.h"
 #include "llvm/Support/GenericDomTree.h"
 #include "llvm/Support/GenericDomTreeConstruction.h"
 #include "llvm/Support/raw_ostream.h"
@@ -44,12 +45,17 @@ class CFGDominatorTreeImpl : public Mana
 public:
   using DominatorTreeBase = llvm::DominatorTreeBase;
 
-  DominatorTreeBase DT;
-
   CFGDominatorTreeImpl() = default;
+
+  CFGDominatorTreeImpl(CFG *cfg) {
+buildDominatorTree(cfg);
+  }
+
   ~CFGDominatorTreeImpl() override = default;
 
-  DominatorTreeBase& getBase() { return *DT; }
+  DominatorTreeBase () { return DT; }
+
+  CFG *getCFG() { return cfg; }
 
   /// \returns the root CFGBlock of the dominators tree.
   CFGBlock *getRoot() const {
@@ -172,11 +178,96 @@ public:
 
 private:
   CFG *cfg;
+  DominatorTreeBase DT;
 };
 
 using CFGDomTree = CFGDominatorTreeImpl;
 using CFGPostDomTree = CFGDominatorTreeImpl;
 
+} // end of namespace clang
+
+namespace llvm {
+namespace IDFCalculatorDetail {
+
+/// Specialize ChildrenGetterTy to skip nullpointer successors.
+template 
+struct ChildrenGetterTy {
+  using NodeRef = typename GraphTraits::NodeRef;
+  using ChildrenTy = SmallVector;
+
+  ChildrenTy get(const NodeRef ) {
+using OrderedNodeTy =
+typename IDFCalculatorBase::OrderedNodeTy;
+
+auto Children = children(N);
+ChildrenTy Ret{Children.begin(), Children.end()};
+Ret.erase(std::remove(Ret.begin(), Ret.end(), nullptr), Ret.end());
+return Ret;
+  }
+};
+
+} // end of namespace IDFCalculatorDetail
+} // end of namespace llvm
+
+namespace clang {
+
+class ControlDependencyCalculator : public ManagedAnalysis {
+  using IDFCalculator = llvm::IDFCalculatorBase;
+  using CFGBlockVector = llvm::SmallVector;
+  using CFGBlockSet = llvm::SmallPtrSet;
+
+  CFGPostDomTree PostDomTree;
+  IDFCalculator IDFCalc;
+
+  llvm::DenseMap ControlDepenencyMap;
+
+public:
+  ControlDependencyCalculator(CFG *cfg)
+: PostDomTree(cfg), IDFCalc(PostDomTree.getBase()) {}
+
+  const CFGPostDomTree () const { return PostDomTree; }
+
+  // Lazily retrieves the set of control dependencies to \p A.
+  const CFGBlockVector (CFGBlock *A) {
+auto It = ControlDepenencyMap.find(A);
+if (It == ControlDepenencyMap.end()) {
+  CFGBlockSet DefiningBlock = {A};
+  IDFCalc.setDefiningBlocks(DefiningBlock);
+
+  CFGBlockVector ControlDependencies;
+  IDFCalc.calculate(ControlDependencies);
+
+  It = ControlDepenencyMap.insert({A, ControlDependencies}).first;
+}
+
+assert(It != ControlDepenencyMap.end());
+return It->second;
+  }
+
+  /// Whether \p A is control dependent on \p B.
+  bool isControlDependent(CFGBlock *A, CFGBlock *B) {
+return llvm::is_contained(getControlDependencies(A), B);
+  }
+
+  // Dumps immediate control dependencies for each block.
+  LLVM_DUMP_METHOD void dump() {
+CFG *cfg = PostDomTree.getCFG();
+llvm::errs() << "Control dependencies (Node#,Dependency#):\n";
+for (CFGBlock *BB : *cfg) {
+
+  assert(BB &&
+ "LLVM's Dominator tree builder uses nullpointers to signify the "
+ "virtual root!");
+
+  for (CFGBlock *isControlDependency : getControlDependencies(BB))
+llvm::errs() << 

[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

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

thanks, looks good.




Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:52
   R"cpp(
-struct A {
-  double SomeMember;
-};
-struct {
-}   $Variable[[HStruct]];
-void $Function[[foo]](int $Variable[[a]]) {
-  auto $Variable[[VeryLongVariableName]] = 12312;
-  A $Variable[[aa]];
-}
-  )cpp",
+  struct AS {
+double SomeMember;

nit: I'd add 2-space to the code, like: 

```
R"cpp(
struct AS {}
...
)cpp, 
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199



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


[PATCH] D64243: [NFC][AArch64] Fix vector vqtb[lx][1-4]_s8 operand

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio created this revision.
dnsampaio added a reviewer: LukeCheeseman.
Herald added subscribers: cfe-commits, kristof.beyls, javed.absar.
Herald added a project: clang.

Change the vqtb[lx][1-4]_s8 instrinsics to have the last argument as vector of 
unsigned valuse, not
signed, accordingly to 
https://developer.arm.com/architectures/instruction-sets/simd-isas/neon/intrinsics


Repository:
  rC Clang

https://reviews.llvm.org/D64243

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-neon-tbl.c

Index: test/CodeGen/aarch64-neon-tbl.c
===
--- test/CodeGen/aarch64-neon-tbl.c
+++ test/CodeGen/aarch64-neon-tbl.c
@@ -16,7 +16,7 @@
 // CHECK-LABEL: define <8 x i8> @test_vqtbl1_s8(<16 x i8> %a, <8 x i8> %b) #1 {
 // CHECK:   [[VTBL1_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbl1.v8i8(<16 x i8> %a, <8 x i8> %b) #3
 // CHECK:   ret <8 x i8> [[VTBL1_I]]
-int8x8_t test_vqtbl1_s8(int8x16_t a, int8x8_t b) {
+int8x8_t test_vqtbl1_s8(int8x16_t a, uint8x8_t b) {
   return vqtbl1_s8(a, b);
 }
 
@@ -59,7 +59,7 @@
 // CHECK:   [[TMP2:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX2_I]], align 16
 // CHECK:   [[VTBL2_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbl2.v8i8(<16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <8 x i8> %b) #3
 // CHECK:   ret <8 x i8> [[VTBL2_I]]
-int8x8_t test_vqtbl2_s8(int8x16x2_t a, int8x8_t b) {
+int8x8_t test_vqtbl2_s8(int8x16x2_t a, uint8x8_t b) {
   return vqtbl2_s8(a, b);
 }
 
@@ -109,7 +109,7 @@
 // CHECK:   [[TMP3:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX4_I]], align 16
 // CHECK:   [[VTBL3_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbl3.v8i8(<16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <16 x i8> [[TMP3]], <8 x i8> %b) #3
 // CHECK:   ret <8 x i8> [[VTBL3_I]]
-int8x8_t test_vqtbl3_s8(int8x16x3_t a, int8x8_t b) {
+int8x8_t test_vqtbl3_s8(int8x16x3_t a, uint8x8_t b) {
   return vqtbl3_s8(a, b);
 }
 
@@ -165,7 +165,7 @@
 // CHECK:   [[TMP4:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX6_I]], align 16
 // CHECK:   [[VTBL4_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbl4.v8i8(<16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <16 x i8> [[TMP3]], <16 x i8> [[TMP4]], <8 x i8> %b) #3
 // CHECK:   ret <8 x i8> [[VTBL4_I]]
-int8x8_t test_vqtbl4_s8(int8x16x4_t a, int8x8_t b) {
+int8x8_t test_vqtbl4_s8(int8x16x4_t a, uint8x8_t b) {
   return vqtbl4_s8(a, b);
 }
 
@@ -348,7 +348,7 @@
 // CHECK-LABEL: define <8 x i8> @test_vqtbx1_s8(<8 x i8> %a, <16 x i8> %b, <8 x i8> %c) #1 {
 // CHECK:   [[VTBX1_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbx1.v8i8(<8 x i8> %a, <16 x i8> %b, <8 x i8> %c) #3
 // CHECK:   ret <8 x i8> [[VTBX1_I]]
-int8x8_t test_vqtbx1_s8(int8x8_t a, int8x16_t b, int8x8_t c) {
+int8x8_t test_vqtbx1_s8(int8x8_t a, int8x16_t b, uint8x8_t c) {
   return vqtbx1_s8(a, b, c);
 }
 
@@ -369,7 +369,7 @@
 // CHECK:   [[TMP2:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX2_I]], align 16
 // CHECK:   [[VTBX2_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbx2.v8i8(<8 x i8> %a, <16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <8 x i8> %c) #3
 // CHECK:   ret <8 x i8> [[VTBX2_I]]
-int8x8_t test_vqtbx2_s8(int8x8_t a, int8x16x2_t b, int8x8_t c) {
+int8x8_t test_vqtbx2_s8(int8x8_t a, int8x16x2_t b, uint8x8_t c) {
   return vqtbx2_s8(a, b, c);
 }
 
@@ -393,7 +393,7 @@
 // CHECK:   [[TMP3:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX4_I]], align 16
 // CHECK:   [[VTBX3_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbx3.v8i8(<8 x i8> %a, <16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <16 x i8> [[TMP3]], <8 x i8> %c) #3
 // CHECK:   ret <8 x i8> [[VTBX3_I]]
-int8x8_t test_vqtbx3_s8(int8x8_t a, int8x16x3_t b, int8x8_t c) {
+int8x8_t test_vqtbx3_s8(int8x8_t a, int8x16x3_t b, uint8x8_t c) {
   return vqtbx3_s8(a, b, c);
 }
 
@@ -420,14 +420,14 @@
 // CHECK:   [[TMP4:%.*]] = load <16 x i8>, <16 x i8>* [[ARRAYIDX6_I]], align 16
 // CHECK:   [[VTBX4_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.tbx4.v8i8(<8 x i8> %a, <16 x i8> [[TMP1]], <16 x i8> [[TMP2]], <16 x i8> [[TMP3]], <16 x i8> [[TMP4]], <8 x i8> %c) #3
 // CHECK:   ret <8 x i8> [[VTBX4_I]]
-int8x8_t test_vqtbx4_s8(int8x8_t a, int8x16x4_t b, int8x8_t c) {
+int8x8_t test_vqtbx4_s8(int8x8_t a, int8x16x4_t b, uint8x8_t c) {
   return vqtbx4_s8(a, b, c);
 }
 
 // CHECK-LABEL: define <16 x i8> @test_vqtbx1q_s8(<16 x i8> %a, <16 x i8> %b, <16 x i8> %c) #1 {
 // CHECK:   [[VTBX1_I:%.*]] = call <16 x i8> @llvm.aarch64.neon.tbx1.v16i8(<16 x i8> %a, <16 x i8> %b, <16 x i8> %c) #3
 // CHECK:   ret <16 x i8> [[VTBX1_I]]
-int8x16_t test_vqtbx1q_s8(int8x16_t a, int8x16_t b, int8x16_t c) {
+int8x16_t test_vqtbx1q_s8(int8x16_t a, int8x16_t b, uint8x16_t c) {
   return vqtbx1q_s8(a, b, c);
 }
 
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1070,16 +1070,16 @@
 
 // Table lookup
 let InstName = "vtbl" in {
-def VQTBL1_A64 : 

r365189 - [NFC] Test commit access

2019-07-05 Thread Endre Fulop via cfe-commits
Author: gamesh411
Date: Fri Jul  5 05:00:52 2019
New Revision: 365189

URL: http://llvm.org/viewvc/llvm-project?rev=365189=rev
Log:
[NFC] Test commit access

Modified:
cfe/trunk/include/clang/AST/ASTImporter.h

Modified: cfe/trunk/include/clang/AST/ASTImporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=365189=365188=365189=diff
==
--- cfe/trunk/include/clang/AST/ASTImporter.h (original)
+++ cfe/trunk/include/clang/AST/ASTImporter.h Fri Jul  5 05:00:52 2019
@@ -201,7 +201,7 @@ class TypeSourceInfo;
   }
 
 private:
-  // All the nodes of the path.
+  // All nodes of the path.
   VecTy Nodes;
   // Auxiliary container to be able to answer "Do we have a cycle ending
   // at last element?" as fast as possible.


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


[PATCH] D64156: Make joined instances of JoinedOrSeparate flags point to the unaliased args, like all other arg types do

2019-07-05 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365186: Make joined instances of JoinedOrSeparate flags 
point to the unaliased args… (authored by nico, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D64156?vs=207873=208146#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64156/new/

https://reviews.llvm.org/D64156

Files:
  cfe/trunk/lib/Driver/Driver.cpp
  lld/trunk/COFF/Driver.cpp
  lld/trunk/ELF/Driver.cpp
  lld/trunk/ELF/DriverUtils.cpp
  lld/trunk/MinGW/Driver.cpp
  lld/trunk/wasm/Driver.cpp
  llvm/trunk/lib/Option/Option.cpp


Index: lld/trunk/MinGW/Driver.cpp
===
--- lld/trunk/MinGW/Driver.cpp
+++ lld/trunk/MinGW/Driver.cpp
@@ -313,7 +313,7 @@
   StringRef Prefix = "";
   bool Static = false;
   for (auto *A : Args) {
-switch (A->getOption().getUnaliasedOption().getID()) {
+switch (A->getOption().getID()) {
 case OPT_INPUT:
   if (StringRef(A->getValue()).endswith_lower(".def"))
 Add("-def:" + StringRef(A->getValue()));
Index: lld/trunk/COFF/Driver.cpp
===
--- lld/trunk/COFF/Driver.cpp
+++ lld/trunk/COFF/Driver.cpp
@@ -332,7 +332,7 @@
   }
 
   for (auto *Arg : Args) {
-switch (Arg->getOption().getUnaliasedOption().getID()) {
+switch (Arg->getOption().getID()) {
 case OPT_aligncomm:
   parseAligncomm(Arg->getValue());
   break;
Index: lld/trunk/wasm/Driver.cpp
===
--- lld/trunk/wasm/Driver.cpp
+++ lld/trunk/wasm/Driver.cpp
@@ -271,7 +271,7 @@
 
 void LinkerDriver::createFiles(opt::InputArgList ) {
   for (auto *Arg : Args) {
-switch (Arg->getOption().getUnaliasedOption().getID()) {
+switch (Arg->getOption().getID()) {
 case OPT_l:
   addLibrary(Arg->getValue());
   break;
@@ -531,7 +531,7 @@
 
   // Copy the command line to the output while rewriting paths.
   for (auto *Arg : Args) {
-switch (Arg->getOption().getUnaliasedOption().getID()) {
+switch (Arg->getOption().getID()) {
 case OPT_reproduce:
   break;
 case OPT_INPUT:
Index: lld/trunk/ELF/Driver.cpp
===
--- lld/trunk/ELF/Driver.cpp
+++ lld/trunk/ELF/Driver.cpp
@@ -1112,7 +1112,7 @@
 
   // Iterate over argv to process input files and positional arguments.
   for (auto *Arg : Args) {
-switch (Arg->getOption().getUnaliasedOption().getID()) {
+switch (Arg->getOption().getID()) {
 case OPT_library:
   addLibrary(Arg->getValue());
   break;
Index: lld/trunk/ELF/DriverUtils.cpp
===
--- lld/trunk/ELF/DriverUtils.cpp
+++ lld/trunk/ELF/DriverUtils.cpp
@@ -172,7 +172,7 @@
 
   // Copy the command line to the output while rewriting paths.
   for (auto *Arg : Args) {
-switch (Arg->getOption().getUnaliasedOption().getID()) {
+switch (Arg->getOption().getID()) {
 case OPT_reproduce:
   break;
 case OPT_INPUT:
Index: llvm/trunk/lib/Option/Option.cpp
===
--- llvm/trunk/lib/Option/Option.cpp
+++ llvm/trunk/lib/Option/Option.cpp
@@ -207,7 +207,7 @@
 // FIXME: Avoid strlen.
 if (ArgSize != strlen(Args.getArgString(Index))) {
   const char *Value = Args.getArgString(Index) + ArgSize;
-  return new Arg(*this, Spelling, Index++, Value);
+  return new Arg(UnaliasedOption, Spelling, Index++, Value);
 }
 
 // Otherwise it must be separate.
Index: cfe/trunk/lib/Driver/Driver.cpp
===
--- cfe/trunk/lib/Driver/Driver.cpp
+++ cfe/trunk/lib/Driver/Driver.cpp
@@ -2180,7 +2180,7 @@
 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
 InputType = types::TY_Object;
   }
-} else if (A->getOption().getID() == options::OPT__SLASH_U) {
+} else if (A->getOption().getID() == options::OPT_U) {
   assert(A->getNumValues() == 1 && "The /U option has one value.");
   StringRef Val = A->getValue(0);
   if (Val.find_first_of("/\\") != StringRef::npos) {


Index: lld/trunk/MinGW/Driver.cpp
===
--- lld/trunk/MinGW/Driver.cpp
+++ lld/trunk/MinGW/Driver.cpp
@@ -313,7 +313,7 @@
   StringRef Prefix = "";
   bool Static = false;
   for (auto *A : Args) {
-switch (A->getOption().getUnaliasedOption().getID()) {
+switch (A->getOption().getID()) {
 case OPT_INPUT:
   if (StringRef(A->getValue()).endswith_lower(".def"))
 Add("-def:" + StringRef(A->getValue()));
Index: lld/trunk/COFF/Driver.cpp
===
--- lld/trunk/COFF/Driver.cpp
+++ lld/trunk/COFF/Driver.cpp
@@ -332,7 +332,7 @@
   }
 
   for (auto *Arg : Args) {
-  

r365186 - Make joined instances of JoinedOrSeparate flags point to the unaliased args, like all other arg types do

2019-07-05 Thread Nico Weber via cfe-commits
Author: nico
Date: Fri Jul  5 04:45:24 2019
New Revision: 365186

URL: http://llvm.org/viewvc/llvm-project?rev=365186=rev
Log:
Make joined instances of JoinedOrSeparate flags point to the unaliased args, 
like all other arg types do

This fixes an 8-year-old regression. r105763 made it so that aliases
always refer to the unaliased option – but it missed the "joined" branch
of JoinedOrSeparate flags. (r162231 then made the Args classes
non-virtual, and r169344 moved them from clang to llvm.)

Back then, there was no JoinedOrSeparate flag that was an alias, so it
wasn't observable. Now /U in CLCompatOptions is a JoinedOrSeparate alias
in clang, and warn_slash_u_filename incorrectly used the aliased arg id
(using the unaliased one isn't really a regression since that warning
checks if the undefined macro contains slash or backslash and only then
emits the warning – and no valid use will pass "-Ufoo/bar" or similar).

Also, lld has many JoinedOrSeparate aliases, and due to this bug it had
to explicitly call `getUnaliasedOption()` in a bunch of places, even
though that shouldn't be necessary by design. After this fix in Option,
these calls really don't have an effect any more, so remove them.

No intended behavior change.

(I accidentally fixed this bug while working on PR29106 but then
wondered why the warn_slash_u_filename broke. When I figured it out, I
thought it would make sense to land this in a separate commit.)

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

Modified:
cfe/trunk/lib/Driver/Driver.cpp

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=365186=365185=365186=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Fri Jul  5 04:45:24 2019
@@ -2180,7 +2180,7 @@ void Driver::BuildInputs(const ToolChain
 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
 InputType = types::TY_Object;
   }
-} else if (A->getOption().getID() == options::OPT__SLASH_U) {
+} else if (A->getOption().getID() == options::OPT_U) {
   assert(A->getNumValues() == 1 && "The /U option has one value.");
   StringRef Val = A->getValue(0);
   if (Val.find_first_of("/\\") != StringRef::npos) {


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


[PATCH] D64156: Make joined instances of JoinedOrSeparate flags point to the unaliased args, like all other arg types do

2019-07-05 Thread Rui Ueyama via Phabricator via cfe-commits
ruiu accepted this revision.
ruiu added a comment.
This revision is now accepted and ready to land.

LGTM


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64156/new/

https://reviews.llvm.org/D64156



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


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom marked 4 inline comments as done.
jvikstrom added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:61
+}
+if(isa(D)) {
+  addToken(Loc, HighlightingKind::Function);

hokein wrote:
> sammccall wrote:
> > jvikstrom wrote:
> > > sammccall wrote:
> > > > note that methods, constructors, and destructors inherit from 
> > > > functiondecl, so if you want to exclude/distinguish those, order 
> > > > matters here
> > > I'm aware of that, but thanks for the heads up. Although should I add it 
> > > in a comment somewhere in the method? Also added an additional testcase 
> > > for classes and FIXMEs to the skip if statement in VisitNamedDecl.
> > I don't think it needs a comment, especially if you're not actually 
> > highlighting them (because they have weird DeclarationNames)
> > 
> > > FIXMEs to the skip if statement in VisitNamedDecl
> > I'm not actually sure there's anything to fix here - it's a bit hard to 
> > talk about constructor/destructor highlighting as distinct from type name 
> > highlighting in C++. If you want them highlighted as classes, then that 
> > should just start working when you start handling TypeLocs.
> I think constructor/destructor can be categorized in the `function` group, 
> like `entity.name.function.constructor`, `entity.name.function.destructor`
I'll have a look at constructors/destructors at the same time as I look at types



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:69
+void $Function[[foo]]() {
+  int $Variable[[b]];
+  auto $Variable[[FN]] = [ $Variable[[b]]](int $Variable[[a]]) -> void {};

hokein wrote:
> nit: even for the test code, could we make the code style consistent (like 
> follow the LLVM code style) here?
I think this should be consistent with LLVM code style. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199



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


[PATCH] D64242: [AArch64] Fix scalar vuqadd intrinsics operands

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio updated this revision to Diff 208144.
dnsampaio added a comment.

- Fix previously existing tests


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64242/new/

https://reviews.llvm.org/D64242

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-neon-intrinsics.c
  test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c


Index: test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
===
--- /dev/null
+++ test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone 
-emit-llvm -o - %s 2>&1 \
+// RUN: | FileCheck %s
+
+#include 
+
+// Check float conversion is not accepted for unsigned int argument
+int8_t test_vuqaddb_s8(){
+  return vuqaddb_s8(1, -1.0f);
+}
+
+int16_t test_vuqaddh_s16() {
+  return vuqaddh_s16(1, -1.0f);
+}
+
+int32_t test_vuqadds_s32() {
+  return vuqadds_s32(1, -1.0f);
+}
+
+int64_t test_vuqaddd_s64() {
+  return vuqaddd_s64(1, -1.0f);
+}
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint8_t' (aka 'unsigned char') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint16_t' (aka 'unsigned short') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint32_t' (aka 'unsigned int') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint64_t' (aka 'unsigned long') is undefined
+
Index: test/CodeGen/aarch64-neon-intrinsics.c
===
--- test/CodeGen/aarch64-neon-intrinsics.c
+++ test/CodeGen/aarch64-neon-intrinsics.c
@@ -13879,7 +13879,7 @@
 // CHECK:   [[VUQADDB_S8_I:%.*]] = call <8 x i8> 
@llvm.aarch64.neon.suqadd.v8i8(<8 x i8> [[TMP0]], <8 x i8> [[TMP1]])
 // CHECK:   [[TMP2:%.*]] = extractelement <8 x i8> [[VUQADDB_S8_I]], i64 0
 // CHECK:   ret i8 [[TMP2]]
-int8_t test_vuqaddb_s8(int8_t a, int8_t b) {
+int8_t test_vuqaddb_s8(int8_t a, uint8_t b) {
   return (int8_t)vuqaddb_s8(a, b);
 }
 
@@ -13889,21 +13889,21 @@
 // CHECK:   [[VUQADDH_S16_I:%.*]] = call <4 x i16> 
@llvm.aarch64.neon.suqadd.v4i16(<4 x i16> [[TMP0]], <4 x i16> [[TMP1]])
 // CHECK:   [[TMP2:%.*]] = extractelement <4 x i16> [[VUQADDH_S16_I]], i64 0
 // CHECK:   ret i16 [[TMP2]]
-int16_t test_vuqaddh_s16(int16_t a, int16_t b) {
+int16_t test_vuqaddh_s16(int16_t a, uint16_t b) {
   return (int16_t)vuqaddh_s16(a, b);
 }
 
 // CHECK-LABEL: @test_vuqadds_s32(
 // CHECK:   [[VUQADDS_S32_I:%.*]] = call i32 @llvm.aarch64.neon.suqadd.i32(i32 
%a, i32 %b)
 // CHECK:   ret i32 [[VUQADDS_S32_I]]
-int32_t test_vuqadds_s32(int32_t a, int32_t b) {
+int32_t test_vuqadds_s32(int32_t a, uint32_t b) {
   return (int32_t)vuqadds_s32(a, b);
 }
 
 // CHECK-LABEL: @test_vuqaddd_s64(
 // CHECK:   [[VUQADDD_S64_I:%.*]] = call i64 @llvm.aarch64.neon.suqadd.i64(i64 
%a, i64 %b)
 // CHECK:   ret i64 [[VUQADDD_S64_I]]
-int64_t test_vuqaddd_s64(int64_t a, int64_t b) {
+int64_t test_vuqaddd_s64(int64_t a, uint64_t b) {
   return (int64_t)vuqaddd_s64(a, b);
 }
 
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1333,7 +1333,7 @@
 
 

 // Scalar Signed Saturating Accumulated of Unsigned Value
-def SCALAR_SUQADD : SInst<"vuqadd", "sss", "ScSsSiSl">;
+def SCALAR_SUQADD : SInst<"vuqadd", "ssb", "ScSsSiSl">;
 
 

 // Scalar Unsigned Saturating Accumulated of Signed Value


Index: test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
===
--- /dev/null
+++ test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone -emit-llvm -o - %s 2>&1 \
+// RUN: | FileCheck %s
+
+#include 
+
+// Check float conversion is not accepted for unsigned int argument
+int8_t test_vuqaddb_s8(){
+  return vuqaddb_s8(1, -1.0f);
+}
+
+int16_t test_vuqaddh_s16() {
+  return vuqaddh_s16(1, -1.0f);
+}
+
+int32_t test_vuqadds_s32() {
+  return vuqadds_s32(1, -1.0f);
+}
+
+int64_t test_vuqaddd_s64() {
+  return vuqaddd_s64(1, -1.0f);
+}
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint8_t' (aka 'unsigned char') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint16_t' (aka 'unsigned short') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint32_t' (aka 'unsigned 

[PATCH] D64127: [clangd] Deduplicate clang-tidy diagnostic messages.

2019-07-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/Diagnostics.cpp:427
   }
+  // Deduplicate clang-tidy diagnostics -- some clang-tidy checks may emit
+  // duplicated messages due to various reasons (e.g. the check doesn't handle

This sorting/partitioning seems a bit heavyweight... what about

```
DenseSet> SeenDiagnostics;
llvm::erase_if([&](const Diag ) {
  return !SeenDiagnostics.try_emplace(D.Range, D.Message).second;
});
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64127/new/

https://reviews.llvm.org/D64127



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


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 208143.
jvikstrom added a comment.

Separated into three testcases.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -49,19 +49,34 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
   R"cpp(
-struct A {
-  double SomeMember;
-};
-struct {
-}   $Variable[[HStruct]];
-void $Function[[foo]](int $Variable[[a]]) {
-  auto $Variable[[VeryLongVariableName]] = 12312;
-  A $Variable[[aa]];
-}
-  )cpp",
+  struct AS {
+double SomeMember;
+  };
+  struct {
+  } $Variable[[S]];
+  void $Function[[foo]](int $Variable[[A]]) {
+auto $Variable[[VeryLongVariableName]] = 12312;
+AS $Variable[[AA]];
+auto $Variable[[L]] = $Variable[[AA]].SomeMember + $Variable[[A]];
+auto $Variable[[FN]] = [ $Variable[[AA]]](int $Variable[[A]]) -> void {};
+$Variable[[FN]](12312);
+  }
+)cpp",
+  R"cpp(
+  void $Function[[foo]](int);
+  void $Function[[Gah]]();
+  void $Function[[foo]]() {
+auto $Variable[[Bou]] = $Function[[Gah]];
+  }
+)cpp",
   R"cpp(
-void $Function[[foo]](int);
-  )cpp"};
+  struct A {
+A();
+~A();
+void $Function[[abc]]();
+void operator<<(int);
+  };
+)cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
   }
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -34,26 +34,46 @@
 return Tokens;
   }
 
-  bool VisitVarDecl(VarDecl *Var) {
-addToken(Var, HighlightingKind::Variable);
+  bool VisitNamedDecl(NamedDecl *ND) {
+// FIXME: (De)Constructors/operator need to be highlighted some other way.
+if (ND->getDeclName().getNameKind() != DeclarationName::Identifier)
+  return true;
+
+if (ND->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return true;
+addToken(ND->getLocation(), ND);
 return true;
   }
-  bool VisitFunctionDecl(FunctionDecl *Func) {
-addToken(Func, HighlightingKind::Function);
+
+  bool VisitDeclRefExpr(DeclRefExpr *Ref) {
+if (Ref->getNameInfo().getName().getNameKind() !=
+DeclarationName::Identifier)
+  // Only want to highlight identifiers.
+  return true;
+
+addToken(Ref->getLocation(), Ref->getDecl());
 return true;
   }
 
 private:
-  void addToken(const NamedDecl *D, HighlightingKind Kind) {
-if (D->getLocation().isMacroID())
-  // FIXME: skip tokens inside macros for now.
+  void addToken(SourceLocation Loc, const Decl *D) {
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Variable);
   return;
+}
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Function);
+  return;
+}
+  }
 
-if (D->getDeclName().isEmpty())
-  // Don't add symbols that don't have any length.
+  void addToken(SourceLocation Loc, HighlightingKind Kind) {
+if (Loc.isMacroID())
+  // FIXME: skip tokens inside macros for now.
   return;
 
-auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+auto R = getTokenRange(SM, Ctx.getLangOpts(), Loc);
 if (!R) {
   // R should always have a value, if it doesn't something is very wrong.
   elog("Tried to add semantic token with an invalid range");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 208140.
jvikstrom added a comment.

Made tests more readable.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -49,19 +49,43 @@
 TEST(SemanticHighlighting, GetsCorrectTokens) {
   const char *TestCases[] = {
   R"cpp(
-struct A {
-  double SomeMember;
-};
-struct {
-}   $Variable[[HStruct]];
-void $Function[[foo]](int $Variable[[a]]) {
-  auto $Variable[[VeryLongVariableName]] = 12312;
-  A $Variable[[aa]];
-}
-  )cpp",
+  struct AS {
+double SomeMember;
+  };
+  void $Function[[foo]](int $Variable[[A]]) {
+auto $Variable[[VeryLongVariableName]] = 12312;
+AS $Variable[[AA]];
+auto $Variable[[L]] = $Variable[[AA]].SomeMember + $Variable[[A]];
+  }
+)cpp",
+  R"cpp(
+  struct {
+  } $Variable[[S]];
+)cpp",
+  R"cpp(
+  void $Function[[foo]](int);
+)cpp",
+  R"cpp(
+  void $Function[[Gah]]();
+  void $Function[[foo]]() {
+auto $Variable[[Bou]] = $Function[[Gah]];
+  }
+)cpp",
+  R"cpp(
+  void $Function[[foo]]() {
+int $Variable[[B]];
+auto $Variable[[FN]] = [ $Variable[[B]]](int $Variable[[A]]) -> void {};
+$Variable[[FN]](12312);
+  }
+)cpp",
   R"cpp(
-void $Function[[foo]](int);
-  )cpp"};
+  struct A {
+A();
+~A();
+void $Function[[abc]]();
+void operator<<(int);
+  };
+)cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
   }
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -34,26 +34,46 @@
 return Tokens;
   }
 
-  bool VisitVarDecl(VarDecl *Var) {
-addToken(Var, HighlightingKind::Variable);
+  bool VisitNamedDecl(NamedDecl *ND) {
+// FIXME: (De)Constructors/operator need to be highlighted some other way.
+if (ND->getDeclName().getNameKind() != DeclarationName::Identifier)
+  return true;
+
+if (ND->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return true;
+addToken(ND->getLocation(), ND);
 return true;
   }
-  bool VisitFunctionDecl(FunctionDecl *Func) {
-addToken(Func, HighlightingKind::Function);
+
+  bool VisitDeclRefExpr(DeclRefExpr *Ref) {
+if (Ref->getNameInfo().getName().getNameKind() !=
+DeclarationName::Identifier)
+  // Only want to highlight identifiers.
+  return true;
+
+addToken(Ref->getLocation(), Ref->getDecl());
 return true;
   }
 
 private:
-  void addToken(const NamedDecl *D, HighlightingKind Kind) {
-if (D->getLocation().isMacroID())
-  // FIXME: skip tokens inside macros for now.
+  void addToken(SourceLocation Loc, const Decl *D) {
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Variable);
   return;
+}
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Function);
+  return;
+}
+  }
 
-if (D->getDeclName().isEmpty())
-  // Don't add symbols that don't have any length.
+  void addToken(SourceLocation Loc, HighlightingKind Kind) {
+if (Loc.isMacroID())
+  // FIXME: skip tokens inside macros for now.
   return;
 
-auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+auto R = getTokenRange(SM, Ctx.getLangOpts(), Loc);
 if (!R) {
   // R should always have a value, if it doesn't something is very wrong.
   elog("Tried to add semantic token with an invalid range");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64242: [AArch64] Fix scalar vuqadd intrinsics operands

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio created this revision.
dnsampaio added a reviewer: LukeCheeseman.
Herald added subscribers: cfe-commits, kristof.beyls, javed.absar.
Herald added a project: clang.

Change the vuqadd scalar instrinsics to have the second argument as unsigned 
values, not signed,
accordingly to 
https://developer.arm.com/architectures/instruction-sets/simd-isas/neon/intrinsics

So now the compiler correctly warns that a undefined negative float conversion 
is being done.


Repository:
  rC Clang

https://reviews.llvm.org/D64242

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c


Index: test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
===
--- /dev/null
+++ test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone 
-emit-llvm -o - %s 2>&1 \
+// RUN: | FileCheck %s
+
+#include 
+
+// Check float conversion is not accepted for unsigned int argument
+int8_t test_vuqaddb_s8(){
+  return vuqaddb_s8(1, -1.0f);
+}
+
+int16_t test_vuqaddh_s16() {
+  return vuqaddh_s16(1, -1.0f);
+}
+
+int32_t test_vuqadds_s32() {
+  return vuqadds_s32(1, -1.0f);
+}
+
+int64_t test_vuqaddd_s64() {
+  return vuqaddd_s64(1, -1.0f);
+}
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint8_t' (aka 'unsigned char') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint16_t' (aka 'unsigned short') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint32_t' (aka 'unsigned int') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 
'uint64_t' (aka 'unsigned long') is undefined
+
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1333,7 +1333,7 @@
 
 

 // Scalar Signed Saturating Accumulated of Unsigned Value
-def SCALAR_SUQADD : SInst<"vuqadd", "sss", "ScSsSiSl">;
+def SCALAR_SUQADD : SInst<"vuqadd", "ssb", "ScSsSiSl">;
 
 

 // Scalar Unsigned Saturating Accumulated of Signed Value


Index: test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
===
--- /dev/null
+++ test/CodeGen/aarch64-neon-vuqadd-float-conversion-warning.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone -emit-llvm -o - %s 2>&1 \
+// RUN: | FileCheck %s
+
+#include 
+
+// Check float conversion is not accepted for unsigned int argument
+int8_t test_vuqaddb_s8(){
+  return vuqaddb_s8(1, -1.0f);
+}
+
+int16_t test_vuqaddh_s16() {
+  return vuqaddh_s16(1, -1.0f);
+}
+
+int32_t test_vuqadds_s32() {
+  return vuqadds_s32(1, -1.0f);
+}
+
+int64_t test_vuqaddd_s64() {
+  return vuqaddd_s64(1, -1.0f);
+}
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint8_t' (aka 'unsigned char') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint16_t' (aka 'unsigned short') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint32_t' (aka 'unsigned int') is undefined
+// CHECK: warning: implicit conversion of out of range value from 'float' to 'uint64_t' (aka 'unsigned long') is undefined
+
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1333,7 +1333,7 @@
 
 
 // Scalar Signed Saturating Accumulated of Unsigned Value
-def SCALAR_SUQADD : SInst<"vuqadd", "sss", "ScSsSiSl">;
+def SCALAR_SUQADD : SInst<"vuqadd", "ssb", "ScSsSiSl">;
 
 
 // Scalar Unsigned Saturating Accumulated of Signed Value
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r365181 - Fix a buildbot failure due to the AST's lifetime ending before the test

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 04:14:57 2019
New Revision: 365181

URL: http://llvm.org/viewvc/llvm-project?rev=365181=rev
Log:
Fix a buildbot failure due to the AST's lifetime ending before the test

Modified:
cfe/trunk/unittests/Analysis/CFGTest.cpp

Modified: cfe/trunk/unittests/Analysis/CFGTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Analysis/CFGTest.cpp?rev=365181=365180=365181=diff
==
--- cfe/trunk/unittests/Analysis/CFGTest.cpp (original)
+++ cfe/trunk/unittests/Analysis/CFGTest.cpp Fri Jul  5 04:14:57 2019
@@ -86,24 +86,10 @@ TEST(CFG, ConditionExpr) {
 return *(cfg->begin() + Index);
   };
 
-  auto GetExprText = [] (const Expr *E) -> std::string {
-// It's very awkward trying to recover the actual expression text without
-// a real source file, so use this as a workaround. We know that the
-// condition expression looks like this:
-//
-// ImplicitCastExpr 0xd07bf8 '_Bool' 
-//  `-DeclRefExpr 0xd07bd8 '_Bool' lvalue ParmVar 0xd07960 'C' '_Bool'
-
-assert(isa(E));
-assert(++E->child_begin() == E->child_end());
-const auto *D = dyn_cast(*E->child_begin());
-return D->getFoundDecl()->getNameAsString();
-  };
-
   EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
-  EXPECT_EQ(GetExprText(GetBlock(4)->getLastCondition()), "A");
-  EXPECT_EQ(GetExprText(GetBlock(3)->getLastCondition()), "B");
-  EXPECT_EQ(GetExprText(GetBlock(2)->getLastCondition()), "C");
+  // Unfortunately, we can't check whether the correct Expr was returned by
+  // getLastCondition, because the lifetime of the AST ends by the time we
+  // retrieve the CFG.
 
   
//======//
 


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


[PATCH] D64241: [ASTImporter] Fix inequivalence of ClassTemplateInstantiations

2019-07-05 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added a reviewer: a_sidorin.
Herald added subscribers: cfe-commits, gamesh411, Szelethus, dkrupp, rnkovacs.
Herald added a reviewer: a.sidorin.
Herald added a project: clang.

We falsely state inequivalence if the template parameter is a
qualified/nonquialified template in the first/second instantiation.
Also, different kinds of TemplateName should be equal if the template
decl (if available) is equal (even if the name kind is different).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D64241

Files:
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -892,6 +892,67 @@
   EXPECT_FALSE(testStructuralMatch(First, Second));
 }
 
+TEST_F(StructuralEquivalenceTemplateTest,
+   TemplateVsSubstTemplateTemplateParmInArgEq) {
+  auto t = makeDecls(
+  R"(
+template  class Arg { };
+template  class P1> class Primary { };
+
+void f() {
+  // Make specialization with simple template.
+  Primary  A;
+}
+  )",
+  R"(
+template  class Arg { };
+template  class P1> class Primary { };
+
+template  class P1> class Templ {
+  void f() {
+// Make specialization with substituted template template param.
+Primary  A;
+  };
+};
+
+// Instantiate with substitution Arg into P1.
+template class Templ ;
+  )",
+  Lang_CXX, classTemplateSpecializationDecl(hasName("Primary")));
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceTemplateTest,
+   TemplateVsSubstTemplateTemplateParmInArgNotEq) {
+  auto t = makeDecls(
+  R"(
+template  class Arg { };
+template  class P1> class Primary { };
+
+void f() {
+  // Make specialization with simple template.
+  Primary  A;
+}
+  )",
+  R"(
+// Arg is different from the other, this should cause non-equivalence.
+template  class Arg { int X; };
+template  class P1> class Primary { };
+
+template  class P1> class Templ {
+  void f() {
+// Make specialization with substituted template template param.
+Primary  A;
+  };
+};
+
+// Instantiate with substitution Arg into P1.
+template class Templ ;
+  )",
+  Lang_CXX, classTemplateSpecializationDecl(hasName("Primary")));
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
 struct StructuralEquivalenceDependentTemplateArgsTest
 : StructuralEquivalenceTemplateTest {};
 
@@ -1030,5 +1091,111 @@
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+TEST_F(
+StructuralEquivalenceTemplateTest,
+ClassTemplSpecWithQualifiedAndNonQualifiedTypeArgsShouldBeEqual) {
+  auto t = makeDecls(
+  R"(
+  template  struct Primary {};
+  namespace N {
+struct Arg;
+  }
+  // Explicit instantiation with qualified name.
+  template struct Primary;
+  )",
+  R"(
+  template  struct Primary {};
+  namespace N {
+struct Arg;
+  }
+  using namespace N;
+  // Explicit instantiation with UNqualified name.
+  template struct Primary;
+  )",
+  Lang_CXX,
+  classTemplateSpecializationDecl(hasName("Primary")));
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(
+StructuralEquivalenceTemplateTest,
+ClassTemplSpecWithInequivalentQualifiedAndNonQualifiedTypeArgs) {
+  auto t = makeDecls(
+  R"(
+  template  struct Primary {};
+  namespace N {
+struct Arg { int a; };
+  }
+  // Explicit instantiation with qualified name.
+  template struct Primary;
+  )",
+  R"(
+  template  struct Primary {};
+  namespace N {
+// This struct is not equivalent with the other in the prev TU.
+struct Arg { double b; }; // -- Field mismatch.
+  }
+  using namespace N;
+  // Explicit instantiation with UNqualified name.
+  template struct Primary;
+  )",
+  Lang_CXX,
+  classTemplateSpecializationDecl(hasName("Primary")));
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(
+StructuralEquivalenceTemplateTest,
+ClassTemplSpecWithQualifiedAndNonQualifiedTemplArgsShouldBeEqual) {
+  auto t = makeDecls(
+  R"(
+  template  class T> struct Primary {};
+  namespace N {
+template  struct Arg;
+  }
+  // Explicit instantiation with qualified name.
+  template struct Primary;
+  )",
+  R"(
+  template  class T> struct Primary {};
+  namespace N {
+template  struct Arg;
+  }
+  using namespace N;
+  // Explicit instantiation with UNqualified name.
+  template struct Primary;
+  )",
+  Lang_CXX,
+  classTemplateSpecializationDecl(hasName("Primary")));
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(
+StructuralEquivalenceTemplateTest,
+ClassTemplSpecWithInequivalentQualifiedAndNonQualifiedTemplArgs) {
+  auto t 

[PATCH] D64239: [AArch64] Fix vsqadd scalar intrinsics operands

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio created this revision.
dnsampaio added a reviewer: LukeCheeseman.
Herald added subscribers: cfe-commits, kristof.beyls, javed.absar.
Herald added a project: clang.

Change the vsqadd scalar instrinsics to have the second argument as signed 
values, not unsigned,
accordingly to 
https://developer.arm.com/architectures/instruction-sets/simd-isas/neon/intrinsics

The existing unsigned argument can cause faulty code as float to unsigned 
conversion is undefined,
which llvm/clang optimizes away.


Repository:
  rC Clang

https://reviews.llvm.org/D64239

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-neon-intrinsics.c
  test/CodeGen/aarch64-neon-vsqadd-float-conversion.c

Index: test/CodeGen/aarch64-neon-vsqadd-float-conversion.c
===
--- /dev/null
+++ test/CodeGen/aarch64-neon-vsqadd-float-conversion.c
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -target-feature +neon \
+// RUN: -fallow-half-arguments-and-returns -S -disable-O0-optnone -emit-llvm -o - %s \
+// RUN: | opt -S -mem2reg -dce \
+// RUN: | FileCheck %s
+
+#include 
+
+// Check float conversion is accepted for int argument
+uint8_t test_vsqaddb_u8(){
+  return vsqaddb_u8(1, -1.0f);
+}
+
+uint16_t test_vsqaddh_u16() {
+  return vsqaddh_u16(1, -1.0f);
+}
+
+uint32_t test_vsqadds_u32() {
+  return vsqadds_u32(1, -1.0f);
+}
+
+uint64_t test_vsqaddd_u64() {
+  return vsqaddd_u64(1, -1.0f);
+}
+
+// CHECK-LABEL: @test_vsqaddb_u8()
+// CHECK: entry:
+// CHECK-NEXT: [[T0:%.*]] = insertelement <8 x i8> undef, i8 1, i64 0
+// CHECK-NEXT: [[T1:%.*]] = insertelement <8 x i8> undef, i8 -1, i64 0
+// CHECK-NEXT: [[V:%.*]] = call <8 x i8> @llvm.aarch64.neon.usqadd.v8i8(<8 x i8> [[T0]], <8 x i8> [[T1]])
+// CHECK-NEXT: [[R:%.*]] = extractelement <8 x i8> [[V]], i64 0
+// CHECK-NEXT: ret i8 [[R]]
+
+// CHECK-LABEL: @test_vsqaddh_u16()
+// CHECK: entry:
+// CHECK-NEXT: [[T0:%.*]] = insertelement <4 x i16> undef, i16 1, i64 0
+// CHECK-NEXT: [[T1:%.*]] = insertelement <4 x i16> undef, i16 -1, i64 0
+// CHECK-NEXT: [[V:%.*]]  = call <4 x i16> @llvm.aarch64.neon.usqadd.v4i16(<4 x i16> [[T0]], <4 x i16> [[T1]])
+// CHECK-NEXT: [[R:%.*]] = extractelement <4 x i16> [[V]], i64 0
+// CHECK-NEXT: ret i16 [[R]]
+
+// CHECK-LABEL: @test_vsqadds_u32()
+// CHECK: entry:
+// CHECK-NEXT: [[V:%.*]] = call i32 @llvm.aarch64.neon.usqadd.i32(i32 1, i32 -1)
+// CHECK-NEXT: ret i32 [[V]]
+
+// CHECK-LABEL: @test_vsqaddd_u64()
+// CHECK: entry:
+// CHECK-NEXT: [[V:%.*]] = call i64 @llvm.aarch64.neon.usqadd.i64(i64 1, i64 -1)
+// CHECK-NEXT: ret i64 [[V]]
+
Index: test/CodeGen/aarch64-neon-intrinsics.c
===
--- test/CodeGen/aarch64-neon-intrinsics.c
+++ test/CodeGen/aarch64-neon-intrinsics.c
@@ -13913,7 +13913,7 @@
 // CHECK:   [[VSQADDB_U8_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.usqadd.v8i8(<8 x i8> [[TMP0]], <8 x i8> [[TMP1]])
 // CHECK:   [[TMP2:%.*]] = extractelement <8 x i8> [[VSQADDB_U8_I]], i64 0
 // CHECK:   ret i8 [[TMP2]]
-uint8_t test_vsqaddb_u8(uint8_t a, uint8_t b) {
+uint8_t test_vsqaddb_u8(uint8_t a, int8_t b) {
   return (uint8_t)vsqaddb_u8(a, b);
 }
 
@@ -13923,21 +13923,21 @@
 // CHECK:   [[VSQADDH_U16_I:%.*]] = call <4 x i16> @llvm.aarch64.neon.usqadd.v4i16(<4 x i16> [[TMP0]], <4 x i16> [[TMP1]])
 // CHECK:   [[TMP2:%.*]] = extractelement <4 x i16> [[VSQADDH_U16_I]], i64 0
 // CHECK:   ret i16 [[TMP2]]
-uint16_t test_vsqaddh_u16(uint16_t a, uint16_t b) {
+uint16_t test_vsqaddh_u16(uint16_t a, int16_t b) {
   return (uint16_t)vsqaddh_u16(a, b);
 }
 
 // CHECK-LABEL: @test_vsqadds_u32(
 // CHECK:   [[VSQADDS_U32_I:%.*]] = call i32 @llvm.aarch64.neon.usqadd.i32(i32 %a, i32 %b)
 // CHECK:   ret i32 [[VSQADDS_U32_I]]
-uint32_t test_vsqadds_u32(uint32_t a, uint32_t b) {
+uint32_t test_vsqadds_u32(uint32_t a, int32_t b) {
   return (uint32_t)vsqadds_u32(a, b);
 }
 
 // CHECK-LABEL: @test_vsqaddd_u64(
 // CHECK:   [[VSQADDD_U64_I:%.*]] = call i64 @llvm.aarch64.neon.usqadd.i64(i64 %a, i64 %b)
 // CHECK:   ret i64 [[VSQADDD_U64_I]]
-uint64_t test_vsqaddd_u64(uint64_t a, uint64_t b) {
+uint64_t test_vsqaddd_u64(uint64_t a, int64_t b) {
   return (uint64_t)vsqaddd_u64(a, b);
 }
 
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1337,7 +1337,7 @@
 
 
 // Scalar Unsigned Saturating Accumulated of Signed Value
-def SCALAR_USQADD : SInst<"vsqadd", "sss", "SUcSUsSUiSUl">;
+def SCALAR_USQADD : SInst<"vsqadd", "ss$", "SUcSUsSUiSUl">;
 
 
 // Signed Saturating Doubling Multiply-Add Long
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D62611: [analyzer][Dominators] Add unittests

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365179: [analyzer][Dominators][NFC] Add unit tests (authored 
by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D62611?vs=207759=208134#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62611/new/

https://reviews.llvm.org/D62611

Files:
  cfe/trunk/unittests/Analysis/CFGBuildResult.h
  cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp
  cfe/trunk/unittests/Analysis/CFGTest.cpp
  cfe/trunk/unittests/Analysis/CMakeLists.txt

Index: cfe/trunk/unittests/Analysis/CFGBuildResult.h
===
--- cfe/trunk/unittests/Analysis/CFGBuildResult.h
+++ cfe/trunk/unittests/Analysis/CFGBuildResult.h
@@ -0,0 +1,69 @@
+//===- unittests/Analysis/CFGBuildResult.h - CFG tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/CFG.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/Tooling.h"
+
+namespace clang {
+namespace analysis {
+
+class BuildResult {
+public:
+  enum Status {
+ToolFailed,
+ToolRan,
+SawFunctionBody,
+BuiltCFG,
+  };
+
+  BuildResult(Status S, std::unique_ptr Cfg = nullptr)
+  : S(S), Cfg(std::move(Cfg)) {}
+
+  Status getStatus() const { return S; }
+  CFG *getCFG() const { return Cfg.get(); }
+
+private:
+  Status S;
+  std::unique_ptr Cfg;
+};
+
+class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
+public:
+  BuildResult TheBuildResult = BuildResult::ToolRan;
+
+  void run(const ast_matchers::MatchFinder::MatchResult ) override {
+const auto *Func = Result.Nodes.getNodeAs("func");
+Stmt *Body = Func->getBody();
+if (!Body)
+  return;
+TheBuildResult = BuildResult::SawFunctionBody;
+CFG::BuildOptions Options;
+Options.AddImplicitDtors = true;
+if (std::unique_ptr Cfg =
+CFG::buildCFG(nullptr, Body, Result.Context, Options))
+  TheBuildResult = {BuildResult::BuiltCFG, std::move(Cfg)};
+  }
+};
+
+inline BuildResult BuildCFG(const char *Code) {
+  CFGCallback Callback;
+
+  ast_matchers::MatchFinder Finder;
+  Finder.addMatcher(ast_matchers::functionDecl().bind("func"), );
+  std::unique_ptr Factory(
+  tooling::newFrontendActionFactory());
+  std::vector Args = {"-std=c++11",
+   "-fno-delayed-template-parsing"};
+  if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args))
+return BuildResult::ToolFailed;
+  return std::move(Callback.TheBuildResult);
+}
+
+} // namespace analysis
+} // namespace clang
Index: cfe/trunk/unittests/Analysis/CFGTest.cpp
===
--- cfe/trunk/unittests/Analysis/CFGTest.cpp
+++ cfe/trunk/unittests/Analysis/CFGTest.cpp
@@ -6,6 +6,7 @@
 //
 //===--===//
 
+#include "CFGBuildResult.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Tooling/Tooling.h"
@@ -17,57 +18,6 @@
 namespace analysis {
 namespace {
 
-class BuildResult {
-public:
-  enum Status {
-ToolFailed,
-ToolRan,
-SawFunctionBody,
-BuiltCFG,
-  };
-
-  BuildResult(Status S, std::unique_ptr Cfg = nullptr)
-  : S(S), Cfg(std::move(Cfg)) {}
-
-  Status getStatus() const { return S; }
-  CFG *getCFG() const { return Cfg.get(); }
-
-private:
-  Status S;
-  std::unique_ptr Cfg;
-};
-
-class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
-public:
-  BuildResult TheBuildResult = BuildResult::ToolRan;
-
-  void run(const ast_matchers::MatchFinder::MatchResult ) override {
-const auto *Func = Result.Nodes.getNodeAs("func");
-Stmt *Body = Func->getBody();
-if (!Body)
-  return;
-TheBuildResult = BuildResult::SawFunctionBody;
-CFG::BuildOptions Options;
-Options.AddImplicitDtors = true;
-if (std::unique_ptr Cfg =
-CFG::buildCFG(nullptr, Body, Result.Context, Options))
-  TheBuildResult = {BuildResult::BuiltCFG, std::move(Cfg)};
-  }
-};
-
-BuildResult BuildCFG(const char *Code) {
-  CFGCallback Callback;
-
-  ast_matchers::MatchFinder Finder;
-  Finder.addMatcher(ast_matchers::functionDecl().bind("func"), );
-  std::unique_ptr Factory(
-  tooling::newFrontendActionFactory());
-  std::vector Args = {"-std=c++11", "-fno-delayed-template-parsing"};
-  if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args))
-return BuildResult::ToolFailed;
-  return std::move(Callback.TheBuildResult);
-}
-
 // Constructing a CFG for a 

r365179 - [analyzer][Dominators][NFC] Add unit tests

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 03:16:36 2019
New Revision: 365179

URL: http://llvm.org/viewvc/llvm-project?rev=365179=rev
Log:
[analyzer][Dominators][NFC] Add unit tests

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

Added:
cfe/trunk/unittests/Analysis/CFGBuildResult.h
cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp
Modified:
cfe/trunk/unittests/Analysis/CFGTest.cpp
cfe/trunk/unittests/Analysis/CMakeLists.txt

Added: cfe/trunk/unittests/Analysis/CFGBuildResult.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Analysis/CFGBuildResult.h?rev=365179=auto
==
--- cfe/trunk/unittests/Analysis/CFGBuildResult.h (added)
+++ cfe/trunk/unittests/Analysis/CFGBuildResult.h Fri Jul  5 03:16:36 2019
@@ -0,0 +1,69 @@
+//===- unittests/Analysis/CFGBuildResult.h - CFG tests 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/CFG.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/Tooling.h"
+
+namespace clang {
+namespace analysis {
+
+class BuildResult {
+public:
+  enum Status {
+ToolFailed,
+ToolRan,
+SawFunctionBody,
+BuiltCFG,
+  };
+
+  BuildResult(Status S, std::unique_ptr Cfg = nullptr)
+  : S(S), Cfg(std::move(Cfg)) {}
+
+  Status getStatus() const { return S; }
+  CFG *getCFG() const { return Cfg.get(); }
+
+private:
+  Status S;
+  std::unique_ptr Cfg;
+};
+
+class CFGCallback : public ast_matchers::MatchFinder::MatchCallback {
+public:
+  BuildResult TheBuildResult = BuildResult::ToolRan;
+
+  void run(const ast_matchers::MatchFinder::MatchResult ) override {
+const auto *Func = Result.Nodes.getNodeAs("func");
+Stmt *Body = Func->getBody();
+if (!Body)
+  return;
+TheBuildResult = BuildResult::SawFunctionBody;
+CFG::BuildOptions Options;
+Options.AddImplicitDtors = true;
+if (std::unique_ptr Cfg =
+CFG::buildCFG(nullptr, Body, Result.Context, Options))
+  TheBuildResult = {BuildResult::BuiltCFG, std::move(Cfg)};
+  }
+};
+
+inline BuildResult BuildCFG(const char *Code) {
+  CFGCallback Callback;
+
+  ast_matchers::MatchFinder Finder;
+  Finder.addMatcher(ast_matchers::functionDecl().bind("func"), );
+  std::unique_ptr Factory(
+  tooling::newFrontendActionFactory());
+  std::vector Args = {"-std=c++11",
+   "-fno-delayed-template-parsing"};
+  if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args))
+return BuildResult::ToolFailed;
+  return std::move(Callback.TheBuildResult);
+}
+
+} // namespace analysis
+} // namespace clang

Added: cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp?rev=365179=auto
==
--- cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp (added)
+++ cfe/trunk/unittests/Analysis/CFGDominatorTree.cpp Fri Jul  5 03:16:36 2019
@@ -0,0 +1,103 @@
+//===- unittests/Analysis/CFGDominatorTree.cpp - CFG tests 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CFGBuildResult.h"
+#include "clang/Analysis/Analyses/Dominators.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace analysis {
+namespace {
+
+TEST(CFGDominatorTree, DomTree) {
+  const char *Code = R"(enum Kind {
+  A
+};
+
+void f() {
+  switch(Kind{}) {
+  case A:
+break;
+  }
+})";
+  BuildResult Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  //  [B3 (ENTRY)]  -> [B1] -> [B2] -> [B0 (EXIT)]
+  //  switch  case A
+
+  CFG *cfg = Result.getCFG();
+
+  // Sanity checks.
+  EXPECT_EQ(cfg->size(), 4u);
+
+  CFGBlock *ExitBlock = *cfg->begin();
+  EXPECT_EQ(ExitBlock, >getExit());
+
+  CFGBlock *SwitchBlock = *(cfg->begin() + 1);
+
+  CFGBlock *CaseABlock = *(cfg->begin() + 2);
+
+  CFGBlock *EntryBlock = *(cfg->begin() + 3);
+  EXPECT_EQ(EntryBlock, >getEntry());
+
+  // Test the dominator tree.
+  CFGDomTree Dom;
+  Dom.buildDominatorTree(cfg);
+
+  EXPECT_TRUE(Dom.dominates(ExitBlock, ExitBlock));
+  EXPECT_FALSE(Dom.properlyDominates(ExitBlock, ExitBlock));
+  EXPECT_TRUE(Dom.dominates(CaseABlock, 

[PATCH] D63538: [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL365177: [CFG] Add a new function to get the proper condition 
of a CFGBlock (authored by Szelethus, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D63538?vs=207904=208130#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63538/new/

https://reviews.llvm.org/D63538

Files:
  cfe/trunk/include/clang/Analysis/CFG.h
  cfe/trunk/lib/Analysis/CFG.cpp
  cfe/trunk/unittests/Analysis/CFGTest.cpp

Index: cfe/trunk/include/clang/Analysis/CFG.h
===
--- cfe/trunk/include/clang/Analysis/CFG.h
+++ cfe/trunk/include/clang/Analysis/CFG.h
@@ -860,6 +860,14 @@
   Stmt *getTerminatorStmt() { return Terminator.getStmt(); }
   const Stmt *getTerminatorStmt() const { return Terminator.getStmt(); }
 
+  /// \returns the last (\c rbegin()) condition, e.g. observe the following code
+  /// snippet:
+  ///   if (A && B && C)
+  /// A block would be created for \c A, \c B, and \c C. For the latter,
+  /// \c getTerminatorStmt() would retrieve the entire condition, rather than
+  /// C itself, while this method would only return C.
+  const Expr *getLastCondition() const;
+
   Stmt *getTerminatorCondition(bool StripParens = true);
 
   const Stmt *getTerminatorCondition(bool StripParens = true) const {
Index: cfe/trunk/lib/Analysis/CFG.cpp
===
--- cfe/trunk/lib/Analysis/CFG.cpp
+++ cfe/trunk/lib/Analysis/CFG.cpp
@@ -5615,6 +5615,30 @@
   Out << JsonFormat(TempOut.str(), AddQuotes);
 }
 
+const Expr *CFGBlock::getLastCondition() const {
+  // If the terminator is a temporary dtor or a virtual base, etc, we can't
+  // retrieve a meaningful condition, bail out.
+  if (Terminator.getKind() != CFGTerminator::StmtBranch)
+return nullptr;
+
+  // Also, if this method was called on a block that doesn't have 2 successors,
+  // this block doesn't have retrievable condition.
+  if (succ_size() < 2)
+return nullptr;
+
+  auto StmtElem = rbegin()->getAs();
+  if (!StmtElem)
+return nullptr;
+
+  const Stmt *Cond = StmtElem->getStmt();
+  if (isa(Cond))
+return nullptr;
+
+  // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
+  // the cast<>.
+  return cast(Cond)->IgnoreParens();
+}
+
 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
   Stmt *Terminator = getTerminatorStmt();
   if (!Terminator)
Index: cfe/trunk/unittests/Analysis/CFGTest.cpp
===
--- cfe/trunk/unittests/Analysis/CFGTest.cpp
+++ cfe/trunk/unittests/Analysis/CFGTest.cpp
@@ -117,6 +117,58 @@
   expectLinear(true,  "void foo() { foo(); }"); // Recursion is not our problem.
 }
 
+TEST(CFG, ConditionExpr) {
+  const char *Code = R"(void f(bool A, bool B, bool C) {
+  if (A && B && C)
+int x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  // [B5 (ENTRY)] -> [B4] -> [B3] -> [B2] -> [B1] -> [B0 (EXIT)]
+  //   \  \   \ /
+  //--->
+
+  CFG *cfg = Result.getCFG();
+
+  auto GetBlock = [cfg] (unsigned Index) -> CFGBlock * {
+assert(Index < cfg->size());
+return *(cfg->begin() + Index);
+  };
+
+  auto GetExprText = [] (const Expr *E) -> std::string {
+// It's very awkward trying to recover the actual expression text without
+// a real source file, so use this as a workaround. We know that the
+// condition expression looks like this:
+//
+// ImplicitCastExpr 0xd07bf8 '_Bool' 
+//  `-DeclRefExpr 0xd07bd8 '_Bool' lvalue ParmVar 0xd07960 'C' '_Bool'
+
+assert(isa(E));
+assert(++E->child_begin() == E->child_end());
+const auto *D = dyn_cast(*E->child_begin());
+return D->getFoundDecl()->getNameAsString();
+  };
+
+  EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
+  EXPECT_EQ(GetExprText(GetBlock(4)->getLastCondition()), "A");
+  EXPECT_EQ(GetExprText(GetBlock(3)->getLastCondition()), "B");
+  EXPECT_EQ(GetExprText(GetBlock(2)->getLastCondition()), "C");
+
+  //======//
+
+  Code = R"(void foo(int x, int y) {
+  (void)(x + y);
+})";
+  Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  // [B2 (ENTRY)] -> [B1] -> [B0 (EXIT)]
+
+  cfg = Result.getCFG();
+  EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
+}
+
 } // namespace
 } // namespace analysis
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r365177 - [CFG] Add a new function to get the proper condition of a CFGBlock

2019-07-05 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Fri Jul  5 02:52:00 2019
New Revision: 365177

URL: http://llvm.org/viewvc/llvm-project?rev=365177=rev
Log:
[CFG] Add a new function to get the proper condition of a CFGBlock

getTerminatorCondition() returned a condition that may be outside of the
block, while the new function returns the proper one:

if (A && B && C) {}

Return C instead of A && B && C.

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

Modified:
cfe/trunk/include/clang/Analysis/CFG.h
cfe/trunk/lib/Analysis/CFG.cpp
cfe/trunk/unittests/Analysis/CFGTest.cpp

Modified: cfe/trunk/include/clang/Analysis/CFG.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CFG.h?rev=365177=365176=365177=diff
==
--- cfe/trunk/include/clang/Analysis/CFG.h (original)
+++ cfe/trunk/include/clang/Analysis/CFG.h Fri Jul  5 02:52:00 2019
@@ -860,6 +860,14 @@ public:
   Stmt *getTerminatorStmt() { return Terminator.getStmt(); }
   const Stmt *getTerminatorStmt() const { return Terminator.getStmt(); }
 
+  /// \returns the last (\c rbegin()) condition, e.g. observe the following 
code
+  /// snippet:
+  ///   if (A && B && C)
+  /// A block would be created for \c A, \c B, and \c C. For the latter,
+  /// \c getTerminatorStmt() would retrieve the entire condition, rather than
+  /// C itself, while this method would only return C.
+  const Expr *getLastCondition() const;
+
   Stmt *getTerminatorCondition(bool StripParens = true);
 
   const Stmt *getTerminatorCondition(bool StripParens = true) const {

Modified: cfe/trunk/lib/Analysis/CFG.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=365177=365176=365177=diff
==
--- cfe/trunk/lib/Analysis/CFG.cpp (original)
+++ cfe/trunk/lib/Analysis/CFG.cpp Fri Jul  5 02:52:00 2019
@@ -5615,6 +5615,30 @@ void CFGBlock::printTerminatorJson(raw_o
   Out << JsonFormat(TempOut.str(), AddQuotes);
 }
 
+const Expr *CFGBlock::getLastCondition() const {
+  // If the terminator is a temporary dtor or a virtual base, etc, we can't
+  // retrieve a meaningful condition, bail out.
+  if (Terminator.getKind() != CFGTerminator::StmtBranch)
+return nullptr;
+
+  // Also, if this method was called on a block that doesn't have 2 successors,
+  // this block doesn't have retrievable condition.
+  if (succ_size() < 2)
+return nullptr;
+
+  auto StmtElem = rbegin()->getAs();
+  if (!StmtElem)
+return nullptr;
+
+  const Stmt *Cond = StmtElem->getStmt();
+  if (isa(Cond))
+return nullptr;
+
+  // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
+  // the cast<>.
+  return cast(Cond)->IgnoreParens();
+}
+
 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
   Stmt *Terminator = getTerminatorStmt();
   if (!Terminator)

Modified: cfe/trunk/unittests/Analysis/CFGTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Analysis/CFGTest.cpp?rev=365177=365176=365177=diff
==
--- cfe/trunk/unittests/Analysis/CFGTest.cpp (original)
+++ cfe/trunk/unittests/Analysis/CFGTest.cpp Fri Jul  5 02:52:00 2019
@@ -117,6 +117,58 @@ TEST(CFG, IsLinear) {
   expectLinear(true,  "void foo() { foo(); }"); // Recursion is not our 
problem.
 }
 
+TEST(CFG, ConditionExpr) {
+  const char *Code = R"(void f(bool A, bool B, bool C) {
+  if (A && B && C)
+int x;
+})";
+  BuildResult Result = BuildCFG(Code);
+  EXPECT_EQ(BuildResult::BuiltCFG, Result.getStatus());
+
+  // [B5 (ENTRY)] -> [B4] -> [B3] -> [B2] -> [B1] -> [B0 (EXIT)]
+  //   \  \   \ /
+  //--->
+
+  CFG *cfg = Result.getCFG();
+
+  auto GetBlock = [cfg] (unsigned Index) -> CFGBlock * {
+assert(Index < cfg->size());
+return *(cfg->begin() + Index);
+  };
+
+  auto GetExprText = [] (const Expr *E) -> std::string {
+// It's very awkward trying to recover the actual expression text without
+// a real source file, so use this as a workaround. We know that the
+// condition expression looks like this:
+//
+// ImplicitCastExpr 0xd07bf8 '_Bool' 
+//  `-DeclRefExpr 0xd07bd8 '_Bool' lvalue ParmVar 0xd07960 'C' '_Bool'
+
+assert(isa(E));
+assert(++E->child_begin() == E->child_end());
+const auto *D = dyn_cast(*E->child_begin());
+return D->getFoundDecl()->getNameAsString();
+  };
+
+  EXPECT_EQ(GetBlock(1)->getLastCondition(), nullptr);
+  EXPECT_EQ(GetExprText(GetBlock(4)->getLastCondition()), "A");
+  EXPECT_EQ(GetExprText(GetBlock(3)->getLastCondition()), "B");
+  EXPECT_EQ(GetExprText(GetBlock(2)->getLastCondition()), "C");
+
+  
//======//
+
+  Code = R"(void 

[PATCH] D64211: [ARM] Fix vector vuqadd intrinsics operands

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio updated this revision to Diff 208127.
dnsampaio added a comment.

- Added tests


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64211/new/

https://reviews.llvm.org/D64211

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-neon-intrinsics.c


Index: test/CodeGen/aarch64-neon-intrinsics.c
===
--- test/CodeGen/aarch64-neon-intrinsics.c
+++ test/CodeGen/aarch64-neon-intrinsics.c
@@ -17528,6 +17528,50 @@
   return vabdd_f64(a, b);
 }
 
+// CHECK-LABEL: @test_vuqaddq_s8(
+// CHECK: entry:
+// CHECK-NEXT:  [[V:%.*]] = call <16 x i8> @llvm.aarch64.neon.suqadd.v16i8(<16 
x i8> %a, <16 x i8> %b)
+// CHECK-NEXT:  ret <16 x i8> [[V]]
+int8x16_t test_vuqaddq_s8(int8x16_t a, uint8x16_t b) {
+  return vuqaddq_s8(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s32(
+// CHECK: [[V:%.*]] = call <4 x i32> @llvm.aarch64.neon.suqadd.v4i32(<4 x i32> 
%a, <4 x i32> %b)
+// CHECK-NEXT:  ret <4 x i32> [[V]]
+int32x4_t test_vuqaddq_s32(int32x4_t a, uint32x4_t b) {
+  return vuqaddq_s32(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s64(
+// CHECK: [[V:%.*]] = call <2 x i64> @llvm.aarch64.neon.suqadd.v2i64(<2 x i64> 
%a, <2 x i64> %b)
+// CHECK-NEXT:  ret <2 x i64> [[V]]
+int64x2_t test_vuqaddq_s64(int64x2_t a, uint64x2_t b) {
+  return vuqaddq_s64(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s16(
+// CHECK: [[V:%.*]] = call <8 x i16> @llvm.aarch64.neon.suqadd.v8i16(<8 x i16> 
%a, <8 x i16> %b)
+// CHECK-NEXT:  ret <8 x i16> [[V]]
+int16x8_t test_vuqaddq_s16(int16x8_t a, uint16x8_t b) {
+  return vuqaddq_s16(a, b);
+}
+
+// CHECK-LABEL: @test_vuqadd_s8(
+// CHECK: entry:
+// CHECK-NEXT: [[V:%.*]] = call <8 x i8> @llvm.aarch64.neon.suqadd.v8i8(<8 x 
i8> %a, <8 x i8> %b)
+// CHECK-NEXT: ret <8 x i8> [[V]]
+int8x8_t test_vuqadd_s8(int8x8_t a, uint8x8_t b) {
+  return vuqadd_s8(a, b);
+}
+
+// CHECK-LABEL: @test_vuqadd_s32(
+// CHECK: [[V:%.*]] = call <2 x i32> @llvm.aarch64.neon.suqadd.v2i32(<2 x i32> 
%a, <2 x i32> %b)
+// CHECK-NEXT:  ret <2 x i32> [[V]]
+int32x2_t test_vuqadd_s32(int32x2_t a, uint32x2_t b) {
+  return vuqadd_s32(a, b);
+}
+
 // CHECK-LABEL: @test_vuqadd_s64(
 // CHECK:   [[TMP0:%.*]] = bitcast <1 x i64> %a to <8 x i8>
 // CHECK:   [[TMP1:%.*]] = bitcast <1 x i64> %b to <8 x i8>
@@ -17537,6 +17581,13 @@
   return vuqadd_s64(a, b);
 }
 
+// CHECK-LABEL: @test_vuqadd_s16(
+// CHECK: [[V:%.*]] = call <4 x i16> @llvm.aarch64.neon.suqadd.v4i16(<4 x i16> 
%a, <4 x i16> %b)
+// CHECK-NEXT:  ret <4 x i16> [[V]]
+int16x4_t test_vuqadd_s16(int16x4_t a, uint16x4_t b) {
+  return vuqadd_s16(a, b);
+}
+
 // CHECK-LABEL: @test_vsqadd_u64(
 // CHECK:   [[TMP0:%.*]] = bitcast <1 x i64> %a to <8 x i8>
 // CHECK:   [[TMP1:%.*]] = bitcast <1 x i64> %b to <8 x i8>
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -703,7 +703,7 @@
 
 

 // Signed Saturating Accumulated of Unsigned Value
-def SUQADD : SInst<"vuqadd", "ddd", "csilQcQsQiQl">;
+def SUQADD : SInst<"vuqadd", "ddu", "csilQcQsQiQl">;
 
 

 // Unsigned Saturating Accumulated of Signed Value


Index: test/CodeGen/aarch64-neon-intrinsics.c
===
--- test/CodeGen/aarch64-neon-intrinsics.c
+++ test/CodeGen/aarch64-neon-intrinsics.c
@@ -17528,6 +17528,50 @@
   return vabdd_f64(a, b);
 }
 
+// CHECK-LABEL: @test_vuqaddq_s8(
+// CHECK: entry:
+// CHECK-NEXT:  [[V:%.*]] = call <16 x i8> @llvm.aarch64.neon.suqadd.v16i8(<16 x i8> %a, <16 x i8> %b)
+// CHECK-NEXT:  ret <16 x i8> [[V]]
+int8x16_t test_vuqaddq_s8(int8x16_t a, uint8x16_t b) {
+  return vuqaddq_s8(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s32(
+// CHECK: [[V:%.*]] = call <4 x i32> @llvm.aarch64.neon.suqadd.v4i32(<4 x i32> %a, <4 x i32> %b)
+// CHECK-NEXT:  ret <4 x i32> [[V]]
+int32x4_t test_vuqaddq_s32(int32x4_t a, uint32x4_t b) {
+  return vuqaddq_s32(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s64(
+// CHECK: [[V:%.*]] = call <2 x i64> @llvm.aarch64.neon.suqadd.v2i64(<2 x i64> %a, <2 x i64> %b)
+// CHECK-NEXT:  ret <2 x i64> [[V]]
+int64x2_t test_vuqaddq_s64(int64x2_t a, uint64x2_t b) {
+  return vuqaddq_s64(a, b);
+}
+
+// CHECK-LABEL: @test_vuqaddq_s16(
+// CHECK: [[V:%.*]] = call <8 x i16> @llvm.aarch64.neon.suqadd.v8i16(<8 x i16> %a, <8 x i16> %b)
+// CHECK-NEXT:  ret <8 x i16> [[V]]
+int16x8_t test_vuqaddq_s16(int16x8_t a, uint16x8_t b) {
+  return vuqaddq_s16(a, b);
+}
+
+// CHECK-LABEL: @test_vuqadd_s8(
+// CHECK: entry:
+// CHECK-NEXT: [[V:%.*]] = call <8 x i8> @llvm.aarch64.neon.suqadd.v8i8(<8 x i8> %a, <8 x i8> %b)
+// CHECK-NEXT: ret <8 x i8> [[V]]
+int8x8_t test_vuqadd_s8(int8x8_t a, uint8x8_t b) {
+  return vuqadd_s8(a, b);
+}
+
+// CHECK-LABEL: 

[PATCH] D64210: [NFC][ARM] Fix vector vsqadd intrinsics operands

2019-07-05 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio added a comment.

In D64210#1570515 , @LukeCheeseman 
wrote:

> Are there some changes/addition to tests attached to this?


Hi,
I can see no difference in the CodeGen test in 
tools/clang/test/CodeGen/aarch64-neon-intrinsics.c, which already tests tests 
these intrinsics with the correct arguments. So technically speaking, it is a 
NFC.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64210/new/

https://reviews.llvm.org/D64210



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


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

the implementation looks good, a few comments on the test.




Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:61
+}
+if(isa(D)) {
+  addToken(Loc, HighlightingKind::Function);

sammccall wrote:
> jvikstrom wrote:
> > sammccall wrote:
> > > note that methods, constructors, and destructors inherit from 
> > > functiondecl, so if you want to exclude/distinguish those, order matters 
> > > here
> > I'm aware of that, but thanks for the heads up. Although should I add it in 
> > a comment somewhere in the method? Also added an additional testcase for 
> > classes and FIXMEs to the skip if statement in VisitNamedDecl.
> I don't think it needs a comment, especially if you're not actually 
> highlighting them (because they have weird DeclarationNames)
> 
> > FIXMEs to the skip if statement in VisitNamedDecl
> I'm not actually sure there's anything to fix here - it's a bit hard to talk 
> about constructor/destructor highlighting as distinct from type name 
> highlighting in C++. If you want them highlighted as classes, then that 
> should just start working when you start handling TypeLocs.
I think constructor/destructor can be categorized in the `function` group, like 
`entity.name.function.constructor`, `entity.name.function.destructor`



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:69
+void $Function[[foo]]() {
+  int $Variable[[b]];
+  auto $Variable[[FN]] = [ $Variable[[b]]](int $Variable[[a]]) -> void {};

nit: even for the test code, could we make the code style consistent (like 
follow the LLVM code style) here?



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:76
+  R"cpp(
+struct A {
+  A();

now we have 4 test cases, the purpose of each testcase is unclear to me (some 
of them are testing duplicated things), could we narrow the testcase so the 
each testcase just test one particular thing (e.g. one test for `Variable` and 
its references; one test for `Function` and its references;)?

I think the testcase here is to verify we don't highlighting the 
constructor/destructor, and operator, just 

```
R"cpp(
struct Foo {
  Foo();
  ~Foo();
  void $Function[[foo]]();
}
)cpp"
```




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199



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


[PATCH] D64123: Add clang-llvm-rename tool.

2019-07-05 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

Hi @ruiu,
Can you comment on how this compares to clang-tidy? I had assumed that the 
readability-identifier-naming clang-tidy rule would largely do the trick.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64123/new/

https://reviews.llvm.org/D64123



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


[PATCH] D64199: [clangd] Added highlighting for variable references (declrefs)

2019-07-05 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 208123.
jvikstrom added a comment.

Added additional testcase.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64199/new/

https://reviews.llvm.org/D64199

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -57,10 +57,32 @@
 void $Function[[foo]](int $Variable[[a]]) {
   auto $Variable[[VeryLongVariableName]] = 12312;
   A $Variable[[aa]];
+  auto $Variable[[l]] = $Variable[[aa]].SomeMember + $Variable[[a]];
 }
   )cpp",
   R"cpp(
 void $Function[[foo]](int);
+  )cpp",
+  R"cpp(
+void $Function[[gah]]();
+void $Function[[foo]]() {
+  int $Variable[[b]];
+  auto $Variable[[FN]] = [ $Variable[[b]]](int $Variable[[a]]) -> void {};
+  $Variable[[FN]](12312);
+  auto $Variable[[bou]] = $Function[[gah]];
+}
+  )cpp",
+  R"cpp(
+struct A {
+  A();
+  ~A();
+  void $Function[[abc]]();
+  void operator<<(int);
+};
+void $Function[[foo]]() {
+  A $Variable[[a]];
+  $Variable[[a]].abc();
+}
   )cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -34,26 +34,46 @@
 return Tokens;
   }
 
-  bool VisitVarDecl(VarDecl *Var) {
-addToken(Var, HighlightingKind::Variable);
+  bool VisitNamedDecl(NamedDecl *ND) {
+// FIXME: (De)Constructors/operator need to be highlighted some other way.
+if (ND->getDeclName().getNameKind() != DeclarationName::Identifier)
+  return true;
+
+if (ND->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return true;
+addToken(ND->getLocation(), ND);
 return true;
   }
-  bool VisitFunctionDecl(FunctionDecl *Func) {
-addToken(Func, HighlightingKind::Function);
+
+  bool VisitDeclRefExpr(DeclRefExpr *Ref) {
+if (Ref->getNameInfo().getName().getNameKind() !=
+DeclarationName::Identifier)
+  // Only want to highlight identifiers.
+  return true;
+
+addToken(Ref->getLocation(), Ref->getDecl());
 return true;
   }
 
 private:
-  void addToken(const NamedDecl *D, HighlightingKind Kind) {
-if (D->getLocation().isMacroID())
-  // FIXME: skip tokens inside macros for now.
+  void addToken(SourceLocation Loc, const Decl *D) {
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Variable);
   return;
+}
+if (isa(D)) {
+  addToken(Loc, HighlightingKind::Function);
+  return;
+}
+  }
 
-if (D->getDeclName().isEmpty())
-  // Don't add symbols that don't have any length.
+  void addToken(SourceLocation Loc, HighlightingKind Kind) {
+if (Loc.isMacroID())
+  // FIXME: skip tokens inside macros for now.
   return;
 
-auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+auto R = getTokenRange(SM, Ctx.getLangOpts(), Loc);
 if (!R) {
   // R should always have a value, if it doesn't something is very wrong.
   elog("Tried to add semantic token with an invalid range");


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -57,10 +57,32 @@
 void $Function[[foo]](int $Variable[[a]]) {
   auto $Variable[[VeryLongVariableName]] = 12312;
   A $Variable[[aa]];
+  auto $Variable[[l]] = $Variable[[aa]].SomeMember + $Variable[[a]];
 }
   )cpp",
   R"cpp(
 void $Function[[foo]](int);
+  )cpp",
+  R"cpp(
+void $Function[[gah]]();
+void $Function[[foo]]() {
+  int $Variable[[b]];
+  auto $Variable[[FN]] = [ $Variable[[b]]](int $Variable[[a]]) -> void {};
+  $Variable[[FN]](12312);
+  auto $Variable[[bou]] = $Function[[gah]];
+}
+  )cpp",
+  R"cpp(
+struct A {
+  A();
+  ~A();
+  void $Function[[abc]]();
+  void operator<<(int);
+};
+void $Function[[foo]]() {
+  A $Variable[[a]];
+  $Variable[[a]].abc();
+}
   )cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp

r365174 - Silence gcc warning "control reaches end of non-void function" [NFCI]

2019-07-05 Thread Mikael Holmen via cfe-commits
Author: uabelho
Date: Thu Jul  4 23:12:24 2019
New Revision: 365174

URL: http://llvm.org/viewvc/llvm-project?rev=365174=rev
Log:
Silence gcc warning "control reaches end of non-void function" [NFCI]

Without this fix gcc (7.4) complains with

 /data/repo/master/clang/lib/CodeGen/CGObjCMac.cpp: In member function 
'std::__cxx11::string 
{anonymous}::CGObjCCommonMac::GetSectionName(llvm::StringRef, llvm::StringRef)':
 /data/repo/master/clang/lib/CodeGen/CGObjCMac.cpp:4944:1: error: control 
reaches end of non-void function [-Werror=return-type]
  }
  ^

All values in the ObjectFormatType enum are currently handled in the switch
but gcc complains anyway.

Modified:
cfe/trunk/lib/CodeGen/CGObjCMac.cpp

Modified: cfe/trunk/lib/CodeGen/CGObjCMac.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGObjCMac.cpp?rev=365174=365173=365174=diff
==
--- cfe/trunk/lib/CodeGen/CGObjCMac.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGObjCMac.cpp Thu Jul  4 23:12:24 2019
@@ -4941,6 +4941,8 @@ std::string CGObjCCommonMac::GetSectionN
 llvm::report_fatal_error(
 "Objective-C support is unimplemented for object file format.");
   }
+
+  llvm_unreachable("Unhandled llvm::Triple::ObjectFormatType enum");
 }
 
 /// EmitImageInfo - Emit the image info marker used to encode some module


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