[PATCH] D68551: [clang-format] [NFC] Ensure clang-format is itself clang-formatted.

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D68551#1696598 , @Eugene.Zelenko 
wrote:

> If clang-format if clang-formatted now completely, I think will be good idea 
> to add rule to check this during build, like Polly does.


This is a great idea... Do you know if is this run as part of the build or as a 
custom rule they have to remember to run? I guess some additional checking 
might be needed to allow bootstrapping this, but I really like this idea of 
once a directory is clean keeping it clean because of its part of a normal 
build.

Keeping code clang-format clean with all the best will in the world is super 
hard, changes drift in very slowly even with asking people to 
`git-clang-format` then if one is missing you are asking for what I'm doing 
here which is making a clang-format only commit and some don't like that.

  # Add target to check formatting of polly files
  file( GLOB_RECURSE files *.h lib/*.cpp lib/*.c tools/*.cpp tools/*.c 
tools/*.h unittests/*.cpp)
  file( GLOB_RECURSE external lib/External/*.h lib/External/*.c 
lib/External/*.cpp isl_config.h)
  list( REMOVE_ITEM files ${external})
  
  set(check_format_depends)
  set(update_format_depends)
  set(i 0)
  foreach (file IN LISTS files)
add_custom_command(OUTPUT polly-check-format${i}
  COMMAND clang-format -sort-includes -style=llvm ${file} | diff -u ${file} 
-
  VERBATIM
  COMMENT "Checking format of ${file}..."
)
list(APPEND check_format_depends "polly-check-format${i}")
  
add_custom_command(OUTPUT polly-update-format${i}
  COMMAND clang-format -sort-includes -i -style=llvm ${file}
  VERBATIM
  COMMENT "Updating format of ${file}..."
)
list(APPEND update_format_depends "polly-update-format${i}")
  
math(EXPR i ${i}+1)
  endforeach ()
  
  add_custom_target(polly-check-format DEPENDS ${check_format_depends})
  set_target_properties(polly-check-format PROPERTIES FOLDER "Polly")
  
  add_custom_target(polly-update-format DEPENDS ${update_format_depends})
  set_target_properties(polly-update-format PROPERTIES FOLDER "Polly")


Repository:
  rC Clang

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

https://reviews.llvm.org/D68551



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


[PATCH] D68539: [clang-tidy] fix for readability-identifier-naming incorrectly fixes variables which become keywords

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I logged the original bug and I like it!

I think the warning is better than mutating with a prefix, Thank you.

I'll let the code owners approve it, but you have my vote!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68539



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


[PATCH] D68551: [clang-format] [NFC] Ensure clang-format is itself clang-formatted.

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I think when polly's script detects a change it's just showing the diff, this 
might be so much nicer if we could implement D68554: [clang-format] Proposal 
for clang-format to give compiler style warnings 



Repository:
  rC Clang

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

https://reviews.llvm.org/D68551



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


[PATCH] D67122: [UBSan][clang][compiler-rt] Applying non-zero offset to nullptr is undefined behaviour

2019-10-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Ping.
Friendly remainder that the unsanitized UB is still being miscompiled.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67122



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


[PATCH] D68554: [clang-format] Proposal for clang-format to give compiler style warnings

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Using a suggestion from D68551: [clang-format] [NFC] Ensure clang-format is 
itself clang-formatted.  as an example of its 
usefulness, I modified my clang-format CMakeList.txt to do as Polly does and 
add clang-format check rules, combining this with this revision gives a nice 
integration into the build system that lets you quickly and easily see where 
violations creep in.

I really feel this could help bring clang-format checking into developers build 
workflows using a similar mechanism and it really highlights what is clean and 
what is not.

  # Add target to check formatting of files
  file( GLOB files *.cpp ../../lib/Format/*.cpp ../../lib/Format*.h 
../../unittests/Format/*.cpp ../../include/clang/Format.h)
  
  set(check_format_depends)
  set(update_format_depends)
  set(i 0)
  foreach (file IN LISTS files)
add_custom_command(OUTPUT clang-format-check-format${i}
  COMMAND clang-format -i -ferror-limit=1 --dry-run -sort-includes 
-style=llvm ${file}
  VERBATIM
  COMMENT "Checking format of ${file}..."
)
list(APPEND check_format_depends "clang-format-check-format${i}")
  
add_custom_command(OUTPUT clang-format-update-format${i}
  COMMAND clang-format -sort-includes -i -style=llvm ${file}
  VERBATIM
  COMMENT "Updating format of ${file}..."
)
list(APPEND update_format_depends "clang-format-update-format${i}")
  
math(EXPR i ${i}+1)
  endforeach ()
  
  add_custom_target(clang-format-check-format DEPENDS ${check_format_depends})
  set_target_properties(clang-format-check-format PROPERTIES FOLDER 
"ClangFormat")
  
  add_custom_target(clang-format-update-format DEPENDS ${update_format_depends})
  set_target_properties(clang-format-update-format PROPERTIES FOLDER 
"ClangFormat")



  [ 94%] Built target obj.clangSema
  [ 94%] Built target clangAST
  [ 94%] Built target clangSema
  [ 94%] Built target clang-format
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/AffectedRangeManager.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/BreakableToken.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/ContinuationIndenter.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/FormatToken.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/Format.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/FormatTokenLexer.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/NamespaceEndCommentsFixer.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/SortJavaScriptImports.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/TokenAnalyzer.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/TokenAnnotator.cpp...
  [ 94%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/UnwrappedLineFormatter.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/UsingDeclarationsSorter.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/UnwrappedLineParser.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../lib/Format/WhitespaceManager.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/CleanupTest.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTest.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestComments.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestCSharp.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestJS.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestJava.cpp...
  
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/CleanupTest.cpp:455:2:
 warning: code should be clang-formatted [-Wclang-format-violations]
  }
   ^
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestProto.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestObjC.cpp...
  [100%] Checking format of 
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestRawStrings.cpp...
  
C:/llvm/llvm-project/clang/tools/clang-format/../../unittests/Format/FormatTestComments.cpp:31:21:
 warning: code should be clang-

r373887 - clang-cl: Ignore the new /ZH options

2019-10-07 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Mon Oct  7 02:30:15 2019
New Revision: 373887

URL: http://llvm.org/viewvc/llvm-project?rev=373887&view=rev
Log:
clang-cl: Ignore the new /ZH options

These were added to the MS docs in
https://github.com/MicrosoftDocs/cpp-docs/commit/85b9b6967e58e485251450f7451673f6fc873e88
and are supposedly available in VS 2019 16.4 (though my 2019 Preview,
version 16.4.0-pre.1.0 don't seem to have them.)

Modified:
cfe/trunk/include/clang/Driver/CLCompatOptions.td
cfe/trunk/test/Driver/cl-options.c

Modified: cfe/trunk/include/clang/Driver/CLCompatOptions.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CLCompatOptions.td?rev=373887&r1=373886&r2=373887&view=diff
==
--- cfe/trunk/include/clang/Driver/CLCompatOptions.td (original)
+++ cfe/trunk/include/clang/Driver/CLCompatOptions.td Mon Oct  7 02:30:15 2019
@@ -401,6 +401,9 @@ def _SLASH_Zc_inline : CLIgnoredFlag<"Zc
 def _SLASH_Zc_rvalueCast : CLIgnoredFlag<"Zc:rvalueCast">;
 def _SLASH_Zc_ternary : CLIgnoredFlag<"Zc:ternary">;
 def _SLASH_Zc_wchar_t : CLIgnoredFlag<"Zc:wchar_t">;
+def _SLASH_ZH_MD5 : CLIgnoredFlag<"ZH:MD5">;
+def _SLASH_ZH_SHA1 : CLIgnoredFlag<"ZH:SHA1">;
+def _SLASH_ZH_SHA_256 : CLIgnoredFlag<"ZH:SHA_256">;
 def _SLASH_Zm : CLIgnoredJoined<"Zm">;
 def _SLASH_Zo : CLIgnoredFlag<"Zo">;
 def _SLASH_Zo_ : CLIgnoredFlag<"Zo-">;

Modified: cfe/trunk/test/Driver/cl-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=373887&r1=373886&r2=373887&view=diff
==
--- cfe/trunk/test/Driver/cl-options.c (original)
+++ cfe/trunk/test/Driver/cl-options.c Mon Oct  7 02:30:15 2019
@@ -377,6 +377,9 @@
 // RUN:/Zc:rvalueCast \
 // RUN:/Zc:ternary \
 // RUN:/Zc:wchar_t \
+// RUN:/ZH:MD5 \
+// RUN:/ZH:SHA1 \
+// RUN:/ZH:SHA_256 \
 // RUN:/Zm \
 // RUN:/Zo \
 // RUN:/Zo- \


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


[PATCH] D67159: [clang] New __attribute__((__clang_arm_mve_alias)).

2019-10-07 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham marked an inline comment as done.
simon_tatham added inline comments.



Comment at: clang/lib/AST/Decl.cpp:3107
+if (!ArmMveAliasValid(BuiltinID, getIdentifier()->getName())) {
+  getASTContext().getDiagnostics().Report(
+getLocation(), diag::err_attribute_arm_mve_alias);

aaron.ballman wrote:
> simon_tatham wrote:
> > aaron.ballman wrote:
> > > simon_tatham wrote:
> > > > aaron.ballman wrote:
> > > > > I'm not certain how comfortable I am with having this function 
> > > > > produce a diagnostic. That seems like unexpected behavior for a 
> > > > > function attempting to get a builtin ID. I think this should be the 
> > > > > responsibility of the caller.
> > > > The //caller//? But there are many possible callers of this function. 
> > > > You surely didn't mean to suggest duplicating the diagnostic at all 
> > > > those call sites.
> > > > 
> > > > Perhaps it would make more sense to have all the calculation in this 
> > > > `getBuiltinID` method move into a function called once, early in the 
> > > > `FunctionDecl`'s lifetime, which figures out the builtin ID (if any) 
> > > > and stashes it in a member variable? Then //that// would issue the 
> > > > diagnostic, if any (and it would be called from a context where that 
> > > > was a sensible thing to do), and `getBuiltinID` itself would become a 
> > > > mere accessor function.
> > > > The caller? But there are many possible callers of this function. You 
> > > > surely didn't mean to suggest duplicating the diagnostic at all those 
> > > > call sites.
> > > 
> > > Yes, I did. :-) No caller is going to expect that calling a `const` 
> > > function that gets a builtin ID is going to issue diagnostics and so this 
> > > runs the risk of generating diagnostics in surprising situations, such as 
> > > from AST matchers.
> > > 
> > > > Perhaps it would make more sense to have all the calculation in this 
> > > > getBuiltinID method move into a function called once, early in the 
> > > > FunctionDecl's lifetime, which figures out the builtin ID (if any) and 
> > > > stashes it in a member variable? Then that would issue the diagnostic, 
> > > > if any (and it would be called from a context where that was a sensible 
> > > > thing to do), and getBuiltinID itself would become a mere accessor 
> > > > function.
> > > 
> > > That might make sense, but I don't have a good idea of what performance 
> > > concerns that might raise. If there are a lot of functions and we never 
> > > need to check if they have a builtin ID, that could be expensive for 
> > > little gain.
> > OK – so actually what you meant to suggest was to put the diagnostic at 
> > just //some// of the call sites for `getBuiltinId`?
> > 
> > With the intended behavior being that the Sema test in this patch should 
> > still provoke all the expected diagnostics in an ordinary compilation 
> > context, but in other situations like AST matchers, it would be better for 
> > `getBuiltinId` to //silently// returns 0 if there's an illegal ArmMveAlias 
> > attribute?
> > 
> > (I'm just checking I've understood you correctly before I do the work...)
> > OK – so actually what you meant to suggest was to put the diagnostic at 
> > just some of the call sites for getBuiltinId?
> 
> Yes! Sorry, I can see how I was unclear before. :-)
> 
> > With the intended behavior being that the Sema test in this patch should 
> > still provoke all the expected diagnostics in an ordinary compilation 
> > context, but in other situations like AST matchers, it would be better for 
> > getBuiltinId to silently returns 0 if there's an illegal ArmMveAlias 
> > attribute?
> 
> Yes. `getBuiltinId()` already returns `0` in error cases without diagnosing, 
> such as the function being unnamed or not being a builtin. I want to retain 
> that property -- this function returns zero if the function is not a builtin. 
> It's up to the caller of the function to decide whether a zero return value 
> should be diagnosed or not.
> 
> To be honest, this diagnostic feels like it belongs in SemaDeclAttr.cpp; it 
> is placing a constraint on which declarations can have the attribute, so that 
> should be checked *before* applying the attribute to the declaration. This 
> also keeps the AST cleaner by not having an attribute on a function which 
> should not be attributed.
> `getBuiltinId()` already returns `0` in error cases without diagnosing

Ah, I hadn't spotted that! That by itself makes it all make a lot more sense to 
me.

> this diagnostic feels like it belongs in SemaDeclAttr.cpp

OK, I'll look at moving it there. Thanks for the pointer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67159



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


[PATCH] D68562: [clangd] Add RemoveUsingNamespace tweak.

2019-10-07 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 created this revision.
Herald added subscribers: cfe-commits, kadircet, arphaman, mgrang, jkorous, 
MaskRay, ilya-biryukov, mgorny.
Herald added a project: clang.

Removes the 'using namespace' under the cursor and qualifies all accesses in 
the current file.
E.g.:

  using namespace std;
  vector foo(std::map);

Would become:

  std::vector foo(std::map);


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68562

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.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
@@ -69,7 +69,8 @@
   EXPECT_EQ(apply("^if (true) {return 100;} else {continue;}"),
 "if (true) {continue;} else {return 100;}");
   EXPECT_EQ(apply("^if () {return 100;} else {continue;}"),
-"if () {continue;} else {return 100;}") << "broken condition";
+"if () {continue;} else {return 100;}")
+  << "broken condition";
   EXPECT_AVAILABLE("^i^f^^(^t^r^u^e^) { return 100; } ^e^l^s^e^ { continue; }");
   EXPECT_UNAVAILABLE("if (true) {^return ^100;^ } else { ^continue^;^ }");
   // Available in subexpressions of the condition;
@@ -100,7 +101,7 @@
   EXPECT_UNAVAILABLE(R"cpp(R"(multi )" ^"token " u8"str\ning")cpp"); // nonascii
   EXPECT_UNAVAILABLE(R"cpp(^R^"^(^multi )" "token " "str\ning")cpp"); // raw
   EXPECT_UNAVAILABLE(R"cpp(^"token\n" __FILE__)cpp"); // chunk is macro
-  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp"); // forbidden escape char
+  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp");   // forbidden escape char
 
   const char *Input = R"cpp(R"(multi
 token)" "\nst^ring\n" "literal")cpp";
@@ -286,11 +287,11 @@
  void f(int a) {
int y = PLUS([[1+a]]);
  })cpp",
-  /*FIXME: It should be extracted like this.
-   R"cpp(#define PLUS(x) x++
- void f(int a) {
-   auto dummy = 1+a; int y = PLUS(dummy);
- })cpp"},*/
+   /*FIXME: It should be extracted like this.
+R"cpp(#define PLUS(x) x++
+  void f(int a) {
+auto dummy = 1+a; int y = PLUS(dummy);
+  })cpp"},*/
R"cpp(#define PLUS(x) x++
  void f(int a) {
auto dummy = PLUS(1+a); int y = dummy;
@@ -301,13 +302,13 @@
if(1)
 LOOP(5 + [[3]])
  })cpp",
-  /*FIXME: It should be extracted like this. SelectionTree needs to be
-* fixed for macros.
-   R"cpp(#define LOOP(x) while (1) {a = x;}
-   void f(int a) {
- auto dummy = 3; if(1)
-  LOOP(5 + dummy)
-   })cpp"},*/
+   /*FIXME: It should be extracted like this. SelectionTree needs to be
+ * fixed for macros.
+R"cpp(#define LOOP(x) while (1) {a = x;}
+void f(int a) {
+  auto dummy = 3; if(1)
+   LOOP(5 + dummy)
+})cpp"},*/
R"cpp(#define LOOP(x) while (1) {a = x;}
  void f(int a) {
auto dummy = LOOP(5 + 3); if(1)
@@ -403,8 +404,8 @@
  void f() {
auto dummy = S(2) + S(3) + S(4); S x = S(1) + dummy + S(5);
  })cpp"},
-   // Don't try to analyze across macro boundaries
-   // FIXME: it'd be nice to do this someday (in a safe way)
+  // Don't try to analyze across macro boundaries
+  // FIXME: it'd be nice to do this someday (in a safe way)
   {R"cpp(#define ECHO(X) X
  void f() {
int x = 1 + [[ECHO(2 + 3) + 4]] + 5;
@@ -521,7 +522,7 @@
   StartsWith("fail: Could not expand type of lambda expression"));
   // inline namespaces
   EXPECT_EQ(apply("au^to x = inl_ns::Visible();"),
-  "Visible x = inl_ns::Visible();");
+"Visible x = inl_ns::Visible();");
   // local class
   EXPECT_EQ(apply("namespace x { void y() { struct S{}; ^auto z = S(); } }"),
 "namespace x { void y() { struct S{}; S z = S(); } }");
@@ -554,7 +555,6 @@
   EXPECT_THAT(apply(" [[int a = 5;]] a++; "), StartsWith("fail"));
   // Don't extract return
   EXPECT_THAT(apply(" if(true) [[return;]] "), StartsWith("fail"));
-  
 }
 
 TEST_F(ExtractFunctionTest, FileTest) {
@@ -648,6 +648,154 @@
   EXPECT_THAT(apply(" for(;;) { [[while(1) break; break;]] }"),
   StartsWith("fail"));
 }
+
+TWEAK_TEST(RemoveUsingNamespace);
+TEST_F(RemoveUsingNamespaceTest, All) {
+  std::pair Cases[] = {
+  {// Remove all occurrenc

[PATCH] D68467: [clangd] If an undocumented definition exists, don't accept documentation from other forward decls.

2019-10-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov 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/D68467/new/

https://reviews.llvm.org/D68467



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


[PATCH] D68564: [clangd] Catch an unchecked "Expected" in HeaderSourceSwitch.

2019-10-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman, jkorous, MaskRay, ilya-biryukov.
Herald added a project: clang.

Also fixes a potential user-after-scope issue of "Path".


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68564

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/HeaderSourceSwitch.cpp
  clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp


Index: clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -125,6 +125,7 @@
   Testing.HeaderCode = R"cpp(
   void B_Sym1();
   void B_Sym2();
+  void B_Sym3_NoDef();
   )cpp";
   Testing.Filename = "b.cpp";
   Testing.Code = R"cpp(
@@ -163,6 +164,12 @@
  void B_Sym1();
)cpp",
testPath("a.cpp")},
+
+   {R"cpp(
+  // We don't have definition in the index, so stay in the header.
+  void B_Sym3_NoDef();
+   )cpp",
+   None},
   };
   for (const auto &Case : TestCases) {
 TestTU TU = TestTU::withCode(Case.HeaderCode);
Index: clang-tools-extra/clangd/HeaderSourceSwitch.cpp
===
--- clang-tools-extra/clangd/HeaderSourceSwitch.cpp
+++ clang-tools-extra/clangd/HeaderSourceSwitch.cpp
@@ -86,7 +86,9 @@
 if (auto TargetPath = URI::resolve(TargetURI, OriginalFile)) {
   if (*TargetPath != OriginalFile) // exclude the original file.
 ++Candidates[*TargetPath];
-};
+} else {
+  elog("Failed to resolve URI {0}: {1}", TargetURI, 
TargetPath.takeError());
+}
   };
   // If we switch from a header, we are looking for the implementation
   // file, so we use the definition loc; otherwise we look for the header file,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -460,7 +460,7 @@
   if (auto CorrespondingFile =
   getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
 return CB(std::move(CorrespondingFile));
-  auto Action = [Path, CB = std::move(CB),
+  auto Action = [Path = Path.str(), CB = std::move(CB),
  this](llvm::Expected InpAST) mutable {
 if (!InpAST)
   return CB(InpAST.takeError());
Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1045,7 +1045,7 @@
 if (!Path)
   return Reply(Path.takeError());
 if (*Path)
-  Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
+  return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
 return Reply(llvm::None);
   });
 }


Index: clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -125,6 +125,7 @@
   Testing.HeaderCode = R"cpp(
   void B_Sym1();
   void B_Sym2();
+  void B_Sym3_NoDef();
   )cpp";
   Testing.Filename = "b.cpp";
   Testing.Code = R"cpp(
@@ -163,6 +164,12 @@
  void B_Sym1();
)cpp",
testPath("a.cpp")},
+
+   {R"cpp(
+  // We don't have definition in the index, so stay in the header.
+  void B_Sym3_NoDef();
+   )cpp",
+   None},
   };
   for (const auto &Case : TestCases) {
 TestTU TU = TestTU::withCode(Case.HeaderCode);
Index: clang-tools-extra/clangd/HeaderSourceSwitch.cpp
===
--- clang-tools-extra/clangd/HeaderSourceSwitch.cpp
+++ clang-tools-extra/clangd/HeaderSourceSwitch.cpp
@@ -86,7 +86,9 @@
 if (auto TargetPath = URI::resolve(TargetURI, OriginalFile)) {
   if (*TargetPath != OriginalFile) // exclude the original file.
 ++Candidates[*TargetPath];
-};
+} else {
+  elog("Failed to resolve URI {0}: {1}", TargetURI, TargetPath.takeError());
+}
   };
   // If we switch from a header, we are looking for the implementation
   // file, so we use the definition loc; otherwise we look for the header file,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -460,7 +460,7 @@
   if (auto CorrespondingFile =
   getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
 return CB(std::move(CorrespondingFile));
-  auto 

[clang-tools-extra] r373889 - [clangd] Collect missing macro references.

2019-10-07 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Oct  7 03:10:31 2019
New Revision: 373889

URL: http://llvm.org/viewvc/llvm-project?rev=373889&view=rev
Log:
[clangd] Collect missing macro references.

Summary: Semantic highlghting is missing a few macro references.

Reviewers: ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/CollectMacros.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CollectMacros.h?rev=373889&r1=373888&r2=373889&view=diff
==
--- clang-tools-extra/trunk/clangd/CollectMacros.h (original)
+++ clang-tools-extra/trunk/clangd/CollectMacros.h Mon Oct  7 03:10:31 2019
@@ -25,7 +25,8 @@ struct MainFileMacros {
   std::vector Ranges;
 };
 
-/// Collects macro definitions and expansions in the main file. It is used to:
+/// Collects macro references (e.g. definitions, expansions) in the main file.
+/// It is used to:
 ///  - collect macros in the preamble section of the main file (in 
Preamble.cpp)
 ///  - collect macros after the preamble of the main file (in ParsedAST.cpp)
 class CollectMainFileMacros : public PPCallbacks {
@@ -49,6 +50,27 @@ public:
 add(MacroName, MD.getMacroInfo());
   }
 
+  void MacroUndefined(const clang::Token &MacroName,
+  const clang::MacroDefinition &MD,
+  const clang::MacroDirective *Undef) override {
+add(MacroName, MD.getMacroInfo());
+  }
+
+  void Ifdef(SourceLocation Loc, const Token &MacroName,
+ const MacroDefinition &MD) override {
+add(MacroName, MD.getMacroInfo());
+  }
+
+  void Ifndef(SourceLocation Loc, const Token &MacroName,
+  const MacroDefinition &MD) override {
+add(MacroName, MD.getMacroInfo());
+  }
+
+  void Defined(const Token &MacroName, const MacroDefinition &MD,
+   SourceRange Range) override {
+add(MacroName, MD.getMacroInfo());
+  }
+
 private:
   void add(const Token &MacroNameTok, const MacroInfo *MI) {
 if (!InMainFile)
@@ -57,7 +79,7 @@ private:
 if (Loc.isMacroID())
   return;
 
-if (auto Range = getTokenRange(SM, LangOpts, MacroNameTok.getLocation())) {
+if (auto Range = getTokenRange(SM, LangOpts, Loc)) {
   Out.Names.insert(MacroNameTok.getIdentifierInfo()->getName());
   Out.Ranges.push_back(*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=373889&r1=373888&r2=373889&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp 
(original)
+++ clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp Mon 
Oct  7 03:10:31 2019
@@ -476,6 +476,20 @@ TEST(SemanticHighlighting, GetsCorrectTo
 $Macro[[assert]]($Variable[[x]] != $Function[[f]]());
   }
 )cpp",
+  // highlighting all macro references
+  R"cpp(
+  #ifndef $Macro[[name]]
+  #define $Macro[[name]]
+  #endif
+
+  #define $Macro[[test]]
+  #undef $Macro[[test]]
+  #ifdef $Macro[[test]]
+  #endif
+
+  #if defined($Macro[[test]])
+  #endif
+)cpp",
   R"cpp(
   struct $Class[[S]] {
 $Primitive[[float]] $Field[[Value]];


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


[PATCH] D68564: [clangd] Catch an unchecked "Expected" in HeaderSourceSwitch.

2019-10-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet 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/D68564/new/

https://reviews.llvm.org/D68564



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


[PATCH] D54834: [analyzer][MallocChecker] Improve warning messages on double-delete errors

2019-10-07 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa82810c56bc9: [analyzer][MallocChecker] Improve warning 
messages on double-delete errors (authored by Szelethus).
Herald added a subscriber: Charusso.
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D54834?vs=178372&id=223469#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54834

Files:
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/test/Analysis/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
  clang/test/Analysis/Malloc+MismatchedDeallocator+NewDelete.cpp
  clang/test/Analysis/NewDelete-checker-test.cpp
  clang/test/Analysis/NewDelete-path-notes.cpp
  clang/test/Analysis/dtor.cpp

Index: clang/test/Analysis/dtor.cpp
===
--- clang/test/Analysis/dtor.cpp
+++ clang/test/Analysis/dtor.cpp
@@ -528,7 +528,7 @@
 return *this;
   }
   ~NonTrivial() {
-delete[] p; // expected-warning {{free released memory}}
+delete[] p; // expected-warning {{delete released memory}}
   }
 };
 
Index: clang/test/Analysis/NewDelete-path-notes.cpp
===
--- clang/test/Analysis/NewDelete-path-notes.cpp
+++ clang/test/Analysis/NewDelete-path-notes.cpp
@@ -11,8 +11,8 @@
 delete p;
 // expected-note@-1 {{Memory is released}}
 
-  delete p; // expected-warning {{Attempt to free released memory}}
-  // expected-note@-1 {{Attempt to free released memory}}
+  delete p; // expected-warning {{Attempt to delete released memory}}
+  // expected-note@-1 {{Attempt to delete released memory}}
 }
 
 struct Odd {
@@ -24,7 +24,7 @@
 void test(Odd *odd) {
 	odd->kill(); // expected-note{{Calling 'Odd::kill'}}
// expected-note@-1 {{Returning; memory was released}}
-	delete odd; // expected-warning {{Attempt to free released memory}}
-  // expected-note@-1 {{Attempt to free released memory}}
+	delete odd; // expected-warning {{Attempt to delete released memory}}
+  // expected-note@-1 {{Attempt to delete released memory}}
 }
 
Index: clang/test/Analysis/NewDelete-checker-test.cpp
===
--- clang/test/Analysis/NewDelete-checker-test.cpp
+++ clang/test/Analysis/NewDelete-checker-test.cpp
@@ -182,7 +182,7 @@
 void testDoubleDelete() {
   int *p = new int;
   delete p;
-  delete p; // expected-warning{{Attempt to free released memory}}
+  delete p; // expected-warning{{Attempt to delete released memory}}
 }
 
 void testExprDeleteArg() {
Index: clang/test/Analysis/Malloc+MismatchedDeallocator+NewDelete.cpp
===
--- clang/test/Analysis/Malloc+MismatchedDeallocator+NewDelete.cpp
+++ clang/test/Analysis/Malloc+MismatchedDeallocator+NewDelete.cpp
@@ -46,7 +46,7 @@
 void testNewDoubleFree() {
   int *p = new int;
   delete p;
-  delete p; // expected-warning{{Attempt to free released memory}}
+  delete p; // expected-warning{{Attempt to delete released memory}}
 }
 
 void testNewLeak() {
Index: clang/test/Analysis/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
===
--- clang/test/Analysis/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
+++ clang/test/Analysis/Inputs/expected-plists/NewDelete-path-notes.cpp.plist
@@ -194,17 +194,17 @@
  
  depth0
  extended_message
- Attempt to free released memory
+ Attempt to delete released memory
  message
- Attempt to free released memory
+ Attempt to delete released memory
 

-   descriptionAttempt to free released memory
+   descriptionAttempt to delete released memory
categoryMemory error
-   typeDouble free
+   typeDouble delete
check_namecplusplus.NewDelete

-   issue_hash_content_of_line_in_contextbd8e324d09c70b9e2be6f824a4942e5a
+   issue_hash_content_of_line_in_context593b185245106bed5175ccf2753039b2
   issue_context_kindfunction
   issue_contexttest
   issue_hash_function_offset8
@@ -423,17 +423,17 @@
  
  depth0
  extended_message
- Attempt to free released memory
+ Attempt to delete released memory
  message
- Attempt to free released memory
+ Attempt to delete released memory
 

-   descriptionAttempt to free released memory
+   descriptionAttempt to delete released memory
categoryMemory error
-   typeDouble free
+   typeDouble delete
check_namecplusplus.NewDelete

-   issue_hash_content_of_line_in_context8bf1a5b9fdae9d86780aa6c4cdce2605
+   issue_hash_content_of_line_in_context6484e9b006ede7362edef2187ba6eb37
   issue_context_kindfunction
   issue_contexttest
   issue_hash_function_offset3
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
=

[PATCH] D68565: [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 created this revision.
usaxena95 added a reviewer: ilya-biryukov.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68565

Files:
  clang/unittests/Lex/LexerTest.cpp

Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -22,6 +24,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "gtest/gtest.h"
+#include 
 
 using namespace clang;
 
@@ -31,12 +34,9 @@
 class LexerTest : public ::testing::Test {
 protected:
   LexerTest()
-: FileMgr(FileMgrOpts),
-  DiagID(new DiagnosticIDs()),
-  Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
-  SourceMgr(Diags, FileMgr),
-  TargetOpts(new TargetOptions)
-  {
+  : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()),
+Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) {
 TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
 Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
   }
@@ -90,7 +90,7 @@
 bool Invalid;
 StringRef Str =
 Lexer::getSourceText(CharSourceRange::getTokenRange(SourceRange(
-Begin.getLocation(), End.getLocation())),
+ Begin.getLocation(), End.getLocation())),
  SourceMgr, LangOpts, &Invalid);
 if (Invalid)
   return "";
@@ -286,30 +286,31 @@
   CharSourceRange macroRange = SourceMgr.getExpansionRange(lsqrLoc);
 
   SourceLocation Loc;
-  EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc));
+  EXPECT_TRUE(
+  Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc));
   EXPECT_EQ(Loc, macroRange.getBegin());
   EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts));
   EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts));
-  EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc));
+  EXPECT_TRUE(
+  Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc));
   EXPECT_EQ(Loc, macroRange.getEnd());
   EXPECT_TRUE(macroRange.isTokenRange());
 
   CharSourceRange range = Lexer::makeFileCharRange(
-   CharSourceRange::getTokenRange(lsqrLoc, idLoc), SourceMgr, LangOpts);
+  CharSourceRange::getTokenRange(lsqrLoc, idLoc), SourceMgr, LangOpts);
   EXPECT_TRUE(range.isInvalid());
-  range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(idLoc, rsqrLoc),
-   SourceMgr, LangOpts);
+  range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(idLoc, rsqrLoc), SourceMgr, LangOpts);
   EXPECT_TRUE(range.isInvalid());
-  range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc),
-   SourceMgr, LangOpts);
+  range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc), SourceMgr, LangOpts);
   EXPECT_TRUE(!range.isTokenRange());
   EXPECT_EQ(range.getAsRange(),
 SourceRange(macroRange.getBegin(),
 macroRange.getEnd().getLocWithOffset(1)));
 
   StringRef text = Lexer::getSourceText(
-   CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc),
-   SourceMgr, LangOpts);
+  CharSourceRange::getTokenRange(lsqrLoc, rsqrLoc), SourceMgr, LangOpts);
   EXPECT_EQ(text, "M(foo)");
 
   SourceLocation macroLsqrLoc = toks[3].getLocation();
@@ -320,29 +321,30 @@
   SourceLocation fileRsqrLoc = SourceMgr.getSpellingLoc(macroRsqrLoc);
 
   range = Lexer::makeFileCharRange(
-  CharSourceRange::getTokenRange(macroLsqrLoc, macroIdLoc),
-  SourceMgr, LangOpts);
+  CharSourceRange::getTokenRange(macroLsqrLoc, macroIdLoc), SourceMgr,
+  LangOpts);
   EXPECT_EQ(SourceRange(fileLsqrLoc, fileIdLoc.getLocWithOffset(3)),
 range.getAsRange());
 
-  range = Lexer::makeFileCharRange(CharSourceRange::getTokenRange(macroIdLoc, macroRsqrLoc),
-   SourceMgr, LangOpts);
+  range = Lexer::makeFileCharRange(
+  CharSourceRange::getTokenRange(macroIdLoc, macroRsqrLoc), SourceMgr,
+  LangOpts);
   EXPECT_EQ(SourceRange(fileIdLoc, fileRsqrLoc.getLocWithOffset(1)),
 range.getAsRange());
 
   macroRange = S

[PATCH] D53066: [Driver] Use forward slashes in most linker arguments

2019-10-07 Thread Martin Storsjö via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcbd73574e43e: Reapply: [Driver] Use forward slashes in most 
linker arguments (authored by mstorsjo).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D53066?vs=171253&id=223478#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53066

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp

Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -1699,7 +1699,7 @@
 if (GCCToolchainDir.back() == '/')
   GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
 
-Prefixes.push_back(GCCToolchainDir);
+Prefixes.push_back(llvm::sys::path::convert_to_slash(GCCToolchainDir));
   } else {
 // If we have a SysRoot, try that first.
 if (!D.SysRoot.empty()) {
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -163,7 +163,7 @@
 
 // Add filenames immediately.
 if (II.isFilename()) {
-  CmdArgs.push_back(II.getFilename());
+  CmdArgs.push_back(Args.MakeArgString(TC.normalizePath(II.getFilename(;
   continue;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3570,7 +3570,8 @@
 for (const auto &II : Inputs) {
   addDashXForInput(Args, II, CmdArgs);
   if (II.isFilename())
-CmdArgs.push_back(II.getFilename());
+CmdArgs.push_back(
+Args.MakeArgString(TC.normalizePath(II.getFilename(;
   else
 II.getInputArg().renderAsInput(Args, CmdArgs);
 }
@@ -4963,7 +4964,8 @@
 // Handled with other dependency code.
   } else if (Output.isFilename()) {
 CmdArgs.push_back("-o");
-CmdArgs.push_back(Output.getFilename());
+CmdArgs.push_back(
+Args.MakeArgString(TC.normalizePath(Output.getFilename(;
   } else {
 assert(Output.isNothing() && "Invalid output.");
   }
@@ -4978,7 +4980,8 @@
 
   for (const InputInfo &Input : FrontendInputs) {
 if (Input.isFilename())
-  CmdArgs.push_back(Input.getFilename());
+  CmdArgs.push_back(
+  Args.MakeArgString(TC.normalizePath(Input.getFilename(;
 else
   Input.getInputArg().renderAsInput(Args, CmdArgs);
   }
@@ -5671,9 +5674,10 @@
   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
   const InputInfo &Input = Inputs[0];
 
-  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
+  const ToolChain &TC = getToolChain();
+  const llvm::Triple &Triple = TC.getEffectiveTriple();
   const std::string &TripleStr = Triple.getTriple();
-  const auto &D = getToolChain().getDriver();
+  const auto &D = TC.getDriver();
 
   // Don't warn about "clang -w -c foo.s"
   Args.ClaimAllArgs(options::OPT_w);
@@ -5847,7 +5851,7 @@
 
   assert(Output.isFilename() && "Unexpected lipo output.");
   CmdArgs.push_back("-o");
-  CmdArgs.push_back(Output.getFilename());
+  CmdArgs.push_back(Args.MakeArgString(TC.normalizePath(Output.getFilename(;
 
   const llvm::Triple &T = getToolChain().getTriple();
   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
@@ -5857,7 +5861,7 @@
   }
 
   assert(Input.isFilename() && "Invalid input.");
-  CmdArgs.push_back(Input.getFilename());
+  CmdArgs.push_back(Args.MakeArgString(TC.normalizePath(Input.getFilename(;
 
   const char *Exec = getToolChain().getDriver().getClangProgramPath();
   C.addCommand(llvm::make_unique(JA, *this, Exec, CmdArgs, Inputs));
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -376,9 +376,10 @@
 
   for (const auto &LibPath : getLibraryPaths()) {
 SmallString<128> P(LibPath);
-llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
+llvm::sys::path::append(P,
+Prefix + Twine("clang_rt.") + Component + Suffix);
 if (getVFS().exists(P))
-  return P.str();
+  return normalizePath(P);
   }
 
   StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
@@ -386,7 +387,7 @@
   SmallString<128> Path(getCompilerRTPath());
   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
 Arch + Env + S

[clang-tools-extra] r373892 - [clangd] If an undocumented definition exists, don't accept documentation from other forward decls.

2019-10-07 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Oct  7 03:53:56 2019
New Revision: 373892

URL: http://llvm.org/viewvc/llvm-project?rev=373892&view=rev
Log:
[clangd] If an undocumented definition exists, don't accept documentation from 
other forward decls.

Summary:
This fixes cases like:
  foo.h
class Undocumented{}
  bar.h
// break an include cycle. we should refactor this!
class Undocumented;
Where the comment doesn't describe the class.

Note that a forward decl that is *visible to the definition* will still have
its doc comment used, by SymbolCollector: Merge isn't involved here.

Reviewers: ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, kadircet, usaxena95, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/Merge.cpp
clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/Merge.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Merge.cpp?rev=373892&r1=373891&r2=373892&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Merge.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Merge.cpp Mon Oct  7 03:53:56 2019
@@ -186,7 +186,10 @@ Symbol mergeSymbol(const Symbol &L, cons
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  if (S.Documentation == "")
+  // Don't accept documentation from bare forward declarations, if there is a
+  // definition and it didn't provide one. S is often an undocumented class,
+  // and O is a non-canonical forward decl preceded by an irrelevant comment.
+  if (S.Documentation == "" && !S.Definition)
 S.Documentation = O.Documentation;
   if (S.ReturnType == "")
 S.ReturnType = O.ReturnType;

Modified: clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp?rev=373892&r1=373891&r2=373892&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp Mon Oct  7 03:53:56 
2019
@@ -413,6 +413,16 @@ TEST(MergeIndexTest, Refs) {
FileURI("unittest:///test2.cc"));
 }
 
+TEST(MergeIndexTest, NonDocumentation) {
+  Symbol L, R;
+  L.ID = R.ID = SymbolID("x");
+  L.Definition.FileURI = "file:/x.h";
+  R.Documentation = "Forward declarations because x.h is too big to include";
+
+  Symbol M = mergeSymbol(L, R);
+  EXPECT_EQ(M.Documentation, "");
+}
+
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
   return (arg.IncludeHeader == IncludeHeader) && (arg.References == 
References);
 }


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


[PATCH] D61627: [clang driver] Allow -fembed-bitcode combined with -mno-red-zone

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders abandoned this revision.
wanders added a comment.

I might revisit this later. But carrying this patch locally for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61627



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


[PATCH] D68564: [clangd] Catch an unchecked "Expected" in HeaderSourceSwitch.

2019-10-07 Thread Merge Guard [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

  Bulid results are available at 
http://results.llvm-merge-guard.org/Phabricator-13

See http://jenkins.llvm-merge-guard.org/job/Phabricator/13/ for more details.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68564



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


[PATCH] D68568: [clang-format] Make '.clang-format' variants finding a loop

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: clang-format.
wanders added a project: clang-format.
Herald added a project: clang.

No functional change intended


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68568

Files:
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,34 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
-
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == 
llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on 
Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
   Status = FS->status(ConfigFile.str());
-  FoundConfigFile = Status && (Status->getType() ==
-   llvm::sys::fs::file_type::regular_file);
-}
 
-if (FoundConfigFile) {
-  llvm::ErrorOr> Text =
-  FS->getBufferForFile(ConfigFile.str());
-  if (std::error_code EC = Text.getError())
-return make_string_error(EC.message());
-  if (std::error_code ec =
-  parseConfiguration(Text.get()->getBuffer(), &Style)) {
-if (ec == ParseError::Unsuitable) {
-  if (!UnsuitableConfigFiles.empty())
-UnsuitableConfigFiles.append(", ");
-  UnsuitableConfigFiles.append(ConfigFile);
-  continue;
+  if (Status && (Status->getType() == 
llvm::sys::fs::file_type::regular_file)) {
+llvm::ErrorOr> Text =
+FS->getBufferForFile(ConfigFile.str());
+if (std::error_code EC = Text.getError())
+  return make_string_error(EC.message());
+if (std::error_code ec =
+parseConfiguration(Text.get()->getBuffer(), &Style)) {
+  if (ec == ParseError::Unsuitable) {
+if (!UnsuitableConfigFiles.empty())
+  UnsuitableConfigFiles.append(", ");
+UnsuitableConfigFiles.append(ConfigFile);
+continue;
+  }
+  return make_string_error("Error reading " + ConfigFile + ": " +
+   ec.message());
 }
-return make_string_error("Error reading " + ConfigFile + ": " +
- ec.message());
+LLVM_DEBUG(llvm::dbgs()
+   << "Using configuration file " << ConfigFile << "\n");
+return Style;
   }
-  LLVM_DEBUG(llvm::dbgs()
- << "Using configuration file " << ConfigFile << "\n");
-  return Style;
 }
   }
   if (!UnsuitableConfigFiles.empty())


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2600,6 +2600,10 @@
   if (std::error_code EC = FS->makeAbsolute(Path))
 return make_string_error(EC.message());
 
+  llvm::SmallVector FilesToLookFor;
+  FilesToLookFor.push_back(".clang-format");
+  FilesToLookFor.push_back("_clang-format");
+
   for (StringRef Directory = Path; !Directory.empty();
Directory = llvm::sys::path::parent_path(Directory)) {
 
@@ -2609,43 +2613,34 @@
   continue;
 }
 
-SmallString<128> ConfigFile(Directory);
+for (const auto &F : FilesToLookFor) {
+  SmallString<128> ConfigFile(Directory);
 
-llvm::sys::path::append(ConfigFile, ".clang-format");
-LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
-
-Status = FS->status(ConfigFile.str());
-bool FoundConfigFile =
-Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
-if (!FoundConfigFile) {
-  // Try _clang-format too, since dotfiles are not commonly used on Windows.
-  ConfigFile = Directory;
-  llvm::sys::path::append(ConfigFile, "_clang-format");
+  llvm::sys::path::append(ConfigFile, F);
   LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
+
   Status = FS->status(ConfigFile.str());
-  FoundConfigFile = Status && (Status->getType() ==
-  

[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: clang-format.
wanders added a project: clang-format.
Herald added a project: clang.

E.g: When formatting foo.cpp it will look for .cpp.clang-format

  

This makes it easy to different formatting for .c/.h files and
.cpp/.hpp files within the same directories.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68569

Files:
  clang/docs/ClangFormat.rst
  clang/lib/Format/Format.cpp


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2601,6 +2601,11 @@
 return make_string_error(EC.message());
 
   llvm::SmallVector FilesToLookFor;
+
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());
+  }
   FilesToLookFor.push_back(".clang-format");
   FilesToLookFor.push_back("_clang-format");
 
Index: clang/docs/ClangFormat.rst
===
--- clang/docs/ClangFormat.rst
+++ clang/docs/ClangFormat.rst
@@ -82,8 +82,10 @@
 
 When the desired code formatting style is different from the available options,
 the style can be customized using the ``-style="{key: value, ...}"`` option or
-by putting your style configuration in the ``.clang-format`` or 
``_clang-format``
-file in your project's directory and using ``clang-format -style=file``.
+by putting your style configuration a file named ``.{ext}.clang-format`` 
(``{ext}``
+is the file name extension, e.g. ``.cpp.clang-format`` is the formatted file
+is named ``something.cpp``), ``.clang-format`` or ``_clang-format`` in your
+project's directory and using ``clang-format -style=file``.
 
 An easy way to create the ``.clang-format`` file is:
 


Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2601,6 +2601,11 @@
 return make_string_error(EC.message());
 
   llvm::SmallVector FilesToLookFor;
+
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());
+  }
   FilesToLookFor.push_back(".clang-format");
   FilesToLookFor.push_back("_clang-format");
 
Index: clang/docs/ClangFormat.rst
===
--- clang/docs/ClangFormat.rst
+++ clang/docs/ClangFormat.rst
@@ -82,8 +82,10 @@
 
 When the desired code formatting style is different from the available options,
 the style can be customized using the ``-style="{key: value, ...}"`` option or
-by putting your style configuration in the ``.clang-format`` or ``_clang-format``
-file in your project's directory and using ``clang-format -style=file``.
+by putting your style configuration a file named ``.{ext}.clang-format`` (``{ext}``
+is the file name extension, e.g. ``.cpp.clang-format`` is the formatted file
+is named ``something.cpp``), ``.clang-format`` or ``_clang-format`` in your
+project's directory and using ``clang-format -style=file``.
 
 An easy way to create the ``.clang-format`` file is:
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

This depends on https://reviews.llvm.org/D68568


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


r373894 - [ASTImporter][NFC] Fix typo in user docs

2019-10-07 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Oct  7 04:14:53 2019
New Revision: 373894

URL: http://llvm.org/viewvc/llvm-project?rev=373894&view=rev
Log:
[ASTImporter][NFC] Fix typo in user docs

Modified:
cfe/trunk/docs/LibASTImporter.rst

Modified: cfe/trunk/docs/LibASTImporter.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTImporter.rst?rev=373894&r1=373893&r2=373894&view=diff
==
--- cfe/trunk/docs/LibASTImporter.rst (original)
+++ cfe/trunk/docs/LibASTImporter.rst Mon Oct  7 04:14:53 2019
@@ -106,7 +106,7 @@ Next, we define a matcher to match ``MyC
 
 .. code-block:: cpp
 
-  auto Matcher = cxxRecordDecl(hasName("C"));
+  auto Matcher = cxxRecordDecl(hasName("MyClass"));
   auto *From = getFirstDecl(Matcher, FromUnit);
 
 Now we create the Importer and do the import:


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


r373895 - [ASTImporter][NFC] Update ASTImporter internals docs

2019-10-07 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Oct  7 04:15:18 2019
New Revision: 373895

URL: http://llvm.org/viewvc/llvm-project?rev=373895&view=rev
Log:
[ASTImporter][NFC] Update ASTImporter internals docs

Modified:
cfe/trunk/docs/InternalsManual.rst

Modified: cfe/trunk/docs/InternalsManual.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/InternalsManual.rst?rev=373895&r1=373894&r2=373895&view=diff
==
--- cfe/trunk/docs/InternalsManual.rst (original)
+++ cfe/trunk/docs/InternalsManual.rst Mon Oct  7 04:15:18 2019
@@ -1519,11 +1519,11 @@ statements are true:
 - A and X are nodes from the same ASTContext.
 - B and Y are nodes from the same ASTContext.
 - A and B may or may not be from the same ASTContext.
-- if A == X (pointer equivalency) then (there is a cycle during the traverse)
+- if A == X and B == Y (pointer equivalency) then (there is a cycle during the
+  traverse)
 
   - A and B are structurally equivalent if and only if
 
-- B and Y are part of the same redeclaration chain,
 - All dependent nodes on the path from  to  are structurally
   equivalent.
 
@@ -1563,15 +1563,6 @@ the whole redeclaration chain of the fun
 declarations - regardless if they are definitions or prototypes - in the order
 as they appear in the "from" context.
 
-.. Structural eq requires proper redecl chains
-
-Another reason why we must maintain and import redeclaration chains properly is
-that the :ref:`Structural Equivalency ` check would report false
-positive in-equivalencies otherwise. We must not allow having two (or more)
-independent redeclaration chains of structurally equivalent declarations.
-Structural equivalency identifies the chains with the canonical declaration,
-that becomes different for independent chains.
-
 .. One definition
 
 If we have an existing definition in the "to" context, then we cannot import


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


[PATCH] D68562: [clangd] Add RemoveUsingNamespace tweak.

2019-10-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

The main comment is about limiting this only to global namespace. PTAL.




Comment at: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:79
+}
+} // namespace
+

continue rest of the file in the anonymous namespace



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:110
+
+  // FIXME: if this is not coming from a macro argument, remove.
+  for (auto *T : Ref.Targets) {

I think I had this FIXME in some of the versions, but TBF I don't remember why 
I added it.
Maybe remove?



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:146
+  for (auto Loc : IdentsToQualify) {
+if (auto Err = R.add(tooling::Replacement(Ctx.getSourceManager(), Loc,
+  /*Length=*/0, Qualifier)))

Qualifying identifiers and removing using namespaces might actually conflict.
Could you add a (commented-out) test with an example that fails and a FIXME?
```
namespace a::b { struct foo {}; }
using namespace a::b;
using namespace b; // we'll try to both qualify this 'b' and remove this line.
```



Comment at: clang-tools-extra/clangd/unittests/TweakTests.cpp:774
+  )cpp"},
+  {// FIXME: Unable to qualify ident from inner ns.
+   R"cpp(

Could we disallow the action outside global namespace for now to make sure it's 
always correct.

```
#include 

using namespace std;
```

is a very common pattern anyway, supporting only it in the first version looks 
ok.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68562



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


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thanks for the patch, I think I understand what you are trying to do, but I 
have a few questions.

Is the premise here that you need slightly different styles for .cpp than for 
.h? could you explain why?

whilst I can see there is value in having such fine control, could you explain 
a little what leads you to needing that? because it feels like you are almost 
saying a bug in clang-format prevents me from using a single file and I'd like 
to understand if that is the case?




Comment at: clang/lib/Format/Format.cpp:2606
+  auto Extension(llvm::sys::path::extension(FileName));
+  if (Extension != "") {
+FilesToLookFor.push_back((Extension + ".clang-format").str());

if Extension is a std::string useif (!Extension.empty())


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D55125: [clang-tidy] Fix a false positive in misc-redundant-expression check

2019-10-07 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp updated this revision to Diff 223501.
dkrupp marked 5 inline comments as done.
dkrupp added a comment.

Thanks @aaron.ballman and @alexfh for your review.
I fixed your findings.


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

https://reviews.llvm.org/D55125

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

Index: clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp
+++ clang-tools-extra/test/clang-tidy/misc-redundant-expression.cpp
@@ -114,6 +114,7 @@
 
 #define COND_OP_MACRO 9
 #define COND_OP_OTHER_MACRO 9
+#define COND_OP_THIRD_MACRO COND_OP_MACRO
 int TestConditional(int x, int y) {
   int k = 0;
   k += (y < 0) ? x : x;
@@ -122,11 +123,27 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: 'true' and 'false' expressions are equivalent
   k += (y < 0) ? COND_OP_MACRO : COND_OP_MACRO;
   // CHECK-MESSAGES: :[[@LINE-1]]:32: warning: 'true' and 'false' expressions are equivalent
+  k += (y < 0) ? COND_OP_MACRO + COND_OP_OTHER_MACRO : COND_OP_MACRO + COND_OP_OTHER_MACRO;
+  // CHECK-MESSAGES: :[[@LINE-1]]:54: warning: 'true' and 'false' expressions are equivalent
 
   // Do not match for conditional operators with a macro and a const.
   k += (y < 0) ? COND_OP_MACRO : 9;
   // Do not match for conditional operators with expressions from different macros.
   k += (y < 0) ? COND_OP_MACRO : COND_OP_OTHER_MACRO;
+  // Do not match for conditional operators when a macro is defined to another macro
+  k += (y < 0) ? COND_OP_MACRO : COND_OP_THIRD_MACRO;
+#undef COND_OP_THIRD_MACRO
+#define   COND_OP_THIRD_MACRO 8
+  k += (y < 0) ? COND_OP_MACRO : COND_OP_THIRD_MACRO;
+#undef COND_OP_THIRD_MACRO
+
+  k += (y < 0) ? sizeof(I64) : sizeof(I64);
+  // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: 'true' and 'false' expressions are equivalent
+  k += (y < 0) ? sizeof(TestConditional(k,y)) : sizeof(TestConditional(k,y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:47: warning: 'true' and 'false' expressions are equivalent
+  // No warning if the expression arguments are different.
+  k += (y < 0) ? sizeof(TestConditional(k,y)) : sizeof(Valid(k,y));
+
   return k;
 }
 #undef COND_OP_MACRO
@@ -134,7 +151,7 @@
 
 // Overloaded operators that compare two instances of a struct.
 struct MyStruct {
-  int x;  
+  int x;
   bool operator==(const MyStruct& rhs) const {return this->x == rhs.x; } // not modifing
   bool operator>=(const MyStruct& rhs) const { return this->x >= rhs.x; } // not modifing
   bool operator<=(MyStruct& rhs) const { return this->x <= rhs.x; }
Index: clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
@@ -131,6 +131,20 @@
   case Stmt::BinaryOperatorClass:
 return cast(Left)->getOpcode() ==
cast(Right)->getOpcode();
+  case Stmt::UnaryExprOrTypeTraitExprClass:
+const auto *LeftUnaryExpr =
+cast(Left);
+const auto *RightUnaryExpr =
+cast(Right);
+if (LeftUnaryExpr->isArgumentType() && RightUnaryExpr->isArgumentType())
+  return LeftUnaryExpr->getArgumentType() ==
+ RightUnaryExpr->getArgumentType();
+else if (!LeftUnaryExpr->isArgumentType() &&
+ !RightUnaryExpr->isArgumentType())
+  return areEquivalentExpr(LeftUnaryExpr->getArgumentExpr(),
+   RightUnaryExpr->getArgumentExpr());
+
+return false;
   }
 }
 
@@ -604,23 +618,62 @@
   return true;
 }
 
+static bool isSameRawIdentifierToken(const Token &T1, const Token &T2,
+const SourceManager &SM) {
+  if (T1.getKind() != T2.getKind())
+return false;
+  if (T1.isNot(tok::raw_identifier))
+return true;
+  if (T1.getLength() != T2.getLength())
+return false;
+  return StringRef(SM.getCharacterData(T1.getLocation()), T1.getLength()) ==
+ StringRef(SM.getCharacterData(T2.getLocation()), T2.getLength());
+}
+
+bool isTokAtEndOfExpr(SourceRange ExprSR, Token T, const SourceManager &SM) {
+  return SM.getExpansionLoc(ExprSR.getEnd()) == T.getLocation();
+}
+
+/// Returns true if both LhsEpxr and RhsExpr are
+/// macro expressions and they are expanded
+/// from different macros.
 static bool areExprsFromDifferentMacros(const Expr *LhsExpr,
 const Expr *RhsExpr,
 const ASTContext *AstCtx) {
   if (!LhsExpr || !RhsExpr)
 return false;
-
-  SourceLocation LhsLoc = LhsExpr->getExprLoc();
-  SourceLocation RhsLoc = RhsExpr->getExprLoc();
-
-  if (!LhsLoc.isMacroID() || !RhsLoc.isMacroID())
+  SourceRange Lsr = LhsExpr->getSourceRange();
+  SourceRange Rsr = RhsExpr->getSourceRange

r373896 - [ASTImporter][NFC] Enable disabled but passing test

2019-10-07 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Oct  7 04:34:54 2019
New Revision: 373896

URL: http://llvm.org/viewvc/llvm-project?rev=373896&view=rev
Log:
[ASTImporter][NFC] Enable disabled but passing test

RedeclChainShouldBeCorrectAmongstNamespaces

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

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=373896&r1=373895&r2=373896&view=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Oct  7 04:34:54 2019
@@ -4785,11 +4785,8 @@ TEST_P(ASTImporterLookupTableTest, Looku
   EXPECT_EQ(*Res.begin(), A);
 }
 
-
-// FIXME This test is disabled currently, upcoming patches will make it
-// possible to enable.
 TEST_P(ASTImporterOptionSpecificTestBase,
-   DISABLED_RedeclChainShouldBeCorrectAmongstNamespaces) {
+   RedeclChainShouldBeCorrectAmongstNamespaces) {
   Decl *FromTU = getTuDecl(
   R"(
   namespace NS {


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


[clang-tools-extra] r373897 - [clangd] Catch an unchecked "Expected" in HeaderSourceSwitch.

2019-10-07 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Oct  7 04:37:25 2019
New Revision: 373897

URL: http://llvm.org/viewvc/llvm-project?rev=373897&view=rev
Log:
[clangd] Catch an unchecked "Expected" in HeaderSourceSwitch.

Summary: Also fixes a potential user-after-scope issue of "Path".

Reviewers: kadircet

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=373897&r1=373896&r2=373897&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Oct  7 04:37:25 2019
@@ -1045,7 +1045,7 @@ void ClangdLSPServer::onSwitchSourceHead
 if (!Path)
   return Reply(Path.takeError());
 if (*Path)
-  Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
+  return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
 return Reply(llvm::None);
   });
 }

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=373897&r1=373896&r2=373897&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Mon Oct  7 04:37:25 2019
@@ -460,7 +460,7 @@ void ClangdServer::switchSourceHeader(
   if (auto CorrespondingFile =
   getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
 return CB(std::move(CorrespondingFile));
-  auto Action = [Path, CB = std::move(CB),
+  auto Action = [Path = Path.str(), CB = std::move(CB),
  this](llvm::Expected InpAST) mutable {
 if (!InpAST)
   return CB(InpAST.takeError());

Modified: clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp?rev=373897&r1=373896&r2=373897&view=diff
==
--- clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp (original)
+++ clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp Mon Oct  7 04:37:25 
2019
@@ -86,7 +86,9 @@ llvm::Optional getCorrespondingHea
 if (auto TargetPath = URI::resolve(TargetURI, OriginalFile)) {
   if (*TargetPath != OriginalFile) // exclude the original file.
 ++Candidates[*TargetPath];
-};
+} else {
+  elog("Failed to resolve URI {0}: {1}", TargetURI, 
TargetPath.takeError());
+}
   };
   // If we switch from a header, we are looking for the implementation
   // file, so we use the definition loc; otherwise we look for the header file,

Modified: clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp?rev=373897&r1=373896&r2=373897&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp 
(original)
+++ clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp Mon 
Oct  7 04:37:25 2019
@@ -125,6 +125,7 @@ TEST(HeaderSourceSwitchTest, FromHeaderT
   Testing.HeaderCode = R"cpp(
   void B_Sym1();
   void B_Sym2();
+  void B_Sym3_NoDef();
   )cpp";
   Testing.Filename = "b.cpp";
   Testing.Code = R"cpp(
@@ -163,6 +164,12 @@ TEST(HeaderSourceSwitchTest, FromHeaderT
  void B_Sym1();
)cpp",
testPath("a.cpp")},
+
+   {R"cpp(
+  // We don't have definition in the index, so stay in the header.
+  void B_Sym3_NoDef();
+   )cpp",
+   None},
   };
   for (const auto &Case : TestCases) {
 TestTU TU = TestTU::withCode(Case.HeaderCode);


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


[PATCH] D68565: [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 223503.
usaxena95 added a comment.

Revert unintended formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68565

Files:
  clang/unittests/Lex/LexerTest.cpp


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -22,6 +24,9 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "gtest/gtest.h"
+#include 
+
+namespace {
 
 using namespace clang;
 
@@ -535,4 +540,22 @@
   EXPECT_EQ(Lexer::getSourceText(CR, SourceMgr, LangOpts), "MOO"); // Was "MO".
 }
 
+TEST_F(LexerTest, FindNextToken) {
+  Lex("int abcd = 0;\n"
+  "int xyz = abcd;\n");
+  std::vector ExpectedTokens = {"abcd", "=", "0",";", "int",
+ "xyz",  "=", "abcd", ";"};
+  std::vector GeneratedByNextToken;
+  SourceLocation Loc =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+  while (true) {
+auto T = Lexer::findNextToken(Loc, SourceMgr, LangOpts);
+ASSERT_TRUE(T.hasValue());
+if (T->is(tok::eof))
+  break;
+GeneratedByNextToken.push_back(getSourceText(*T, *T));
+Loc = T->getLocation();
+  }
+  EXPECT_EQ(ExpectedTokens, GeneratedByNextToken);
+}
 } // anonymous namespace


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -22,6 +24,9 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "gtest/gtest.h"
+#include 
+
+namespace {
 
 using namespace clang;
 
@@ -535,4 +540,22 @@
   EXPECT_EQ(Lexer::getSourceText(CR, SourceMgr, LangOpts), "MOO"); // Was "MO".
 }
 
+TEST_F(LexerTest, FindNextToken) {
+  Lex("int abcd = 0;\n"
+  "int xyz = abcd;\n");
+  std::vector ExpectedTokens = {"abcd", "=", "0",";", "int",
+ "xyz",  "=", "abcd", ";"};
+  std::vector GeneratedByNextToken;
+  SourceLocation Loc =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+  while (true) {
+auto T = Lexer::findNextToken(Loc, SourceMgr, LangOpts);
+ASSERT_TRUE(T.hasValue());
+if (T->is(tok::eof))
+  break;
+GeneratedByNextToken.push_back(getSourceText(*T, *T));
+Loc = T->getLocation();
+  }
+  EXPECT_EQ(ExpectedTokens, GeneratedByNextToken);
+}
 } // anonymous namespace
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

I'm not seeing any merrit this brings over existing 
https://clang.llvm.org/docs/ClangFormatStyleOptions.html `Language` option.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D68565: [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Could you add a rationale in the change description? E.g. something like `we do 
not have any tests for findNextToken`




Comment at: clang/unittests/Lex/LexerTest.cpp:559
+  }
+  EXPECT_EQ(ExpectedTokens, GeneratedByNextToken);
+}

NIT: could be replaced with
```
EXPECT_THAT(GeneratedByNextToken, ElementsAre("abcd", "=", ))
```

To avoid creating an extra variable.
But up to you, this version also looks ok.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68565



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


[PATCH] D68568: [clang-format] Make '.clang-format' variants finding a loop

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thank you for the patch,

I think this looks cleaner and generally LGTM, I think its always good to put a 
little description of the change along with the NFC in the title to let people 
know that functionally there isn't any change without having to work though the 
code change. Maybe even giving a little rationale as to why you are thinking of 
making the change.. (which I see from D68569: [clang-format] Also look for 
.{ext}.clang-format file )

As I understand it, you have changed the code to read the configs from a list 
of file in a loop rather than reading one and then trying another if that 
cannot be found, subsequently, this would make it relatively easy to add higher 
priority search options without confusing the code

I think there is some commonality here that could be used with another 
suggestion which was to allow  --style= D50147: clang-format: support 
external styles 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68568



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


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders added a comment.

The "Language" option can not distinguish between C and C++.

We have projects which contains both C and C++ code. Using different style 
(yes..) for C and C++.  Our C++ headers are named hpp.

In our toplevel we have the following symlinks
.c.clang-format -> clang-format/c.clang-format
.h.clang-format -> clang-format/c.clang-format
.cpp.clang-format -> clang-format/cpp.clang-format
.hpp.clang-format -> clang-format/cpp.clang-format

Before this we had a horrible wrapper script that used cd into different 
directories depending on extension, and those directories had different 
.clang-format files, and then had to run clang-format from stdin.

An alternative implementation I did consider was to add some kind of path 
matching in the configuration file doing multiple yaml documents in the 
configuration file. So in my case it would be something like:

  ---
  Language: Cpp
  IndentWidth: 4
  TabWidth: 4
  MoreStuff...
  ---
  PathMatch: [ *.cpp, *.hpp ]
  SpaceBeforeParen: ControlStatements
  ---
  PathMatch [ *.c, *.h ]
  SpaceBeforeParen: Never
  ---


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D68565: [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 223524.
usaxena95 marked an inline comment as done.
usaxena95 added a comment.

Addressed comments and fixed build failure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68565

Files:
  clang/unittests/Lex/LexerTest.cpp


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -21,11 +23,13 @@
 #include "clang/Lex/ModuleLoader.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
-using namespace clang;
+#include 
 
 namespace {
+using namespace clang;
+using testing::ElementsAre;
 
 // The test fixture.
 class LexerTest : public ::testing::Test {
@@ -535,4 +539,21 @@
   EXPECT_EQ(Lexer::getSourceText(CR, SourceMgr, LangOpts), "MOO"); // Was "MO".
 }
 
+TEST_F(LexerTest, FindNextToken) {
+  Lex("int abcd = 0;\n"
+  "int xyz = abcd;\n");
+  std::vector GeneratedByNextToken;
+  SourceLocation Loc =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+  while (true) {
+auto T = Lexer::findNextToken(Loc, SourceMgr, LangOpts);
+ASSERT_TRUE(T.hasValue());
+if (T->is(tok::eof))
+  break;
+GeneratedByNextToken.push_back(getSourceText(*T, *T));
+Loc = T->getLocation();
+  }
+  EXPECT_THAT(GeneratedByNextToken, ElementsAre("abcd", "=", "0", ";", "int",
+"xyz", "=", "abcd", ";"));
+}
 } // anonymous namespace


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -21,11 +23,13 @@
 #include "clang/Lex/ModuleLoader.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
-using namespace clang;
+#include 
 
 namespace {
+using namespace clang;
+using testing::ElementsAre;
 
 // The test fixture.
 class LexerTest : public ::testing::Test {
@@ -535,4 +539,21 @@
   EXPECT_EQ(Lexer::getSourceText(CR, SourceMgr, LangOpts), "MOO"); // Was "MO".
 }
 
+TEST_F(LexerTest, FindNextToken) {
+  Lex("int abcd = 0;\n"
+  "int xyz = abcd;\n");
+  std::vector GeneratedByNextToken;
+  SourceLocation Loc =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+  while (true) {
+auto T = Lexer::findNextToken(Loc, SourceMgr, LangOpts);
+ASSERT_TRUE(T.hasValue());
+if (T->is(tok::eof))
+  break;
+GeneratedByNextToken.push_back(getSourceText(*T, *T));
+Loc = T->getLocation();
+  }
+  EXPECT_THAT(GeneratedByNextToken, ElementsAre("abcd", "=", "0", ";", "int",
+"xyz", "=", "abcd", ";"));
+}
 } // anonymous namespace
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.






Comment at: clang/lib/Format/Format.cpp:2603
 
   llvm::SmallVector FilesToLookFor;
+

Nit: almost every file has an extension should this be 3?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D34096: [Sema][C++1z] Ensure structured binding's bindings in dependent foreach have non-null type

2019-10-07 Thread Erik Pilkington via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG21ff345d64b9: [Sema][C++1z] Ensure binding in dependent 
range for have non-null type (authored by erik.pilkington).
Herald added subscribers: ributzka, dexonsmith, jkorous.
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D34096?vs=102191&id=223537#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D34096

Files:
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/cxx1z-decomposition.cpp


Index: clang/test/SemaCXX/cxx1z-decomposition.cpp
===
--- clang/test/SemaCXX/cxx1z-decomposition.cpp
+++ clang/test/SemaCXX/cxx1z-decomposition.cpp
@@ -70,4 +70,10 @@
   return foobar_; // expected-error {{undeclared identifier 'foobar_'}}
 }
 
+// PR32172
+template  void dependent_foreach(T t) {
+  for (auto [a,b,c] : t)
+a,b,c;
+}
+
 // FIXME: by-value array copies
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -2206,8 +2206,12 @@
 
 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
 // them in properly when we instantiate the loop.
-if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
+if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
+  if (auto *DD = dyn_cast(LoopVar))
+for (auto *Binding : DD->bindings())
+  Binding->setType(Context.DependentTy);
   LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
+}
   } else if (!BeginDeclStmt.get()) {
 SourceLocation RangeLoc = RangeVar->getLocation();
 


Index: clang/test/SemaCXX/cxx1z-decomposition.cpp
===
--- clang/test/SemaCXX/cxx1z-decomposition.cpp
+++ clang/test/SemaCXX/cxx1z-decomposition.cpp
@@ -70,4 +70,10 @@
   return foobar_; // expected-error {{undeclared identifier 'foobar_'}}
 }
 
+// PR32172
+template  void dependent_foreach(T t) {
+  for (auto [a,b,c] : t)
+a,b,c;
+}
+
 // FIXME: by-value array copies
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -2206,8 +2206,12 @@
 
 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
 // them in properly when we instantiate the loop.
-if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
+if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
+  if (auto *DD = dyn_cast(LoopVar))
+for (auto *Binding : DD->bindings())
+  Binding->setType(Context.DependentTy);
   LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
+}
   } else if (!BeginDeclStmt.get()) {
 SourceLocation RangeLoc = RangeVar->getLocation();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68569: [clang-format] Also look for .{ext}.clang-format file

2019-10-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D68569#1697248 , @wanders wrote:

> The "Language" option can not distinguish between C and C++.
>
> We have projects which contains both C and C++ code. Using different style 
> (yes..) for C and C++.  Our C++ headers are named hpp.


That seems like a much smaller bug/feature to fix ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68569



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


[PATCH] D31540: Prefer non-friend to friend in in redeclaration chain

2019-10-07 Thread Yaron Keren via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG27e2ff964fc3: Address http://bugs.llvm.org/pr30994 so that a 
non-friend can properly replace… (authored by yaron.keren).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D31540?vs=95425&id=223543#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D31540

Files:
  clang/include/clang/AST/DeclBase.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/test/SemaTemplate/friend-template.cpp

Index: clang/test/SemaTemplate/friend-template.cpp
===
--- clang/test/SemaTemplate/friend-template.cpp
+++ clang/test/SemaTemplate/friend-template.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
 // PR5057
 namespace test0 {
   namespace std {
@@ -68,17 +68,12 @@
   Foo foo;
 
   template struct X2a;
-
-  template struct X2b;
+  template struct X2b;// expected-note {{previous non-type template parameter with type 'int' is here}}
 
   template
   class X3 {
 template friend struct X2a;
-
-// FIXME: the redeclaration note ends up here because redeclaration
-// lookup ends up finding the friend target from X3.
-template friend struct X2b; // expected-error {{template non-type parameter has a different type 'long' in template redeclaration}} \
-  // expected-note {{previous non-type template parameter with type 'int' is here}}
+template friend struct X2b; // expected-error {{template non-type parameter has a different type 'long' in template redeclaration}} 
   };
 
   X3 x3i; // okay
@@ -297,14 +292,11 @@
   int n = C::D().f();
 
   struct F {
-template struct G;
+template struct G; // expected-note {{previous}}
   };
   template struct H {
-// FIXME: As with cases above, the note here is on an unhelpful declaration,
-// and should point to the declaration of G within F.
 template friend struct F::G; // \
-  // expected-error {{different type 'char' in template redeclaration}} \
-  // expected-note {{previous}}
+  // expected-error {{different type 'char' in template redeclaration}}
   };
   H h1; // ok
   H h2; // expected-note {{instantiation}}
@@ -329,3 +321,11 @@
 foo(b); // expected-note {{in instantiation}}
   }
 }
+namespace PR30994 {
+  void f();
+  struct A {
+[[deprecated]] friend void f() {} // \
+  expected-note {{has been explicitly marked deprecated here}}
+  };
+  void g() { f(); } // expected-warning {{is deprecated}}
+}
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -861,6 +861,21 @@
   return Ty->getAs();
 }
 
+bool Decl::isThisDeclarationADefinition() const {
+  if (auto *TD = dyn_cast(this))
+return TD->isThisDeclarationADefinition();
+  if (auto *FD = dyn_cast(this))
+return FD->isThisDeclarationADefinition();
+  if (auto *VD = dyn_cast(this))
+return VD->isThisDeclarationADefinition();
+  if (auto *CTD = dyn_cast(this))
+return CTD->isThisDeclarationADefinition();
+  if (auto *FTD = dyn_cast(this))
+return FTD->isThisDeclarationADefinition();
+  if (auto *VTD = dyn_cast(this))
+return VTD->isThisDeclarationADefinition();
+  return false;
+}
 
 /// Starting at a given context (a Decl or DeclContext), look for a
 /// code context that is not a closure (a lambda, block, etc.).
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -1536,6 +1536,10 @@
   if (isa(this))
 return false;
 
+  if (getFriendObjectKind() > OldD->getFriendObjectKind() &&
+  !isThisDeclarationADefinition())
+return false;
+
   // For parameters, pick the newer one. This is either an error or (in
   // Objective-C) permitted as an extension.
   if (isa(this))
Index: clang/include/clang/AST/DeclBase.h
===
--- clang/include/clang/AST/DeclBase.h
+++ clang/include/clang/AST/DeclBase.h
@@ -417,6 +417,8 @@
 return const_cast(this)->getTranslationUnitDecl();
   }
 
+  bool isThisDeclarationADefinition() const;
+
   bool isInAnonymousNamespace() const;
 
   bool isInStdNamespace() const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68565: [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68565



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


[PATCH] D67159: [clang] New __attribute__((__clang_arm_mve_alias)).

2019-10-07 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 223550.
simon_tatham added a comment.

Moved the diagnostic into `SemaDeclAttr.cpp` as suggested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67159

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/Decl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/arm-mve-alias-attribute.c

Index: clang/test/Sema/arm-mve-alias-attribute.c
===
--- /dev/null
+++ clang/test/Sema/arm-mve-alias-attribute.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple armv8.1m.main-arm-none-eabi -verify -fsyntax-only %s
+
+static __inline__ __attribute__((__clang_arm_mve_alias(__builtin_arm_nop))) // expected-error {{'__clang_arm_mve_alias' attribute can only be applied to an ARM MVE builtin}}
+void nop(void);
+
+static __inline__ __attribute__((__clang_arm_mve_alias)) // expected-error {{'__clang_arm_mve_alias' attribute takes one argument}}
+void noparens(void);
+
+static __inline__ __attribute__((__clang_arm_mve_alias())) // expected-error {{'__clang_arm_mve_alias' attribute takes one argument}}
+void emptyparens(void);
+
+static __inline__ __attribute__((__clang_arm_mve_alias("string literal"))) // expected-error {{'__clang_arm_mve_alias' attribute requires parameter 1 to be an identifier}}
+void stringliteral(void);
+
+static __inline__ __attribute__((__clang_arm_mve_alias(1))) // expected-error {{'__clang_arm_mve_alias' attribute requires parameter 1 to be an identifier}}
+void integer(void);
+
+static __inline__ __attribute__((__clang_arm_mve_alias(__builtin_arm_nop, 2))) // expected-error {{'__clang_arm_mve_alias' attribute takes one argument}}
+void twoargs(void);
+
+static __attribute__((__clang_arm_mve_alias(__builtin_arm_nop))) // expected-error {{'__clang_arm_mve_alias' attribute only applies to functions}}
+int variable;
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -17,6 +17,7 @@
 // CHECK-NEXT: Annotate ()
 // CHECK-NEXT: AnyX86NoCfCheck (SubjectMatchRule_hasType_functionType)
 // CHECK-NEXT: ArcWeakrefUnavailable (SubjectMatchRule_objc_interface)
+// CHECK-NEXT: ArmMveAlias (SubjectMatchRule_function)
 // CHECK-NEXT: AssumeAligned (SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: Availability ((SubjectMatchRule_record, SubjectMatchRule_enum, SubjectMatchRule_enum_constant, SubjectMatchRule_field, SubjectMatchRule_function, SubjectMatchRule_namespace, SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, SubjectMatchRule_record, SubjectMatchRule_type_alias, SubjectMatchRule_variable))
 // CHECK-NEXT: CFAuditedTransfer (SubjectMatchRule_function)
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -23,6 +23,7 @@
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
@@ -4830,6 +4831,33 @@
  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
 }
 
+static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
+  // FIXME: this will be filled in by Tablegen which isn't written yet
+  return false;
+}
+
+static void handleArmMveAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  if (!checkAttributeNumArgs(S, AL, 1))
+return;
+
+  if (!AL.isArgIdent(0)) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
+<< AL << 1 << AANT_ArgumentIdentifier;
+return;
+  }
+
+  IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
+  unsigned BuiltinID = Ident->getBuiltinID();
+
+  if (!ArmMveAliasValid(BuiltinID,
+cast(D)->getIdentifier()->getName())) {
+S.Diag(AL.getLoc(), diag::err_attribute_arm_mve_alias);
+return;
+  }
+
+  D->addAttr(::new (S.Context) ArmMveAliasAttr(S.Context, AL, Ident));
+}
+
 //===--===//
 // Checker-specific attribute handlers.
 //===--===//
@@ -7160,6 +7188,10 @@
   case ParsedAttr::AT_MSAllocator:
 handleMSAllocatorAttr(S, D, AL);
 break;
+
+ 

[PATCH] D67159: [clang] New __attribute__((__clang_arm_mve_alias)).

2019-10-07 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham marked an inline comment as done.
simon_tatham added inline comments.



Comment at: clang/lib/AST/Decl.cpp:3107
+if (!ArmMveAliasValid(BuiltinID, getIdentifier()->getName())) {
+  getASTContext().getDiagnostics().Report(
+getLocation(), diag::err_attribute_arm_mve_alias);

simon_tatham wrote:
> aaron.ballman wrote:
> > simon_tatham wrote:
> > > aaron.ballman wrote:
> > > > simon_tatham wrote:
> > > > > aaron.ballman wrote:
> > > > > > I'm not certain how comfortable I am with having this function 
> > > > > > produce a diagnostic. That seems like unexpected behavior for a 
> > > > > > function attempting to get a builtin ID. I think this should be the 
> > > > > > responsibility of the caller.
> > > > > The //caller//? But there are many possible callers of this function. 
> > > > > You surely didn't mean to suggest duplicating the diagnostic at all 
> > > > > those call sites.
> > > > > 
> > > > > Perhaps it would make more sense to have all the calculation in this 
> > > > > `getBuiltinID` method move into a function called once, early in the 
> > > > > `FunctionDecl`'s lifetime, which figures out the builtin ID (if any) 
> > > > > and stashes it in a member variable? Then //that// would issue the 
> > > > > diagnostic, if any (and it would be called from a context where that 
> > > > > was a sensible thing to do), and `getBuiltinID` itself would become a 
> > > > > mere accessor function.
> > > > > The caller? But there are many possible callers of this function. You 
> > > > > surely didn't mean to suggest duplicating the diagnostic at all those 
> > > > > call sites.
> > > > 
> > > > Yes, I did. :-) No caller is going to expect that calling a `const` 
> > > > function that gets a builtin ID is going to issue diagnostics and so 
> > > > this runs the risk of generating diagnostics in surprising situations, 
> > > > such as from AST matchers.
> > > > 
> > > > > Perhaps it would make more sense to have all the calculation in this 
> > > > > getBuiltinID method move into a function called once, early in the 
> > > > > FunctionDecl's lifetime, which figures out the builtin ID (if any) 
> > > > > and stashes it in a member variable? Then that would issue the 
> > > > > diagnostic, if any (and it would be called from a context where that 
> > > > > was a sensible thing to do), and getBuiltinID itself would become a 
> > > > > mere accessor function.
> > > > 
> > > > That might make sense, but I don't have a good idea of what performance 
> > > > concerns that might raise. If there are a lot of functions and we never 
> > > > need to check if they have a builtin ID, that could be expensive for 
> > > > little gain.
> > > OK – so actually what you meant to suggest was to put the diagnostic at 
> > > just //some// of the call sites for `getBuiltinId`?
> > > 
> > > With the intended behavior being that the Sema test in this patch should 
> > > still provoke all the expected diagnostics in an ordinary compilation 
> > > context, but in other situations like AST matchers, it would be better 
> > > for `getBuiltinId` to //silently// returns 0 if there's an illegal 
> > > ArmMveAlias attribute?
> > > 
> > > (I'm just checking I've understood you correctly before I do the work...)
> > > OK – so actually what you meant to suggest was to put the diagnostic at 
> > > just some of the call sites for getBuiltinId?
> > 
> > Yes! Sorry, I can see how I was unclear before. :-)
> > 
> > > With the intended behavior being that the Sema test in this patch should 
> > > still provoke all the expected diagnostics in an ordinary compilation 
> > > context, but in other situations like AST matchers, it would be better 
> > > for getBuiltinId to silently returns 0 if there's an illegal ArmMveAlias 
> > > attribute?
> > 
> > Yes. `getBuiltinId()` already returns `0` in error cases without 
> > diagnosing, such as the function being unnamed or not being a builtin. I 
> > want to retain that property -- this function returns zero if the function 
> > is not a builtin. It's up to the caller of the function to decide whether a 
> > zero return value should be diagnosed or not.
> > 
> > To be honest, this diagnostic feels like it belongs in SemaDeclAttr.cpp; it 
> > is placing a constraint on which declarations can have the attribute, so 
> > that should be checked *before* applying the attribute to the declaration. 
> > This also keeps the AST cleaner by not having an attribute on a function 
> > which should not be attributed.
> > `getBuiltinId()` already returns `0` in error cases without diagnosing
> 
> Ah, I hadn't spotted that! That by itself makes it all make a lot more sense 
> to me.
> 
> > this diagnostic feels like it belongs in SemaDeclAttr.cpp
> 
> OK, I'll look at moving it there. Thanks for the pointer.
I made this change, and discovered that as a side effect, this diagnostic is 
now reported on the same one of the two source lines as all the others in my 
test f

[PATCH] D28213: [Frontend] Correct values of ATOMIC_*_LOCK_FREE to match builtin

2019-10-07 Thread Michał Górny via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdc155744c82f: [Frontend] Correct values of 
ATOMIC_*_LOCK_FREE to match builtin (authored by mgorny).
Herald added a subscriber: dexonsmith.
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D28213?vs=83677&id=223551#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D28213

Files:
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/test/Sema/atomic-ops.c


Index: clang/test/Sema/atomic-ops.c
===
--- clang/test/Sema/atomic-ops.c
+++ clang/test/Sema/atomic-ops.c
@@ -14,11 +14,7 @@
 _Static_assert(__GCC_ATOMIC_SHORT_LOCK_FREE == 2, "");
 _Static_assert(__GCC_ATOMIC_INT_LOCK_FREE == 2, "");
 _Static_assert(__GCC_ATOMIC_LONG_LOCK_FREE == 2, "");
-#ifdef __i386__
-_Static_assert(__GCC_ATOMIC_LLONG_LOCK_FREE == 1, "");
-#else
 _Static_assert(__GCC_ATOMIC_LLONG_LOCK_FREE == 2, "");
-#endif
 _Static_assert(__GCC_ATOMIC_POINTER_LOCK_FREE == 2, "");
 
 _Static_assert(__c11_atomic_is_lock_free(1), "");
Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -286,12 +286,12 @@
 
 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
 /// the specified properties.
-static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
-unsigned InlineWidth) {
+static const char *getLockFreeValue(unsigned TypeWidth, unsigned InlineWidth) {
   // Fully-aligned, power-of-2 sizes no larger than the inline
   // width will be inlined as lock-free operations.
-  if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
-  TypeWidth <= InlineWidth)
+  // Note: we do not need to check alignment since _Atomic(T) is always
+  // appropriately-aligned in clang.
+  if ((TypeWidth & (TypeWidth - 1)) == 0 && TypeWidth <= InlineWidth)
 return "2"; // "always lock free"
   // We cannot be certain what operations the lib calls might be
   // able to implement as lock-free on future processors.
@@ -881,7 +881,6 @@
 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
 Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
 getLockFreeValue(TI.get##Type##Width(), \
- TI.get##Type##Align(), \
  InlineWidthBits));
 DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
 DEFINE_LOCK_FREE_MACRO(CHAR, Char);
@@ -894,7 +893,6 @@
 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
 Builder.defineMacro("__GCC_ATOMIC_POINTER_LOCK_FREE",
 getLockFreeValue(TI.getPointerWidth(0),
- TI.getPointerAlign(0),
  InlineWidthBits));
 #undef DEFINE_LOCK_FREE_MACRO
   }


Index: clang/test/Sema/atomic-ops.c
===
--- clang/test/Sema/atomic-ops.c
+++ clang/test/Sema/atomic-ops.c
@@ -14,11 +14,7 @@
 _Static_assert(__GCC_ATOMIC_SHORT_LOCK_FREE == 2, "");
 _Static_assert(__GCC_ATOMIC_INT_LOCK_FREE == 2, "");
 _Static_assert(__GCC_ATOMIC_LONG_LOCK_FREE == 2, "");
-#ifdef __i386__
-_Static_assert(__GCC_ATOMIC_LLONG_LOCK_FREE == 1, "");
-#else
 _Static_assert(__GCC_ATOMIC_LLONG_LOCK_FREE == 2, "");
-#endif
 _Static_assert(__GCC_ATOMIC_POINTER_LOCK_FREE == 2, "");
 
 _Static_assert(__c11_atomic_is_lock_free(1), "");
Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -286,12 +286,12 @@
 
 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
 /// the specified properties.
-static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
-unsigned InlineWidth) {
+static const char *getLockFreeValue(unsigned TypeWidth, unsigned InlineWidth) {
   // Fully-aligned, power-of-2 sizes no larger than the inline
   // width will be inlined as lock-free operations.
-  if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 &&
-  TypeWidth <= InlineWidth)
+  // Note: we do not need to check alignment since _Atomic(T) is always
+  // appropriately-aligned in clang.
+  if ((TypeWidth & (TypeWidth - 1)) == 0 && TypeWidth <= InlineWidth)
 return "2"; // "always lock free"
   // We cannot be certain what operations the lib calls might be
   // able to implement as lock-free on future processors.
@@ -881,7 +881,6 @@
 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
 Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
 getLockFreeValue(TI.get##Type##Width(), \
-   

[PATCH] D24119: [libc++] add linker option "-Wl,-z,defs" in standalone build

2019-10-07 Thread Michał Górny via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4601ac04c738: [cmake] Add linker option 
"-Wl,-z,defs" in standalone build (authored by mgorny).
Herald added subscribers: libcxx-commits, ldionne, christof.
Herald added a project: libc++.

Changed prior to commit:
  https://reviews.llvm.org/D24119?vs=72632&id=223558#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D24119

Files:
  libcxx/CMakeLists.txt


Index: libcxx/CMakeLists.txt
===
--- libcxx/CMakeLists.txt
+++ libcxx/CMakeLists.txt
@@ -319,6 +319,18 @@
 # so they don't get transformed into -Wno and -errors respectivly.
 remove_flags(-Wno-pedantic -pedantic-errors -pedantic)
 
+# FIXME: this is cribbed from HandleLLVMOptions.cmake.
+if(LIBCXX_STANDALONE_BUILD)
+  # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
+  # build might work on ELF but fail on MachO/COFF.
+  if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR WIN32 OR CYGWIN OR
+  ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR
+  ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") AND
+ NOT LLVM_USE_SANITIZER)
+set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
+  endif()
+endif()
+
 # Required flags ==
 set(LIBCXX_STANDARD_VER c++11 CACHE INTERNAL "internal option to change build 
dialect")
 add_compile_flags_if_supported(-std=${LIBCXX_STANDARD_VER})


Index: libcxx/CMakeLists.txt
===
--- libcxx/CMakeLists.txt
+++ libcxx/CMakeLists.txt
@@ -319,6 +319,18 @@
 # so they don't get transformed into -Wno and -errors respectivly.
 remove_flags(-Wno-pedantic -pedantic-errors -pedantic)
 
+# FIXME: this is cribbed from HandleLLVMOptions.cmake.
+if(LIBCXX_STANDALONE_BUILD)
+  # Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
+  # build might work on ELF but fail on MachO/COFF.
+  if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR WIN32 OR CYGWIN OR
+  ${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR
+  ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") AND
+ NOT LLVM_USE_SANITIZER)
+set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
+  endif()
+endif()
+
 # Required flags ==
 set(LIBCXX_STANDARD_VER c++11 CACHE INTERNAL "internal option to change build dialect")
 add_compile_flags_if_supported(-std=${LIBCXX_STANDARD_VER})
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D22834: Added 'inline' attribute to basic_string's destructor

2019-10-07 Thread Aditya Kumar via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb839888af8f2: Added 'inline' attribute to 
basic_string's destructor (authored by hiraditya).
Herald added subscribers: libcxx-commits, christof.
Herald added a project: libc++.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D22834

Files:
  libcxx/include/string


Index: libcxx/include/string
===
--- libcxx/include/string
+++ libcxx/include/string
@@ -1798,6 +1798,7 @@
 #endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
 
 template 
+inline _LIBCPP_INLINE_VISIBILITY
 basic_string<_CharT, _Traits, _Allocator>::~basic_string()
 {
 #if _LIBCPP_DEBUG_LEVEL >= 2


Index: libcxx/include/string
===
--- libcxx/include/string
+++ libcxx/include/string
@@ -1798,6 +1798,7 @@
 #endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
 
 template 
+inline _LIBCPP_INLINE_VISIBILITY
 basic_string<_CharT, _Traits, _Allocator>::~basic_string()
 {
 #if _LIBCPP_DEBUG_LEVEL >= 2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr.
Herald added a project: clang.

`toString` generates a string representation of the stencil.

Patch by Harshal T. Lehri.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68574

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -389,4 +389,59 @@
   auto S2 = cat(run(F));
   EXPECT_NE(S1, S2);
 }
+
+TEST(StencilToStringTest, RawTextOp) {
+  auto S = cat("foo bar baz");
+  EXPECT_EQ(S.toString(), R"("foo bar baz")");
+}
+
+TEST(StencilToStringTest, RawTextOpEscaping) {
+  auto S = cat("foo \"bar\" baz\\n");
+  EXPECT_EQ(S.toString(), R"("foo \"bar\" baz\\n")");
+}
+
+TEST(StencilToStringTest, DebugPrintNodeOp) {
+  auto S = cat(dPrint("Id"));
+  EXPECT_EQ(S.toString(), R"repr(dPrint("Id"))repr");
+}
+
+TEST(StencilToStringTest, ExpressionOp) {
+  auto S = cat(expression("Id"));
+  EXPECT_EQ(S.toString(), R"repr(expression("Id"))repr");
+}
+
+TEST(StencilToStringTest, DerefOp) {
+  auto S = cat(deref("Id"));
+  EXPECT_EQ(S.toString(), R"repr(deref("Id"))repr");
+}
+
+TEST(StencilToStringTest, AddressOfOp) {
+  auto S = cat(addressOf("Id"));
+  EXPECT_EQ(S.toString(), R"repr(addressOf("Id"))repr");
+}
+
+TEST(StencilToStringTest, AccessOp) {
+  auto S = cat(access("Id", text("memberData")));
+  EXPECT_EQ(S.toString(), R"repr(access("Id", "memberData"))repr");
+}
+
+TEST(StencilToStringTest, AccessOpStencilPart) {
+  auto S = cat(access("Id", access("subId", "memberData")));
+  EXPECT_EQ(S.toString(),
+R"repr(access("Id", access("subId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, IfBoundOp) {
+  auto S = cat(ifBound("Id", text("trueText"), access("exprId", "memberData")));
+  EXPECT_EQ(
+  S.toString(),
+  R"repr(ifBound("Id", "trueText", access("exprId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, MultipleOp) {
+  auto S = cat("foo", access("x", "m()"), "bar",
+   ifBound("x", text("t"), access("e", "f")));
+  EXPECT_EQ(S.toString(), R"repr("foo", access("x", "m()"), "bar", )repr"
+  R"repr(ifBound("x", "t", access("e", "f")))repr");
+}
 } // namespace
Index: clang/lib/Tooling/Refactoring/Stencil.cpp
===
--- clang/lib/Tooling/Refactoring/Stencil.cpp
+++ clang/lib/Tooling/Refactoring/Stencil.cpp
@@ -15,6 +15,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring/SourceCode.h"
 #include "clang/Tooling/Refactoring/SourceCodeBuilders.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/Errc.h"
 #include 
 #include 
@@ -128,6 +129,54 @@
   return false;
 }
 
+std::string toStringData(const RawTextData &Data) {
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  OS << "\"";
+  OS.write_escaped(Data.Text);
+  OS << "\"";
+  OS.flush();
+  return Result;
+}
+
+std::string toStringData(const DebugPrintNodeData &Data) {
+  return (llvm::Twine("dPrint(\"") + Data.Id + "\")").str();
+}
+
+std::string toStringData(const UnaryOperationData &Data) {
+  StringRef OpName;
+  switch (Data.Op) {
+  case UnaryNodeOperator::Parens:
+OpName = "expression";
+break;
+  case UnaryNodeOperator::Deref:
+OpName = "deref";
+break;
+  case UnaryNodeOperator::Address:
+OpName = "addressOf";
+break;
+  }
+  return (OpName + "(\"" + Data.Id + "\")").str();
+}
+
+std::string toStringData(const SelectorData &) { return "SelectorData()"; }
+
+std::string toStringData(const AccessData &Data) {
+  return (llvm::Twine("access(\"") + Data.BaseId + "\", " +
+  Data.Member.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const IfBoundData &Data) {
+  return (llvm::Twine("ifBound(\"") + Data.Id + "\", " +
+  Data.TruePart.toString() + ", " + Data.FalsePart.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const MatchConsumer &) {
+  return "MatchConsumer()";
+}
+
 // The `evalData()` overloads evaluate the given stencil data to a string, given
 // the match result, and append it to `Result`. We define an overload for each
 // type of stencil data.
@@ -247,6 +296,10 @@
   return isEqualData(Data, OtherPtr->Data);
 return false;
   }
+
+  std::string toString() const override {
+return toStringData(Data);
+  }
 };
 } // namespace
 
Index: clang/include/clang/Tooling/Refactoring/Stencil.h
===
--- clang/include/clang/Tooling/Refactoring/Stencil.h
+++ clang/include/clang/Tooling/Refactoring/Stencil.h
@@ -50,6 +50,11 @@
 
   virtual bool isEqual(const StencilPartInterface &other) const = 0;
 
+  // Returns a string representation for the StencilPart. StencilParts

[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 223566.
ymandel added a comment.

clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68574

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -389,4 +389,59 @@
   auto S2 = cat(run(F));
   EXPECT_NE(S1, S2);
 }
+
+TEST(StencilToStringTest, RawTextOp) {
+  auto S = cat("foo bar baz");
+  EXPECT_EQ(S.toString(), R"("foo bar baz")");
+}
+
+TEST(StencilToStringTest, RawTextOpEscaping) {
+  auto S = cat("foo \"bar\" baz\\n");
+  EXPECT_EQ(S.toString(), R"("foo \"bar\" baz\\n")");
+}
+
+TEST(StencilToStringTest, DebugPrintNodeOp) {
+  auto S = cat(dPrint("Id"));
+  EXPECT_EQ(S.toString(), R"repr(dPrint("Id"))repr");
+}
+
+TEST(StencilToStringTest, ExpressionOp) {
+  auto S = cat(expression("Id"));
+  EXPECT_EQ(S.toString(), R"repr(expression("Id"))repr");
+}
+
+TEST(StencilToStringTest, DerefOp) {
+  auto S = cat(deref("Id"));
+  EXPECT_EQ(S.toString(), R"repr(deref("Id"))repr");
+}
+
+TEST(StencilToStringTest, AddressOfOp) {
+  auto S = cat(addressOf("Id"));
+  EXPECT_EQ(S.toString(), R"repr(addressOf("Id"))repr");
+}
+
+TEST(StencilToStringTest, AccessOp) {
+  auto S = cat(access("Id", text("memberData")));
+  EXPECT_EQ(S.toString(), R"repr(access("Id", "memberData"))repr");
+}
+
+TEST(StencilToStringTest, AccessOpStencilPart) {
+  auto S = cat(access("Id", access("subId", "memberData")));
+  EXPECT_EQ(S.toString(),
+R"repr(access("Id", access("subId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, IfBoundOp) {
+  auto S = cat(ifBound("Id", text("trueText"), access("exprId", "memberData")));
+  EXPECT_EQ(
+  S.toString(),
+  R"repr(ifBound("Id", "trueText", access("exprId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, MultipleOp) {
+  auto S = cat("foo", access("x", "m()"), "bar",
+   ifBound("x", text("t"), access("e", "f")));
+  EXPECT_EQ(S.toString(), R"repr("foo", access("x", "m()"), "bar", )repr"
+  R"repr(ifBound("x", "t", access("e", "f")))repr");
+}
 } // namespace
Index: clang/lib/Tooling/Refactoring/Stencil.cpp
===
--- clang/lib/Tooling/Refactoring/Stencil.cpp
+++ clang/lib/Tooling/Refactoring/Stencil.cpp
@@ -15,6 +15,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring/SourceCode.h"
 #include "clang/Tooling/Refactoring/SourceCodeBuilders.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/Errc.h"
 #include 
 #include 
@@ -128,6 +129,54 @@
   return false;
 }
 
+std::string toStringData(const RawTextData &Data) {
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  OS << "\"";
+  OS.write_escaped(Data.Text);
+  OS << "\"";
+  OS.flush();
+  return Result;
+}
+
+std::string toStringData(const DebugPrintNodeData &Data) {
+  return (llvm::Twine("dPrint(\"") + Data.Id + "\")").str();
+}
+
+std::string toStringData(const UnaryOperationData &Data) {
+  StringRef OpName;
+  switch (Data.Op) {
+  case UnaryNodeOperator::Parens:
+OpName = "expression";
+break;
+  case UnaryNodeOperator::Deref:
+OpName = "deref";
+break;
+  case UnaryNodeOperator::Address:
+OpName = "addressOf";
+break;
+  }
+  return (OpName + "(\"" + Data.Id + "\")").str();
+}
+
+std::string toStringData(const SelectorData &) { return "SelectorData()"; }
+
+std::string toStringData(const AccessData &Data) {
+  return (llvm::Twine("access(\"") + Data.BaseId + "\", " +
+  Data.Member.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const IfBoundData &Data) {
+  return (llvm::Twine("ifBound(\"") + Data.Id + "\", " +
+  Data.TruePart.toString() + ", " + Data.FalsePart.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const MatchConsumer &) {
+  return "MatchConsumer()";
+}
+
 // The `evalData()` overloads evaluate the given stencil data to a string, given
 // the match result, and append it to `Result`. We define an overload for each
 // type of stencil data.
@@ -247,6 +296,8 @@
   return isEqualData(Data, OtherPtr->Data);
 return false;
   }
+
+  std::string toString() const override { return toStringData(Data); }
 };
 } // namespace
 
Index: clang/include/clang/Tooling/Refactoring/Stencil.h
===
--- clang/include/clang/Tooling/Refactoring/Stencil.h
+++ clang/include/clang/Tooling/Refactoring/Stencil.h
@@ -50,6 +50,11 @@
 
   virtual bool isEqual(const StencilPartInterface &other) const = 0;
 
+  // Returns a string representation for the StencilPart. StencilParts generated
+  // by the `selection` and `run `f

[PATCH] D20561: Warn when taking address of packed member

2019-10-07 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf7b9f3149b76: Add missing tests (authored by rogfer01).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D20561?vs=67807&id=223564#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D20561

Files:
  clang/test/Sema/address-packed-member-memops.c
  clang/test/Sema/address-packed.c
  clang/test/SemaCXX/address-packed-member-memops.cpp
  clang/test/SemaCXX/address-packed.cpp

Index: clang/test/SemaCXX/address-packed.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/address-packed.cpp
@@ -0,0 +1,114 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
+extern void f1(int *);
+extern void f2(char *);
+
+struct __attribute__((packed)) Arguable {
+  int x;
+  char c;
+  static void foo();
+};
+
+extern void f3(void());
+
+namespace Foo {
+struct __attribute__((packed)) Arguable {
+  char c;
+  int x;
+  static void foo();
+};
+}
+
+struct Arguable *get_arguable();
+
+void f4(int &);
+
+void to_void(void *);
+
+template 
+void sink(T...);
+
+void g0() {
+  {
+Foo::Arguable arguable;
+f1(&arguable.x);   // expected-warning {{packed member 'x' of class or structure 'Foo::Arguable'}}
+f2(&arguable.c);   // no-warning
+f3(&arguable.foo); // no-warning
+
+to_void(&arguable.x); // no-warning
+void *p1 = &arguable.x;   // no-warning
+void *p2 = static_cast(&arguable.x);  // no-warning
+void *p3 = reinterpret_cast(&arguable.x); // no-warning
+void *p4 = (void *)&arguable.x;   // no-warning
+sink(p1, p2, p3, p4);
+  }
+  {
+Arguable arguable1;
+Arguable &arguable(arguable1);
+f1(&arguable.x);   // expected-warning {{packed member 'x' of class or structure 'Arguable'}}
+f2(&arguable.c);   // no-warning
+f3(&arguable.foo); // no-warning
+  }
+  {
+Arguable *arguable1;
+Arguable *&arguable(arguable1);
+f1(&arguable->x);   // expected-warning {{packed member 'x' of class or structure 'Arguable'}}
+f2(&arguable->c);   // no-warning
+f3(&arguable->foo); // no-warning
+  }
+}
+
+struct __attribute__((packed)) A {
+  int x;
+  char c;
+
+  int *f0() {
+return &this->x; // expected-warning {{packed member 'x' of class or structure 'A'}}
+  }
+
+  int *g0() {
+return &x; // expected-warning {{packed member 'x' of class or structure 'A'}}
+  }
+
+  char *h0() {
+return &c; // no-warning
+  }
+};
+
+struct B : A {
+  int *f1() {
+return &this->x; // expected-warning {{packed member 'x' of class or structure 'A'}}
+  }
+
+  int *g1() {
+return &x; // expected-warning {{packed member 'x' of class or structure 'A'}}
+  }
+
+  char *h1() {
+return &c; // no-warning
+  }
+};
+
+template 
+class __attribute__((packed)) S {
+  Ty X;
+
+public:
+  const Ty *get() const {
+return &X; // expected-warning {{packed member 'X' of class or structure 'S'}}
+   // expected-warning@-1 {{packed member 'X' of class or structure 'S'}}
+  }
+};
+
+template 
+void h(Ty *);
+
+void g1() {
+  S s1;
+  s1.get(); // expected-note {{in instantiation of member function 'S::get'}}
+
+  S s2;
+  s2.get();
+
+  S s3;
+  s3.get(); // expected-note {{in instantiation of member function 'S::get'}}
+}
Index: clang/test/SemaCXX/address-packed-member-memops.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/address-packed-member-memops.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+struct B {
+  int x, y, z, w;
+} b;
+
+struct __attribute__((packed)) A {
+  struct B b;
+} a;
+
+typedef __typeof__(sizeof(int)) size_t;
+
+extern "C" {
+void *memcpy(void *dest, const void *src, size_t n);
+int memcmp(const void *s1, const void *s2, size_t n);
+void *memmove(void *dest, const void *src, size_t n);
+void *memset(void *s, int c, size_t n);
+}
+
+int x;
+
+void foo() {
+  memcpy(&a.b, &b, sizeof(b));
+  memmove(&a.b, &b, sizeof(b));
+  memset(&a.b, 0, sizeof(b));
+  x = memcmp(&a.b, &b, sizeof(b));
+}
Index: clang/test/Sema/address-packed.c
===
--- /dev/null
+++ clang/test/Sema/address-packed.c
@@ -0,0 +1,163 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+#include 
+
+extern void f1(int *);
+extern void f2(char *);
+
+struct Ok {
+  char c;
+  int x;
+};
+
+struct __attribute__((packed)) Arguable {
+  char c0;
+  int x;
+  char c1;
+};
+
+union __attribute__((packed)) UnionArguable {
+  char c;
+  int x;
+};
+
+typedef struct Arguable ArguableT;
+
+struct Arguable *get_arguable();
+
+void to_void(void *);
+
+void g0(void) {
+  {
+struct Ok ok;
+f1(&ok.x); // no-warning
+f2(&ok.c); // no-warning
+  }
+  {
+struct Arguable arguable

[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 223573.
ymandel added a comment.

comment tweaks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68574

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -389,4 +389,59 @@
   auto S2 = cat(run(F));
   EXPECT_NE(S1, S2);
 }
+
+TEST(StencilToStringTest, RawTextOp) {
+  auto S = cat("foo bar baz");
+  EXPECT_EQ(S.toString(), R"("foo bar baz")");
+}
+
+TEST(StencilToStringTest, RawTextOpEscaping) {
+  auto S = cat("foo \"bar\" baz\\n");
+  EXPECT_EQ(S.toString(), R"("foo \"bar\" baz\\n")");
+}
+
+TEST(StencilToStringTest, DebugPrintNodeOp) {
+  auto S = cat(dPrint("Id"));
+  EXPECT_EQ(S.toString(), R"repr(dPrint("Id"))repr");
+}
+
+TEST(StencilToStringTest, ExpressionOp) {
+  auto S = cat(expression("Id"));
+  EXPECT_EQ(S.toString(), R"repr(expression("Id"))repr");
+}
+
+TEST(StencilToStringTest, DerefOp) {
+  auto S = cat(deref("Id"));
+  EXPECT_EQ(S.toString(), R"repr(deref("Id"))repr");
+}
+
+TEST(StencilToStringTest, AddressOfOp) {
+  auto S = cat(addressOf("Id"));
+  EXPECT_EQ(S.toString(), R"repr(addressOf("Id"))repr");
+}
+
+TEST(StencilToStringTest, AccessOp) {
+  auto S = cat(access("Id", text("memberData")));
+  EXPECT_EQ(S.toString(), R"repr(access("Id", "memberData"))repr");
+}
+
+TEST(StencilToStringTest, AccessOpStencilPart) {
+  auto S = cat(access("Id", access("subId", "memberData")));
+  EXPECT_EQ(S.toString(),
+R"repr(access("Id", access("subId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, IfBoundOp) {
+  auto S = cat(ifBound("Id", text("trueText"), access("exprId", "memberData")));
+  EXPECT_EQ(
+  S.toString(),
+  R"repr(ifBound("Id", "trueText", access("exprId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, MultipleOp) {
+  auto S = cat("foo", access("x", "m()"), "bar",
+   ifBound("x", text("t"), access("e", "f")));
+  EXPECT_EQ(S.toString(), R"repr("foo", access("x", "m()"), "bar", )repr"
+  R"repr(ifBound("x", "t", access("e", "f")))repr");
+}
 } // namespace
Index: clang/lib/Tooling/Refactoring/Stencil.cpp
===
--- clang/lib/Tooling/Refactoring/Stencil.cpp
+++ clang/lib/Tooling/Refactoring/Stencil.cpp
@@ -15,6 +15,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring/SourceCode.h"
 #include "clang/Tooling/Refactoring/SourceCodeBuilders.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/Errc.h"
 #include 
 #include 
@@ -128,6 +129,54 @@
   return false;
 }
 
+std::string toStringData(const RawTextData &Data) {
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  OS << "\"";
+  OS.write_escaped(Data.Text);
+  OS << "\"";
+  OS.flush();
+  return Result;
+}
+
+std::string toStringData(const DebugPrintNodeData &Data) {
+  return (llvm::Twine("dPrint(\"") + Data.Id + "\")").str();
+}
+
+std::string toStringData(const UnaryOperationData &Data) {
+  StringRef OpName;
+  switch (Data.Op) {
+  case UnaryNodeOperator::Parens:
+OpName = "expression";
+break;
+  case UnaryNodeOperator::Deref:
+OpName = "deref";
+break;
+  case UnaryNodeOperator::Address:
+OpName = "addressOf";
+break;
+  }
+  return (OpName + "(\"" + Data.Id + "\")").str();
+}
+
+std::string toStringData(const SelectorData &) { return "SelectorData()"; }
+
+std::string toStringData(const AccessData &Data) {
+  return (llvm::Twine("access(\"") + Data.BaseId + "\", " +
+  Data.Member.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const IfBoundData &Data) {
+  return (llvm::Twine("ifBound(\"") + Data.Id + "\", " +
+  Data.TruePart.toString() + ", " + Data.FalsePart.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const MatchConsumer &) {
+  return "MatchConsumer()";
+}
+
 // The `evalData()` overloads evaluate the given stencil data to a string, given
 // the match result, and append it to `Result`. We define an overload for each
 // type of stencil data.
@@ -247,6 +296,8 @@
   return isEqualData(Data, OtherPtr->Data);
 return false;
   }
+
+  std::string toString() const override { return toStringData(Data); }
 };
 } // namespace
 
Index: clang/include/clang/Tooling/Refactoring/Stencil.h
===
--- clang/include/clang/Tooling/Refactoring/Stencil.h
+++ clang/include/clang/Tooling/Refactoring/Stencil.h
@@ -50,6 +50,11 @@
 
   virtual bool isEqual(const StencilPartInterface &other) const = 0;
 
+  /// Constructs a string representation of the StencilPart. StencilParts
+  /// generated by the `selection` and `

r373904 - AST - silence static analyzer getAs<> null dereference warnings. NFCI.

2019-10-07 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Mon Oct  7 06:58:05 2019
New Revision: 373904

URL: http://llvm.org/viewvc/llvm-project?rev=373904&view=rev
Log:
AST - silence static analyzer getAs<> null dereference warnings. NFCI.

The static analyzer is warning about potential null dereferences, but in these 
cases we should be able to use castAs<> directly and if not assert will fire 
for us.

Modified:
cfe/trunk/lib/AST/ExprCXX.cpp
cfe/trunk/lib/AST/Interp/Program.cpp
cfe/trunk/lib/AST/Mangle.cpp
cfe/trunk/lib/AST/StmtPrinter.cpp
cfe/trunk/lib/AST/TemplateBase.cpp
cfe/trunk/lib/AST/TypePrinter.cpp

Modified: cfe/trunk/lib/AST/ExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprCXX.cpp?rev=373904&r1=373903&r2=373904&view=diff
==
--- cfe/trunk/lib/AST/ExprCXX.cpp (original)
+++ cfe/trunk/lib/AST/ExprCXX.cpp Mon Oct  7 06:58:05 2019
@@ -251,7 +251,7 @@ QualType CXXDeleteExpr::getDestroyedType
   if (ArgType->isDependentType() && !ArgType->isPointerType())
 return QualType();
 
-  return ArgType->getAs()->getPointeeType();
+  return ArgType->castAs()->getPointeeType();
 }
 
 // CXXPseudoDestructorExpr
@@ -1512,11 +1512,8 @@ CXXRecordDecl *UnresolvedMemberExpr::get
   // Otherwise the naming class must have been the base class.
   else {
 QualType BaseType = getBaseType().getNonReferenceType();
-if (isArrow()) {
-  const auto *PT = BaseType->getAs();
-  assert(PT && "base of arrow member access is not pointer");
-  BaseType = PT->getPointeeType();
-}
+if (isArrow())
+  BaseType = BaseType->castAs()->getPointeeType();
 
 Record = BaseType->getAsCXXRecordDecl();
 assert(Record && "base of member expression does not name record");

Modified: cfe/trunk/lib/AST/Interp/Program.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Interp/Program.cpp?rev=373904&r1=373903&r2=373904&view=diff
==
--- cfe/trunk/lib/AST/Interp/Program.cpp (original)
+++ cfe/trunk/lib/AST/Interp/Program.cpp Mon Oct  7 06:58:05 2019
@@ -123,7 +123,7 @@ llvm::Optional Program::getOrC
   auto &ASTCtx = Ctx.getASTContext();
 
   // Create a pointer to an incomplete array of the specified elements.
-  QualType ElemTy = PD->getType()->getAs()->getPointeeType();
+  QualType ElemTy = PD->getType()->castAs()->getPointeeType();
   QualType Ty = ASTCtx.getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
 
   // Dedup blocks since they are immutable and pointers cannot be compared.

Modified: cfe/trunk/lib/AST/Mangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Mangle.cpp?rev=373904&r1=373903&r2=373904&view=diff
==
--- cfe/trunk/lib/AST/Mangle.cpp (original)
+++ cfe/trunk/lib/AST/Mangle.cpp Mon Oct  7 06:58:05 2019
@@ -386,7 +386,7 @@ public:
 auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
   auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
  /*IsCXXMethod=*/true);
-  auto CC = MD->getType()->getAs()->getCallConv();
+  auto CC = MD->getType()->castAs()->getCallConv();
   return CC == DefaultCC;
 };
 

Modified: cfe/trunk/lib/AST/StmtPrinter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/StmtPrinter.cpp?rev=373904&r1=373903&r2=373904&view=diff
==
--- cfe/trunk/lib/AST/StmtPrinter.cpp (original)
+++ cfe/trunk/lib/AST/StmtPrinter.cpp Mon Oct  7 06:58:05 2019
@@ -1102,7 +1102,7 @@ void StmtPrinter::VisitIntegerLiteral(In
   OS << Node->getValue().toString(10, isSigned);
 
   // Emit suffixes.  Integer literals are always a builtin integer type.
-  switch (Node->getType()->getAs()->getKind()) {
+  switch (Node->getType()->castAs()->getKind()) {
   default: llvm_unreachable("Unexpected type for integer literal!");
   case BuiltinType::Char_S:
   case BuiltinType::Char_U:OS << "i8"; break;
@@ -1123,7 +1123,7 @@ void StmtPrinter::VisitFixedPointLiteral
 return;
   OS << Node->getValueAsString(/*Radix=*/10);
 
-  switch (Node->getType()->getAs()->getKind()) {
+  switch (Node->getType()->castAs()->getKind()) {
 default: llvm_unreachable("Unexpected type for fixed point literal!");
 case BuiltinType::ShortFract:   OS << "hr"; break;
 case BuiltinType::ShortAccum:   OS << "hk"; break;
@@ -1152,7 +1152,7 @@ static void PrintFloatingLiteral(raw_ost
 return;
 
   // Emit suffixes.  Float literals are always a builtin float type.
-  switch (Node->getType()->getAs()->getKind()) {
+  switch (Node->getType()->castAs()->getKind()) {
   default: llvm_unreachable("Unexpected type for float literal!");
   case BuiltinType::Half:   break; // FIXME: suffix?
   case BuiltinType::Double: break; // no suffix.
@@ -1

r373905 - RewriteModernObjC - silence static analyzer getAs<> null dereference warnings. NFCI.

2019-10-07 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Mon Oct  7 06:58:15 2019
New Revision: 373905

URL: http://llvm.org/viewvc/llvm-project?rev=373905&view=rev
Log:
RewriteModernObjC - silence static analyzer getAs<> null dereference warnings. 
NFCI.

The static analyzer is warning about potential null dereferences, but in these 
cases we should be able to use castAs<> directly and if not assert will fire 
for us.

Modified:
cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp

Modified: cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp?rev=373905&r1=373904&r2=373905&view=diff
==
--- cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp (original)
+++ cfe/trunk/lib/Frontend/Rewrite/RewriteModernObjC.cpp Mon Oct  7 06:58:15 
2019
@@ -2752,7 +2752,7 @@ Stmt *RewriteModernObjC::RewriteObjCArra
 
   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
   ObjCInterfaceDecl *Class =
-expType->getPointeeType()->getAs()->getInterface();
+expType->getPointeeType()->castAs()->getInterface();
 
   IdentifierInfo *clsName = Class->getIdentifier();
   ClsExprs.push_back(getStringLiteral(clsName->getName()));
@@ -2806,7 +2806,7 @@ Stmt *RewriteModernObjC::RewriteObjCArra
   // Don't forget the parens to enforce the proper binding.
   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
 
-  const FunctionType *FT = msgSendType->getAs();
+  const FunctionType *FT = msgSendType->castAs();
   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
   VK_RValue, EndLoc);
   ReplaceStmt(Exp, CE);
@@ -2894,7 +2894,7 @@ Stmt *RewriteModernObjC::RewriteObjCDict
 
   // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
   ObjCInterfaceDecl *Class =
-  expType->getPointeeType()->getAs()->getInterface();
+  expType->getPointeeType()->castAs()->getInterface();
 
   IdentifierInfo *clsName = Class->getIdentifier();
   ClsExprs.push_back(getStringLiteral(clsName->getName()));
@@ -2957,7 +2957,7 @@ Stmt *RewriteModernObjC::RewriteObjCDict
   // Don't forget the parens to enforce the proper binding.
   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
 
-  const FunctionType *FT = msgSendType->getAs();
+  const FunctionType *FT = msgSendType->castAs();
   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
   VK_RValue, EndLoc);
   ReplaceStmt(Exp, CE);
@@ -3309,7 +3309,7 @@ Stmt *RewriteModernObjC::SynthMessageExp
   case ObjCMessageExpr::Class: {
 SmallVector ClsExprs;
 ObjCInterfaceDecl *Class
-  = Exp->getClassReceiver()->getAs()->getInterface();
+  = Exp->getClassReceiver()->castAs()->getInterface();
 IdentifierInfo *clsName = Class->getIdentifier();
 ClsExprs.push_back(getStringLiteral(clsName->getName()));
 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, 
ClsExprs,
@@ -3530,7 +3530,7 @@ Stmt *RewriteModernObjC::SynthMessageExp
   // Don't forget the parens to enforce the proper binding.
   ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
 
-  const FunctionType *FT = msgSendType->getAs();
+  const FunctionType *FT = msgSendType->castAs();
   CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
   VK_RValue, EndLoc);
   Stmt *ReplacingStmt = CE;
@@ -3660,7 +3660,7 @@ bool RewriteModernObjC::RewriteObjCField
 }
   }
   else if (Type->isEnumeralType()) {
-EnumDecl *ED = Type->getAs()->getDecl();
+EnumDecl *ED = Type->castAs()->getDecl();
 if (ED->isCompleteDefinition()) {
   Result += "\n\tenum ";
   Result += ED->getName();


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


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D67536#1694098 , @MaskRay wrote:

> Why "inactive region", not "skipped ranges"?


I got the name from "$cquery/publishInactiveRegions" :) But I don't 
particularly care what we call it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 223577.
nridge added a comment.

Update to use `PPCallbacks::SourceRangeSkipped`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536

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

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
@@ -50,6 +50,9 @@
 # CHECK-NEXT:"storage.type.primitive.cpp"
 # CHECK-NEXT:  ],
 # CHECK-NEXT:  [
+# CHECK-NEXT:"meta.disabled"
+# CHECK-NEXT:  ],
+# CHECK-NEXT:  [
 # CHECK-NEXT:"entity.name.function.preprocessor.cpp"
 # CHECK-NEXT:  ]
 # CHECK-NEXT:]
Index: clang-tools-extra/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/clangd/SemanticHighlighting.h
+++ clang-tools-extra/clangd/SemanticHighlighting.h
@@ -41,8 +41,9 @@
   TemplateParameter,
   Primitive,
   Macro,
+  InactiveCode,
 
-  LastKind = Macro
+  LastKind = InactiveCode
 };
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, HighlightingKind K);
 
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -137,6 +137,27 @@
   // the end of the Tokens).
   TokRef = TokRef.drop_front(Conflicting.size());
 }
+// Add inactive highlighting tokens.
+const SourceManager &SM = AST.getSourceManager();
+for (const SourceRange &R : AST.getSkippedRanges()) {
+  if (isInsideMainFile(R.getBegin(), SM)) {
+// Create one token for each line in the skipped range, so it works
+// with line-based diffing.
+Position Begin = sourceLocToPosition(SM, R.getBegin());
+Position End = sourceLocToPosition(SM, R.getEnd());
+assert(Begin.line <= End.line);
+for (int Line = Begin.line; Line < End.line; ++Line) {
+  // Don't bother computing the offset for the end of the line, just use
+  // zero. The client will treat this highlighting kind specially, and
+  // highlight the entire line visually (i.e. not just to where the text
+  // on the line ends, but to the end of the screen).
+  NonConflicting.push_back({HighlightingKind::InactiveCode,
+{Position{Line, 0}, Position{Line, 0}}});
+}
+  }
+}
+// Re-sort the tokens because that's what the diffing expects.
+llvm::sort(NonConflicting);
 return NonConflicting;
   }
 
@@ -347,6 +368,8 @@
 return OS << "Primitive";
   case HighlightingKind::Macro:
 return OS << "Macro";
+  case HighlightingKind::InactiveCode:
+return OS << "InactiveCode";
   }
   llvm_unreachable("invalid HighlightingKind");
 }
@@ -476,6 +499,8 @@
 return "storage.type.primitive.cpp";
   case HighlightingKind::Macro:
 return "entity.name.function.preprocessor.cpp";
+  case HighlightingKind::InactiveCode:
+return "meta.disabled";
   }
   llvm_unreachable("unhandled HighlightingKind");
 }
Index: clang-tools-extra/clangd/ParsedAST.h
===
--- clang-tools-extra/clangd/ParsedAST.h
+++ clang-tools-extra/clangd/ParsedAST.h
@@ -97,13 +97,18 @@
   /// (!) does not have tokens from the preamble.
   const syntax::TokenBuffer &getTokens() const { return Tokens; }
 
+  const std::vector &getSkippedRanges() const {
+return SkippedRanges;
+  }
+
 private:
   ParsedAST(std::shared_ptr Preamble,
 std::unique_ptr Clang,
 std::unique_ptr Action, syntax::TokenBuffer Tokens,
 MainFileMacros Macros, std::vector LocalTopLevelDecls,
 std::vector Diags, IncludeStructure Includes,
-CanonicalIncludes CanonIncludes);
+CanonicalIncludes CanonIncludes,
+std::vector SkippedRanges);
 
   // In-memory preambles must outlive the AST, it is important that this member
   // goes before Clang and Action.
@@ -130,6 +135,8 @@
   std::vector LocalTopLevelDecls;
   IncludeStructure Includes;
   CanonicalIncludes CanonIncludes;
+  // Ranges skipped during preprocessing.
+  std::vector SkippedRanges;
 };
 
 /// Build an AST from provided user inputs. This function does not check if
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ 

[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

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



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:140
 }
+// Add inactive highlighting tokens.
+const SourceManager &SM = AST.getSourceManager();

I think this comment could be clearer, e.g. // Add tokens indicating lines 
skipped by the preprocessor.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:152
+  // Don't bother computing the offset for the end of the line, just 
use
+  // zero. The client will treat this highlighting kind specially, and
+  // highlight the entire line visually (i.e. not just to where the 
text

nridge wrote:
> hokein wrote:
> > This seems too couple with VSCode client, I would prefer to calculate the 
> > range of the line and return to the client.
> > 
> > Is there any big differences in VSCode between highlighting with the 
> > `isWholeLine` and highlighting with the range of the line? 
> I took some screenshots to illustrate to difference.
> 
> Highlighting only to the end of the line of text:
> 
> {F10158508}
> 
> Highlighting the whole line:
> 
> {F10158515}
> 
> I think the first one looks pretty bad, and is inconsistent with existing 
> practice.
> 
> Note also that the suggestion is not to special-case the VSCode client 
> specifically; it's to special-case one particular highlighting, which any 
> client can implement.
> 
> If this special-casing is really unpalatable, we could instead try this 
> suggestion by @sammccall:
> 
> > Failing that, I'd suggest encoding a list of line-styles on 
> > SemanticHighlightingInformation, that should be combined with any tokens on 
> > that line.
> 
> I guess one consideration when evaluating these options is, do we expect to 
> use that "list of line-styles" for anything else in the future? I can't think 
> of anything at the moment, but perhaps there are other uses for it.
> 
> If not, we could do something slightly simpler, and add a single `isInactive` 
> flag to `SemanticHighlightingInformation`.
Three approaches seem feasible here:
1. clients that know about the specific scope can extend it to the whole line. 
2. [0,0) or so indicates "highlight the whole line"
3. use a dedicated property for line styles (vs token styles)

3 is clearly better than 2 I think, it's more explicit. I don't have a strong 
opinion of 1 vs 3, but if going with 1 I think it's a good idea to measure the 
line as Haojian says, so we at least get a basic version of the feature if the 
client doesn't know about line styles.

> I guess one consideration when evaluating these options is, do we expect to 
> use that "list of line-styles" for anything else in the future? I can't think 
> of anything at the moment
Preprocessor directives maybe? (Though these are easy enough for clients to 
highlight with regex)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D67837: [CUDA][HIP] Fix host/device check with -fopenmp

2019-10-07 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Sema/SemaCUDA.cpp:604
 // Do we know that we will eventually codegen the given function?
 static bool IsKnownEmitted(Sema &S, FunctionDecl *FD) {
+  return S.getEmissionStatus(FD) == Sema::FunctionEmissionStatus::Emitted;

I believe this function can be removed



Comment at: lib/Sema/SemaDecl.cpp:17619
+
+  auto OMPES = FunctionEmissionStatus::Unknown;
+  if (LangOpts.OpenMPIsDevice) {

Better to use real type here, not `auto`



Comment at: lib/Sema/SemaDecl.cpp:17623-17626
+if (DevTy.hasValue())
+  OMPES = (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
+   ? FunctionEmissionStatus::OMPDiscarded
+   : FunctionEmissionStatus::Emitted;

Enclose in braces



Comment at: lib/Sema/SemaDecl.cpp:17626
+   ? FunctionEmissionStatus::OMPDiscarded
+   : FunctionEmissionStatus::Emitted;
+  } else if (LangOpts.OpenMP) {

Hmm, it must be marked as know-emitted only if 
`S.DeviceKnownEmittedFns.count(FD) > 0`. Otherwise, it must be unknown.



Comment at: lib/Sema/SemaDecl.cpp:17629-17631
+if (LangOpts.OpenMP <= 45)
+  OMPES = FunctionEmissionStatus::Emitted;
+else {

Enclose in braces, not goo to have `else` branch enclosed in braces and `then` 
branch without.



Comment at: lib/Sema/SemaDecl.cpp:17641
+ ? FunctionEmissionStatus::OMPDiscarded
+ : FunctionEmissionStatus::Emitted;
+}

Same here, it must be marked as know-emitted only if 
`S.DeviceKnownEmittedFns.count(FD) > 0`. Otherwise, it must be unknown.



Comment at: lib/Sema/SemaDecl.cpp:17684-17689
+  // If we have
+  //   host fn calls kernel fn calls host+device,
+  // the HD function does not get instantiated on the host.  We model this by
+  // omitting at the call to the kernel from the callgraph.  This ensures
+  // that, when compiling for host, only HD functions actually called from the
+  // host get marked as known-emitted.

Reformat the comment here



Comment at: lib/Sema/SemaOpenMP.cpp:1629-1630
+auto CalleeS = getEmissionStatus(Callee);
+assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
+   CallerS != FunctionEmissionStatus::CUDADiscarded &&
+   "CUDADiscarded unexpected in OpenMP device function check");

The same condition is checked twice, one of them must be for `CalleeS`, I 
believe



Comment at: lib/Sema/SemaOpenMP.cpp:1674
+(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
+   CallerS != FunctionEmissionStatus::CUDADiscarded)) 
&&
+"CUDADiscarded unexpected in OpenMP host function check");

Again, the same condition checked twice.


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

https://reviews.llvm.org/D67837



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


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked 5 inline comments as done.
nridge added inline comments.



Comment at: clang-tools-extra/clangd/Compiler.cpp:66
   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
+  CI->getPreprocessorOpts().DetailedRecord = true;
   return CI;

ilya-biryukov wrote:
> hokein wrote:
> > I'm not sure how does this flag impact the size of Preamble/AST, 
> > @ilya-biryukov any thoughts?
> Have no idea, but why do we need this in the first place?
> `PPCallbacks::SourceRangeSkipped` should allow to record all skipped ranges 
> in the main file. Can we use it?
Yes, `PPCallbacks::SourceRangeSkipped` works in place of using 
`DetailedRecord`. Thank you for the suggestion.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.h:43
   Primitive,
+  InactivePreprocessorBranch,
   Macro,

hokein wrote:
> This is a different kind group, I would put it after the Macro,  we'd need to 
> update the LastKind. 
> 
> The name seems too specific, how about "UnreachableCode"?
I changed it to "InactiveCode". ("Unreachable" seemed like the wrong word, it 
brings to mind control flow.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked 2 inline comments as done.
nridge added a comment.

How would one even measure the line length? `SourceManager` doesn't sem to have 
a method like `getLineLength()` or similar.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D68213: [LTO] Support for embedding bitcode section during LTO

2019-10-07 Thread Josef Eisl via Phabricator via cfe-commits
zapster added a comment.

(ping)


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

https://reviews.llvm.org/D68213



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


[PATCH] D68562: [clangd] Add RemoveUsingNamespace tweak.

2019-10-07 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 223592.
usaxena95 marked 3 inline comments as done.
usaxena95 added a comment.

Make the tweak trigger only for TopLevelDecl.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68562

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.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
@@ -69,7 +69,8 @@
   EXPECT_EQ(apply("^if (true) {return 100;} else {continue;}"),
 "if (true) {continue;} else {return 100;}");
   EXPECT_EQ(apply("^if () {return 100;} else {continue;}"),
-"if () {continue;} else {return 100;}") << "broken condition";
+"if () {continue;} else {return 100;}")
+  << "broken condition";
   EXPECT_AVAILABLE("^i^f^^(^t^r^u^e^) { return 100; } ^e^l^s^e^ { continue; }");
   EXPECT_UNAVAILABLE("if (true) {^return ^100;^ } else { ^continue^;^ }");
   // Available in subexpressions of the condition;
@@ -100,7 +101,7 @@
   EXPECT_UNAVAILABLE(R"cpp(R"(multi )" ^"token " u8"str\ning")cpp"); // nonascii
   EXPECT_UNAVAILABLE(R"cpp(^R^"^(^multi )" "token " "str\ning")cpp"); // raw
   EXPECT_UNAVAILABLE(R"cpp(^"token\n" __FILE__)cpp"); // chunk is macro
-  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp"); // forbidden escape char
+  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp");   // forbidden escape char
 
   const char *Input = R"cpp(R"(multi
 token)" "\nst^ring\n" "literal")cpp";
@@ -286,11 +287,11 @@
  void f(int a) {
int y = PLUS([[1+a]]);
  })cpp",
-  /*FIXME: It should be extracted like this.
-   R"cpp(#define PLUS(x) x++
- void f(int a) {
-   auto dummy = 1+a; int y = PLUS(dummy);
- })cpp"},*/
+   /*FIXME: It should be extracted like this.
+R"cpp(#define PLUS(x) x++
+  void f(int a) {
+auto dummy = 1+a; int y = PLUS(dummy);
+  })cpp"},*/
R"cpp(#define PLUS(x) x++
  void f(int a) {
auto dummy = PLUS(1+a); int y = dummy;
@@ -301,13 +302,13 @@
if(1)
 LOOP(5 + [[3]])
  })cpp",
-  /*FIXME: It should be extracted like this. SelectionTree needs to be
-* fixed for macros.
-   R"cpp(#define LOOP(x) while (1) {a = x;}
-   void f(int a) {
- auto dummy = 3; if(1)
-  LOOP(5 + dummy)
-   })cpp"},*/
+   /*FIXME: It should be extracted like this. SelectionTree needs to be
+ * fixed for macros.
+R"cpp(#define LOOP(x) while (1) {a = x;}
+void f(int a) {
+  auto dummy = 3; if(1)
+   LOOP(5 + dummy)
+})cpp"},*/
R"cpp(#define LOOP(x) while (1) {a = x;}
  void f(int a) {
auto dummy = LOOP(5 + 3); if(1)
@@ -403,8 +404,8 @@
  void f() {
auto dummy = S(2) + S(3) + S(4); S x = S(1) + dummy + S(5);
  })cpp"},
-   // Don't try to analyze across macro boundaries
-   // FIXME: it'd be nice to do this someday (in a safe way)
+  // Don't try to analyze across macro boundaries
+  // FIXME: it'd be nice to do this someday (in a safe way)
   {R"cpp(#define ECHO(X) X
  void f() {
int x = 1 + [[ECHO(2 + 3) + 4]] + 5;
@@ -521,7 +522,7 @@
   StartsWith("fail: Could not expand type of lambda expression"));
   // inline namespaces
   EXPECT_EQ(apply("au^to x = inl_ns::Visible();"),
-  "Visible x = inl_ns::Visible();");
+"Visible x = inl_ns::Visible();");
   // local class
   EXPECT_EQ(apply("namespace x { void y() { struct S{}; ^auto z = S(); } }"),
 "namespace x { void y() { struct S{}; S z = S(); } }");
@@ -656,6 +657,160 @@
   EXPECT_THAT(apply(" for(;;) { [[while(1) break; break;]] }"),
   StartsWith("fail"));
 }
+
+TWEAK_TEST(RemoveUsingNamespace);
+TEST_F(RemoveUsingNamespaceTest, All) {
+  std::pair Cases[] = {
+  {// Remove all occurrences of ns. Qualify only unqualified.
+   R"cpp(
+  namespace ns1 { struct vector {}; }
+  namespace ns2 { struct map {}; }
+  using namespace n^s1;
+  using namespace ns2;
+  using namespace ns1;
+  int main() {
+ns1::vector v1;
+vector v2;
+map m1;
+  }
+)cpp",
+   R"cpp(
+  namespace ns1 { struct vect

r373910 - [clang] Add test for FindNextToken in Lexer.

2019-10-07 Thread Utkarsh Saxena via cfe-commits
Author: usaxena95
Date: Mon Oct  7 07:20:46 2019
New Revision: 373910

URL: http://llvm.org/viewvc/llvm-project?rev=373910&view=rev
Log:
[clang] Add test for FindNextToken in Lexer.

Reviewers: ilya-biryukov

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/unittests/Lex/LexerTest.cpp

Modified: cfe/trunk/unittests/Lex/LexerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/LexerTest.cpp?rev=373910&r1=373909&r2=373910&view=diff
==
--- cfe/trunk/unittests/Lex/LexerTest.cpp (original)
+++ cfe/trunk/unittests/Lex/LexerTest.cpp Mon Oct  7 07:20:46 2019
@@ -11,9 +11,11 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/MacroArgs.h"
@@ -21,11 +23,13 @@
 #include "clang/Lex/ModuleLoader.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
-using namespace clang;
+#include 
 
 namespace {
+using namespace clang;
+using testing::ElementsAre;
 
 // The test fixture.
 class LexerTest : public ::testing::Test {
@@ -535,4 +539,21 @@ TEST_F(LexerTest, CharRangeOffByOne) {
   EXPECT_EQ(Lexer::getSourceText(CR, SourceMgr, LangOpts), "MOO"); // Was "MO".
 }
 
+TEST_F(LexerTest, FindNextToken) {
+  Lex("int abcd = 0;\n"
+  "int xyz = abcd;\n");
+  std::vector GeneratedByNextToken;
+  SourceLocation Loc =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+  while (true) {
+auto T = Lexer::findNextToken(Loc, SourceMgr, LangOpts);
+ASSERT_TRUE(T.hasValue());
+if (T->is(tok::eof))
+  break;
+GeneratedByNextToken.push_back(getSourceText(*T, *T));
+Loc = T->getLocation();
+  }
+  EXPECT_THAT(GeneratedByNextToken, ElementsAre("abcd", "=", "0", ";", "int",
+"xyz", "=", "abcd", ";"));
+}
 } // anonymous namespace


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


r373911 - Sema - silence static analyzer getAs<> null dereference warnings. NFCI.

2019-10-07 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Mon Oct  7 07:25:46 2019
New Revision: 373911

URL: http://llvm.org/viewvc/llvm-project?rev=373911&view=rev
Log:
Sema - silence static analyzer getAs<> null dereference warnings. NFCI.

The static analyzer is warning about potential null dereferences, but in these 
cases we should be able to use castAs<> directly and if not assert will fire 
for us.

Modified:
cfe/trunk/lib/Sema/SemaAccess.cpp
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/lib/Sema/SemaCoroutine.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp

Modified: cfe/trunk/lib/Sema/SemaAccess.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAccess.cpp?rev=373911&r1=373910&r2=373911&view=diff
==
--- cfe/trunk/lib/Sema/SemaAccess.cpp (original)
+++ cfe/trunk/lib/Sema/SemaAccess.cpp Mon Oct  7 07:25:46 2019
@@ -1551,7 +1551,7 @@ Sema::AccessResult Sema::CheckUnresolved
 
   QualType BaseType = E->getBaseType();
   if (E->isArrow())
-BaseType = BaseType->getAs()->getPointeeType();
+BaseType = BaseType->castAs()->getPointeeType();
 
   AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
   Found, BaseType);

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373911&r1=373910&r2=373911&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Oct  7 07:25:46 2019
@@ -484,7 +484,7 @@ static bool checkOpenCLBlockArgs(Sema &S
   const BlockPointerType *BPT =
   cast(BlockArg->getType().getCanonicalType());
   ArrayRef Params =
-  BPT->getPointeeType()->getAs()->getParamTypes();
+  BPT->getPointeeType()->castAs()->getParamTypes();
   unsigned ArgCounter = 0;
   bool IllegalParams = false;
   // Iterate through the block parameters until either one is found that is not
@@ -583,7 +583,7 @@ static bool checkOpenCLEnqueueVariadicAr
   const BlockPointerType *BPT =
   cast(BlockArg->getType().getCanonicalType());
   unsigned NumBlockParams =
-  BPT->getPointeeType()->getAs()->getNumParams();
+  BPT->getPointeeType()->castAs()->getNumParams();
   unsigned TotalNumArgs = TheCall->getNumArgs();
 
   // For each argument passed to the block, a corresponding uint needs to
@@ -676,7 +676,7 @@ static bool SemaOpenCLBuiltinEnqueueKern
 // we have a block type, check the prototype
 const BlockPointerType *BPT =
 cast(Arg3->getType().getCanonicalType());
-if (BPT->getPointeeType()->getAs()->getNumParams() > 0) 
{
+if (BPT->getPointeeType()->castAs()->getNumParams() > 
0) {
   S.Diag(Arg3->getBeginLoc(),
  diag::err_opencl_enqueue_kernel_blocks_no_args);
   return true;
@@ -4664,7 +4664,7 @@ ExprResult Sema::BuildAtomicExpr(SourceR
   << Ptr->getSourceRange();
   return ExprError();
 }
-ValType = AtomTy->getAs()->getValueType();
+ValType = AtomTy->castAs()->getValueType();
   } else if (Form != Load && Form != LoadCopy) {
 if (ValType.isConstQualified()) {
   Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
@@ -5473,7 +5473,7 @@ static bool checkVAStartABI(Sema &S, uns
   if (IsX64 || IsAArch64) {
 CallingConv CC = CC_C;
 if (const FunctionDecl *FD = S.getCurFunctionDecl())
-  CC = FD->getType()->getAs()->getCallConv();
+  CC = FD->getType()->castAs()->getCallConv();
 if (IsMSVAStart) {
   // Don't allow this in System V ABI functions.
   if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
@@ -5603,7 +5603,7 @@ bool Sema::SemaBuiltinVAStart(unsigned B
return false;
  if (!Type->isEnumeralType())
return true;
- const EnumDecl *ED = Type->getAs()->getDecl();
+ const EnumDecl *ED = Type->castAs()->getDecl();
  return !(ED &&
   Context.typesAreCompatible(ED->getPromotionType(), 
Type));
}()) {
@@ -10756,7 +10756,7 @@ static bool AnalyzeBitFieldAssignment(Se
  return false;
 
   if (BitfieldType->isEnumeralType()) {
-EnumDecl *BitfieldEnumDecl = BitfieldType->getAs()->getDecl();
+EnumDecl *BitfieldEnumDecl = BitfieldType->castAs()->getDecl();
 // If the underlying enum type was not explicitly specified as an unsigned
 // type and the enum contain only positive values, MSVC++ will cause an
 // inconsistency by storing this as a signed type.

Modified: cfe/trunk/lib/Sema/SemaCoroutine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCoroutine.cpp?rev=373911&r1=373910&r2=373911&view=diff
==
--- cfe/trunk/lib/Sema/SemaCoroutine.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCoroutine.cpp Mon Oct  7 07:25:46 2019
@@ -83,7 +83,7 @@ static Qua

[PATCH] D28213: [Frontend] Correct values of ATOMIC_*_LOCK_FREE to match builtin

2019-10-07 Thread James Y Knight via Phabricator via cfe-commits
jyknight reopened this revision.
jyknight added a comment.
This revision is now accepted and ready to land.

The close was due to phabricator problem, reopening.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D28213



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


[PATCH] D68578: [HIP] Fix device stub name

2019-10-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, rjmccall, hliao.
Herald added a subscriber: erik.pilkington.

HIP emits a device stub function for each kernel in host code.

The HIP debugger requires device stub function to have a different unmangled 
name as the kernel.

Currently the name of the device stub function is the mangled name with a 
postfix .stub. However,
this does not work with the HIP debugger since the unmangled name is the same 
as the kernel.

This patch adds prefix `__device__stub__` to the unmangled name of the device 
stub before mangling,
therefore the device stub function has a valid mangled name which is different 
than the device kernel
name. The device side kernel name is kept unchanged. kernels with extern "C" 
also gets the prefix added
to the corresponding device stub function.


https://reviews.llvm.org/D68578

Files:
  include/clang/AST/Mangle.h
  lib/AST/ItaniumMangle.cpp
  lib/CodeGen/CGCUDANV.cpp
  test/CodeGenCUDA/kernel-stub-name.cu

Index: test/CodeGenCUDA/kernel-stub-name.cu
===
--- test/CodeGenCUDA/kernel-stub-name.cu
+++ test/CodeGenCUDA/kernel-stub-name.cu
@@ -6,15 +6,44 @@
 
 #include "Inputs/cuda.h"
 
+extern "C" __global__ void ckernel() {}
+
+namespace ns {
+__global__ void nskernel() {}
+} // namespace ns
+
 template
 __global__ void kernelfunc() {}
 
+// Device side kernel names
+
+// CHECK: @[[CKERN:[0-9]*]] = {{.*}} c"ckernel\00"
+// CHECK: @[[NSKERN:[0-9]*]] = {{.*}} c"_ZN2ns8nskernelEv\00"
+// CHECK: @[[TKERN:[0-9]*]] = {{.*}} c"_Z10kernelfuncIiEvv\00"
+
+// Non-template kernel stub functions
+
+// CHECK: define{{.*}}@[[CSTUB:__device_stub__ckernel]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[CSTUB]]
+// CHECK: define{{.*}}@[[NSSTUB:_ZN2ns23__device_stub__nskernelEv]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[NSSTUB]]
+
 // CHECK-LABEL: define{{.*}}@_Z8hostfuncv()
-// CHECK: call void @[[STUB:_Z10kernelfuncIiEvv.stub]]()
-void hostfunc(void) { kernelfunc<<<1, 1>>>(); }
+// CHECK: call void @[[CSTUB]]()
+// CHECK: call void @[[NSSTUB]]()
+// CHECK: call void @[[TSTUB:_Z25__device_stub__kernelfuncIiEvv]]()
+void hostfunc(void) {
+  ckernel<<<1, 1>>>();
+  ns::nskernel<<<1, 1>>>();
+  kernelfunc<<<1, 1>>>();
+}
+
+// Template kernel stub functions
 
-// CHECK: define{{.*}}@[[STUB]]
-// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[STUB]]
+// CHECK: define{{.*}}@[[TSTUB]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[TSTUB]]
 
 // CHECK-LABEL: define{{.*}}@__hip_register_globals
-// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[STUB]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[CSTUB]]{{.*}}@[[CKERN]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[NSSTUB]]{{.*}}@[[NSKERN]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[TSTUB]]{{.*}}@[[TKERN]]
Index: lib/CodeGen/CGCUDANV.cpp
===
--- lib/CodeGen/CGCUDANV.cpp
+++ lib/CodeGen/CGCUDANV.cpp
@@ -166,6 +166,7 @@
   CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
   VoidPtrTy = cast(Types.ConvertType(Ctx.VoidPtrTy));
   VoidPtrPtrTy = VoidPtrTy->getPointerTo();
+  DeviceMC->setPrefixDeviceStub(false);
 }
 
 llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
@@ -231,6 +232,7 @@
   assert((CGF.CGM.getContext().getAuxTargetInfo() &&
   (CGF.CGM.getContext().getAuxTargetInfo()->getCXXABI() !=
CGF.CGM.getContext().getTargetInfo().getCXXABI())) ||
+ CGF.getLangOpts().HIP ||
  getDeviceStubName(getDeviceSideName(CGF.CurFuncDecl)) ==
  CGF.CurFn->getName());
 
@@ -798,9 +800,9 @@
 }
 
 std::string CGNVCUDARuntime::getDeviceStubName(llvm::StringRef Name) const {
-  if (!CGM.getLangOpts().HIP)
+  if (!CGM.getLangOpts().HIP || Name.startswith("_Z"))
 return Name;
-  return (Name + ".stub").str();
+  return ("__device_stub__" + Name).str();
 }
 
 CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
Index: lib/AST/ItaniumMangle.cpp
===
--- lib/AST/ItaniumMangle.cpp
+++ lib/AST/ItaniumMangle.cpp
@@ -122,6 +122,9 @@
   llvm::DenseMap Discriminator;
   llvm::DenseMap Uniquifier;
 
+  // Add prefix to HIP device stub function.
+  bool PrefixDevStub = true;
+
 public:
   explicit ItaniumMangleContextImpl(ASTContext &Context,
 DiagnosticsEngine &Diags)
@@ -203,6 +206,11 @@
 disc = discriminator-2;
 return true;
   }
+  virtual bool shouldPrefixDeviceStub() const override { return PrefixDevStub; }
+  virtual void setPrefixDeviceStub(bool Prefix) override {
+PrefixDevStub = Prefix;
+  }
+
   /// @}
 };
 
@@ -483,6 +491,7 @@
   const AbiTagList *AdditionalAbiTags);
   void mangleSourceName(const IdentifierInfo *II);
   void mangleRegCallName(const IdentifierInfo *II);
+  void mangleDeviceStubName(const IdentifierInfo *II);
   void mangleSo

Re: r373743 - [NFCI] Improve the -Wbool-operation's warning message

2019-10-07 Thread Nico Weber via cfe-commits
FWIW I found the "always evaluates to 'true'" bit important to understand
the warning.

We did hit this (at least once) in Chromium after all [1] (looks like a
real bug – nothing for you to do about that, and thanks for the warning),
and I don't think I would've understood what the warning wanted from me if
I hadn't seen the old warning text in the commit.

[1]: https://bugs.chromium.org/p/chromium/issues/detail?id=1011810

On Fri, Oct 4, 2019 at 8:53 AM David Bolvansky via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: xbolva00
> Date: Fri Oct  4 05:55:13 2019
> New Revision: 373743
>
> URL: http://llvm.org/viewvc/llvm-project?rev=373743&view=rev
> Log:
> [NFCI] Improve the -Wbool-operation's warning message
>
> Based on the request from the post commit review. Also added one new test.
>
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/test/Sema/warn-bitwise-negation-bool.c
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=373743&r1=373742&r2=373743&view=diff
>
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Oct  4
> 05:55:13 2019
> @@ -6638,7 +6638,7 @@ def note_member_declared_here : Note<
>  def note_member_first_declared_here : Note<
>"member %0 first declared here">;
>  def warn_bitwise_negation_bool : Warning<
> -  "bitwise negation of a boolean expression always evaluates to 'true'">,
> +  "bitwise negation of a boolean expression; did you mean a logicial
> negation?">,
>InGroup>;
>  def err_decrement_bool : Error<"cannot decrement expression of type
> bool">;
>  def warn_increment_bool : Warning<
>
> Modified: cfe/trunk/test/Sema/warn-bitwise-negation-bool.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-bitwise-negation-bool.c?rev=373743&r1=373742&r2=373743&view=diff
>
> ==
> --- cfe/trunk/test/Sema/warn-bitwise-negation-bool.c (original)
> +++ cfe/trunk/test/Sema/warn-bitwise-negation-bool.c Fri Oct  4 05:55:13
> 2019
> @@ -12,9 +12,11 @@ typedef _Bool boolean;
>  #endif
>
>  void test(boolean b, int i) {
> -  b = ~b; // expected-warning {{bitwise negation of a boolean expression
> always evaluates to 'true'}}
> +  b = ~b; // expected-warning {{bitwise negation of a boolean expression;
> did you mean a logicial negation?}}
>// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:8}:"!"
> -  b = ~(b); // expected-warning {{bitwise negation of a boolean
> expression always evaluates to 'true'}}
> +  b = ~(b); // expected-warning {{bitwise negation of a boolean
> expression; did you mean a logicial negation?}}
>// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:8}:"!"
>b = ~i;
> +  i = ~b; // expected-warning {{bitwise negation of a boolean expression;
> did you mean a logicial negation?}}
> +  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:8}:"!"
>  }
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r373743 - [NFCI] Improve the -Wbool-operation's warning message

2019-10-07 Thread Dávid Bolvanský via cfe-commits
Okey, I will see what I can do (I know I need to move checking code somewhere 
else).

> Dňa 7. 10. 2019 o 16:54 užívateľ Nico Weber  napísal:
> 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D67536#1697533 , @nridge wrote:

> How would one even measure the line length? `SourceManager` doesn't sem to 
> have a method like `getLineLength()` or similar.


If you look at functions like `offsetToPosition` in SourceCode.h, basically you 
get the buffer as a string (contains utf-8), find the offset you're interested 
in, and then zoom around looking for `\n`. Once you have a substring, calling 
`lspLength()` on it will give you the length in UTF-16 or whatever LSP is 
speaking at the moment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

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

In D67536#1697533 , @nridge wrote:

> How would one even measure the line length? `SourceManager` doesn't sem to 
> have a method like `getLineLength()` or similar.


Yes, there is no existing API for that, I think you'd need to get the source 
code from the SM at the specific offset, and do the `\n` counting.




Comment at: clang-tools-extra/clangd/ParsedAST.h:100
 
+  const std::vector &getSkippedRanges() const {
+return SkippedRanges;

Instead of adding new member and methods in `ParsedAST`, I think we can do it 
in `CollectMainFileMacros` (adding a new field SkippRanges in 
`MainFileMacros`), then we can get the skipped ranges for preamble region 
within the main file for free.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:152
+  // Don't bother computing the offset for the end of the line, just 
use
+  // zero. The client will treat this highlighting kind specially, and
+  // highlight the entire line visually (i.e. not just to where the 
text

sammccall wrote:
> nridge wrote:
> > hokein wrote:
> > > This seems too couple with VSCode client, I would prefer to calculate the 
> > > range of the line and return to the client.
> > > 
> > > Is there any big differences in VSCode between highlighting with the 
> > > `isWholeLine` and highlighting with the range of the line? 
> > I took some screenshots to illustrate to difference.
> > 
> > Highlighting only to the end of the line of text:
> > 
> > {F10158508}
> > 
> > Highlighting the whole line:
> > 
> > {F10158515}
> > 
> > I think the first one looks pretty bad, and is inconsistent with existing 
> > practice.
> > 
> > Note also that the suggestion is not to special-case the VSCode client 
> > specifically; it's to special-case one particular highlighting, which any 
> > client can implement.
> > 
> > If this special-casing is really unpalatable, we could instead try this 
> > suggestion by @sammccall:
> > 
> > > Failing that, I'd suggest encoding a list of line-styles on 
> > > SemanticHighlightingInformation, that should be combined with any tokens 
> > > on that line.
> > 
> > I guess one consideration when evaluating these options is, do we expect to 
> > use that "list of line-styles" for anything else in the future? I can't 
> > think of anything at the moment, but perhaps there are other uses for it.
> > 
> > If not, we could do something slightly simpler, and add a single 
> > `isInactive` flag to `SemanticHighlightingInformation`.
> Three approaches seem feasible here:
> 1. clients that know about the specific scope can extend it to the whole 
> line. 
> 2. [0,0) or so indicates "highlight the whole line"
> 3. use a dedicated property for line styles (vs token styles)
> 
> 3 is clearly better than 2 I think, it's more explicit. I don't have a strong 
> opinion of 1 vs 3, but if going with 1 I think it's a good idea to measure 
> the line as Haojian says, so we at least get a basic version of the feature 
> if the client doesn't know about line styles.
> 
> > I guess one consideration when evaluating these options is, do we expect to 
> > use that "list of line-styles" for anything else in the future? I can't 
> > think of anything at the moment
> Preprocessor directives maybe? (Though these are easy enough for clients to 
> highlight with regex)
I can't say whether highlighting the line is better than highlighting the range 
of the line text, but below is the how the inactive TS code is highlighted in 
VSCode (only the range of text), I personally prefer this style.

{F10189885}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


Re: r371605 - [Diagnostics] Add -Wsizeof-array-div

2019-10-07 Thread Nico Weber via cfe-commits
I gave this another try now that we have a compiler with rL372600. Another
thing the warning currently warns on is code like this:

  char memory[kOpcodeMemory];
  OpcodeFactory opcode_maker(memory, sizeof(memory));
  size_t count = sizeof(memory) / sizeof(PolicyOpcode);

or

  int32_t fds[sizeof(buffer->data) / sizeof(int32_t)], i, count;
  size_t size;

(the latter from wayland).

What do you think about also not emitting the warning if the lhs sizeof is
an array of signed or unsigned char? The warning wants the rhs sizeof to be
sizeof(char) which is 1, and dividing by that doesn't really make sense. So
this might be a change that improves false negative rate while probably not
hurting true positive rate.

On Mon, Sep 23, 2019 at 9:11 AM Dávid Bolvanský 
wrote:

> Yeah, this needs to be handled a bit differently (if we want so).
>
> po 23. 9. 2019 o 15:07 Nico Weber  napísal(a):
>
>> It still warns if the inner array is in a struct. That's probably ok
>> though.
>>
>> struct Point {
>>   int xy[2];
>> };
>>
>> void f() {
>>   Point points[3];
>>   for (int i = 0; i < sizeof(points) / sizeof(int); ++i)
>> (&points[0].xy[0])[i] = 0;
>> }
>>
>> On Mon, Sep 23, 2019 at 8:54 AM Nico Weber  wrote:
>>
>>> That was fast. Thanks much! :)
>>>
>>> On Mon, Sep 23, 2019 at 8:52 AM Dávid Bolvanský <
>>> david.bolvan...@gmail.com> wrote:
>>>
 Hello,

 Thanks for the proposed idea, implemented in rL372600.

 po 23. 9. 2019 o 14:23 Nico Weber  napísal(a):

> We're looking at turning this one.
>
> One thing that this warns about that's a false positive where we've
> seen it is this code for nested arrays:
>
>   float m[4][4];
>   for (int i = 0; i < sizeof(m) / sizeof(**m); ++i) (&**m)[i] = 0;
>
> (Why would anyone write code like this? It's a reduced example;
> consider e.g. wanting to call std::generate_n() on all elements of a 
> nested
> array.)
>
> Can we make the warning not fire when dividing the size of a nested
> array by the size of the deepest base type?
>
> On Wed, Sep 11, 2019 at 6:58 AM David Bolvansky via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: xbolva00
>> Date: Wed Sep 11 03:59:47 2019
>> New Revision: 371605
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=371605&view=rev
>> Log:
>> [Diagnostics] Add -Wsizeof-array-div
>>
>> Summary: Clang version of https://www.viva64.com/en/examples/v706/
>>
>> Reviewers: rsmith
>>
>> Differential Revision: https://reviews.llvm.org/D67287
>>
>> Added:
>> cfe/trunk/test/Sema/div-sizeof-array.cpp
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> cfe/trunk/lib/Sema/SemaExpr.cpp
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371605&r1=371604&r2=371605&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed Sep 11
>> 03:59:47 2019
>> @@ -3406,6 +3406,10 @@ def note_pointer_declared_here : Note<
>>  def warn_division_sizeof_ptr : Warning<
>>"'%0' will return the size of the pointer, not the array itself">,
>>InGroup>;
>> +def warn_division_sizeof_array : Warning<
>> +  "expression does not compute the number of elements in this array;
>> element "
>> +  "type is %0, not %1">,
>> +  InGroup>;
>>
>>  def note_function_warning_silence : Note<
>>  "prefix with the address-of operator to silence this warning">;
>>
>> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371605&r1=371604&r2=371605&view=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Sep 11 03:59:47 2019
>> @@ -9158,17 +9158,28 @@ static void DiagnoseDivisionSizeofPointe
>>else
>>  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
>>
>> -  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
>> -return;
>> -  if
>> (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() !=
>> -  RHSTy.getCanonicalType().getUnqualifiedType())
>> -return;
>> +  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
>> +if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(),
>> RHSTy))
>> +  return;
>>
>> -  S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS <<
>> LHS->getSourceRange();
>> -  if (const auto *DRE = dyn_cast(LHSArg)) {
>> -if (co

Re: r371605 - [Diagnostics] Add -Wsizeof-array-div

2019-10-07 Thread Dávid Bolvanský via cfe-commits
D68526 should fix it. Take a look please.


> Dňa 7. 10. 2019 o 17:09 užívateľ Nico Weber  napísal:
> 
> 
> I gave this another try now that we have a compiler with rL372600. Another 
> thing the warning currently warns on is code like this:
> 
>   char memory[kOpcodeMemory];
>   OpcodeFactory opcode_maker(memory, sizeof(memory));
>   size_t count = sizeof(memory) / sizeof(PolicyOpcode);
> 
> or
> 
>   int32_t fds[sizeof(buffer->data) / sizeof(int32_t)], i, count;
>   size_t size;
> 
> (the latter from wayland).
> 
> What do you think about also not emitting the warning if the lhs sizeof is an 
> array of signed or unsigned char? The warning wants the rhs sizeof to be 
> sizeof(char) which is 1, and dividing by that doesn't really make sense. So 
> this might be a change that improves false negative rate while probably not 
> hurting true positive rate.
> 
>> On Mon, Sep 23, 2019 at 9:11 AM Dávid Bolvanský  
>> wrote:
>> Yeah, this needs to be handled a bit differently (if we want so).
>> 
>> po 23. 9. 2019 o 15:07 Nico Weber  napísal(a):
>>> It still warns if the inner array is in a struct. That's probably ok though.
>>> 
>>> struct Point {
>>>   int xy[2];
>>> };
>>> 
>>> void f() {
>>>   Point points[3];
>>>   for (int i = 0; i < sizeof(points) / sizeof(int); ++i)
>>> (&points[0].xy[0])[i] = 0;
>>> }
>>> 
 On Mon, Sep 23, 2019 at 8:54 AM Nico Weber  wrote:
 That was fast. Thanks much! :)
 
> On Mon, Sep 23, 2019 at 8:52 AM Dávid Bolvanský 
>  wrote:
> Hello,
> 
> Thanks for the proposed idea, implemented in rL372600.
> 
> po 23. 9. 2019 o 14:23 Nico Weber  napísal(a):
>> We're looking at turning this one.
>> 
>> One thing that this warns about that's a false positive where we've seen 
>> it is this code for nested arrays:
>> 
>>   float m[4][4];
>>   for (int i = 0; i < sizeof(m) / sizeof(**m); ++i) (&**m)[i] = 0;
>> 
>> (Why would anyone write code like this? It's a reduced example; consider 
>> e.g. wanting to call std::generate_n() on all elements of a nested 
>> array.)
>> 
>> Can we make the warning not fire when dividing the size of a nested 
>> array by the size of the deepest base type?
>> 
>>> On Wed, Sep 11, 2019 at 6:58 AM David Bolvansky via cfe-commits 
>>>  wrote:
>>> Author: xbolva00
>>> Date: Wed Sep 11 03:59:47 2019
>>> New Revision: 371605
>>> 
>>> URL: http://llvm.org/viewvc/llvm-project?rev=371605&view=rev
>>> Log:
>>> [Diagnostics] Add -Wsizeof-array-div
>>> 
>>> Summary: Clang version of https://www.viva64.com/en/examples/v706/
>>> 
>>> Reviewers: rsmith
>>> 
>>> Differential Revision: https://reviews.llvm.org/D67287
>>> 
>>> Added:
>>> cfe/trunk/test/Sema/div-sizeof-array.cpp
>>> Modified:
>>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>>> cfe/trunk/lib/Sema/SemaExpr.cpp
>>> 
>>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>>> URL: 
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=371605&r1=371604&r2=371605&view=diff
>>> ==
>>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed Sep 11 
>>> 03:59:47 2019
>>> @@ -3406,6 +3406,10 @@ def note_pointer_declared_here : Note<
>>>  def warn_division_sizeof_ptr : Warning<
>>>"'%0' will return the size of the pointer, not the array itself">,
>>>InGroup>;
>>> +def warn_division_sizeof_array : Warning<
>>> +  "expression does not compute the number of elements in this array; 
>>> element "
>>> +  "type is %0, not %1">,
>>> +  InGroup>;
>>> 
>>>  def note_function_warning_silence : Note<
>>>  "prefix with the address-of operator to silence this warning">;
>>> 
>>> Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
>>> URL: 
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=371605&r1=371604&r2=371605&view=diff
>>> ==
>>> --- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
>>> +++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Sep 11 03:59:47 2019
>>> @@ -9158,17 +9158,28 @@ static void DiagnoseDivisionSizeofPointe
>>>else
>>>  RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
>>> 
>>> -  if (!LHSTy->isPointerType() || RHSTy->isPointerType())
>>> -return;
>>> -  if (LHSTy->getPointeeType().getCanonicalType().getUnqualifiedType() 
>>> !=
>>> -  RHSTy.getCanonicalType().getUnqualifiedType())
>>> -return;
>>> +  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
>>> +if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), 
>>> RHSTy

[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

One thing that may be worth considering as well, is that if the client prefers 
to highlight the text of the line only, it can calculate the length of the line 
itself. In VSCode for instance, the line lengths are readily available; I 
imagine other editors are similar since they need that information for many 
purposes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D68562: [clangd] Add RemoveUsingNamespace tweak.

2019-10-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:86
+  if (const Decl *ParentDecl = Node->Parent->ASTNode.get()) {
+return llvm::isa(ParentDecl);
+  }

NIT: remove redundant `{}`  around this `return`



Comment at: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:99
+return false;
+  if (!dyn_cast(TargetDirective->getDeclContext()))
+return false;

I believe this check is redundant in presence of `isTopLevelDecl()`...
(It used to check the 'using namespace' is not inside a function body)



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:121
+  for (auto *T : Ref.Targets) {
+// FIXME: handle inline namespaces, unscoped enumerators.
+if (T->getDeclContext() != TargetDirective->getNominatedNamespace())

Could you take a look at handling these?

Also happy if we make it a separate change, but we shouldn't delay this.
Both are important cases.

The examples should roughly be:
```
namespace std {
inline namespace v1 {
  struct vector {};
}
}

using namespace std;
vector v;
```

and
```
namespace tokens {
enum Token {
  comma, identifier, numeric
};
}

using namespace tokens;
auto x = comma; 
```



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:163
+std::string RemoveUsingNamespace::title() const {
+  return llvm::formatv("Remove using namespace, add qualifiers instead");
+}

NIT: could you rephrase as `re-qualify names instead`
"add qualifiers" confuses some people, this can be read as "add a const 
qualifier"



Comment at: clang-tools-extra/clangd/unittests/TweakTests.cpp:781
+namespace bb { struct map {}; }
+using namespace bb; // Qualifies this.
+  }

Argh, this should definitely be fixed :-(
One simple way to handle this particular only qualify references, which come 
**after** the first `using namespace` we are removing.

There's a `SourceManager::isBeforeInTranslationUnit` function that can be used 
to find out whether something is written before or after a particular point.

This won't fix all of the cases, but fixing in the general case seems hard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68562



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


[PATCH] D68581: Include leading attributes in DeclStmt's SourceRange

2019-10-07 Thread Stephan Bergmann via Phabricator via cfe-commits
sberg created this revision.
sberg added reviewers: aaron.ballman, rsmith, Nathan-Huckleberry.
Herald added a project: clang.

For a `DeclStmt` like

  [[maybe_unused]] int i;

`getBeginLoc()` returned the start of `int` instead of the start of `[[` (see 
http://lists.llvm.org/pipermail/cfe-dev/2019-September/063434.html "[cfe-dev] 
Poor DeclStmt source range with leading [[attributes]]?").

Is there a good way to write a test for this?


Repository:
  rC Clang

https://reviews.llvm.org/D68581

Files:
  clang/lib/Parse/ParseStmt.cpp


Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -220,6 +220,8 @@
 Decl =
 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, Attrs);
   }
+  if (Attrs.Range.getBegin().isValid())
+  DeclStart = Attrs.Range.getBegin();
   return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
 }
 


Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -220,6 +220,8 @@
 Decl =
 ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, Attrs);
   }
+  if (Attrs.Range.getBegin().isValid())
+  DeclStart = Attrs.Range.getBegin();
   return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r373743 - [NFCI] Improve the -Wbool-operation's warning message

2019-10-07 Thread Arthur O'Dwyer via cfe-commits
On Mon, Oct 7, 2019 at 10:59 AM Dávid Bolvanský via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Okey, I will see what I can do (I know I need to move checking code
> somewhere else).
>
> > Dňa 7. 10. 2019 o 16:54 užívateľ Nico Weber 
> napísal:
> > FWIW I found the "always evaluates to 'true'" bit important to
> understand the warning.
>

+1, I think "always evaluates to true" is useful, especially for people who
don't immediately intuit the difference between "bitwise negation" and
"logical negation." (Although the fixit will help clear up the difference.)

Also, Dávid, you misspelled "logical" as "logicial" in the patch I saw. So
you might need to push a fix for that typo, unless you already caught it.
My suggested message follows—

-  "bitwise negation of a boolean expression; did you mean a logicial
negation?">,
+  "bitwise negation of a boolean expression is always true; did you mean
logical negation?">,

my $.02,
–Arthur
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r373743 - [NFCI] Improve the -Wbool-operation's warning message

2019-10-07 Thread Dávid Bolvanský via cfe-commits
Typo was fixed some days ago :)

Odoslané z iPhonu

> Dňa 7. 10. 2019 o 17:22 užívateľ Arthur O'Dwyer  
> napísal:
> 
> 
>> On Mon, Oct 7, 2019 at 10:59 AM Dávid Bolvanský via cfe-commits 
>>  wrote:
> 
>> Okey, I will see what I can do (I know I need to move checking code 
>> somewhere else).
>> 
>> > Dňa 7. 10. 2019 o 16:54 užívateľ Nico Weber  napísal:
>> > FWIW I found the "always evaluates to 'true'" bit important to understand 
>> > the warning.
> 
> +1, I think "always evaluates to true" is useful, especially for people who 
> don't immediately intuit the difference between "bitwise negation" and 
> "logical negation." (Although the fixit will help clear up the difference.)
> 
> Also, Dávid, you misspelled "logical" as "logicial" in the patch I saw. So 
> you might need to push a fix for that typo, unless you already caught it.
> My suggested message follows—
> 
> -  "bitwise negation of a boolean expression; did you mean a logicial 
> negation?">,
> +  "bitwise negation of a boolean expression is always true; did you mean 
> logical negation?">,
> 
> my $.02,
> –Arthur
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:54
+  /// Constructs a string representation of the StencilPart. StencilParts
+  /// generated by the `selection` and `run `functions do not have a unique
+  /// string representation.

No space between "run" and backtick.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68574



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


[PATCH] D68584: Fix Calling Convention through aliases

2019-10-07 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: rnk, pcc.
Herald added a subscriber: hiraditya.
Herald added a project: LLVM.

r369697 changed the behavior of stripPointerCasts to no longer include
aliases.  However, the code in CGDeclCXX.cpp's createAtExitStub counted
on the looking through aliases to properly set the calling convention of
a call.

  

The result of the change was that the calling convention mismatch of the
call would be replaced with a llvm.trap, causing a runtime crash.


https://reviews.llvm.org/D68584

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/test/CodeGenCXX/call-conv-thru-alias.cpp
  llvm/include/llvm/IR/Value.h
  llvm/lib/IR/Value.cpp

Index: llvm/lib/IR/Value.cpp
===
--- llvm/lib/IR/Value.cpp
+++ llvm/lib/IR/Value.cpp
@@ -455,6 +455,7 @@
 // Various metrics for how much to strip off of pointers.
 enum PointerStripKind {
   PSK_ZeroIndices,
+  PSK_ZeroIndicesAndAliases,
   PSK_ZeroIndicesSameRepresentation,
   PSK_ZeroIndicesAndInvariantGroups,
   PSK_InBoundsConstantIndices,
@@ -475,6 +476,7 @@
 if (auto *GEP = dyn_cast(V)) {
   switch (StripKind) {
   case PSK_ZeroIndices:
+  case PSK_ZeroIndicesAndAliases:
   case PSK_ZeroIndicesSameRepresentation:
   case PSK_ZeroIndicesAndInvariantGroups:
 if (!GEP->hasAllZeroIndices())
@@ -497,6 +499,8 @@
   // TODO: If we know an address space cast will not change the
   //   representation we could look through it here as well.
   V = cast(V)->getOperand(0);
+} else if (StripKind == PSK_ZeroIndicesAndAliases && isa(V)) {
+  V = cast(V)->getAliasee();
 } else {
   if (const auto *Call = dyn_cast(V)) {
 if (const Value *RV = Call->getReturnedArgOperand()) {
@@ -526,6 +530,10 @@
   return stripPointerCastsAndOffsets(this);
 }
 
+const Value *Value::stripPointerCastsAndAliases() const {
+  return stripPointerCastsAndOffsets(this);
+}
+
 const Value *Value::stripPointerCastsSameRepresentation() const {
   return stripPointerCastsAndOffsets(this);
 }
Index: llvm/include/llvm/IR/Value.h
===
--- llvm/include/llvm/IR/Value.h
+++ llvm/include/llvm/IR/Value.h
@@ -523,6 +523,16 @@
 static_cast(this)->stripPointerCasts());
   }
 
+  /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
+  ///
+  /// Returns the original uncasted value.  If this is called on a non-pointer
+  /// value, it returns 'this'.
+  const Value *stripPointerCastsAndAliases() const;
+  Value *stripPointerCastsAndAliases() {
+return const_cast(
+static_cast(this)->stripPointerCastsAndAliases());
+  }
+
   /// Strip off pointer casts, all-zero GEPs and address space casts
   /// but ensures the representation of the result stays the same.
   ///
Index: clang/test/CodeGenCXX/call-conv-thru-alias.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/call-conv-thru-alias.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple i686-windows-pc -emit-llvm -o - -mconstructor-aliases -O1 -disable-llvm-passes %s | FileCheck %s
+
+struct Base { virtual ~Base(); };
+struct Derived : Base {
+  virtual ~Derived();
+  static Derived inst;
+};
+
+Base::~Base(){}
+Derived::~Derived(){}
+Derived Derived::inst;
+
+// CHECK: @"??1Derived@@UAE@XZ" = dso_local unnamed_addr alias void (%struct.Derived*), bitcast (void (%struct.Base*)* @"??1Base@@UAE@XZ" to void (%struct.Derived*)*)
+
+// CHECK: define dso_local x86_thiscallcc void @"??1Base@@UAE@XZ"
+// CHECK: define internal void @"??__E?inst@Derived@@2U1@A@@YAXXZ"
+// CHECK: call i32 @atexit(void ()* @"??__F?inst@Derived@@2U1@A@@YAXXZ"
+//
+// CHECK: define internal void @"??__F?inst@Derived@@2U1@A@@YAXXZ"
+// CHECK-NEXT: entry:
+// CHECK-NEXT: call x86_thiscallcc void @"??1Derived@@UAE@XZ"
Index: clang/lib/CodeGen/CGDeclCXX.cpp
===
--- clang/lib/CodeGen/CGDeclCXX.cpp
+++ clang/lib/CodeGen/CGDeclCXX.cpp
@@ -248,8 +248,8 @@
   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
 
  // Make sure the call and the callee agree on calling convention.
-  if (llvm::Function *dtorFn =
-  dyn_cast(dtor.getCallee()->stripPointerCasts()))
+  if (llvm::Function *dtorFn = dyn_cast(
+  dtor.getCallee()->stripPointerCastsAndAliases()))
 call->setCallingConv(dtorFn->getCallingConv());
 
   CGF.FinishFunction();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68526: [Diagnostics] Silence -Wsizeof-array-div for character buffers

2019-10-07 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

@tkanis wrote in post commit review:

“What do you think about also not emitting the warning if the lhs sizeof is an 
array of signed or unsigned char? The warning wants the rhs sizeof to be 
sizeof(char) which is 1, and dividing by that doesn't really make sense. ”

I agree with him. I think you can land this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68526



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


[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 223619.
ymandel added a comment.

fix comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68574

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -389,4 +389,59 @@
   auto S2 = cat(run(F));
   EXPECT_NE(S1, S2);
 }
+
+TEST(StencilToStringTest, RawTextOp) {
+  auto S = cat("foo bar baz");
+  EXPECT_EQ(S.toString(), R"("foo bar baz")");
+}
+
+TEST(StencilToStringTest, RawTextOpEscaping) {
+  auto S = cat("foo \"bar\" baz\\n");
+  EXPECT_EQ(S.toString(), R"("foo \"bar\" baz\\n")");
+}
+
+TEST(StencilToStringTest, DebugPrintNodeOp) {
+  auto S = cat(dPrint("Id"));
+  EXPECT_EQ(S.toString(), R"repr(dPrint("Id"))repr");
+}
+
+TEST(StencilToStringTest, ExpressionOp) {
+  auto S = cat(expression("Id"));
+  EXPECT_EQ(S.toString(), R"repr(expression("Id"))repr");
+}
+
+TEST(StencilToStringTest, DerefOp) {
+  auto S = cat(deref("Id"));
+  EXPECT_EQ(S.toString(), R"repr(deref("Id"))repr");
+}
+
+TEST(StencilToStringTest, AddressOfOp) {
+  auto S = cat(addressOf("Id"));
+  EXPECT_EQ(S.toString(), R"repr(addressOf("Id"))repr");
+}
+
+TEST(StencilToStringTest, AccessOp) {
+  auto S = cat(access("Id", text("memberData")));
+  EXPECT_EQ(S.toString(), R"repr(access("Id", "memberData"))repr");
+}
+
+TEST(StencilToStringTest, AccessOpStencilPart) {
+  auto S = cat(access("Id", access("subId", "memberData")));
+  EXPECT_EQ(S.toString(),
+R"repr(access("Id", access("subId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, IfBoundOp) {
+  auto S = cat(ifBound("Id", text("trueText"), access("exprId", "memberData")));
+  EXPECT_EQ(
+  S.toString(),
+  R"repr(ifBound("Id", "trueText", access("exprId", "memberData")))repr");
+}
+
+TEST(StencilToStringTest, MultipleOp) {
+  auto S = cat("foo", access("x", "m()"), "bar",
+   ifBound("x", text("t"), access("e", "f")));
+  EXPECT_EQ(S.toString(), R"repr("foo", access("x", "m()"), "bar", )repr"
+  R"repr(ifBound("x", "t", access("e", "f")))repr");
+}
 } // namespace
Index: clang/lib/Tooling/Refactoring/Stencil.cpp
===
--- clang/lib/Tooling/Refactoring/Stencil.cpp
+++ clang/lib/Tooling/Refactoring/Stencil.cpp
@@ -15,6 +15,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring/SourceCode.h"
 #include "clang/Tooling/Refactoring/SourceCodeBuilders.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/Errc.h"
 #include 
 #include 
@@ -128,6 +129,54 @@
   return false;
 }
 
+std::string toStringData(const RawTextData &Data) {
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  OS << "\"";
+  OS.write_escaped(Data.Text);
+  OS << "\"";
+  OS.flush();
+  return Result;
+}
+
+std::string toStringData(const DebugPrintNodeData &Data) {
+  return (llvm::Twine("dPrint(\"") + Data.Id + "\")").str();
+}
+
+std::string toStringData(const UnaryOperationData &Data) {
+  StringRef OpName;
+  switch (Data.Op) {
+  case UnaryNodeOperator::Parens:
+OpName = "expression";
+break;
+  case UnaryNodeOperator::Deref:
+OpName = "deref";
+break;
+  case UnaryNodeOperator::Address:
+OpName = "addressOf";
+break;
+  }
+  return (OpName + "(\"" + Data.Id + "\")").str();
+}
+
+std::string toStringData(const SelectorData &) { return "SelectorData()"; }
+
+std::string toStringData(const AccessData &Data) {
+  return (llvm::Twine("access(\"") + Data.BaseId + "\", " +
+  Data.Member.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const IfBoundData &Data) {
+  return (llvm::Twine("ifBound(\"") + Data.Id + "\", " +
+  Data.TruePart.toString() + ", " + Data.FalsePart.toString() + ")")
+  .str();
+}
+
+std::string toStringData(const MatchConsumer &) {
+  return "MatchConsumer()";
+}
+
 // The `evalData()` overloads evaluate the given stencil data to a string, given
 // the match result, and append it to `Result`. We define an overload for each
 // type of stencil data.
@@ -247,6 +296,8 @@
   return isEqualData(Data, OtherPtr->Data);
 return false;
   }
+
+  std::string toString() const override { return toStringData(Data); }
 };
 } // namespace
 
Index: clang/include/clang/Tooling/Refactoring/Stencil.h
===
--- clang/include/clang/Tooling/Refactoring/Stencil.h
+++ clang/include/clang/Tooling/Refactoring/Stencil.h
@@ -50,6 +50,11 @@
 
   virtual bool isEqual(const StencilPartInterface &other) const = 0;
 
+  /// Constructs a string representation of the StencilPart. StencilParts
+  /// generated by the `selection` and `run

[PATCH] D68578: [HIP] Fix device stub name

2019-10-07 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

Could you elaborate on how exactly current implementation does not work?

I would expect the kernel and the stub to be two distinct entities, as far as 
debugger is concerned. It does have enough information to track each 
independently (different address, .stub suffix, perhaps knowledge whether it's 
device or host code). Without the details, it looks to me that this is 
something that can and should be dealt with in the debugger. I've asked the 
same question in D63335  but I don't think 
I've got a good answer.


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

https://reviews.llvm.org/D68578



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


r373916 - [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Mon Oct  7 09:20:22 2019
New Revision: 373916

URL: http://llvm.org/viewvc/llvm-project?rev=373916&view=rev
Log:
[libTooling] Add `toString` method to the Stencil class

Summary:
`toString` generates a string representation of the stencil.

Patch by Harshal T. Lehri.

Reviewers: gribozavr

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h
cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp
cfe/trunk/unittests/Tooling/StencilTest.cpp

Modified: cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h?rev=373916&r1=373915&r2=373916&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h Mon Oct  7 09:20:22 
2019
@@ -50,6 +50,11 @@ public:
 
   virtual bool isEqual(const StencilPartInterface &other) const = 0;
 
+  /// Constructs a string representation of the StencilPart. StencilParts
+  /// generated by the `selection` and `run` functions do not have a unique
+  /// string representation.
+  virtual std::string toString() const = 0;
+
   const void *typeId() const { return TypeId; }
 
 protected:
@@ -86,6 +91,12 @@ public:
 return Impl->isEqual(*Other.Impl);
   }
 
+  std::string toString() const {
+if (Impl == nullptr)
+  return "";
+return Impl->toString();
+  }
+
 private:
   std::shared_ptr Impl;
 };
@@ -120,6 +131,16 @@ public:
 return eval(Result);
   }
 
+  /// Constructs a string representation of the Stencil. The string is not
+  /// guaranteed to be unique.
+  std::string toString() const {
+std::vector PartStrings;
+PartStrings.reserve(Parts.size());
+for (const auto &Part : Parts)
+  PartStrings.push_back(Part.toString());
+return llvm::join(PartStrings, ", ");
+  }
+
 private:
   friend bool operator==(const Stencil &A, const Stencil &B);
   static StencilPart wrap(llvm::StringRef Text);

Modified: cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp?rev=373916&r1=373915&r2=373916&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp Mon Oct  7 09:20:22 2019
@@ -15,6 +15,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring/SourceCode.h"
 #include "clang/Tooling/Refactoring/SourceCodeBuilders.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/Errc.h"
 #include 
 #include 
@@ -128,6 +129,54 @@ bool isEqualData(const MatchConsumer &) {
+  return "MatchConsumer()";
+}
+
 // The `evalData()` overloads evaluate the given stencil data to a string, 
given
 // the match result, and append it to `Result`. We define an overload for each
 // type of stencil data.
@@ -247,6 +296,8 @@ public:
   return isEqualData(Data, OtherPtr->Data);
 return false;
   }
+
+  std::string toString() const override { return toStringData(Data); }
 };
 } // namespace
 

Modified: cfe/trunk/unittests/Tooling/StencilTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/StencilTest.cpp?rev=373916&r1=373915&r2=373916&view=diff
==
--- cfe/trunk/unittests/Tooling/StencilTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/StencilTest.cpp Mon Oct  7 09:20:22 2019
@@ -389,4 +389,59 @@ TEST(StencilEqualityTest, InEqualityRun)
   auto S2 = cat(run(F));
   EXPECT_NE(S1, S2);
 }
+
+TEST(StencilToStringTest, RawTextOp) {
+  auto S = cat("foo bar baz");
+  EXPECT_EQ(S.toString(), R"("foo bar baz")");
+}
+
+TEST(StencilToStringTest, RawTextOpEscaping) {
+  auto S = cat("foo \"bar\" baz\\n");
+  EXPECT_EQ(S.toString(), R"("foo \"bar\" baz\\n")");
+}
+
+TEST(StencilToStringTest, DebugPrintNodeOp) {
+  auto S = cat(dPrint("Id"));
+  EXPECT_EQ(S.toString(), R"repr(dPrint("Id"))repr");
+}
+
+TEST(StencilToStringTest, ExpressionOp) {
+  auto S = cat(expression("Id"));
+  EXPECT_EQ(S.toString(), R"repr(expression("Id"))repr");
+}
+
+TEST(StencilToStringTest, DerefOp) {
+  auto S = cat(deref("Id"));
+  EXPECT_EQ(S.toString(), R"repr(deref("Id"))repr");
+}
+
+TEST(StencilToStringTest, AddressOfOp) {
+  auto S = cat(addressOf("Id"));
+  EXPECT_EQ(S.toString(), R"repr(addressOf("Id"))repr");
+}
+
+TEST(StencilToStringTest, AccessOp) {
+  auto S = cat(access("Id", text("memberData")));
+  EXPECT_EQ(S.toString(), R"repr(access("Id", "memberData"))repr");
+}
+
+TEST(StencilToStringTest, AccessOpStencilPart) {
+  auto S = cat(access("Id", access("subId", "memberData")));
+  EXPECT_EQ(S.toString(),
+R"repr(access("Id", access("subId", "memberData")))repr");
+}
+
+TEST(St

[PATCH] D67536: [WIP] [clangd] Add support for an inactive regions notification

2019-10-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D67536#1697696 , @nridge wrote:

> One thing that may be worth considering as well, is that if the client 
> prefers to highlight the text of the line only, it can calculate the length 
> of the line itself. In VSCode for instance, the line lengths are readily 
> available; I imagine other editors are similar since they need that 
> information for many purposes.


So I don't think clients will/should prefer that - for best rendering they 
should know this is a line highlight.

I think this comes down to how line highlights are represented in the protocol:

- by a separate field: no need to send line length
- by a special token bounds (e.g. [0,0)): no need to send line length
- by a special scope: sending line length is a nice-to-have as it provides 
graceful degradation for clients that don't understand this extension




Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:152
+  // Don't bother computing the offset for the end of the line, just 
use
+  // zero. The client will treat this highlighting kind specially, and
+  // highlight the entire line visually (i.e. not just to where the 
text

hokein wrote:
> sammccall wrote:
> > nridge wrote:
> > > hokein wrote:
> > > > This seems too couple with VSCode client, I would prefer to calculate 
> > > > the range of the line and return to the client.
> > > > 
> > > > Is there any big differences in VSCode between highlighting with the 
> > > > `isWholeLine` and highlighting with the range of the line? 
> > > I took some screenshots to illustrate to difference.
> > > 
> > > Highlighting only to the end of the line of text:
> > > 
> > > {F10158508}
> > > 
> > > Highlighting the whole line:
> > > 
> > > {F10158515}
> > > 
> > > I think the first one looks pretty bad, and is inconsistent with existing 
> > > practice.
> > > 
> > > Note also that the suggestion is not to special-case the VSCode client 
> > > specifically; it's to special-case one particular highlighting, which any 
> > > client can implement.
> > > 
> > > If this special-casing is really unpalatable, we could instead try this 
> > > suggestion by @sammccall:
> > > 
> > > > Failing that, I'd suggest encoding a list of line-styles on 
> > > > SemanticHighlightingInformation, that should be combined with any 
> > > > tokens on that line.
> > > 
> > > I guess one consideration when evaluating these options is, do we expect 
> > > to use that "list of line-styles" for anything else in the future? I 
> > > can't think of anything at the moment, but perhaps there are other uses 
> > > for it.
> > > 
> > > If not, we could do something slightly simpler, and add a single 
> > > `isInactive` flag to `SemanticHighlightingInformation`.
> > Three approaches seem feasible here:
> > 1. clients that know about the specific scope can extend it to the whole 
> > line. 
> > 2. [0,0) or so indicates "highlight the whole line"
> > 3. use a dedicated property for line styles (vs token styles)
> > 
> > 3 is clearly better than 2 I think, it's more explicit. I don't have a 
> > strong opinion of 1 vs 3, but if going with 1 I think it's a good idea to 
> > measure the line as Haojian says, so we at least get a basic version of the 
> > feature if the client doesn't know about line styles.
> > 
> > > I guess one consideration when evaluating these options is, do we expect 
> > > to use that "list of line-styles" for anything else in the future? I 
> > > can't think of anything at the moment
> > Preprocessor directives maybe? (Though these are easy enough for clients to 
> > highlight with regex)
> I can't say whether highlighting the line is better than highlighting the 
> range of the line text, but below is the how the inactive TS code is 
> highlighted in VSCode (only the range of text), I personally prefer this 
> style.
> 
> {F10189885}
I think that's an argument for making sure clients clearly distinguish between 
regular tokens and marking lines: overlapping tokens don't compose well, but we 
can easily say lines and token styles should compose.

(That particular style is not for me, but it doesn't matter)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536



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


[PATCH] D68481: [clang-format] [PR27004] omits leading space for noexcept when formatting operator delete()

2019-10-07 Thread Mitchell via Phabricator via cfe-commits
mitchell-stellar accepted this revision.
mitchell-stellar added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D68481



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


[PATCH] D67161: [clang,ARM] Initial ACLE intrinsics for MVE.

2019-10-07 Thread Dave Green via Phabricator via cfe-commits
dmgreen added subscribers: samparker, SjoerdMeijer.
dmgreen added a comment.

This is looking good to me. My understanding is that is has some dependencies? 
The llvm side will likely needed to go in first, plus a couple of clang patches?




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8529
   "argument should be a multiple of %0">;
+def err_argument_not_power_of_2 : Error<
+  "argument should be a power of 2">;

simon_tatham wrote:
> dmgreen wrote:
> > Do we have any/should we have some tests for these errors?
> By the time we finish implementing all the intrinsics, there will be tests 
> for these errors. The intrinsics that need them aren't in this preliminary 
> commit, though.
OK. That's fair.



Comment at: clang/test/CodeGen/arm-mve-intrinsics/scalar-shifts.c:2
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang --target=arm-arm-none-eabi -march=armv8.1m.main+mve.fp 
-mfloat-abi=hard -O3 -S -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang --target=arm-arm-none-eabi -march=armv8.1m.main+mve.fp 
-mfloat-abi=hard -DPOLYMORPHIC -O3 -S -emit-llvm -o - %s | FileCheck %s

simon_tatham wrote:
> dmgreen wrote:
> > These tests all run -O3, the entire pass pipeline. I see quite a few tests 
> > in the same folder do the same thing, but in this case we will be adding 
> > quite a few tests. Random mid-end optimizations may well keep on altering 
> > them.
> > 
> > Is it possible to use -disable-O0-optnone and pipe them into opt -mem2reg? 
> > What would that do to the codegen, would it be a lot more verbose than it 
> > is now?
> > 
> > Also could/should they be using clang_cc1?
> The immediate problem is that if you use any form of `clang | opt | 
> FileCheck` command line, then `update_cc_test_checks.py` says 'skipping 
> non-FileChecked line', because it doesn't support anything more complicated 
> than a two-stage pipeline consisting of clang and FileCheck.
> 
> I've enhanced `update_cc_test_checks` to handle that case, in D68406, and 
> respun these tests accordingly. But if that patch doesn't get approval then 
> I'll have to rethink this again.
> 
> (For `vld24.c` I ended up running `opt -sroa -early-cse` to avoid the IR 
> becoming noticeably more verbose. The rest worked fine with just `mem2reg`, 
> though.)
> 
> 
> Patching `update_cc_test_checks.py` to support more complex pipelines, it 
> seems to work OK: most codegen changes are trivial ones, such as modifiers 
> not appearing on IR operations (`call` instead of `tail call`, plain `shl` in 
> place of `shl nuw`). Only `vld24` becomes significantly more complicated: for 
> that one file I had to run `opt -mem2reg -sroa -early-cse` instead.
Yeah, they look OK. Thanks for making the change. It looks like a useful 
feature being added.



Comment at: clang/test/CodeGen/arm-mve-intrinsics/vcvt.c:13
+{
+return vcvttq_f16_f32(a, b);
+}

Tests for bottom too would be good to see too. In general, more tests are 
better.



Comment at: clang/test/CodeGen/arm-mve-intrinsics/vcvt.c:20
+// CHECK-NEXT:[[TMP1:%.*]] = call <4 x i1> @llvm.arm.mve.pred.i2v.v4i1(i32 
[[TMP0]])
+// CHECK-NEXT:[[TMP2:%.*]] = call <8 x half> 
@llvm.arm.mve.fltnarrow.predicated(<8 x half> [[A:%.*]], <4 x float> [[B:%.*]], 
i32 1, <4 x i1> [[TMP1]])
+// CHECK-NEXT:ret <8 x half> [[TMP2]]

Are these tests still using old names? I'm not missing something about how 
these are generated, am I?



Comment at: clang/utils/TableGen/MveEmitter.cpp:132
+// the pointee type.
+Pointer,
+  };

simon_tatham wrote:
> dmgreen wrote:
> > The gathers are really a Vector of Pointers, in a way. But in the 
> > intrinsics (and IR), they are just treated as a vector of ints, so I 
> > presume a new type is not needed? We may (but not yet) want to make use of 
> > the llvm masked gathers. We would have to add codegen support for them 
> > first though (which I don't think we have plans for in the near term).
> Yes, I'm working so far on the assumption that we don't need to represent 
> scatter/gather address vectors as a special vector-of-pointers type.
> 
> (If nothing else, it would be a bit strange for the 64-bit versions, where 
> the vector element isn't even the same //size// as a pointer.)
> 
> If auto-generation of gather loads during vectorization turns out to need a 
> special representation, then I suppose we'll have to rethink.
Sounds good.



Comment at: clang/utils/TableGen/MveEmitter.cpp:207
+// pointer, especially if the pointee is also const.
+if (isa(Pointee)) {
+  if (Const)

simon_tatham wrote:
> dmgreen wrote:
> > Would making this always east const be simpler? Do we generate anything 
> > with inner pointer types? Should there be a whitespace before the "const " 
> > in Name += "const "?
> There shouldn'

[PATCH] D66647: [clangd] DefineInline action apply logic with fully qualified names

2019-10-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 223620.
kadircet marked 9 inline comments as done.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66647

Files:
  clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.h
  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
@@ -25,6 +25,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -103,7 +104,7 @@
   EXPECT_UNAVAILABLE(R"cpp(R"(multi )" ^"token " u8"str\ning")cpp"); // nonascii
   EXPECT_UNAVAILABLE(R"cpp(^R^"^(^multi )" "token " "str\ning")cpp"); // raw
   EXPECT_UNAVAILABLE(R"cpp(^"token\n" __FILE__)cpp"); // chunk is macro
-  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp"); // forbidden escape char
+  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp");   // forbidden escape char
 
   const char *Input = R"cpp(R"(multi
 token)" "\nst^ring\n" "literal")cpp";
@@ -814,6 +815,514 @@
   })cpp");
 }
 
+TEST_F(DefineInlineTest, TransformUsings) {
+  EXPECT_EQ(apply(R"cpp(
+  namespace a {
+  void bar();
+  namespace b {
+  void baz();
+  namespace c {
+  void aux();
+  }
+  }
+  }
+
+  void foo();
+  void f^oo() {
+using namespace a;
+
+using namespace b;
+using namespace a::b;
+
+using namespace c;
+using namespace b::c;
+using namespace a::b::c;
+
+using a::bar;
+
+using b::baz;
+using a::b::baz;
+
+using c::aux;
+using b::c::aux;
+using a::b::c::aux;
+
+namespace d = c;
+namespace d = b::c;
+  }
+  )cpp"),
+R"cpp(
+  namespace a {
+  void bar();
+  namespace b {
+  void baz();
+  namespace c {
+  void aux();
+  }
+  }
+  }
+
+  void foo(){
+using namespace a;
+
+using namespace a::b;
+using namespace a::b;
+
+using namespace a::b::c;
+using namespace a::b::c;
+using namespace a::b::c;
+
+using a::bar;
+
+using a::b::baz;
+using a::b::baz;
+
+using a::b::c::aux;
+using a::b::c::aux;
+using a::b::c::aux;
+
+namespace d = a::b::c;
+namespace d = a::b::c;
+  }
+  
+  )cpp");
+}
+
+TEST_F(DefineInlineTest, TransformDecls) {
+  EXPECT_EQ(apply(R"cpp(
+  void foo()/*Comment -_-*/  ;
+
+  void f^oo() {
+class Foo {
+public:
+  void foo();
+  int x;
+  static int y;
+};
+Foo::y = 0;
+
+enum En { Zero, One };
+En x = Zero;
+
+enum class EnClass { Zero, One };
+EnClass y = EnClass::Zero;
+
+template  class Bar {};
+Bar z;
+  }
+  )cpp"),
+R"cpp(
+  void foo()/*Comment -_-*/  {
+class Foo {
+public:
+  void foo();
+  int x;
+  static int y;
+};
+Foo::y = 0;
+
+enum En { Zero, One };
+En x = Zero;
+
+enum class EnClass { Zero, One };
+EnClass y = EnClass::Zero;
+
+template  class Bar {};
+Bar z;
+  }
+
+  
+  )cpp");
+}
+
+TEST_F(DefineInlineTest, TransformTemplDecls) {
+  EXPECT_EQ(apply(R"cpp(
+  namespace a {
+template  class Bar {
+public:
+  void bar();
+};
+template  T bar;
+template  void aux() {}
+  }
+
+  void foo()/*Comment -_-*/  ;
+
+  void f^oo() {
+using namespace a;
+bar>.bar();
+aux>();
+  }
+  )cpp"),
+R"cpp(
+  namespace a {
+template  class Bar {
+public:
+  void bar();
+};
+template  T bar;
+template  void aux() {}
+  }
+
+  void foo()/*Comment -_-*/  {
+using namespace a;
+a::bar>.bar();
+a::aux>();
+  }
+
+  
+  )cpp");
+}
+
+MATCHER_P2(FileWithContents, FileName, Contents, "") {
+  return arg.first() == FileName && arg.second == Contents;
+}
+
+TEST_F(DefineInlineTest, TransformMembers) {
+  EXPECT_EQ(apply(R"cpp(
+  class Foo {
+void foo()/*Comment -_-*/  ;
+  };
+
+  void Foo::f^oo() {
+return;
+  }
+  )cpp"),
+R"cpp(
+  class Foo {
+void foo()/*Comment -_-*/  {
+return;
+  }
+  };
+
+  
+  )cpp");
+
+  ExtraFiles["a.h"] = R"cpp(
+  class Foo {
+void foo()/*Comment -_-*/  ;
+  };)cpp";
+
+  llvm::StringMap EditedFiles;
+  EXPECT_EQ(apply(R"cpp(
+  #include "a.h"
+  void Foo::f^oo() {
+return;
+  })cpp",
+  &EditedFiles),
+R"cpp(
+  #include "a.h"
+  )cpp");
+  EXPECT_THAT(EditedFiles,
+  testing::ElementsAre(FileWithContents(testPath("a.h"),
+R"cpp(
+  class Foo {
+void foo()/*Comment -_-*/  {
+return

[PATCH] D68551: [clang-format] [NFC] Ensure clang-format is itself clang-formatted.

2019-10-07 Thread Mitchell via Phabricator via cfe-commits
mitchell-stellar accepted this revision.
mitchell-stellar added a comment.
This revision is now accepted and ready to land.

LGTM.

I agree that a system in place that either enforces clang-formatting on commit 
or after the fact would be ideal. Otherwise, I don't see a need to have to 
approve these NFC commits.


Repository:
  rC Clang

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

https://reviews.llvm.org/D68551



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


[PATCH] D53768: Add VerboseOutputStream to CompilerInstance

2019-10-07 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added a comment.

Ping


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

https://reviews.llvm.org/D53768



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


[PATCH] D68535: Fix loop unrolling initialization in the new pass manager

2019-10-07 Thread Alina Sbirlea via Phabricator via cfe-commits
asbirlea added a comment.

Maybe elaborate in the patch description what `determine when and how we will 
unroll loops.` means?
e.g.: 
"The default before and after this patch is for LoopUnroll to be enabled, and 
for it to use a cost model to determine whether to unroll the loop 
(`OnlyWhenForced = false`). Before this patch, disabling loop unroll would not 
run the LoopUnroll pass. After this patch, the LoopUnroll pass is being run, 
but it restricts unrolling to only the loops marked by a pragma 
(`OnlyWhenForced = true`).
In addition, this patch disables the UnrollAndJam pass when disabling 
unrolling."

Otherwise LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68535



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


[PATCH] D66647: [clangd] DefineInline action apply logic with fully qualified names

2019-10-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp:196
+
+std::string Qualifier = printNamespaceScope(*ND->getDeclContext());
+if (auto Err = Replacements.add(

ilya-biryukov wrote:
> You would want to use `ND->printNestedNameSpecifier()` instead to avoid 
> printing inline namespaces:
> ```
> namespace std { inline namespace v1 { 
>  struct vector {};
> }}
> ```
> 
> ^-- I believe the current code would print `std::v1::` for `vector` and we 
> want `std::`.
> Could you add this example to tests too?
it is the opposite, `printNamespaceScope` skips anonymous and inline 
namespaces, whereas `printNestedNameSpecifier` also prints those. adding a test.



Comment at: clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp:226
+llvm::Expected
+renameParameters(const FunctionDecl *Dest, const FunctionDecl *Source) {
+  const SourceManager &SM = Dest->getASTContext().getSourceManager();

ilya-biryukov wrote:
> This does not rename any references to those parameters, right?
> E.g.
> ```
> template  void foo(T x);
> 
> template  void foo(U x) {}
> ```
> 
> would turn into
> ```
> template  void foo(T x);
> ```
> right?
yes that's right, just adding a unittest will address this later on


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66647



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


r373918 - Codegen - silence static analyzer getAs<> null dereference warnings. NFCI.

2019-10-07 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Mon Oct  7 09:42:25 2019
New Revision: 373918

URL: http://llvm.org/viewvc/llvm-project?rev=373918&view=rev
Log:
Codegen - silence static analyzer getAs<> null dereference warnings. NFCI.

The static analyzer is warning about potential null dereferences, but in these 
cases we should be able to use castAs<> directly and if not assert will fire 
for us.

Modified:
cfe/trunk/lib/CodeGen/CGAtomic.cpp
cfe/trunk/lib/CodeGen/CGCXX.cpp
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/CodeGen/CGObjCGNU.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/lib/CodeGen/TargetInfo.cpp

Modified: cfe/trunk/lib/CodeGen/CGAtomic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGAtomic.cpp?rev=373918&r1=373917&r2=373918&view=diff
==
--- cfe/trunk/lib/CodeGen/CGAtomic.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGAtomic.cpp Mon Oct  7 09:42:25 2019
@@ -970,7 +970,7 @@ RValue CodeGenFunction::EmitAtomicExpr(A
 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
   if (!E->isOpenCL())
 return V;
-  auto AS = PT->getAs()->getPointeeType().getAddressSpace();
+  auto AS = PT->castAs()->getPointeeType().getAddressSpace();
   if (AS == LangAS::opencl_generic)
 return V;
   auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);

Modified: cfe/trunk/lib/CodeGen/CGCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCXX.cpp?rev=373918&r1=373917&r2=373918&view=diff
==
--- cfe/trunk/lib/CodeGen/CGCXX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCXX.cpp Mon Oct  7 09:42:25 2019
@@ -104,8 +104,8 @@ bool CodeGenModule::TryEmitBaseDestructo
   // Give up if the calling conventions don't match. We could update the call,
   // but it is probably not worth it.
   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
-  if (BaseD->getType()->getAs()->getCallConv() !=
-  D->getType()->getAs()->getCallConv())
+  if (BaseD->getType()->castAs()->getCallConv() !=
+  D->getType()->castAs()->getCallConv())
 return true;
 
   GlobalDecl AliasDecl(D, Dtor_Base);

Modified: cfe/trunk/lib/CodeGen/CGClass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGClass.cpp?rev=373918&r1=373917&r2=373918&view=diff
==
--- cfe/trunk/lib/CodeGen/CGClass.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGClass.cpp Mon Oct  7 09:42:25 2019
@@ -739,7 +739,7 @@ bool CodeGenFunction::IsConstructorDeleg
 
   // We also disable the optimization for variadic functions because
   // it's impossible to "re-pass" varargs.
-  if (Ctor->getType()->getAs()->isVariadic())
+  if (Ctor->getType()->castAs()->isVariadic())
 return false;
 
   // FIXME: Decide if we can do a delegation of a delegating constructor.

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=373918&r1=373917&r2=373918&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Mon Oct  7 09:42:25 2019
@@ -1659,7 +1659,7 @@ void CGDebugInfo::CollectCXXMemberFuncti
 if (!Method || Method->isImplicit() || Method->hasAttr())
   continue;
 
-if (Method->getType()->getAs()->getContainedAutoType())
+if (Method->getType()->castAs()->getContainedAutoType())
   continue;
 
 // Reuse the existing member function declaration if it exists.
@@ -4561,7 +4561,7 @@ void CGDebugInfo::EmitUsingDecl(const Us
   // return type in the definition)
   if (const auto *FD = dyn_cast(USD.getUnderlyingDecl()))
 if (const auto *AT =
-FD->getType()->getAs()->getContainedAutoType())
+FD->getType()->castAs()->getContainedAutoType())
   if (AT->getDeducedType().isNull())
 return;
   if (llvm::DINode *Target =

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=373918&r1=373917&r2=373918&view=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Mon Oct  7 09:42:25 2019
@@ -997,7 +997,7 @@ EmitComplexPrePostIncDec(const UnaryOper
 // Add the inc/dec to the real part.
 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
   } else {
-QualType ElemTy = E->getType()->getAs()->getElementType();
+QualType ElemTy = E->getType()->castAs()->getElementType();
 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
 if (!isInc)
   FVal.changeSign();
@@ -2194,7 

[PATCH] D68578: [HIP] Fix device stub name

2019-10-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D68578#1697822 , @tra wrote:

> Could you elaborate on how exactly current implementation does not work?
>
> I would expect the kernel and the stub to be two distinct entities, as far as 
> debugger is concerned. It does have enough information to track each 
> independently (different address, .stub suffix, perhaps knowledge whether 
> it's device or host code). Without the details, it looks to me that this is 
> something that can and should be dealt with in the debugger. I've asked the 
> same question in D63335  but I don't think 
> I've got a good answer.


HIP debugger is a branch of gdb and the changes to support HIP will be 
upstreamed. When users set break point on a kernel, they intend to set a break 
point on the real kernel, not the device stub function. The device stub 
function is only a compiler generated helper function to help launch the 
kernel. Therefore it should have a different name so that it does not interfere 
with the symbol resolution of the real kernel.


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

https://reviews.llvm.org/D68578



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


[PATCH] D29039: [clang-format] Proposal for clang-format -r option

2019-10-07 Thread Mitchell via Phabricator via cfe-commits
mitchell-stellar added a subscriber: djasper.
mitchell-stellar added a comment.

I agree with @djasper that this is outside the scope of clang-format. git for 
Windows gives you a full set of bash utilities to utilize, so doing stuff like 
this on Windows is much easier now.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D29039



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


[PATCH] D68578: [HIP] Fix device stub name

2019-10-07 Thread Michael Liao via Phabricator via cfe-commits
hliao added inline comments.



Comment at: lib/CodeGen/CGCUDANV.cpp:235
CGF.CGM.getContext().getTargetInfo().getCXXABI())) ||
+ CGF.getLangOpts().HIP ||
  getDeviceStubName(getDeviceSideName(CGF.CurFuncDecl)) ==

keeping the original assertion in HIP is still valuable to capture naming 
mismatch issue for unnamed types


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

https://reviews.llvm.org/D68578



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


r373921 - [clang-format] [NFC] Ensure clang-format is itself clang-formatted.

2019-10-07 Thread Paul Hoad via cfe-commits
Author: paulhoad
Date: Mon Oct  7 09:53:35 2019
New Revision: 373921

URL: http://llvm.org/viewvc/llvm-project?rev=373921&view=rev
Log:
[clang-format] [NFC] Ensure clang-format is itself clang-formatted.

Summary:
Before making a proposed change, ensure ClangFormat.cpp is fully 
clang-formatted,

no functional change just clang-formatting using the in tree .clang-format.

Reviewers: mitchell-stellar

Reviewed By: mitchell-stellar

Subscribers: Eugene.Zelenko, cfe-commits

Tags: #clang-format, #clang

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

Modified:
cfe/trunk/tools/clang-format/ClangFormat.cpp

Modified: cfe/trunk/tools/clang-format/ClangFormat.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-format/ClangFormat.cpp?rev=373921&r1=373920&r2=373921&view=diff
==
--- cfe/trunk/tools/clang-format/ClangFormat.cpp (original)
+++ cfe/trunk/tools/clang-format/ClangFormat.cpp Mon Oct  7 09:53:35 2019
@@ -51,13 +51,14 @@ static cl::list
  "Can only be used with one input file."),
 cl::cat(ClangFormatCategory));
 static cl::list
-LineRanges("lines", cl::desc(": - format a range of\n"
- "lines (both 1-based).\n"
- "Multiple ranges can be formatted by specifying\n"
- "several -lines arguments.\n"
- "Can't be used with -offset and -length.\n"
- "Can only be used with one input file."),
-   cl::cat(ClangFormatCategory));
+LineRanges("lines",
+   cl::desc(": - format a range of\n"
+"lines (both 1-based).\n"
+"Multiple ranges can be formatted by specifying\n"
+"several -lines arguments.\n"
+"Can't be used with -offset and -length.\n"
+"Can only be used with one input file."),
+   cl::cat(ClangFormatCategory));
 static cl::opt
 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
   cl::init(clang::format::DefaultFormatStyle),
@@ -72,12 +73,12 @@ static cl::opt
   cl::init(clang::format::DefaultFallbackStyle),
   cl::cat(ClangFormatCategory));
 
-static cl::opt
-AssumeFileName("assume-filename",
-   cl::desc("When reading from stdin, clang-format assumes this\n"
-"filename to look for a style config file (with\n"
-"-style=file) and to determine the language."),
-   cl::init(""), cl::cat(ClangFormatCategory));
+static cl::opt AssumeFileName(
+"assume-filename",
+cl::desc("When reading from stdin, clang-format assumes this\n"
+ "filename to look for a style config file (with\n"
+ "-style=file) and to determine the language."),
+cl::init(""), cl::cat(ClangFormatCategory));
 
 static cl::opt Inplace("i",
  cl::desc("Inplace edit s, if specified."),
@@ -249,8 +250,8 @@ static bool format(StringRef FileName) {
   // On Windows, overwriting a file with an open file mapping doesn't work,
   // so read the whole file into memory when formatting in-place.
   ErrorOr> CodeOrErr =
-  !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
-  MemoryBuffer::getFileOrSTDIN(FileName);
+  !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName)
+: MemoryBuffer::getFileOrSTDIN(FileName);
   if (std::error_code EC = CodeOrErr.getError()) {
 errs() << EC.message() << "\n";
 return true;
@@ -264,20 +265,21 @@ static bool format(StringRef FileName) {
   // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
   // for more information.
   StringRef BufStr = Code->getBuffer();
-  const char *InvalidBOM = llvm::StringSwitch(BufStr)
-.StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
-  "UTF-32 (BE)")
-.StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
-  "UTF-32 (LE)")
-.StartsWith("\xFE\xFF", "UTF-16 (BE)")
-.StartsWith("\xFF\xFE", "UTF-16 (LE)")
-.StartsWith("\x2B\x2F\x76", "UTF-7")
-.StartsWith("\xF7\x64\x4C", "UTF-1")
-.StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
-.StartsWith("\x0E\xFE\xFF", "SCSU")
-.StartsWith("\xFB\xEE\x28", "BOCU-1")
-.StartsWith("\x84\x31\x95\x33", "GB-18030")
-.Default(nullptr);
+  const char *InvalidBOM =
+  llvm::StringSwitch(BufStr)
+  .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
+  "UTF-32 (BE)")
+  .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
+  "UTF-32 (LE)")
+  .StartsWith("\xFE\xFF", "UTF-16 (BE)")
+ 

[PATCH] D68554: [clang-format] Proposal for clang-format to give compiler style warnings

2019-10-07 Thread Mitchell via Phabricator via cfe-commits
mitchell-stellar added a comment.

I don't care for the command line switches that try to emulate compiler flags. 
I am also of the opinion that external scripts should be used for this 
functionality. git for Windows gives you a full set of bash utilities to 
utilize, so doing stuff like this on Windows is much easier now.


Repository:
  rC Clang

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

https://reviews.llvm.org/D68554



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


r373922 - [clang-format] [PR27004] omits leading space for noexcept when formatting operator delete()

2019-10-07 Thread Paul Hoad via cfe-commits
Author: paulhoad
Date: Mon Oct  7 10:03:44 2019
New Revision: 373922

URL: http://llvm.org/viewvc/llvm-project?rev=373922&view=rev
Log:
[clang-format] [PR27004] omits leading space for noexcept when formatting 
operator delete()

Summary:
clang-format is incorrectly thinking the parameter parens are part of a cast 
operation, this is resulting in there sometimes being not space between the 
paren and the noexcept (and other keywords like volatile etc..)

```
void operator++(int) noexcept;
void operator++(int &) noexcept;
void operator delete(void *, std::size_t, const std::nothrow_t &)noexcept;
```

Reviewers: klimek, owenpan, mitchell-stellar

Reviewed By: mitchell-stellar

Subscribers: cfe-commits

Tags: #clang-format, #clang

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

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

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=373922&r1=373921&r2=373922&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Oct  7 10:03:44 2019
@@ -1611,6 +1611,13 @@ private:
 if (Tok.Next->is(tok::question))
   return false;
 
+// Functions which end with decorations like volatile, noexcept are 
unlikely
+// to be casts.
+if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
+  tok::kw_throw, tok::l_square, tok::arrow,
+  Keywords.kw_override, Keywords.kw_final))
+  return false;
+
 // As Java has no function types, a "(" after the ")" likely means that 
this
 // is a cast.
 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=373922&r1=373921&r2=373922&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Mon Oct  7 10:03:44 2019
@@ -14678,6 +14678,33 @@ TEST_F(FormatTest, AlternativeOperators)
   */
 }
 
+TEST_F(FormatTest, NotCastRPaen) {
+
+  verifyFormat("void operator++(int) noexcept;");
+  verifyFormat("void operator++(int &) noexcept;");
+  verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t 
"
+   "&) noexcept;");
+  verifyFormat(
+  "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(foo &) noexcept;");
+  verifyFormat("void operator delete(foo) noexcept;");
+  verifyFormat("void operator delete(int) noexcept;");
+  verifyFormat("void operator delete(int &) noexcept;");
+  verifyFormat("void operator delete(int &) volatile noexcept;");
+  verifyFormat("void operator delete(int &) const");
+  verifyFormat("void operator delete(int &) = default");
+  verifyFormat("void operator delete(int &) = delete");
+  verifyFormat("void operator delete(int &) [[noreturn]]");
+  verifyFormat("void operator delete(int &) throw();");
+  verifyFormat("void operator delete(int &) throw(int);");
+  verifyFormat("auto operator delete(int &) -> int;");
+  verifyFormat("auto operator delete(int &) override");
+  verifyFormat("auto operator delete(int &) final");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


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


[PATCH] D63960: [C++20] Add consteval-specific semantic for functions

2019-10-07 Thread Tyker via Phabricator via cfe-commits
Tyker updated this revision to Diff 223624.

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

https://reviews.llvm.org/D63960

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp

Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -12,6 +12,7 @@
 }
 
 constexpr auto l_eval = [](int i) consteval {
+// expected-note@-1+ {{declared here}}
 
   return i;
 };
@@ -23,6 +24,7 @@
 
 struct A {
   consteval int f1(int i) const {
+// expected-note@-1 {{declared here}}
 return i;
   }
   consteval A(int i);
@@ -62,3 +64,203 @@
 consteval int main() { // expected-error {{'main' is not allowed to be declared consteval}}
   return 0;
 }
+
+consteval int f_eval(int i) {
+// expected-note@-1+ {{declared here}}
+  return i;
+}
+
+namespace taking_address {
+
+using func_type = int(int);
+
+func_type* p1 = (&f_eval);
+// expected-error@-1 {{take address}}
+func_type* p7 = __builtin_addressof(f_eval);
+// expected-error@-1 {{take address}}
+
+auto p = f_eval;
+// expected-error@-1 {{take address}}
+
+auto m1 = &basic_sema::A::f1;
+// expected-error@-1 {{take address}}
+auto l1 = &decltype(basic_sema::l_eval)::operator();
+// expected-error@-1 {{take address}}
+
+consteval int f(int i) {
+// expected-note@-1+ {{declared here}}
+  return i;
+}
+
+auto ptr = &f;
+// expected-error@-1 {{take address}}
+
+auto f1() {
+  return &f;
+// expected-error@-1 {{take address}}
+}
+
+}
+
+namespace invalid_function {
+using size_t = unsigned long;
+struct A {
+  consteval void *operator new(size_t count);
+  // expected-error@-1 {{'operator new' cannot be declared consteval}}
+  consteval void *operator new[](size_t count);
+  // expected-error@-1 {{'operator new[]' cannot be declared consteval}}
+  consteval void operator delete(void* ptr);
+  // expected-error@-1 {{'operator delete' cannot be declared consteval}}
+  consteval void operator delete[](void* ptr);
+  // expected-error@-1 {{'operator delete[]' cannot be declared consteval}}
+};
+
+}
+
+namespace nested {
+consteval int f() {
+  return 0;
+}
+
+consteval int f1(...) {
+  return 1;
+}
+
+enum E {};
+
+using T = int(&)();
+
+consteval auto operator+ (E, int(*a)()) {
+  return 0;
+}
+
+void d() {
+  auto i = f1(E() + &f);
+}
+
+auto l0 = [](auto) consteval {
+  return 0;
+};
+
+int i0 = l0(&f1);
+
+int i1 = f1(l0(4));
+
+int i2 = f1(&f1, &f1, &f1, &f1, &f1, &f1, &f1);
+
+int i3 = f1(f1(f1(&f1, &f1), f1(&f1, &f1), f1(f1(&f1, &f1), &f1)));
+
+}
+
+namespace user_defined_literal {
+
+consteval int operator"" _test(unsigned long long i) {
+// expected-note@-1+ {{declared here}}
+  return 0;
+}
+
+int i = 0_test;
+
+auto ptr = &operator"" _test;
+// expected-error@-1 {{take address}}
+
+}
+
+namespace return_address {
+
+consteval int f() {
+  return 0;
+}
+
+consteval int(*ret1(int i))() {
+  return &f;
+}
+
+auto ptr = ret1(0);
+// expected-error@-1 {{could not be evaluated}}
+// expected-note@-2 {{pointer to a consteval}}
+
+struct A {
+  consteval int f(int) {
+return 0;
+  }
+};
+
+using mem_ptr_type = int (A::*)(int);
+
+template
+struct C {};
+
+C<&A::f> c;
+// expected-error@-1 {{is not a constant expression}}
+// expected-note@-2 {{pointer to a consteval}}
+
+consteval mem_ptr_type ret2() {
+  return &A::f;
+}
+
+C c1;
+// expected-error@-1 {{is not a constant expression}}
+// expected-note@-2 {{pointer to a consteval}}
+
+}
+
+namespace context {
+
+int g_i;
+// expected-note@-1 {{declared here}}
+
+consteval int f(int) {
+  return 0;
+}
+
+constexpr int c_i = 0;
+
+int t1 = f(g_i);
+// expected-error@-1 {{could not be evaluated}}
+// expected-note@-2 {{read of non-const variable}}
+int t3 = f(c_i);
+
+constexpr int f_c(int i) {
+// expected-note@-1 {{declared here}}
+  int t = f(i);
+// expected-error@-1 {{could not be evaluated}}
+// expected-note@-2 {{read of non-const variable}}
+  return f(0);  
+}
+
+consteval int f_eval(int i) {
+  return f(i);
+}
+
+auto l0 = [](int i) consteval {
+  return f(i);
+};
+
+auto l1 = [](int i) constexpr {
+// expected-note@-1 {{declared here}}
+  int t = f(i);
+// expected-error@-1 {{could not be evaluated}}
+// expected-note@-2 {{read of non-const variable}}
+  return f(0);  
+};
+
+}
+
+namespace cleanup {
+
+struct A {
+  int *p = new int(42);
+  consteval int get() { return *p; }
+  constexpr ~A() { delete p; }
+};
+int k1 = A().get();
+
+struct B {
+  int *p = new in

[clang-tools-extra] r373924 - [clangd] Fix raciness in code completion tests

2019-10-07 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Mon Oct  7 10:12:18 2019
New Revision: 373924

URL: http://llvm.org/viewvc/llvm-project?rev=373924&view=rev
Log:
[clangd] Fix raciness in code completion tests

Reviewers: sammccall, ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/unittests/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/CodeCompleteTests.cpp?rev=373924&r1=373923&r2=373924&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/CodeCompleteTests.cpp Mon Oct  7 
10:12:18 2019
@@ -18,6 +18,7 @@
 #include "TestFS.h"
 #include "TestIndex.h"
 #include "TestTU.h"
+#include "Threading.h"
 #include "index/Index.h"
 #include "index/MemIndex.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
@@ -27,6 +28,8 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -1112,8 +1115,9 @@ public:
   bool
   fuzzyFind(const FuzzyFindRequest &Req,
 llvm::function_ref Callback) const override {
-std::lock_guard Lock(Mut);
+std::unique_lock Lock(Mut);
 Requests.push_back(Req);
+ReceivedRequestCV.notify_one();
 return true;
   }
 
@@ -1131,8 +1135,10 @@ public:
   // isn't used in production code.
   size_t estimateMemoryUsage() const override { return 0; }
 
-  const std::vector consumeRequests() const {
-std::lock_guard Lock(Mut);
+  const std::vector consumeRequests(size_t Num) const {
+std::unique_lock Lock(Mut);
+EXPECT_TRUE(wait(Lock, ReceivedRequestCV, timeoutSeconds(10),
+ [this, Num] { return Requests.size() == Num; }));
 auto Reqs = std::move(Requests);
 Requests = {};
 return Reqs;
@@ -1140,16 +1146,21 @@ public:
 
 private:
   // We need a mutex to handle async fuzzy find requests.
+  mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
   mutable std::vector Requests;
 };
 
-std::vector captureIndexRequests(llvm::StringRef Code) {
+// Clients have to consume exactly Num requests.
+std::vector captureIndexRequests(llvm::StringRef Code,
+   size_t Num = 1) {
   clangd::CodeCompleteOptions Opts;
   IndexRequestCollector Requests;
   Opts.Index = &Requests;
   completions(Code, {}, Opts);
-  return Requests.consumeRequests();
+  const auto Reqs = Requests.consumeRequests(Num);
+  EXPECT_EQ(Reqs.size(), Num);
+  return Reqs;
 }
 
 TEST(CompletionTest, UnqualifiedIdQuery) {
@@ -2098,18 +2109,15 @@ TEST(CompletionTest, EnableSpeculativeIn
 
   auto CompleteAtPoint = [&](StringRef P) {
 cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
-// Sleep for a while to make sure asynchronous call (if applicable) is also
-// triggered before callback is invoked.
-std::this_thread::sleep_for(std::chrono::milliseconds(100));
   };
 
   CompleteAtPoint("1");
-  auto Reqs1 = Requests.consumeRequests();
+  auto Reqs1 = Requests.consumeRequests(1);
   ASSERT_EQ(Reqs1.size(), 1u);
   EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
 
   CompleteAtPoint("2");
-  auto Reqs2 = Requests.consumeRequests();
+  auto Reqs2 = Requests.consumeRequests(1);
   // Speculation succeeded. Used speculative index result.
   ASSERT_EQ(Reqs2.size(), 1u);
   EXPECT_EQ(Reqs2[0], Reqs1[0]);
@@ -2117,7 +2125,7 @@ TEST(CompletionTest, EnableSpeculativeIn
   CompleteAtPoint("3");
   // Speculation failed. Sent speculative index request and the new index
   // request after sema.
-  auto Reqs3 = Requests.consumeRequests();
+  auto Reqs3 = Requests.consumeRequests(2);
   ASSERT_EQ(Reqs3.size(), 2u);
 }
 


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


[PATCH] D68574: [libTooling] Add `toString` method to the Stencil class

2019-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

The tests broke the build on some platforms because of the use of raw strings 
in macros. Fixing now...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68574



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


[PATCH] D67985: CFI: wrong type passed to llvm.type.test with multiple inheritance devirtualization

2019-10-07 Thread Filipe Cabecinhas via Phabricator via cfe-commits
filcab added subscribers: pcc, filcab.
filcab added a comment.

It seems there's a FIXME anticipating this problem.

@pcc: Can you double-check, please?

Thank you,
Filipe


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67985



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


[PATCH] D67985: CFI: wrong type passed to llvm.type.test with multiple inheritance devirtualization

2019-10-07 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc added a comment.

Can you add a CodeGenCXX test as well, please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67985



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


[PATCH] D68584: Fix Calling Convention through aliases

2019-10-07 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc accepted this revision.
pcc added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:251
  // Make sure the call and the callee agree on calling convention.
-  if (llvm::Function *dtorFn =
-  dyn_cast(dtor.getCallee()->stripPointerCasts()))
+  if (llvm::Function *dtorFn = dyn_cast(
+  dtor.getCallee()->stripPointerCastsAndAliases()))

Nit: while here you could change this to `auto *`.


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

https://reviews.llvm.org/D68584



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


  1   2   >