[PATCH] D67695: [clangd] Implement getBeginning for overloaded operators.

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



Comment at: clang-tools-extra/clangd/SourceCode.cpp:256
+
 SourceLocation getBeginningOfIdentifier(const Position &Pos,
 const SourceManager &SM,

hokein wrote:
> the function name doesn't match what it does now, considering a new name for 
> it, `getBeginningOfIdentifierOrOverloadedOperator` seems too verbose, maybe 
> just `getBeginning`?
`getBeginning` sounds too generic too me, would definitely avoid that. I think 
`getBeginningOfIdentifier` creates less confusion, albeit it definitely creates 
**some**.

No better alternative comes to mind, though. Maybe keep as is and update the 
comment to mention it also handles tokens for operators?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67695



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


[clang-tools-extra] r373304 - [clang-tidy] Fix module registry name and description for Darwin clang-tidy module.

2019-10-01 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Tue Oct  1 00:17:26 2019
New Revision: 373304

URL: http://llvm.org/viewvc/llvm-project?rev=373304&view=rev
Log:
[clang-tidy] Fix module registry name and description for Darwin clang-tidy 
module.

Summary: When creating the module, must have copy-pasted from the misc module, 
and forgotten to update the name/description of the module in the registry.

Reviewers: stephanemoore, benhamilton, gribozavr

Reviewed By: gribozavr

Subscribers: xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra, #llvm

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

Modified:
clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp

Modified: clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp?rev=373304&r1=373303&r2=373304&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp Tue Oct  1 
00:17:26 2019
@@ -27,7 +27,7 @@ public:
 
 // Register the DarwinTidyModule using this statically initialized variable.
 static ClangTidyModuleRegistry::Add
-X("misc-module", "Adds miscellaneous lint checks.");
+X("darwin-module", "Adds Darwin-specific lint checks.");
 
 // This anchor is used to force the linker to link in the generated object file
 // and thus register the DarwinModule.


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


[PATCH] D68251: [clang-tidy] Fix module registry name and description for Darwin clang-tidy module.

2019-10-01 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373304: [clang-tidy] Fix module registry name and 
description for Darwin clang-tidy… (authored by gribozavr, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68251?vs=222512&id=222551#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68251

Files:
  clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp


Index: clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
===
--- clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
+++ clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
@@ -27,7 +27,7 @@
 
 // Register the DarwinTidyModule using this statically initialized variable.
 static ClangTidyModuleRegistry::Add
-X("misc-module", "Adds miscellaneous lint checks.");
+X("darwin-module", "Adds Darwin-specific lint checks.");
 
 // This anchor is used to force the linker to link in the generated object file
 // and thus register the DarwinModule.


Index: clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
===
--- clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
+++ clang-tools-extra/trunk/clang-tidy/darwin/DarwinTidyModule.cpp
@@ -27,7 +27,7 @@
 
 // Register the DarwinTidyModule using this statically initialized variable.
 static ClangTidyModuleRegistry::Add
-X("misc-module", "Adds miscellaneous lint checks.");
+X("darwin-module", "Adds Darwin-specific lint checks.");
 
 // This anchor is used to force the linker to link in the generated object file
 // and thus register the DarwinModule.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r373305 - [clangd] Handle OverloadExpr in targetDecl

2019-10-01 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Oct  1 00:27:55 2019
New Revision: 373305

URL: http://llvm.org/viewvc/llvm-project?rev=373305&view=rev
Log:
[clangd] Handle OverloadExpr in targetDecl

Reviewers: sammccall

Reviewed By: sammccall

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/FindTarget.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.cpp?rev=373305&r1=373304&r2=373305&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp Tue Oct  1 00:27:55 2019
@@ -189,6 +189,10 @@ public:
   D = USD;
 Outer.add(D, Flags);
   }
+  void VisitOverloadExpr(const OverloadExpr *OE) {
+for (auto *D : OE->decls())
+  Outer.add(D, Flags);
+  }
   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
 Outer.add(CCE->getConstructor(), Flags);
   }

Modified: clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp?rev=373305&r1=373304&r2=373305&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp Tue Oct  1 
00:27:55 2019
@@ -393,6 +393,32 @@ TEST_F(TargetDeclTest, Lambda) {
   EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
 }
 
+TEST_F(TargetDeclTest, OverloadExpr) {
+  Code = R"cpp(
+void func(int*);
+void func(char*);
+
+template 
+void foo(T t) {
+  [[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char 
*)");
+
+  Code = R"cpp(
+struct X {
+  void func(int*);
+  void func(char*);
+};
+
+template 
+void foo(X x, T t) {
+  x.[[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char 
*)");
+}
+
 TEST_F(TargetDeclTest, ObjC) {
   Flags = {"-xobjective-c"};
   Code = R"cpp(


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


Re: r371027 - Revert r361885 "[Driver] Fix -working-directory issues"

2019-10-01 Thread Mikael Holmén via cfe-commits
Hi,

On 2019-09-27 10:13, Hans Wennborg wrote:
> Committed a fix in r373049, and I'll ask to have it merged for 9.0.1
> as well. Sorry again for the breakage.

No worries. Thanks for the fix!

/Mikael

> 
> On Thu, Sep 26, 2019 at 7:09 PM Mikael Holmén
>  wrote:
>>
>> Hi,
>>
>> As Karl-Johan said I'll be out of office for a few days so please submit a 
>> fix if you can find the time.
>>
>> Thanks,
>> Mikael
>>
>> Den 26 sep. 2019 15:39 skrev Hans Wennborg :
>>
>> On Thu, Sep 26, 2019 at 12:55 PM Mikael Holmén via cfe-commits
>>  wrote:
>>>
>>> Hi Hans,
>>>
>>> I'm a bit suspicious against the part
>>>
>>>   > This also revertes the part of r369938 which checked that
>>> -working-directory works.
>>>
>>> in this revert.
>>>
>>> You do:
>>>
>>>   > +  SmallString<128> Buf;
>>>   > +  if (!llvm::sys::fs::current_path(Buf))
>>>   > +Buf = ".";
>>>   > +  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
>>>
>>> But if I look at r369938 it seems like before r369938 it looked like
>>>
>>> -  SmallString<128> Buf;
>>> -  if (llvm::sys::fs::current_path(Buf))
>>> -Buf = ".";
>>> -  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
>>>
>>> Note the difference in the condition, where you do
>>>
>>>if (!llvm::sys::fs::current_path(Buf))
>>>
>>> but before it was
>>>
>>>if (llvm::sys::fs::current_path(Buf))
>>>
>>>
>>> We noticed this since
>>>
>>>clang -MJ test.json -O2 -nostdinc empty.c -S -o - && cat test.json
>>>
>>> started to behave differently after this revert. The "directory: " part
>>> in the output suddenly became ".".
>>
>> You're right, it definitely looks like I messed up the revert :-(
>> Looking at the code again, I was probably thrown off by the
>> current_path returning false on success.
>>
>> Since you've been investigating, are you set up to land a fix with a
>> test maybe? Otherwise I can do it, please let me know.
>>
>> Thanks,
>> Hans
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68119: [clangd] Handle OverloadExpr in targetDecl

2019-10-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373305: [clangd] Handle OverloadExpr in targetDecl (authored 
by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68119?vs=222083&id=222552#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68119

Files:
  clang-tools-extra/trunk/clangd/FindTarget.cpp
  clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp


Index: clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
@@ -393,6 +393,32 @@
   EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
 }
 
+TEST_F(TargetDeclTest, OverloadExpr) {
+  Code = R"cpp(
+void func(int*);
+void func(char*);
+
+template 
+void foo(T t) {
+  [[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char 
*)");
+
+  Code = R"cpp(
+struct X {
+  void func(int*);
+  void func(char*);
+};
+
+template 
+void foo(X x, T t) {
+  x.[[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char 
*)");
+}
+
 TEST_F(TargetDeclTest, ObjC) {
   Flags = {"-xobjective-c"};
   Code = R"cpp(
Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -189,6 +189,10 @@
   D = USD;
 Outer.add(D, Flags);
   }
+  void VisitOverloadExpr(const OverloadExpr *OE) {
+for (auto *D : OE->decls())
+  Outer.add(D, Flags);
+  }
   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
 Outer.add(CCE->getConstructor(), Flags);
   }


Index: clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
@@ -393,6 +393,32 @@
   EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
 }
 
+TEST_F(TargetDeclTest, OverloadExpr) {
+  Code = R"cpp(
+void func(int*);
+void func(char*);
+
+template 
+void foo(T t) {
+  [[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)");
+
+  Code = R"cpp(
+struct X {
+  void func(int*);
+  void func(char*);
+};
+
+template 
+void foo(X x, T t) {
+  x.[[func]](t);
+};
+  )cpp";
+  EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");
+}
+
 TEST_F(TargetDeclTest, ObjC) {
   Flags = {"-xobjective-c"};
   Code = R"cpp(
Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -189,6 +189,10 @@
   D = USD;
 Outer.add(D, Flags);
   }
+  void VisitOverloadExpr(const OverloadExpr *OE) {
+for (auto *D : OE->decls())
+  Outer.add(D, Flags);
+  }
   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
 Outer.add(CCE->getConstructor(), Flags);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68260: Decrease the verbosity of the -ftime-trace optionAnd move the relevant information in the doc.

2019-10-01 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru created this revision.
sylvestre.ledru added a reviewer: anton-afanasyev.
Herald added a project: clang.

Currently, building a large software like Firefox shows
'Use chrome://tracing or Speedscope App (https://www.speedscope.app) for 
flamegraph visualization'
for each file.


Repository:
  rC Clang

https://reviews.llvm.org/D68260

Files:
  docs/ClangCommandLineReference.rst
  tools/driver/cc1_main.cpp


Index: tools/driver/cc1_main.cpp
===
--- tools/driver/cc1_main.cpp
+++ tools/driver/cc1_main.cpp
@@ -271,9 +271,6 @@
 llvm::timeTraceProfilerCleanup();
 
 llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
-llvm::errs()
-<< "Use chrome://tracing or Speedscope App "
-   "(https://www.speedscope.app) for flamegraph visualization\n";
   }
 
   // Our error handler depends on the Diagnostics object, which we're
Index: docs/ClangCommandLineReference.rst
===
--- docs/ClangCommandLineReference.rst
+++ docs/ClangCommandLineReference.rst
@@ -1942,7 +1942,8 @@
 
 .. option:: -ftime-trace
 
-Turn on time profiler
+Turn on time profiler. Results can be analyzed with chrome://tracing or
+`Speedscope App `_ for flamegraph visualization
 
 .. option:: -ftime-trace-granularity=
 


Index: tools/driver/cc1_main.cpp
===
--- tools/driver/cc1_main.cpp
+++ tools/driver/cc1_main.cpp
@@ -271,9 +271,6 @@
 llvm::timeTraceProfilerCleanup();
 
 llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
-llvm::errs()
-<< "Use chrome://tracing or Speedscope App "
-   "(https://www.speedscope.app) for flamegraph visualization\n";
   }
 
   // Our error handler depends on the Diagnostics object, which we're
Index: docs/ClangCommandLineReference.rst
===
--- docs/ClangCommandLineReference.rst
+++ docs/ClangCommandLineReference.rst
@@ -1942,7 +1942,8 @@
 
 .. option:: -ftime-trace
 
-Turn on time profiler
+Turn on time profiler. Results can be analyzed with chrome://tracing or
+`Speedscope App `_ for flamegraph visualization
 
 .. option:: -ftime-trace-granularity=
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68260: Decrease the verbosity of the -ftime-trace optionAnd move the relevant information in the doc.

2019-10-01 Thread Anton Afanasyev via Phabricator via cfe-commits
anton-afanasyev accepted this revision.
anton-afanasyev added a comment.
This revision is now accepted and ready to land.

I believe it's better solution, LGTM.


Repository:
  rC Clang

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

https://reviews.llvm.org/D68260



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


r373308 - Decrease the verbosity of the -ftime-trace option

2019-10-01 Thread Sylvestre Ledru via cfe-commits
Author: sylvestre
Date: Tue Oct  1 00:52:42 2019
New Revision: 373308

URL: http://llvm.org/viewvc/llvm-project?rev=373308&view=rev
Log:
Decrease the verbosity of the -ftime-trace option
And move the relevant information in the doc.

Summary:
Currently, building a large software like Firefox shows
'Use chrome://tracing or Speedscope App (https://www.speedscope.app) for 
flamegraph visualization'
for each file.

Reviewers: anton-afanasyev

Reviewed By: anton-afanasyev

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/docs/ClangCommandLineReference.rst
cfe/trunk/tools/driver/cc1_main.cpp

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=373308&r1=373307&r2=373308&view=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Tue Oct  1 00:52:42 2019
@@ -1942,7 +1942,8 @@ Perform ThinLTO importing using provided
 
 .. option:: -ftime-trace
 
-Turn on time profiler
+Turn on time profiler. Results can be analyzed with chrome://tracing or
+`Speedscope App `_ for flamegraph visualization
 
 .. option:: -ftime-trace-granularity=
 

Modified: cfe/trunk/tools/driver/cc1_main.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/driver/cc1_main.cpp?rev=373308&r1=373307&r2=373308&view=diff
==
--- cfe/trunk/tools/driver/cc1_main.cpp (original)
+++ cfe/trunk/tools/driver/cc1_main.cpp Tue Oct  1 00:52:42 2019
@@ -271,9 +271,6 @@ int cc1_main(ArrayRef Argv
 llvm::timeTraceProfilerCleanup();
 
 llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
-llvm::errs()
-<< "Use chrome://tracing or Speedscope App "
-   "(https://www.speedscope.app) for flamegraph visualization\n";
   }
 
   // Our error handler depends on the Diagnostics object, which we're


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


[PATCH] D68137: [clangd] Handle template arguments in findExplicitReferences

2019-10-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 6 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/FindTarget.cpp:556
 
+  // We re-define Traverse*, since there's no corresponding Visit*.
+  bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {

kadircet wrote:
> ... and we need it because, template template decls are visited through it ?
Yes, exactly. Amended this to the comment.



Comment at: clang-tools-extra/clangd/FindTarget.cpp:567
+  break;
+case TemplateArgument::Declaration:
+  break; // FIXME: can this actually happen in TemplateArgumentLoc?

kadircet wrote:
> I suppose these corresponds to non-type template paramters, don't they? 
> (which should make it similar to integral case)
Yes, e.g. see the `wrapper` example from the tests.
However, these arguments seem to be stored and visited as expressions in the 
`TemplateArgumentLoc`.

IIUC, `Declaration` can only happen in template arguments outside 
`TemplateArgumentLoc`.



Comment at: clang-tools-extra/clangd/FindTarget.cpp:618
-if (Ref->NameLoc.isInvalid()) {
-  dlog("invalid location at node {0}", nodeToString(N));
   return;

kadircet wrote:
> can we keep dlog ?
I've initially removed it to avoid passing `DynTypedNode` to `reportReference`, 
but I also agree this `dlog` is useful.

So making the function signature a bit clunky for the sake of debug logging


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68137



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


[PATCH] D68260: Decrease the verbosity of the -ftime-trace optionAnd move the relevant information in the doc.

2019-10-01 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

thanks :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D68260



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


[PATCH] D68137: [clangd] Handle template arguments in findExplicitReferences

2019-10-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 222554.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Restore dlog()
- Check reference to function pointer non-type template parameters in tests
- Extend comment of TraverseTemplateArgumentLoc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68137

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -750,6 +750,39 @@
 }
 )cpp",
"0: targets = {I}\n"},
+  // Template template parameters.
+  {R"cpp(
+template  struct vector {};
+
+template  class TT, template class ...TP>
+void foo() {
+  $0^TT x;
+  $1^foo<$2^TT>();
+  $3^foo<$4^vector>()
+  $5^foo<$6^TP...>();
+}
+)cpp",
+   "0: targets = {TT}\n"
+   "1: targets = {foo}\n"
+   "2: targets = {TT}\n"
+   "3: targets = {foo}\n"
+   "4: targets = {vector}\n"
+   "5: targets = {foo}\n"
+   "6: targets = {TP}\n"},
+  // Non-type template parameters with declarations.
+  {R"cpp(
+int func();
+template  struct wrapper {};
+
+template 
+void foo() {
+  $0^wrapper<$1^func> w;
+  $2^FuncParam();
+}
+)cpp",
+   "0: targets = {wrapper<&func>}\n"
+   "1: targets = {func}\n"
+   "2: targets = {FuncParam}\n"},
   };
 
   for (const auto &C : Cases) {
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
@@ -565,6 +566,34 @@
 return true;
   }
 
+  // We re-define Traverse*, since there's no corresponding Visit*.
+  // TemplateArgumentLoc is the only way to get locations for references to
+  // template template parameters.
+  bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
+switch (A.getArgument().getKind()) {
+case TemplateArgument::Template:
+case TemplateArgument::TemplateExpansion:
+  reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
+   A.getTemplateNameLoc(),
+   {A.getArgument()
+.getAsTemplateOrTemplatePattern()
+.getAsTemplateDecl()}},
+  DynTypedNode::create(A.getArgument()));
+  break;
+case TemplateArgument::Declaration:
+  break; // FIXME: can this actually happen in TemplateArgumentLoc?
+case TemplateArgument::Integral:
+case TemplateArgument::Null:
+case TemplateArgument::NullPtr:
+  break; // no references.
+case TemplateArgument::Pack:
+case TemplateArgument::Type:
+case TemplateArgument::Expression:
+  break; // Handled by VisitType and VisitExpression.
+};
+return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
+  }
+
   bool VisitDecl(Decl *D) {
 visitNode(DynTypedNode::create(*D));
 return true;
@@ -623,15 +652,19 @@
 auto Ref = explicitReference(N);
 if (!Ref)
   return;
+reportReference(*Ref, N);
+  }
+
+  void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
 // Our promise is to return only references from the source code. If we lack
 // location information, skip these nodes.
 // Normally this should not happen in practice, unless there are bugs in the
 // traversals or users started the traversal at an implicit node.
-if (Ref->NameLoc.isInvalid()) {
+if (Ref.NameLoc.isInvalid()) {
   dlog("invalid location at node {0}", nodeToString(N));
   return;
 }
-Out(*Ref);
+Out(Ref);
   }
 
   llvm::function_ref Out;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68260: Decrease the verbosity of the -ftime-trace optionAnd move the relevant information in the doc.

2019-10-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373308: Decrease the verbosity of the -ftime-trace option 
(authored by sylvestre, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68260

Files:
  cfe/trunk/docs/ClangCommandLineReference.rst
  cfe/trunk/tools/driver/cc1_main.cpp


Index: cfe/trunk/tools/driver/cc1_main.cpp
===
--- cfe/trunk/tools/driver/cc1_main.cpp
+++ cfe/trunk/tools/driver/cc1_main.cpp
@@ -271,9 +271,6 @@
 llvm::timeTraceProfilerCleanup();
 
 llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
-llvm::errs()
-<< "Use chrome://tracing or Speedscope App "
-   "(https://www.speedscope.app) for flamegraph visualization\n";
   }
 
   // Our error handler depends on the Diagnostics object, which we're
Index: cfe/trunk/docs/ClangCommandLineReference.rst
===
--- cfe/trunk/docs/ClangCommandLineReference.rst
+++ cfe/trunk/docs/ClangCommandLineReference.rst
@@ -1942,7 +1942,8 @@
 
 .. option:: -ftime-trace
 
-Turn on time profiler
+Turn on time profiler. Results can be analyzed with chrome://tracing or
+`Speedscope App `_ for flamegraph visualization
 
 .. option:: -ftime-trace-granularity=
 


Index: cfe/trunk/tools/driver/cc1_main.cpp
===
--- cfe/trunk/tools/driver/cc1_main.cpp
+++ cfe/trunk/tools/driver/cc1_main.cpp
@@ -271,9 +271,6 @@
 llvm::timeTraceProfilerCleanup();
 
 llvm::errs() << "Time trace json-file dumped to " << Path.str() << "\n";
-llvm::errs()
-<< "Use chrome://tracing or Speedscope App "
-   "(https://www.speedscope.app) for flamegraph visualization\n";
   }
 
   // Our error handler depends on the Diagnostics object, which we're
Index: cfe/trunk/docs/ClangCommandLineReference.rst
===
--- cfe/trunk/docs/ClangCommandLineReference.rst
+++ cfe/trunk/docs/ClangCommandLineReference.rst
@@ -1942,7 +1942,8 @@
 
 .. option:: -ftime-trace
 
-Turn on time profiler
+Turn on time profiler. Results can be analyzed with chrome://tracing or
+`Speedscope App `_ for flamegraph visualization
 
 .. option:: -ftime-trace-granularity=
 
___
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-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D66647#1686021 , @kadircet wrote:

> So currently AST doesn't store any information regarding template parameter 
> locations except the deepest one.
>  Therefore I've changed the availability to discard any methods inside 
> templated classes, since there is no way to
>  validate the template parameter names. Hopefully this should be a rare 
> use-case, and I believe most of the times
>  people have same template paramater names on declaration and definition. Let 
> me know what you think about
>  it.


Thanks! LG, I also think this should be a rare case. The deepest template 
parameters are typically the only ones anyway.

> In addition to that implemented renaming for function parameters and template 
> parameters in case of templated
>  functions.

Thanks, will take a look!


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


[PATCH] D14484: [clang-format] Formatting constructor initializer lists by putting them always on different lines

2019-10-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay requested changes to this revision.
MyDeveloperDay added a comment.
This revision now requires changes to proceed.

Looking at this I'm wondering if this Isn't at least partially handled by the 
`BreakConstructorInitializersStyle`  in combination with 
`ConstructorInitializerAllOnOneLineOrOnePerLine` style?

I can't be exactly sure but I think BreakConstructorInitializersStyle  didn't 
exist before 2017 D32479: clang-format: Introduce BreakConstructorInitializers 
option  when this original patch was submitted

  BreakConstructorInitializers: BeforeComma
  ConstructorInitializerAllOnOneLineOrOnePerLine: true
  
  SomeClass::Constructor() : aa(aaa), bb(bbb), cc(cc) {}
  
  SomeClass::Constructor()
  : aa(a, aaa,
   aaa)
  , bb(bbb)
  , cc(cc) {}



  BreakConstructorInitializers: BeforeComma
  ConstructorInitializerAllOnOneLineOrOnePerLine: false
  
  SomeClass::Constructor()
  : aa(aaa)
  , bb(bbb)
  , cc(cc) {}
  
  SomeClass::Constructor()
  : aa(a, aaa,
   aaa)
  , bb(bbb)
  , cc(cc) {}

At least the unit tests appear to be covered by using those styles?

Nit: At a minimum, this patch would need to be rebased and be a full context 
diff, can anyone see a  use case that can't be covered with what we have?

Moving to "request changes" (really request to abandon if not necessary any 
longer)


Repository:
  rL LLVM

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

https://reviews.llvm.org/D14484



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


[PATCH] D68261: [clangd] Add "inline" keyword to prevent ODR-violations in DefineInline

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: ilya-biryukov, hokein.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68261

Files:
  clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.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
@@ -1307,6 +1307,66 @@
 
 )cpp");
 }
+
+TEST_F(DefineInlineTest, AddInline) {
+  ExtraFiles["a.h"] = "void foo();";
+  apply(R"cpp(#include "a.h"
+  void fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+   testPath("a.h"), "inline void foo(){}")));
+
+  // Check we put inline before cv-qualifiers.
+  ExtraFiles["a.h"] = "const int foo();";
+  apply(R"cpp(#include "a.h"
+  const int fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+   testPath("a.h"), "inline const int foo(){}")));
+
+  // No double inline.
+  ExtraFiles["a.h"] = "inline void foo();";
+  apply(R"cpp(#include "a.h"
+  inline void fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+   testPath("a.h"), "inline void foo(){}")));
+
+  // Constexprs don't need "inline".
+  ExtraFiles["a.h"] = "constexpr void foo();";
+  apply(R"cpp(#include "a.h"
+  constexpr void fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents(
+   testPath("a.h"), "constexpr void foo(){}")));
+
+  // Class members don't need "inline".
+  ExtraFiles["a.h"] = "struct Foo { void foo(); }";
+  apply(R"cpp(#include "a.h"
+  void Foo::fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles,
+  testing::ElementsAre(FileWithContents(
+  testPath("a.h"), "struct Foo { void foo(){} }")));
+
+  // Function template doesn't need to be "inline"d.
+  ExtraFiles["a.h"] = "template  void foo();";
+  apply(R"cpp(#include "a.h"
+  template 
+  void fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles,
+  testing::ElementsAre(FileWithContents(
+  testPath("a.h"), "template  void foo(){}")));
+
+  // Specializations needs to be marked "inline".
+  ExtraFiles["a.h"] = R"cpp(
+template  void foo();
+template <> void foo();)cpp";
+  apply(R"cpp(#include "a.h"
+  template <>
+  void fo^o() {})cpp");
+  EXPECT_THAT(EditedFiles,
+  testing::ElementsAre(FileWithContents(testPath("a.h"),
+R"cpp(
+template  void foo();
+template <> inline void foo(){})cpp")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/TweakTesting.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTesting.cpp
+++ clang-tools-extra/clangd/unittests/TweakTesting.cpp
@@ -114,7 +114,7 @@
 if (It.first() == testPath(TU.Filename))
   EditedMainFile = Unwrapped;
 else
-  EditedFiles.try_emplace(It.first(), Unwrapped.str());
+  EditedFiles[It.first()] = Unwrapped.str();
   }
   return EditedMainFile;
 }
Index: clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
@@ -32,6 +32,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
+#include "clang/Driver/Types.h"
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
@@ -297,6 +298,30 @@
   return FD->getBeginLoc();
 }
 
+llvm::Optional
+addInlineIfInHeader(const FunctionDecl *FD) {
+  // This includes inline functions and constexpr functions.
+  if (FD->isInlined() || llvm::isa(FD))
+return llvm::None;
+  // Primary template doesn't need inline.
+  if (FD->isTemplated() && !FD->isFunctionTemplateSpecialization())
+return llvm::None;
+
+  const SourceManager &SM = FD->getASTContext().getSourceManager();
+  llvm::StringRef FileName = SM.getFilename(FD->getLocation());
+
+  auto Type = driver::types::lookupTypeForExtension(
+  llvm::sys::path::extension(FileName).substr(1));
+
+  // If it is not a header we don't need to mark function as "inline".
+  if (Type == driver::types::TY_INVALID ||
+   

r373312 - [clang][lldb][NFC] Encapsulate ExternalASTMerger::ImporterSource

2019-10-01 Thread Raphael Isemann via cfe-commits
Author: teemperor
Date: Tue Oct  1 02:02:05 2019
New Revision: 373312

URL: http://llvm.org/viewvc/llvm-project?rev=373312&view=rev
Log:
[clang][lldb][NFC] Encapsulate ExternalASTMerger::ImporterSource

NFC preparation work for upcoming ExternalASTMerger patches.

Modified:
cfe/trunk/include/clang/AST/ExternalASTMerger.h
cfe/trunk/lib/AST/ExternalASTMerger.cpp
cfe/trunk/tools/clang-import-test/clang-import-test.cpp

Modified: cfe/trunk/include/clang/AST/ExternalASTMerger.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ExternalASTMerger.h?rev=373312&r1=373311&r2=373312&view=diff
==
--- cfe/trunk/include/clang/AST/ExternalASTMerger.h (original)
+++ cfe/trunk/include/clang/AST/ExternalASTMerger.h Tue Oct  1 02:02:05 2019
@@ -80,10 +80,17 @@ public:
   /// import SourceLocations properly.  Additionally, when import occurs for
   /// a DeclContext whose origin has been overridden, then this
   /// ExternalASTMerger must be able to determine that.
-  struct ImporterSource {
+  class ImporterSource {
 ASTContext &AST;
 FileManager &FM;
 const OriginMap &OM;
+
+  public:
+ImporterSource(ASTContext &_AST, FileManager &_FM, const OriginMap &_OM)
+: AST(_AST), FM(_FM), OM(_OM) {}
+ASTContext &getASTContext() const { return AST; }
+FileManager &getFileManager() const { return FM; }
+const OriginMap &getOriginMap() const { return OM; }
   };
 
 private:

Modified: cfe/trunk/lib/AST/ExternalASTMerger.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExternalASTMerger.cpp?rev=373312&r1=373311&r2=373312&view=diff
==
--- cfe/trunk/lib/AST/ExternalASTMerger.cpp (original)
+++ cfe/trunk/lib/AST/ExternalASTMerger.cpp Tue Oct  1 02:02:05 2019
@@ -105,15 +105,16 @@ private:
   llvm::raw_ostream &logs() { return Parent.logs(); }
 public:
   LazyASTImporter(ExternalASTMerger &_Parent, ASTContext &ToContext,
-  FileManager &ToFileManager, ASTContext &FromContext,
-  FileManager &FromFileManager,
-  const ExternalASTMerger::OriginMap &_FromOrigins,
+  FileManager &ToFileManager,
+  const ExternalASTMerger::ImporterSource &_Source,
   std::shared_ptr SharedState)
-  : ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,
+  : ASTImporter(ToContext, ToFileManager, _Source.getASTContext(),
+_Source.getFileManager(),
 /*MinimalImport=*/true, SharedState),
-Parent(_Parent), Reverse(FromContext, FromFileManager, ToContext,
- ToFileManager, /*MinimalImport=*/true),
-FromOrigins(_FromOrigins) {}
+Parent(_Parent),
+Reverse(_Source.getASTContext(), _Source.getFileManager(), ToContext,
+ToFileManager, /*MinimalImport=*/true),
+FromOrigins(_Source.getOriginMap()) {}
 
   /// Whenever a DeclContext is imported, ensure that ExternalASTSource's 
origin
   /// map is kept up to date.  Also set the appropriate flags.
@@ -323,23 +324,23 @@ ExternalASTMerger::ExternalASTMerger(con
 
 void ExternalASTMerger::AddSources(llvm::ArrayRef Sources) {
   for (const ImporterSource &S : Sources) {
-assert(&S.AST != &Target.AST);
+assert(&S.getASTContext() != &Target.AST);
 Importers.push_back(std::make_unique(
-*this, Target.AST, Target.FM, S.AST, S.FM, S.OM, SharedState));
+*this, Target.AST, Target.FM, S, SharedState));
   }
 }
 
 void ExternalASTMerger::RemoveSources(llvm::ArrayRef Sources) {
   if (LoggingEnabled())
 for (const ImporterSource &S : Sources)
-  logs() << "(ExternalASTMerger*)" << (void*)this
- << " removing source (ASTContext*)" << (void*)&S.AST
+  logs() << "(ExternalASTMerger*)" << (void *)this
+ << " removing source (ASTContext*)" << (void *)&S.getASTContext()
  << "\n";
   Importers.erase(
   std::remove_if(Importers.begin(), Importers.end(),
  [&Sources](std::unique_ptr &Importer) -> 
bool {
for (const ImporterSource &S : Sources) {
- if (&Importer->getFromContext() == &S.AST)
+ if (&Importer->getFromContext() == &S.getASTContext())
return true;
}
return false;
@@ -349,7 +350,7 @@ void ExternalASTMerger::RemoveSources(ll
 std::pair Origin = *OI;
 bool Erase = false;
 for (const ImporterSource &S : Sources) {
-  if (&S.AST == Origin.second.AST) {
+  if (&S.getASTContext() == Origin.second.AST) {
 Erase = true;
 break;
   }

Modified: cfe/trunk/tools/clang-import-test/clang-import-test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-import-test/clang-import-test

[PATCH] D68227: [clang-format] [PR43372] - clang-format shows replacements in DOS files when no replacement is needed

2019-10-01 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added inline comments.



Comment at: clang/lib/Format/Format.cpp:1828
 
+// Replace "\r\n" with "\n"
+std::string replaceCRLF(std::string Code) {

nit: missing trailing fullstop.



Comment at: clang/lib/Format/Format.cpp:1832
+  while ((Pos = Code.find("\r\n", Pos)) != std::string::npos) {
+Code.replace(Pos, 2, "\n");
+Pos += 1;

The worst-case complexity of this code is quadratic, since 
`std::string::replace` is linear in the size of the resulting string.
If we have an include block of a few hundred lines, each a hundred or so 
characters, I could imagine that could easily add up.
I'd suggest constructing the result by appending to a fresh string to keep the 
overall complexity linear.
You can then take the argument by const reference.



Comment at: clang/lib/Format/Format.cpp:1838
+
+// Compares two strings but ignores any \r in either strings.
+static bool compareIgnoringCarriageReturns(std::string Result,

Maybe refine this comment: ignoring any `\r`, followed by `\n` in either 
strings.
Alternatively, since this function is just performing a comparison, consider 
directly inlining it in the `if` statements below (not too strong opinion).


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

https://reviews.llvm.org/D68227



___
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-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 222562.
kadircet added a comment.

- Fix getSemiColon to handle semicolons at the end of file


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";
@@ -815,6 +816,497 @@
   })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";
+  EXPECT_EQ(apply(R"cpp(
+  #include "a.h"
+  void Foo::f^oo() {
+return;
+  })cpp"),
+R"cpp(
+  #include "a.h"
+  )cpp");
+  EXPECT_THAT(EditedFiles,
+  testing::ElementsAre(FileWithContents(testPath("a.h"),
+R"cpp(
+  class Foo {
+void foo()/*Comment -_-*/  {
+return;
+  }
+  };)cpp")));
+}
+
+TEST_F(DefineInlineTest, TransformDependen

[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 222566.
balazske added a comment.

- Various code cleanups. Eval functions use CallEvent, CallExpr is removed from 
state.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706

Files:
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream.c

Index: clang/test/Analysis/stream.c
===
--- clang/test/Analysis/stream.c
+++ clang/test/Analysis/stream.c
@@ -1,6 +1,7 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=alpha.unix.Stream -analyzer-store region -verify %s
 
 typedef __typeof__(sizeof(int)) size_t;
+typedef __typeof__(sizeof(int)) fpos_t;
 typedef struct _IO_FILE FILE;
 #define SEEK_SET	0	/* Seek from beginning of file.  */
 #define SEEK_CUR	1	/* Seek from current position.  */
@@ -9,36 +10,93 @@
 extern FILE *tmpfile(void);
 extern int fclose(FILE *fp);
 extern size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
+extern size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
 extern int fseek (FILE *__stream, long int __off, int __whence);
 extern long int ftell (FILE *__stream);
 extern void rewind (FILE *__stream);
+extern int fgetpos(FILE *stream, fpos_t *pos);
+extern int fsetpos(FILE *stream, const fpos_t *pos);
+extern void clearerr(FILE *stream);
+extern int feof(FILE *stream);
+extern int ferror(FILE *stream);
+extern int fileno(FILE *stream);
 
-void f1(void) {
-  FILE *p = fopen("foo", "r");
-  char buf[1024];
-  fread(buf, 1, 1, p); // expected-warning {{Stream pointer might be NULL}}
-  fclose(p);
+void check_fread() {
+  FILE *fp = tmpfile();
+  fread(0, 0, 0, fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
 }
 
-void f2(void) {
-  FILE *p = fopen("foo", "r");
-  fseek(p, 1, SEEK_SET); // expected-warning {{Stream pointer might be NULL}}
-  fclose(p);
+void check_fwrite() {
+  FILE *fp = tmpfile();
+  fwrite(0, 0, 0, fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
 }
 
-void f3(void) {
-  FILE *p = fopen("foo", "r");
-  ftell(p); // expected-warning {{Stream pointer might be NULL}}
-  fclose(p);
+void check_fseek() {
+  FILE *fp = tmpfile();
+  fseek(fp, 0, 0); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_ftell() {
+  FILE *fp = tmpfile();
+  ftell(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_rewind() {
+  FILE *fp = tmpfile();
+  rewind(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_fgetpos() {
+  FILE *fp = tmpfile();
+  fpos_t pos;
+  fgetpos(fp, &pos); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_fsetpos() {
+  FILE *fp = tmpfile();
+  fpos_t pos;
+  fsetpos(fp, &pos); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_clearerr() {
+  FILE *fp = tmpfile();
+  clearerr(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_feof() {
+  FILE *fp = tmpfile();
+  feof(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void check_ferror() {
+  FILE *fp = tmpfile();
+  ferror(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
 }
 
-void f4(void) {
+void check_fileno() {
+  FILE *fp = tmpfile();
+  fileno(fp); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
+void f_open(void) {
   FILE *p = fopen("foo", "r");
-  rewind(p); // expected-warning {{Stream pointer might be NULL}}
+  char buf[1024];
+  fread(buf, 1, 1, p); // expected-warning {{Stream pointer might be NULL}}
   fclose(p);
 }
 
-void f5(void) {
+void f_seek(void) {
   FILE *p = fopen("foo", "r");
   if (!p)
 return;
@@ -47,26 +105,20 @@
   fclose(p);
 }
 
-void f6(void) {
+void f_double_close(void) {
   FILE *p = fopen("foo", "r");
   fclose(p); 
   fclose(p); // expected-warning {{Try to close a file Descriptor already closed. Cause undefined behaviour}}
 }
 
-void f7(void) {
-  FILE *p = tmpfile();
-  ftell(p); // expected-warning {{Stream pointer might be NULL}}
-  fclose(p);
-}
-
-void f8(int c) {
+void f_leak(int c) {
   FILE *p = fopen("foo.c", "r");
   if(c)
 return; // expected-warning {{Opened File never closed. Potential Resource leak}}
   fclose(p);
 }
 
-FILE *f9(void) {
+FILE *f_null_checked(void) {
   FILE *p = fopen("foo.c", "r");
   if (p)
 return p; // no-warning
@@ -82,4 +134,3 @@
 void pr8081(FILE *stream, long offset, int whence) {
   fseek(stream, offset, whence);
 }
-
Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -27,76 +27,77 @@
 
 struct StreamState {
   enum Kind { Opened, Closed, OpenFailed, Escaped } K;
-  

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

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

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143

Files:
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/AST/ast-dump-decl.cpp
  clang/test/AST/ast-dump-record-definition-data-json.cpp
  clang/test/AST/ast-dump-template-decls-json.cpp
  clang/test/AST/ast-dump-template-decls.cpp
  clang/test/ASTMerge/class-template/test.cpp
  clang/test/Index/index-templates.cpp

Index: clang/test/Index/index-templates.cpp
===
--- clang/test/Index/index-templates.cpp
+++ clang/test/Index/index-templates.cpp
@@ -155,7 +155,7 @@
 // CHECK-LOAD: index-templates.cpp:36:44: DeclRefExpr=OneDimension:35:16 Extent=[36:44 - 36:56]
 // CHECK-LOAD: index-templates.cpp:40:8: ClassTemplate=storage:40:8 (Definition) Extent=[39:1 - 40:19]
 // CHECK-LOAD: index-templates.cpp:39:45: TemplateTemplateParameter=DataStructure:39:45 (Definition) Extent=[39:10 - 39:66]
-// CHECK-LOAD: index-templates.cpp:39:19: TemplateTypeParameter=:39:19 (Definition) Extent=[39:19 - 39:27]
+// CHECK-LOAD: index-templates.cpp:39:27: TemplateTypeParameter=:39:27 (Definition) Extent=[39:19 - 39:27]
 // CHECK-LOAD: index-templates.cpp:39:37: NonTypeTemplateParameter=:39:37 (Definition) Extent=[39:29 - 39:37]
 // CHECK-LOAD: index-templates.cpp:39:61: TemplateRef=array:37:8 Extent=[39:61 - 39:66]
 // CHECK-LOAD: index-templates.cpp:42:18: TypedefDecl=Unsigned:42:18 (Definition) Extent=[42:1 - 42:26]
Index: clang/test/ASTMerge/class-template/test.cpp
===
--- clang/test/ASTMerge/class-template/test.cpp
+++ clang/test/ASTMerge/class-template/test.cpp
@@ -9,13 +9,13 @@
 // CHECK: class-template2.cpp:9:15: note: declared here with type 'long'
 
 // CHECK: class-template1.cpp:12:14: warning: template parameter has different kinds in different translation units
-// CHECK: class-template2.cpp:12:10: note: template parameter declared here
+// CHECK: class-template2.cpp:12:18: note: template parameter declared here
 
 // CHECK: class-template1.cpp:18:23: warning: non-type template parameter declared with incompatible types in different translation units ('long' vs. 'int')
 // CHECK: class-template2.cpp:18:23: note: declared here with type 'int'
 
-// CHECK: class-template1.cpp:21:10: warning: template parameter has different kinds in different translation units
-// CHECK: class-template2.cpp:21:10: note: template parameter declared here
+// CHECK: class-template1.cpp:21:18: warning: template parameter has different kinds in different translation units
+// CHECK: class-template2.cpp:21:31: note: template parameter declared here
 
 // CHECK: class-template2.cpp:27:20: warning: external variable 'x0r' declared with incompatible types in different translation units ('X0 *' vs. 'X0 *')
 // CHECK: class-template1.cpp:26:19: note: declared here with type 'X0 *'
Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -26,7 +26,7 @@
 // CHECK: FunctionTemplateDecl 0x{{[^ ]*}}  col:6 d
 // CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:20 referenced typename depth 0 index 0 Ty
 // CHECK-NEXT: TemplateTemplateParmDecl 0x{{[^ ]*}}  col:52 depth 0 index 1 Uy
-// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:33 typename depth 1 index 0
+// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:41 typename depth 1 index 0
 void d(Ty, Uy);
 
 template 
@@ -47,7 +47,7 @@
 
 template 
 // CHECK: FunctionTemplateDecl 0x{{[^ ]*}}  col:6 h
-// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:11 typename depth 0 index 0
+// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:20 typename depth 0 index 0
 // CHECK-NEXT: TemplateArgument type 'void'
 void h();
 
Index: clang/test/AST/ast-dump-template-decls-json.cpp
===
--- clang/test/AST/ast-dump-template-decls-json.cpp
+++ clang/test/AST/ast-dump-template-decls-json.cpp
@@ -656,8 +656,8 @@
 // CHECK-NEXT:"id": "0x{{.*}}",
 // CHECK-NEXT:"kind": "TemplateTypeParmDecl",
 // CHECK-NEXT:"loc": {
-// CHECK-NEXT: "col": 33,
-// CHECK-NEXT: "tokLen": 8
+// CHECK-NEXT: "col": 41,
+// CHECK-NEXT: "tokLen": 1
 // CHECK-NEXT:},
 // CHECK-NEXT:"range": {
 // CHECK-NEXT: "begin": {
@@ -1099,8 +1099,8 @@
 // CHECK-NEXT:  "kind": "TemplateTypeParmDecl",
 // CHECK-NEXT:  "loc": {
 // CHECK-NEXT:   "line": 27,
-// CHECK-NEXT:   "col": 11,
-// CHECK-NEXT:   "tokLen": 8
+// CHECK-NEXT:   "col": 20,
+// CHECK-NEXT:   "tokLen": 

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

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



Comment at: clang/lib/AST/DeclTemplate.cpp:513
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  else if(getName().empty())
+return SourceRange(getBeginLoc());

ilya-biryukov wrote:
> Could you provide more details why we need this change?
added comments, you can also see the similar case in 
`DeclaratorDecl::getSourceRange()`



Comment at: clang/lib/Parse/ParseTemplate.cpp:633
   // Grab the template parameter name (if given)
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;

ilya-biryukov wrote:
> What happens if there's a comment? E.g.
> ```
> template 
> ```
> 
> where would we point to and does that align with the function parameter case?
that's same with parmvardecl case, both refer to beginning of the next token 
that has been lexed.



Comment at: clang/test/AST/ast-dump-record-definition-data-json.cpp:398
 // CHECK-NEXT:  "range": {
-// CHECK-NEXT:   "begin": {
-// CHECK-NEXT:"col": 29,
-// CHECK-NEXT:"tokLen": 4
-// CHECK-NEXT:   },
-// CHECK-NEXT:   "end": {
-// CHECK-NEXT:"col": 29,
-// CHECK-NEXT:"tokLen": 4
-// CHECK-NEXT:   }
+// CHECK-NEXT:   "begin": {},
+// CHECK-NEXT:   "end": {}

ilya-biryukov wrote:
> Does that mean we do not have locations in some cases now?
> Is that a regression?
I believe not, this test is a little bit weird, if you look at the code at the 
beginning, it doesn't contain any "template" stuff explicitly.
So this is rather coming from implicit nodes(that doesn't have any line numbers 
but only column numbers)

Previously test was checking the "class" as the name of the parmdecl, hence the 
`tokLen: 4`, now it is unnamed therefore no ranges for it.
though we still have the location marker for `class` (col:29 tokLen: 4)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143



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


[PATCH] D68137: [clangd] Handle template arguments in findExplicitReferences

2019-10-01 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, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68137



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


[PATCH] D68245: [Clangd] ExtractFunction: Don't extract body of enclosing function.

2019-10-01 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, thanks




Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:231
+  if (const Stmt *S = Child->ASTNode.get())
+if (EnclosingFunc->hasBody() && EnclosingFunc->getBody() == S)
+  return false;

I believe it is not possible to have an `EnclosingFunc` without a body at this 
point. Let's make it an assertion instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68245



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


[PATCH] D50078: clang-format: support aligned nested conditionals formatting

2019-10-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

Thank you for this patch, (and by your patience ;-) )

This LGTM,  Were there any objections from anyone else? otherwise I'd say this 
was ok.


Repository:
  rC Clang

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

https://reviews.llvm.org/D50078



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


[clang-tools-extra] r373318 - [clangd] Handle template arguments in findExplicitReferences

2019-10-01 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Oct  1 03:02:23 2019
New Revision: 373318

URL: http://llvm.org/viewvc/llvm-project?rev=373318&view=rev
Log:
[clangd] Handle template arguments in findExplicitReferences

Reviewers: kadircet

Reviewed By: kadircet

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/FindTarget.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.cpp?rev=373318&r1=373317&r2=373318&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp Tue Oct  1 03:02:23 2019
@@ -22,6 +22,7 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
@@ -565,6 +566,34 @@ public:
 return true;
   }
 
+  // We re-define Traverse*, since there's no corresponding Visit*.
+  // TemplateArgumentLoc is the only way to get locations for references to
+  // template template parameters.
+  bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
+switch (A.getArgument().getKind()) {
+case TemplateArgument::Template:
+case TemplateArgument::TemplateExpansion:
+  reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
+   A.getTemplateNameLoc(),
+   {A.getArgument()
+.getAsTemplateOrTemplatePattern()
+.getAsTemplateDecl()}},
+  DynTypedNode::create(A.getArgument()));
+  break;
+case TemplateArgument::Declaration:
+  break; // FIXME: can this actually happen in TemplateArgumentLoc?
+case TemplateArgument::Integral:
+case TemplateArgument::Null:
+case TemplateArgument::NullPtr:
+  break; // no references.
+case TemplateArgument::Pack:
+case TemplateArgument::Type:
+case TemplateArgument::Expression:
+  break; // Handled by VisitType and VisitExpression.
+};
+return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
+  }
+
   bool VisitDecl(Decl *D) {
 visitNode(DynTypedNode::create(*D));
 return true;
@@ -623,15 +652,19 @@ private:
 auto Ref = explicitReference(N);
 if (!Ref)
   return;
+reportReference(*Ref, N);
+  }
+
+  void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
 // Our promise is to return only references from the source code. If we 
lack
 // location information, skip these nodes.
 // Normally this should not happen in practice, unless there are bugs in 
the
 // traversals or users started the traversal at an implicit node.
-if (Ref->NameLoc.isInvalid()) {
+if (Ref.NameLoc.isInvalid()) {
   dlog("invalid location at node {0}", nodeToString(N));
   return;
 }
-Out(*Ref);
+Out(Ref);
   }
 
   llvm::function_ref Out;

Modified: clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp?rev=373318&r1=373317&r2=373318&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp Tue Oct  1 
03:02:23 2019
@@ -750,6 +750,39 @@ TEST_F(FindExplicitReferencesTest, All)
 }
 )cpp",
"0: targets = {I}\n"},
+  // Template template parameters.
+  {R"cpp(
+template  struct vector {};
+
+template  class TT, template class ...TP>
+void foo() {
+  $0^TT x;
+  $1^foo<$2^TT>();
+  $3^foo<$4^vector>()
+  $5^foo<$6^TP...>();
+}
+)cpp",
+   "0: targets = {TT}\n"
+   "1: targets = {foo}\n"
+   "2: targets = {TT}\n"
+   "3: targets = {foo}\n"
+   "4: targets = {vector}\n"
+   "5: targets = {foo}\n"
+   "6: targets = {TP}\n"},
+  // Non-type template parameters with declarations.
+  {R"cpp(
+int func();
+template  struct wrapper {};
+
+template 
+void foo() {
+  $0^wrapper<$1^func> w;
+  $2^FuncParam();
+}
+)cpp",
+   "0: targets = {wrapper<&func>}\n"
+   "1: targets = {func}\n"
+   "2: targets = {FuncParam}\n"},
   };
 
   for (const auto &C : Cases) {


___
cf

[PATCH] D68137: [clangd] Handle template arguments in findExplicitReferences

2019-10-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373318: [clangd] Handle template arguments in 
findExplicitReferences (authored by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68137?vs=222554&id=222573#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68137

Files:
  clang-tools-extra/trunk/clangd/FindTarget.cpp
  clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
@@ -565,6 +566,34 @@
 return true;
   }
 
+  // We re-define Traverse*, since there's no corresponding Visit*.
+  // TemplateArgumentLoc is the only way to get locations for references to
+  // template template parameters.
+  bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
+switch (A.getArgument().getKind()) {
+case TemplateArgument::Template:
+case TemplateArgument::TemplateExpansion:
+  reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
+   A.getTemplateNameLoc(),
+   {A.getArgument()
+.getAsTemplateOrTemplatePattern()
+.getAsTemplateDecl()}},
+  DynTypedNode::create(A.getArgument()));
+  break;
+case TemplateArgument::Declaration:
+  break; // FIXME: can this actually happen in TemplateArgumentLoc?
+case TemplateArgument::Integral:
+case TemplateArgument::Null:
+case TemplateArgument::NullPtr:
+  break; // no references.
+case TemplateArgument::Pack:
+case TemplateArgument::Type:
+case TemplateArgument::Expression:
+  break; // Handled by VisitType and VisitExpression.
+};
+return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
+  }
+
   bool VisitDecl(Decl *D) {
 visitNode(DynTypedNode::create(*D));
 return true;
@@ -623,15 +652,19 @@
 auto Ref = explicitReference(N);
 if (!Ref)
   return;
+reportReference(*Ref, N);
+  }
+
+  void reportReference(const ReferenceLoc &Ref, DynTypedNode N) {
 // Our promise is to return only references from the source code. If we lack
 // location information, skip these nodes.
 // Normally this should not happen in practice, unless there are bugs in the
 // traversals or users started the traversal at an implicit node.
-if (Ref->NameLoc.isInvalid()) {
+if (Ref.NameLoc.isInvalid()) {
   dlog("invalid location at node {0}", nodeToString(N));
   return;
 }
-Out(*Ref);
+Out(Ref);
   }
 
   llvm::function_ref Out;
Index: clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp
@@ -750,6 +750,39 @@
 }
 )cpp",
"0: targets = {I}\n"},
+  // Template template parameters.
+  {R"cpp(
+template  struct vector {};
+
+template  class TT, template class ...TP>
+void foo() {
+  $0^TT x;
+  $1^foo<$2^TT>();
+  $3^foo<$4^vector>()
+  $5^foo<$6^TP...>();
+}
+)cpp",
+   "0: targets = {TT}\n"
+   "1: targets = {foo}\n"
+   "2: targets = {TT}\n"
+   "3: targets = {foo}\n"
+   "4: targets = {vector}\n"
+   "5: targets = {foo}\n"
+   "6: targets = {TP}\n"},
+  // Non-type template parameters with declarations.
+  {R"cpp(
+int func();
+template  struct wrapper {};
+
+template 
+void foo() {
+  $0^wrapper<$1^func> w;
+  $2^FuncParam();
+}
+)cpp",
+   "0: targets = {wrapper<&func>}\n"
+   "1: targets = {func}\n"
+   "2: targets = {FuncParam}\n"},
   };
 
   for (const auto &C : Cases) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68182: [Clangd] Ensure children are always RootStmt in ExtractFunction (Fixes #153)

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



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:110
 // begins in selection range, ends in selection range and any scope that begins
 // outside the selection range, ends outside as well.
 const Node *getParentOfRootStmts(const Node *CommonAnc) {

can you also update the comment to mention

`returns null if any child of the parent is not a root statement`



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:111
 // outside the selection range, ends outside as well.
 const Node *getParentOfRootStmts(const Node *CommonAnc) {
   if (!CommonAnc)

can we restructure this into:
```
if (!CommonAnc) return nullptr;
const Node *Parent = nullptr;
switch(...) {
...Fill In Parent...
default:
llvm_unreachable(..)
}
return llvm::all_of(..)
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68182



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


[PATCH] D68211: [clangd] Use the index-based API to do the header-source switch.

2019-10-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 222574.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68211

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

Index: clang-tools-extra/clangd/unittests/SyncAPI.h
===
--- clang-tools-extra/clangd/unittests/SyncAPI.h
+++ clang-tools-extra/clangd/unittests/SyncAPI.h
@@ -56,6 +56,9 @@
 llvm::Expected>
 runSemanticRanges(ClangdServer &Server, PathRef File, Position Pos);
 
+llvm::Expected>
+runSwitchHeaderSource(ClangdServer &Server, PathRef File);
+
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/SyncAPI.cpp
===
--- clang-tools-extra/clangd/unittests/SyncAPI.cpp
+++ clang-tools-extra/clangd/unittests/SyncAPI.cpp
@@ -152,5 +152,12 @@
   return std::move(*Result);
 }
 
+llvm::Expected>
+runSwitchHeaderSource(ClangdServer &Server, PathRef File) {
+  llvm::Optional>> Result;
+  Server.switchSourceHeader(File, capture(Result));
+  return std::move(*Result);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -8,6 +8,7 @@
 
 #include "HeaderSourceSwitch.h"
 
+#include "SyncAPI.h"
 #include "TestFS.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
@@ -240,6 +241,32 @@
   }
 }
 
+TEST(HeaderSourceSwitchTest, ClangdServerIntegration) {
+  class IgnoreDiagnostics : public DiagnosticsConsumer {
+void onDiagnosticsReady(PathRef File,
+std::vector Diagnostics) override {}
+  } DiagConsumer;
+  MockCompilationDatabase CDB;
+  CDB.ExtraClangFlags = {"-I" +
+ testPath("src/include")}; // add search directory.
+  MockFSProvider FS;
+  // File heuristic fails here, we rely on the index to find the .h file.
+  std::string CppPath = testPath("src/lib/test.cpp");
+  std::string HeaderPath = testPath("src/include/test.h");
+  FS.Files[HeaderPath] = "void foo();";
+  const std::string FileContent = R"cpp(
+#include "test.h"
+void foo() {};
+  )cpp";
+  FS.Files[CppPath] = FileContent;
+  auto Options = ClangdServer::optsForTest();
+  Options.BuildDynamicSymbolIndex = true;
+  ClangdServer Server(CDB, FS, DiagConsumer, Options);
+  runAddDocument(Server, CppPath, FileContent);
+  EXPECT_EQ(HeaderPath,
+*llvm::cantFail(runSwitchHeaderSource(Server, CppPath)));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -192,9 +192,10 @@
   void locateSymbolAt(PathRef File, Position Pos,
   Callback> CB);
 
-  /// Helper function that returns a path to the corresponding source file when
-  /// given a header file and vice versa.
-  llvm::Optional switchSourceHeader(PathRef Path);
+  /// Switch to a corresponding source file when given a header file, and vice
+  /// versa.
+  void switchSourceHeader(PathRef Path,
+  Callback> CB);
 
   /// Get document highlights for a given position.
   void findDocumentHighlights(PathRef File, Position Pos,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -449,8 +449,24 @@
   WorkScheduler.runWithAST("Definitions", File, std::move(Action));
 }
 
-llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
-  return getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem());
+void ClangdServer::switchSourceHeader(
+PathRef Path, Callback> CB) {
+  // We want to return the result as fast as possible, stragety is:
+  //  1) use the file-only heuristic, it requires some IO but it is much
+  // faster than building AST, but it only works when .h/.cc files are in
+  // the same directory.
+  //  2) if 1) fails, we use the AST&Index approach, it is slower but supports
+  // different code layout.
+  if (auto CorrespondingFile =
+  getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
+return CB(std::move(CorrespondingFile));
+  auto Action = [Path, CB = std::move(CB),
+

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

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



Comment at: clang/lib/AST/DeclTemplate.cpp:513
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  else if(getName().empty())
+return SourceRange(getBeginLoc());

kadircet wrote:
> ilya-biryukov wrote:
> > Could you provide more details why we need this change?
> added comments, you can also see the similar case in 
> `DeclaratorDecl::getSourceRange()`
Could you provide an example? What the range was before and what is it now?




Comment at: clang/lib/Parse/ParseTemplate.cpp:633
   // Grab the template parameter name (if given)
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;

kadircet wrote:
> ilya-biryukov wrote:
> > What happens if there's a comment? E.g.
> > ```
> > template 
> > ```
> > 
> > where would we point to and does that align with the function parameter 
> > case?
> that's same with parmvardecl case, both refer to beginning of the next token 
> that has been lexed.
ok, LG, thanks



Comment at: clang/test/AST/ast-dump-record-definition-data-json.cpp:398
 // CHECK-NEXT:  "range": {
-// CHECK-NEXT:   "begin": {
-// CHECK-NEXT:"col": 29,
-// CHECK-NEXT:"tokLen": 4
-// CHECK-NEXT:   },
-// CHECK-NEXT:   "end": {
-// CHECK-NEXT:"col": 29,
-// CHECK-NEXT:"tokLen": 4
-// CHECK-NEXT:   }
+// CHECK-NEXT:   "begin": {},
+// CHECK-NEXT:   "end": {}

kadircet wrote:
> ilya-biryukov wrote:
> > Does that mean we do not have locations in some cases now?
> > Is that a regression?
> I believe not, this test is a little bit weird, if you look at the code at 
> the beginning, it doesn't contain any "template" stuff explicitly.
> So this is rather coming from implicit nodes(that doesn't have any line 
> numbers but only column numbers)
> 
> Previously test was checking the "class" as the name of the parmdecl, hence 
> the `tokLen: 4`, now it is unnamed therefore no ranges for it.
> though we still have the location marker for `class` (col:29 tokLen: 4)
Agree, these tests do not seem to test this at all, e.g. there are other nodes 
which are output without any locations.
LGTM




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143



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


[clang-tools-extra] r373320 - [clangd] Use the index-based API to do the header-source switch.

2019-10-01 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Oct  1 03:21:15 2019
New Revision: 373320

URL: http://llvm.org/viewvc/llvm-project?rev=373320&view=rev
Log:
[clangd] Use the index-based API to do the header-source switch.

Summary:
If the file heuristic fails, we try to use the index&AST to do the
header/source inference.

Reviewers: kadircet

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=373320&r1=373319&r2=373320&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Tue Oct  1 03:21:15 2019
@@ -1038,10 +1038,16 @@ void ClangdLSPServer::onGoToDeclaration(
 void ClangdLSPServer::onSwitchSourceHeader(
 const TextDocumentIdentifier &Params,
 Callback> Reply) {
-  if (auto Result = Server->switchSourceHeader(Params.uri.file()))
-Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
-  else
-Reply(llvm::None);
+  Server->switchSourceHeader(
+  Params.uri.file(),
+  [Reply = std::move(Reply),
+   Params](llvm::Expected> Path) mutable {
+if (!Path)
+  return Reply(Path.takeError());
+if (*Path)
+  Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
+return Reply(llvm::None);
+  });
 }
 
 void ClangdLSPServer::onDocumentHighlight(

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=373320&r1=373319&r2=373320&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Tue Oct  1 03:21:15 2019
@@ -449,8 +449,24 @@ void ClangdServer::locateSymbolAt(PathRe
   WorkScheduler.runWithAST("Definitions", File, std::move(Action));
 }
 
-llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
-  return getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem());
+void ClangdServer::switchSourceHeader(
+PathRef Path, Callback> CB) {
+  // We want to return the result as fast as possible, stragety is:
+  //  1) use the file-only heuristic, it requires some IO but it is much
+  // faster than building AST, but it only works when .h/.cc files are in
+  // the same directory.
+  //  2) if 1) fails, we use the AST&Index approach, it is slower but supports
+  // different code layout.
+  if (auto CorrespondingFile =
+  getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
+return CB(std::move(CorrespondingFile));
+  auto Action = [Path, CB = std::move(CB),
+ this](llvm::Expected InpAST) mutable {
+if (!InpAST)
+  return CB(InpAST.takeError());
+CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index));
+  };
+  WorkScheduler.runWithAST("SwitchHeaderSource", Path, std::move(Action));
 }
 
 llvm::Expected

Modified: clang-tools-extra/trunk/clangd/ClangdServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.h?rev=373320&r1=373319&r2=373320&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.h Tue Oct  1 03:21:15 2019
@@ -192,9 +192,10 @@ public:
   void locateSymbolAt(PathRef File, Position Pos,
   Callback> CB);
 
-  /// Helper function that returns a path to the corresponding source file when
-  /// given a header file and vice versa.
-  llvm::Optional switchSourceHeader(PathRef Path);
+  /// Switch to a corresponding source file when given a header file, and vice
+  /// versa.
+  void switchSourceHeader(PathRef Path,
+  Callback> CB);
 
   /// Get document highlights for a given position.
   void findDocumentHighlights(PathRef File, Position Pos,

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=373320&r1=373319&r2=373320&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp 
(original)
+++ clang-tools-extra/trunk/cl

[PATCH] D68211: [clangd] Use the index-based API to do the header-source switch.

2019-10-01 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373320: [clangd] Use the index-based API to do the 
header-source switch. (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68211?vs=222574&id=222575#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68211

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.h
  clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp
  clang-tools-extra/trunk/clangd/unittests/SyncAPI.cpp
  clang-tools-extra/trunk/clangd/unittests/SyncAPI.h

Index: clang-tools-extra/trunk/clangd/ClangdServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp
@@ -449,8 +449,24 @@
   WorkScheduler.runWithAST("Definitions", File, std::move(Action));
 }
 
-llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
-  return getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem());
+void ClangdServer::switchSourceHeader(
+PathRef Path, Callback> CB) {
+  // We want to return the result as fast as possible, stragety is:
+  //  1) use the file-only heuristic, it requires some IO but it is much
+  // faster than building AST, but it only works when .h/.cc files are in
+  // the same directory.
+  //  2) if 1) fails, we use the AST&Index approach, it is slower but supports
+  // different code layout.
+  if (auto CorrespondingFile =
+  getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem()))
+return CB(std::move(CorrespondingFile));
+  auto Action = [Path, CB = std::move(CB),
+ this](llvm::Expected InpAST) mutable {
+if (!InpAST)
+  return CB(InpAST.takeError());
+CB(getCorrespondingHeaderOrSource(Path, InpAST->AST, Index));
+  };
+  WorkScheduler.runWithAST("SwitchHeaderSource", Path, std::move(Action));
 }
 
 llvm::Expected
Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -1038,10 +1038,16 @@
 void ClangdLSPServer::onSwitchSourceHeader(
 const TextDocumentIdentifier &Params,
 Callback> Reply) {
-  if (auto Result = Server->switchSourceHeader(Params.uri.file()))
-Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
-  else
-Reply(llvm::None);
+  Server->switchSourceHeader(
+  Params.uri.file(),
+  [Reply = std::move(Reply),
+   Params](llvm::Expected> Path) mutable {
+if (!Path)
+  return Reply(Path.takeError());
+if (*Path)
+  Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
+return Reply(llvm::None);
+  });
 }
 
 void ClangdLSPServer::onDocumentHighlight(
Index: clang-tools-extra/trunk/clangd/ClangdServer.h
===
--- clang-tools-extra/trunk/clangd/ClangdServer.h
+++ clang-tools-extra/trunk/clangd/ClangdServer.h
@@ -192,9 +192,10 @@
   void locateSymbolAt(PathRef File, Position Pos,
   Callback> CB);
 
-  /// Helper function that returns a path to the corresponding source file when
-  /// given a header file and vice versa.
-  llvm::Optional switchSourceHeader(PathRef Path);
+  /// Switch to a corresponding source file when given a header file, and vice
+  /// versa.
+  void switchSourceHeader(PathRef Path,
+  Callback> CB);
 
   /// Get document highlights for a given position.
   void findDocumentHighlights(PathRef File, Position Pos,
Index: clang-tools-extra/trunk/clangd/unittests/SyncAPI.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/SyncAPI.cpp
+++ clang-tools-extra/trunk/clangd/unittests/SyncAPI.cpp
@@ -152,5 +152,12 @@
   return std::move(*Result);
 }
 
+llvm::Expected>
+runSwitchHeaderSource(ClangdServer &Server, PathRef File) {
+  llvm::Optional>> Result;
+  Server.switchSourceHeader(File, capture(Result));
+  return std::move(*Result);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/unittests/SyncAPI.h
===
--- clang-tools-extra/trunk/clangd/unittests/SyncAPI.h
+++ clang-tools-extra/trunk/clangd/unittests/SyncAPI.h
@@ -56,6 +56,9 @@
 llvm::Expected>
 runSemanticRanges(ClangdServer &Server, PathRef File, Position Pos);
 
+llvm::Expected>
+runSwitchHeaderSource(ClangdServer &Server, PathRef File);
+
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/trunk/clangd/unittests/HeaderSourceSw

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added inline comments.



Comment at: clang/lib/AST/DeclTemplate.cpp:513
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  else if(getName().empty())
+return SourceRange(getBeginLoc());

ilya-biryukov wrote:
> kadircet wrote:
> > ilya-biryukov wrote:
> > > Could you provide more details why we need this change?
> > added comments, you can also see the similar case in 
> > `DeclaratorDecl::getSourceRange()`
> Could you provide an example? What the range was before and what is it now?
> 
TypeDecl::getSourceRange will also include the next token if template parameter 
is unnamed for example:

```
template 
  ~
```

has the following `>` covered inside typerange.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143



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


[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

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



Comment at: clang/lib/AST/DeclTemplate.cpp:513
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  else if(getName().empty())
+return SourceRange(getBeginLoc());

kadircet wrote:
> ilya-biryukov wrote:
> > kadircet wrote:
> > > ilya-biryukov wrote:
> > > > Could you provide more details why we need this change?
> > > added comments, you can also see the similar case in 
> > > `DeclaratorDecl::getSourceRange()`
> > Could you provide an example? What the range was before and what is it now?
> > 
> TypeDecl::getSourceRange will also include the next token if template 
> parameter is unnamed for example:
> 
> ```
> template 
>   ~
> ```
> 
> has the following `>` covered inside typerange.
Thanks for clearing this up. Could you mention in the comment why 
`TypeDecl::getSourceRange` is wrong in that case?

From offline discussion, I figured that it should not be pointing to the name 
location in the case of un-named parameters as this would lead to the closing 
angle bracket being included in the range for template parameter, i.e. we'll 
get `<[[class>]]` instead of `<[[class]]>`



Comment at: clang/lib/AST/DeclTemplate.cpp:515
+  // wrong for unnamed template parameters.
+  else if(getName().empty())
+return SourceRange(getBeginLoc());

`getName()` may fail if the name is not an identifier. 
Even though this shouldn't happen for `TypeDecls`, could you please change to 
`getDeclName().isEmpty()`?

It's equivalent and does not have any assertions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143



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


[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 222581.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143

Files:
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/AST/ast-dump-decl.cpp
  clang/test/AST/ast-dump-record-definition-data-json.cpp
  clang/test/AST/ast-dump-template-decls-json.cpp
  clang/test/AST/ast-dump-template-decls.cpp
  clang/test/ASTMerge/class-template/test.cpp
  clang/test/Index/index-templates.cpp

Index: clang/test/Index/index-templates.cpp
===
--- clang/test/Index/index-templates.cpp
+++ clang/test/Index/index-templates.cpp
@@ -155,7 +155,7 @@
 // CHECK-LOAD: index-templates.cpp:36:44: DeclRefExpr=OneDimension:35:16 Extent=[36:44 - 36:56]
 // CHECK-LOAD: index-templates.cpp:40:8: ClassTemplate=storage:40:8 (Definition) Extent=[39:1 - 40:19]
 // CHECK-LOAD: index-templates.cpp:39:45: TemplateTemplateParameter=DataStructure:39:45 (Definition) Extent=[39:10 - 39:66]
-// CHECK-LOAD: index-templates.cpp:39:19: TemplateTypeParameter=:39:19 (Definition) Extent=[39:19 - 39:27]
+// CHECK-LOAD: index-templates.cpp:39:27: TemplateTypeParameter=:39:27 (Definition) Extent=[39:19 - 39:27]
 // CHECK-LOAD: index-templates.cpp:39:37: NonTypeTemplateParameter=:39:37 (Definition) Extent=[39:29 - 39:37]
 // CHECK-LOAD: index-templates.cpp:39:61: TemplateRef=array:37:8 Extent=[39:61 - 39:66]
 // CHECK-LOAD: index-templates.cpp:42:18: TypedefDecl=Unsigned:42:18 (Definition) Extent=[42:1 - 42:26]
Index: clang/test/ASTMerge/class-template/test.cpp
===
--- clang/test/ASTMerge/class-template/test.cpp
+++ clang/test/ASTMerge/class-template/test.cpp
@@ -9,13 +9,13 @@
 // CHECK: class-template2.cpp:9:15: note: declared here with type 'long'
 
 // CHECK: class-template1.cpp:12:14: warning: template parameter has different kinds in different translation units
-// CHECK: class-template2.cpp:12:10: note: template parameter declared here
+// CHECK: class-template2.cpp:12:18: note: template parameter declared here
 
 // CHECK: class-template1.cpp:18:23: warning: non-type template parameter declared with incompatible types in different translation units ('long' vs. 'int')
 // CHECK: class-template2.cpp:18:23: note: declared here with type 'int'
 
-// CHECK: class-template1.cpp:21:10: warning: template parameter has different kinds in different translation units
-// CHECK: class-template2.cpp:21:10: note: template parameter declared here
+// CHECK: class-template1.cpp:21:18: warning: template parameter has different kinds in different translation units
+// CHECK: class-template2.cpp:21:31: note: template parameter declared here
 
 // CHECK: class-template2.cpp:27:20: warning: external variable 'x0r' declared with incompatible types in different translation units ('X0 *' vs. 'X0 *')
 // CHECK: class-template1.cpp:26:19: note: declared here with type 'X0 *'
Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -26,7 +26,7 @@
 // CHECK: FunctionTemplateDecl 0x{{[^ ]*}}  col:6 d
 // CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:20 referenced typename depth 0 index 0 Ty
 // CHECK-NEXT: TemplateTemplateParmDecl 0x{{[^ ]*}}  col:52 depth 0 index 1 Uy
-// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:33 typename depth 1 index 0
+// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:41 typename depth 1 index 0
 void d(Ty, Uy);
 
 template 
@@ -47,7 +47,7 @@
 
 template 
 // CHECK: FunctionTemplateDecl 0x{{[^ ]*}}  col:6 h
-// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:11 typename depth 0 index 0
+// CHECK-NEXT: TemplateTypeParmDecl 0x{{[^ ]*}}  col:20 typename depth 0 index 0
 // CHECK-NEXT: TemplateArgument type 'void'
 void h();
 
Index: clang/test/AST/ast-dump-template-decls-json.cpp
===
--- clang/test/AST/ast-dump-template-decls-json.cpp
+++ clang/test/AST/ast-dump-template-decls-json.cpp
@@ -656,8 +656,8 @@
 // CHECK-NEXT:"id": "0x{{.*}}",
 // CHECK-NEXT:"kind": "TemplateTypeParmDecl",
 // CHECK-NEXT:"loc": {
-// CHECK-NEXT: "col": 33,
-// CHECK-NEXT: "tokLen": 8
+// CHECK-NEXT: "col": 41,
+// CHECK-NEXT: "tokLen": 1
 // CHECK-NEXT:},
 // CHECK-NEXT:"range": {
 // CHECK-NEXT: "begin": {
@@ -1099,8 +1099,8 @@
 // CHECK-NEXT:  "kind": "TemplateTypeParmDecl",
 // CHECK-NEXT:  "loc": {
 // CHECK-NEXT:   "line": 27,
-// CHECK-NEXT:   "col": 11,
-// CHECK-NEXT:   "tokLen": 8
+// CHECK-NEXT:   "col": 20,
+// CHECK-NEXT:   "tokLen": 1
 // CHECK-NEXT:  },
 // CHECK-NEXT:  

[PATCH] D68024: [clangd] Implement GetEligiblePoints

2019-10-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

looks good.




Comment at: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp:610
+   /*FullyQualifiedName=*/const char *,
+   /*CurrentNamespace*/ const char *>
+  Cases[] = {

nit: I'd use a struct, it is hard to infer the member by reading `get<0>`,  
`get<1>` (I have to go back to the top)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68024



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


[PATCH] D67695: [clangd] Implement getBeginning for overloaded operators.

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

add one more testcase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67695

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -441,6 +441,15 @@
   auto x = m^akeX();
 }
   )cpp",
+
+  R"cpp(
+struct X {
+  X& [[operator]]++() {}
+};
+void foo(X& x) {
+  +^+x;
+}
+  )cpp",
   };
   for (const char *Test : Tests) {
 Annotations T(Test);
Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -319,14 +319,29 @@
 Bar* bar;
   )cpp";
   // First ^ is the expected beginning, last is the search position.
-  for (std::string Text : std::vector{
+  for (const std::string &Text : std::vector{
"int ^f^oo();", // inside identifier
"int ^foo();",  // beginning of identifier
"int ^foo^();", // end of identifier
"int foo(^);",  // non-identifier
"^int foo();",  // beginning of file (can't back up)
"int ^f0^0();", // after a digit (lexing at N-1 is wrong)
-   "int ^λλ^λ();", // UTF-8 handled properly when backing up
+   "/^/ comments", // non-interesting token
+   "void f(int abc) { abc ^ ++; }",// whitespace
+   "void f(int abc) { ^abc^++; }", // range of identifier
+   "void f(int abc) { ++^abc^; }", // range of identifier
+   "void f(int abc) { ++^abc; }",  // range of identifier
+   "void f(int abc) { ^+^+abc; }", // range of operator
+   "void f(int abc) { ^abc^ ++; }",// range of identifier
+   "void f(int abc) { abc ^++^; }",// range of operator
+   "void f(int abc) { ^++^ abc; }",// range of operator
+   "void f(int abc) { ++ ^abc^; }",// range of identifier
+   "void f(int abc) { ^++^/**/abc; }", // range of operator
+   "void f(int abc) { ++/**/^abc; }",  // range of identifier
+   "void f(int abc) { ^abc^/**/++; }", // range of identifier
+   "void f(int abc) { abc/**/^++; }",  // range of operator
+   "void f() {^ }", // outside of identifier and operator
+   "int ^λλ^λ();",  // UTF-8 handled properly when backing up
 
// identifier in macro arg
"MACRO(bar->^func())",  // beginning of identifier
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -79,7 +79,7 @@
 Position P);
 
 /// Get the beginning SourceLocation at a specified \p Pos in the main file.
-/// May be invalid if Pos is, or if there's no identifier.
+/// May be invalid if Pos is, or if there's no identifier or operators.
 /// The returned position is in the main file, callers may prefer to
 /// obtain the macro expansion location.
 SourceLocation getBeginningOfIdentifier(const Position &Pos,
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -237,6 +237,45 @@
   return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
 }
 
+namespace {
+
+enum TokenFlavor { Identifier, Operator, Whitespace, Other };
+
+bool isOverloadedOperator(const Token &Tok) {
+  switch (Tok.getKind()) {
+#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
+  case tok::Token:
+#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
+#include "clang/Basic/OperatorKinds.def"
+return true;
+
+  default:
+break;
+  }
+  return false;
+}
+
+TokenFlavor getTokenFlavor(SourceLocation Loc, const SourceManager &SM,
+   const LangOptions &LangOpts) {
+  Token Tok;
+  Tok.setKind(tok::NUM_TOKENS);
+  if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
+ /*IgnoreWhiteSpace*/ false))
+return Other;
+
+  // getRawToken will return false without setting Tok when the token is
+  // whitespace, so if the flag is not set, we are sure this is a whitespace.
+  if (Tok.is(tok::TokenKind::NUM_TOKENS))
+return Whitespace;
+ 

[PATCH] D67695: [clangd] Implement getBeginning for overloaded operators.

2019-10-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp:330
+   "/^/ comments", // non-interesting token
+   "void f(int abc) { abc ^ ++; }",// whitespace
+   "void f(int abc) { ^abc^++; }", // range of identifier

ilya-biryukov wrote:
> Do we test `++^^abc` anywhere?
no, but we have a similar test ` ++/**/^abc`, added it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67695



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


[PATCH] D68182: [Clangd] Ensure children are always RootStmt in ExtractFunction (Fixes #153)

2019-10-01 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 222585.
SureYeaah marked 2 inline comments as done.
SureYeaah added a comment.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68182

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.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
@@ -554,7 +554,7 @@
   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) {
@@ -631,6 +631,9 @@
 F ([[int x = 0;]])
   )cpp";
   EXPECT_EQ(apply(MacroFailInput), "unavailable");
+
+  // Shouldn't crash.
+  EXPECT_EQ(apply("void f([[int a]]);"), "unavailable");
 }
 
 TEST_F(ExtractFunctionTest, ControlFlow) {
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -104,6 +104,7 @@
 }
 
 // Returns the (unselected) parent of all RootStmts given the commonAncestor.
+// Returns null if any child is not a RootStmt.
 // We only support extraction of RootStmts since it allows us to extract 
without
 // having to change the selection range. Also, this means that any scope that
 // begins in selection range, ends in selection range and any scope that begins
@@ -111,10 +112,11 @@
 const Node *getParentOfRootStmts(const Node *CommonAnc) {
   if (!CommonAnc)
 return nullptr;
+  const Node *Parent = nullptr;
   switch (CommonAnc->Selected) {
   case SelectionTree::Selection::Unselected:
-// Ensure all Children are RootStmts.
-return llvm::all_of(CommonAnc->Children, isRootStmt) ? CommonAnc : nullptr;
+Parent = CommonAnc;
+break;
   case SelectionTree::Selection::Partial:
 // Treat Partially selected VarDecl as completely selected since
 // SelectionTree doesn't always select VarDecls correctly.
@@ -125,14 +127,17 @@
   case SelectionTree::Selection::Complete:
 // If the Common Ancestor is completely selected, then it's a root 
statement
 // and its parent will be unselected.
-const Node *Parent = CommonAnc->Parent;
+Parent = CommonAnc->Parent;
 // If parent is a DeclStmt, even though it's unselected, we consider it a
 // root statement and return its parent. This is done because the VarDecls
 // claim the entire selection range of the Declaration and DeclStmt is
 // always unselected.
-return Parent->ASTNode.get() ? Parent->Parent : Parent;
+if (Parent->ASTNode.get())
+  Parent = Parent->Parent;
+break;
   }
-  llvm_unreachable("Unhandled SelectionTree::Selection enum");
+  // Ensure all Children are RootStmts.
+  return llvm::all_of(Parent->Children, isRootStmt) ? Parent : nullptr;
 }
 
 // The ExtractionZone class forms a view of the code wrt Zone.


Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -554,7 +554,7 @@
   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) {
@@ -631,6 +631,9 @@
 F ([[int x = 0;]])
   )cpp";
   EXPECT_EQ(apply(MacroFailInput), "unavailable");
+
+  // Shouldn't crash.
+  EXPECT_EQ(apply("void f([[int a]]);"), "unavailable");
 }
 
 TEST_F(ExtractFunctionTest, ControlFlow) {
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -104,6 +104,7 @@
 }
 
 // Returns the (unselected) parent of all RootStmts given the commonAncestor.
+// Returns null if any child is not a RootStmt.
 // We only support extraction of RootStmts since it allows us to extract without
 // having to change the selection range. Also, this means that any scope that
 // begins in selection range, ends in selection range and any scope that begins
@@ -111,10 +112,11 @@
 const Node *getParentOfRootStmts(const Node *CommonAnc) {
   if (!CommonAnc)
 return nullptr;
+  const Node *Parent = nullptr;
   switch (CommonAnc->Selected) {
   case SelectionTree::Selection::Unselected:
-// Ensure all Children are RootStmts.
-return llvm::all_of(CommonAnc->Children, isRootStmt) ? CommonAnc : nullptr;
+

[clang-tools-extra] r373323 - [clangd] Implement getBeginning for overloaded operators.

2019-10-01 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Oct  1 04:03:56 2019
New Revision: 373323

URL: http://llvm.org/viewvc/llvm-project?rev=373323&view=rev
Log:
[clangd] Implement getBeginning for overloaded operators.

Summary:
This will fix some bugs where navigation doesn't work on cases like
`std::cout <^< "hello"`.

Reviewers: ilya-biryukov

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/SourceCode.cpp
clang-tools-extra/trunk/clangd/SourceCode.h
clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp

Modified: clang-tools-extra/trunk/clangd/SourceCode.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SourceCode.cpp?rev=373323&r1=373322&r2=373323&view=diff
==
--- clang-tools-extra/trunk/clangd/SourceCode.cpp (original)
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp Tue Oct  1 04:03:56 2019
@@ -237,6 +237,45 @@ llvm::Optional getTokenRange(cons
   return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
 }
 
+namespace {
+
+enum TokenFlavor { Identifier, Operator, Whitespace, Other };
+
+bool isOverloadedOperator(const Token &Tok) {
+  switch (Tok.getKind()) {
+#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) 
\
+  case tok::Token:
+#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
+#include "clang/Basic/OperatorKinds.def"
+return true;
+
+  default:
+break;
+  }
+  return false;
+}
+
+TokenFlavor getTokenFlavor(SourceLocation Loc, const SourceManager &SM,
+   const LangOptions &LangOpts) {
+  Token Tok;
+  Tok.setKind(tok::NUM_TOKENS);
+  if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
+ /*IgnoreWhiteSpace*/ false))
+return Other;
+
+  // getRawToken will return false without setting Tok when the token is
+  // whitespace, so if the flag is not set, we are sure this is a whitespace.
+  if (Tok.is(tok::TokenKind::NUM_TOKENS))
+return Whitespace;
+  if (Tok.is(tok::TokenKind::raw_identifier))
+return Identifier;
+  if (isOverloadedOperator(Tok))
+return Operator;
+  return Other;
+}
+
+} // namespace
+
 SourceLocation getBeginningOfIdentifier(const Position &Pos,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
@@ -247,27 +286,57 @@ SourceLocation getBeginningOfIdentifier(
 return SourceLocation();
   }
 
-  // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
-  // if the cursor is at the end of the identifier.
-  // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
-  //  1) at the beginning of an identifier, we'll be looking at something
-  //  that isn't an identifier.
-  //  2) at the middle or end of an identifier, we get the identifier.
-  //  3) anywhere outside an identifier, we'll get some non-identifier thing.
-  // We can't actually distinguish cases 1 and 3, but returning the original
-  // location is correct for both!
+  // GetBeginningOfToken(InputLoc) is almost what we want, but does the wrong
+  // thing if the cursor is at the end of the token (identifier or operator).
+  // The cases are:
+  //   1) at the beginning of the token
+  //   2) at the middle of the token
+  //   3) at the end of the token
+  //   4) anywhere outside the identifier or operator
+  // To distinguish all cases, we lex both at the
+  // GetBeginningOfToken(InputLoc-1) and GetBeginningOfToken(InputLoc), for
+  // cases 1 and 4, we just return the original location.
   SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
-  if (*Offset == 0) // Case 1 or 3.
+  if (*Offset == 0) // Case 1 or 4.
 return InputLoc;
   SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
+  SourceLocation BeforeTokBeginning =
+  Lexer::GetBeginningOfToken(Before, SM, LangOpts);
+  TokenFlavor BeforeKind = getTokenFlavor(BeforeTokBeginning, SM, LangOpts);
 
-  Before = Lexer::GetBeginningOfToken(Before, SM, LangOpts);
-  Token Tok;
-  if (Before.isValid() &&
-  !Lexer::getRawToken(Before, Tok, SM, LangOpts, false) &&
-  Tok.is(tok::raw_identifier))
-return Before; // Case 2.
-  return InputLoc; // Case 1 or 3.
+  SourceLocation CurrentTokBeginning =
+  Lexer::GetBeginningOfToken(InputLoc, SM, LangOpts);
+  TokenFlavor CurrentKind = getTokenFlavor(CurrentTokBeginning, SM, LangOpts);
+
+  // At the middle of the token.
+  if (BeforeTokBeginning == CurrentTokBeginning) {
+// For interesting token, we return the beginning of the token.
+if (CurrentKind == Identifier || CurrentKind == Operator)
+  return CurrentTokBeginning;
+// otherwise, we return the original loc.
+return InputLoc;
+  }
+
+  // Whitespace is not interesting.

[PATCH] D67695: [clangd] Implement getBeginning for overloaded operators.

2019-10-01 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373323: [clangd] Implement getBeginning for overloaded 
operators. (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67695?vs=222583&id=222586#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67695

Files:
  clang-tools-extra/trunk/clangd/SourceCode.cpp
  clang-tools-extra/trunk/clangd/SourceCode.h
  clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
  clang-tools-extra/trunk/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/trunk/clangd/SourceCode.cpp
===
--- clang-tools-extra/trunk/clangd/SourceCode.cpp
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp
@@ -237,6 +237,45 @@
   return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
 }
 
+namespace {
+
+enum TokenFlavor { Identifier, Operator, Whitespace, Other };
+
+bool isOverloadedOperator(const Token &Tok) {
+  switch (Tok.getKind()) {
+#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
+  case tok::Token:
+#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
+#include "clang/Basic/OperatorKinds.def"
+return true;
+
+  default:
+break;
+  }
+  return false;
+}
+
+TokenFlavor getTokenFlavor(SourceLocation Loc, const SourceManager &SM,
+   const LangOptions &LangOpts) {
+  Token Tok;
+  Tok.setKind(tok::NUM_TOKENS);
+  if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
+ /*IgnoreWhiteSpace*/ false))
+return Other;
+
+  // getRawToken will return false without setting Tok when the token is
+  // whitespace, so if the flag is not set, we are sure this is a whitespace.
+  if (Tok.is(tok::TokenKind::NUM_TOKENS))
+return Whitespace;
+  if (Tok.is(tok::TokenKind::raw_identifier))
+return Identifier;
+  if (isOverloadedOperator(Tok))
+return Operator;
+  return Other;
+}
+
+} // namespace
+
 SourceLocation getBeginningOfIdentifier(const Position &Pos,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
@@ -247,27 +286,57 @@
 return SourceLocation();
   }
 
-  // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
-  // if the cursor is at the end of the identifier.
-  // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
-  //  1) at the beginning of an identifier, we'll be looking at something
-  //  that isn't an identifier.
-  //  2) at the middle or end of an identifier, we get the identifier.
-  //  3) anywhere outside an identifier, we'll get some non-identifier thing.
-  // We can't actually distinguish cases 1 and 3, but returning the original
-  // location is correct for both!
+  // GetBeginningOfToken(InputLoc) is almost what we want, but does the wrong
+  // thing if the cursor is at the end of the token (identifier or operator).
+  // The cases are:
+  //   1) at the beginning of the token
+  //   2) at the middle of the token
+  //   3) at the end of the token
+  //   4) anywhere outside the identifier or operator
+  // To distinguish all cases, we lex both at the
+  // GetBeginningOfToken(InputLoc-1) and GetBeginningOfToken(InputLoc), for
+  // cases 1 and 4, we just return the original location.
   SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
-  if (*Offset == 0) // Case 1 or 3.
+  if (*Offset == 0) // Case 1 or 4.
 return InputLoc;
   SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
+  SourceLocation BeforeTokBeginning =
+  Lexer::GetBeginningOfToken(Before, SM, LangOpts);
+  TokenFlavor BeforeKind = getTokenFlavor(BeforeTokBeginning, SM, LangOpts);
+
+  SourceLocation CurrentTokBeginning =
+  Lexer::GetBeginningOfToken(InputLoc, SM, LangOpts);
+  TokenFlavor CurrentKind = getTokenFlavor(CurrentTokBeginning, SM, LangOpts);
+
+  // At the middle of the token.
+  if (BeforeTokBeginning == CurrentTokBeginning) {
+// For interesting token, we return the beginning of the token.
+if (CurrentKind == Identifier || CurrentKind == Operator)
+  return CurrentTokBeginning;
+// otherwise, we return the original loc.
+return InputLoc;
+  }
 
-  Before = Lexer::GetBeginningOfToken(Before, SM, LangOpts);
-  Token Tok;
-  if (Before.isValid() &&
-  !Lexer::getRawToken(Before, Tok, SM, LangOpts, false) &&
-  Tok.is(tok::raw_identifier))
-return Before; // Case 2.
-  return InputLoc; // Case 1 or 3.
+  // Whitespace is not interesting.
+  if (BeforeKind == Whitespace)
+return CurrentTokBeginning;
+  if (CurrentKind == Whitespace)
+return BeforeTokBeginning;
+
+  // The cursor is at the token boundary, e.g. "Before^Current", we prefer
+  // identifiers to other tokens.
+  if (Curre

[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

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

A few nits inline, otherwise the patch is awesome, thank you!!




Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:60-61
 private:
-  void Fopen(CheckerContext &C, const CallExpr *CE) const;
-  void Tmpfile(CheckerContext &C, const CallExpr *CE) const;
-  void Fclose(CheckerContext &C, const CallExpr *CE) const;
-  void Fread(CheckerContext &C, const CallExpr *CE) const;
-  void Fwrite(CheckerContext &C, const CallExpr *CE) const;
-  void Fseek(CheckerContext &C, const CallExpr *CE) const;
-  void Ftell(CheckerContext &C, const CallExpr *CE) const;
-  void Rewind(CheckerContext &C, const CallExpr *CE) const;
-  void Fgetpos(CheckerContext &C, const CallExpr *CE) const;
-  void Fsetpos(CheckerContext &C, const CallExpr *CE) const;
-  void Clearerr(CheckerContext &C, const CallExpr *CE) const;
-  void Feof(CheckerContext &C, const CallExpr *CE) const;
-  void Ferror(CheckerContext &C, const CallExpr *CE) const;
-  void Fileno(CheckerContext &C, const CallExpr *CE) const;
-
-  void OpenFileAux(CheckerContext &C, const CallExpr *CE) const;
-
-  ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state,
- CheckerContext &C) const;
-  ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef state,
- CheckerContext &C) const;
+  typedef void (StreamChecker::*FnCheck)(const CallEvent &,
+ CheckerContext &) const;
+

Prefer using. When I wrote D68165, I spent about 10 minutes figuring out how to 
do it... Ah, the joys of the C++ syntax.
```lang=c++
using FnCheck = void (StreamChecker::*)(const CallEvent &,
CheckerContext &) const;
```



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:109-110
 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
+  if (!Call.isGlobalCFunction())
+return false;
+

Isn't this redundant with my other inline about parameter types?



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

I'm not sure why we need this, is it true that *all* stream related functions 
return a pointer or a numerical value? Are we actually checking whether this 
really is a library function? If so, this looks pretty arbitrary.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:156
+void StreamChecker::evalFread(const CallEvent &Call, CheckerContext &C) const {
+  (void)CheckNullStream(Call.getArgSVal(3), C);
 }

Why the need for `(void)`? `CheckNullSteam` doesn't seem to have an 
`LLVM_NODISCARD` attribute.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


[PATCH] D68024: [clangd] Implement GetEligiblePoints

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 222590.
kadircet marked an inline comment as done.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68024

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp

Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -603,6 +604,67 @@
 Test.llvm::Annotations::point("bar"));
 }
 
+TEST(SourceCodeTests, GetEligiblePoints) {
+  constexpr struct {
+const char *Code;
+const char *FullyQualifiedName;
+const char *EnclosingNamespace;
+  } Cases[] = {
+  {R"cpp(// FIXME: We should also mark positions before and after
+ //declarations/definitions as eligible.
+  namespace ns1 {
+  namespace a { namespace ns2 {} }
+  namespace ns2 {^
+  void foo();
+  namespace {}
+  void bar() {}
+  namespace ns3 {}
+  class T {};
+  ^}
+  using namespace ns2;
+  })cpp",
+   "ns1::ns2::symbol", "ns1::ns2::"},
+  {R"cpp(
+  namespace ns1 {^
+  namespace a { namespace ns2 {} }
+  namespace b {}
+  namespace ns {}
+  ^})cpp",
+   "ns1::ns2::symbol", "ns1::"},
+  {R"cpp(
+  namespace x {
+  namespace a { namespace ns2 {} }
+  namespace b {}
+  namespace ns {}
+  }^)cpp",
+   "ns1::ns2::symbol", ""},
+  {R"cpp(
+  namespace ns1 {
+  namespace ns2 {^^}
+  namespace b {}
+  namespace ns2 {^^}
+  }
+  namespace ns1 {namespace ns2 {^^}})cpp",
+   "ns1::ns2::symbol", "ns1::ns2::"},
+  {R"cpp(
+  namespace ns1 {^
+  namespace ns {}
+  namespace b {}
+  namespace ns {}
+  ^}
+  namespace ns1 {^namespace ns {}^})cpp",
+   "ns1::ns2::symbol", "ns1::"},
+  };
+  for (auto Case : Cases) {
+Annotations Test(Case.Code);
+
+auto Res = getEligiblePoints(Test.code(), Case.FullyQualifiedName,
+ format::getLLVMStyle());
+EXPECT_THAT(Res.EligiblePoints, testing::ElementsAreArray(Test.points()))
+<< Test.code();
+EXPECT_EQ(Res.EnclosingNamespace, Case.EnclosingNamespace) << Test.code();
+  }
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -262,6 +262,27 @@
 std::vector visibleNamespaces(llvm::StringRef Code,
const format::FormatStyle &Style);
 
+/// Represents locations that can accept a definition.
+struct EligibleRegion {
+  /// Namespace that owns all of the EligiblePoints, e.g.
+  /// namespace a{ namespace b {^ void foo();^} }
+  /// It will be “a::b” for both carrot locations.
+  std::string EnclosingNamespace;
+  /// Offsets into the code marking eligible points to insert a function
+  /// definition.
+  std::vector EligiblePoints;
+};
+
+/// Returns most eligible region to insert a definition for \p
+/// FullyQualifiedName in the \p Code.
+/// Pseudo parses \pCode under the hood to determine namespace decls and
+/// possible insertion points. Choses the region that matches the longest prefix
+/// of \p FullyQualifiedName. Returns EOF if there are no shared namespaces.
+/// \p FullyQualifiedName should not contain anonymous namespaces.
+EligibleRegion getEligiblePoints(llvm::StringRef Code,
+ llvm::StringRef FullyQualifiedName,
+ const format::FormatStyle &Style);
+
 struct DefinedMacro {
   llvm::StringRef Name;
   const MacroInfo *Info;
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -20,9 +20,11 @@
 #include "clang/Format/Format.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/None.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llv

r373327 - [clang] Ignore builtin namespaces in test/Import/cxx-anon-namespace

2019-10-01 Thread Raphael Isemann via cfe-commits
Author: teemperor
Date: Tue Oct  1 04:53:20 2019
New Revision: 373327

URL: http://llvm.org/viewvc/llvm-project?rev=373327&view=rev
Log:
[clang] Ignore builtin namespaces in test/Import/cxx-anon-namespace

Some platforms (e.g. AArch64) put __va_list in the 'std' namespace which might
end up being the first namespace we match in this test. Instead let
the first namespace match via file name/line so that we skip the
builtin namespaces.

Modified:
cfe/trunk/test/Import/cxx-anon-namespace/test.cpp

Modified: cfe/trunk/test/Import/cxx-anon-namespace/test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Import/cxx-anon-namespace/test.cpp?rev=373327&r1=373326&r2=373327&view=diff
==
--- cfe/trunk/test/Import/cxx-anon-namespace/test.cpp (original)
+++ cfe/trunk/test/Import/cxx-anon-namespace/test.cpp Tue Oct  1 04:53:20 2019
@@ -2,9 +2,13 @@
 
 // The implicit UsingDirectiveDecls for the anonymous namespaces are created 
by the Sema.
 
-// CHECK: NamespaceDecl
+// There might be another builtin namespace before our first namespace, so we 
can't
+// just look for NamespaceDecl. Instead look for the first line of F.cpp 
(which only
+// contains the namespace we are looking for but no other decl).
+// CHECK: F.cpp:1:1
 // The nested anonymous namespace.
 // CHECK-NEXT: NamespaceDecl
+// CHECK-SAME: 
 // CHECK: FunctionDecl
 // CHECK-SAME: func4
 // CHECK-NEXT: CompoundStmt


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


[PATCH] D53137: Scalable vector core instruction support + size queries

2019-10-01 Thread Graham Hunter via Phabricator via cfe-commits
huntergr added inline comments.



Comment at: llvm/include/llvm/IR/DataLayout.h:454
+auto BaseSize = getTypeSizeInBits(Ty);
+return { (BaseSize.getKnownMinSize() + 7) / 8, BaseSize.isScalable() };
   }

rovka wrote:
> We already overload operator /, why not overload + as well so we don't have 
> to change the body of this method?
Scaling a size with * or / has a clear meaning to me, since it's independent of 
vscale; getting a vector that's half the size or four times larger just works.

Using + (or -) on the other hand doesn't seem to be as clear; I wasn't sure if 
a standalone int should be automatically treated as being the same as the 
TypeSize, or always considered Fixed. If we try for the former I can imagine 
quite a few bugs arising.

I could add a roundBitsToNearestByteSize method to move the arithmetic 
elsewhere if that would be acceptable?



Comment at: llvm/include/llvm/IR/DataLayout.h:656
+ 
getTypeSizeInBits(VTy->getElementType()).getKnownMinSize();
+return ScalableSize(MinBits, EltCnt.Scalable);
   }

rovka wrote:
> Maybe just return VTy->getElementCount() * 
> getTypeSizeInBits(VTy->getElementType()).getFixedSize().
There's no support for generating a TypeSize from an ElementCount in that way; 
is that an interface you feel is useful?

(I'll certainly change the `getKnownMinSize` to `getFixedSize` though, since 
we're just referring to a scalar)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53137



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


[PATCH] D53137: Scalable vector core instruction support + size queries

2019-10-01 Thread Graham Hunter via Phabricator via cfe-commits
huntergr updated this revision to Diff 222593.
huntergr added a comment.
Herald added a subscriber: dexonsmith.

- Renamed `ScalableSize` to `TypeSize`, including header name.
- added `alignTo` function that takes and returns a `TypeSize`. I wasn't sure 
if this should be added to MathExtras.h where the other variants live, so just 
kept it in TypeSize.h for now


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53137

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  llvm/include/llvm/ADT/DenseMapInfo.h
  llvm/include/llvm/IR/DataLayout.h
  llvm/include/llvm/IR/DerivedTypes.h
  llvm/include/llvm/IR/InstrTypes.h
  llvm/include/llvm/IR/Type.h
  llvm/include/llvm/Support/MachineValueType.h
  llvm/include/llvm/Support/ScalableSize.h
  llvm/include/llvm/Support/TypeSize.h
  llvm/lib/Analysis/InlineCost.cpp
  llvm/lib/CodeGen/Analysis.cpp
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/IR/Type.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Transforms/Scalar/SROA.cpp
  llvm/test/Other/scalable-vectors-core-ir.ll
  llvm/unittests/CodeGen/ScalableVectorMVTsTest.cpp
  llvm/unittests/IR/VectorTypesTest.cpp

Index: llvm/unittests/IR/VectorTypesTest.cpp
===
--- llvm/unittests/IR/VectorTypesTest.cpp
+++ llvm/unittests/IR/VectorTypesTest.cpp
@@ -6,9 +6,10 @@
 //
 //===--===//
 
+#include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/LLVMContext.h"
-#include "llvm/Support/ScalableSize.h"
+#include "llvm/Support/TypeSize.h"
 #include "gtest/gtest.h"
 using namespace llvm;
 
@@ -161,4 +162,117 @@
   ASSERT_TRUE(EltCnt.Scalable);
 }
 
+TEST(VectorTypesTest, FixedLenComparisons) {
+  LLVMContext Ctx;
+  DataLayout DL("");
+
+  Type *Int32Ty = Type::getInt32Ty(Ctx);
+  Type *Int64Ty = Type::getInt64Ty(Ctx);
+
+  VectorType *V2Int32Ty = VectorType::get(Int32Ty, 2);
+  VectorType *V4Int32Ty = VectorType::get(Int32Ty, 4);
+
+  VectorType *V2Int64Ty = VectorType::get(Int64Ty, 2);
+
+  TypeSize V2I32Len = V2Int32Ty->getPrimitiveSizeInBits();
+  EXPECT_EQ(V2I32Len.getKnownMinSize(), 64U);
+  EXPECT_FALSE(V2I32Len.isScalable());
+
+  EXPECT_LT(V2Int32Ty->getPrimitiveSizeInBits(),
+V4Int32Ty->getPrimitiveSizeInBits());
+  EXPECT_GT(V2Int64Ty->getPrimitiveSizeInBits(),
+V2Int32Ty->getPrimitiveSizeInBits());
+  EXPECT_EQ(V4Int32Ty->getPrimitiveSizeInBits(),
+V2Int64Ty->getPrimitiveSizeInBits());
+  EXPECT_NE(V2Int32Ty->getPrimitiveSizeInBits(),
+V2Int64Ty->getPrimitiveSizeInBits());
+
+  // Check that a fixed-only comparison works for fixed size vectors.
+  EXPECT_EQ(V2Int64Ty->getPrimitiveSizeInBits().getFixedSize(),
+V4Int32Ty->getPrimitiveSizeInBits().getFixedSize());
+
+  // Check the DataLayout interfaces.
+  EXPECT_EQ(DL.getTypeSizeInBits(V2Int64Ty),
+DL.getTypeSizeInBits(V4Int32Ty));
+  EXPECT_EQ(DL.getTypeSizeInBits(V2Int32Ty), 64U);
+  EXPECT_EQ(DL.getTypeSizeInBits(V2Int64Ty), 128U);
+  EXPECT_EQ(DL.getTypeStoreSize(V2Int64Ty),
+DL.getTypeStoreSize(V4Int32Ty));
+  EXPECT_NE(DL.getTypeStoreSizeInBits(V2Int32Ty),
+DL.getTypeStoreSizeInBits(V2Int64Ty));
+  EXPECT_EQ(DL.getTypeStoreSizeInBits(V2Int32Ty), 64U);
+  EXPECT_EQ(DL.getTypeStoreSize(V2Int64Ty), 16U);
+  EXPECT_EQ(DL.getTypeAllocSize(V4Int32Ty),
+DL.getTypeAllocSize(V2Int64Ty));
+  EXPECT_NE(DL.getTypeAllocSizeInBits(V2Int32Ty),
+DL.getTypeAllocSizeInBits(V2Int64Ty));
+  EXPECT_EQ(DL.getTypeAllocSizeInBits(V4Int32Ty), 128U);
+  EXPECT_EQ(DL.getTypeAllocSize(V2Int32Ty), 8U);
+  ASSERT_TRUE(DL.typeSizeEqualsStoreSize(V4Int32Ty));
+}
+
+TEST(VectorTypesTest, ScalableComparisons) {
+  LLVMContext Ctx;
+  DataLayout DL("");
+
+  Type *Int32Ty = Type::getInt32Ty(Ctx);
+  Type *Int64Ty = Type::getInt64Ty(Ctx);
+
+  VectorType *ScV2Int32Ty = VectorType::get(Int32Ty, {2, true});
+  VectorType *ScV4Int32Ty = VectorType::get(Int32Ty, {4, true});
+
+  VectorType *ScV2Int64Ty = VectorType::get(Int64Ty, {2, true});
+
+  TypeSize ScV2I32Len = ScV2Int32Ty->getPrimitiveSizeInBits();
+  EXPECT_EQ(ScV2I32Len.getKnownMinSize(), 64U);
+  EXPECT_TRUE(ScV2I32Len.isScalable());
+
+  EXPECT_LT(ScV2Int32Ty->getPrimitiveSizeInBits(),
+ScV4Int32Ty->getPrimitiveSizeInBits());
+  EXPECT_GT(ScV2Int64Ty->getPrimitiveSizeInBits(),
+ScV2Int32Ty->getPrimitiveSizeInBits());
+  EXPECT_EQ(ScV4Int32Ty->getPrimitiveSizeInBits(),
+ScV2Int64Ty->getPrimitiveSizeInBits());
+  EXPECT_NE(ScV2Int32Ty->getPrimitiveSizeInBits(),
+ScV2Int64Ty->getPrimitiveSizeInBits());
+
+  // Check the DataLayout interfaces.
+  EXPECT_EQ(DL.getTypeSizeInBits(ScV2Int64Ty),
+DL.getTypeSizeInBits(ScV4Int32Ty));
+  EXPECT

[PATCH] D68028: [clang] Add no_builtin attribute

2019-10-01 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet marked 7 inline comments as done.
gchatelet added a comment.

thx @aaron.ballman , I'm waiting for your reply before uploading the new patch 
(some of my comments won't have the accompanying code update sorry)




Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1072
+NoBuiltinAttr *
+Sema::mergeNoBuiltinAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
+ llvm::ArrayRef FunctionNames) {

aaron.ballman wrote:
> You're missing a call to this function within `mergeDeclAttribute()` in 
> SemaDecl.cpp.
Thx, I rearranged the signature a bit, do you happen to know how 
`mergeDeclAttribute` is tested?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1078-1079
+  // Insert previous NoBuiltin attributes.
+  if (D->hasAttr())
+for (StringRef FunctionName : D->getAttr()->functionNames())
+  FunctionNamesSet.insert(FunctionName);

aaron.ballman wrote:
> Instead of doing `hasAttr<>` followed by `getAttr<>`, this should be:
> ```
> if (const auto *NBA = D->getAttr()) {
>   for (StringRef FunctionName : NBA->functionNames())
> ...
> }
> ```
> But are you able to use `llvm::copy()` instead of a manual loop?
I had to use a vector instead of a set and //uniquify// by hand.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1086-1089
+  if (FunctionNamesSet.count(Wildcard) > 0) {
+FunctionNamesSet.clear();
+FunctionNamesSet.insert(Wildcard);
+  }

aaron.ballman wrote:
> Rather than walking the entire set like this, would it make more sense to 
> look for the wildcard in the above loop before inserting the name, and set a 
> local variable if found, so that you can do the clear without having to 
> rescan the entire list?
This is is conflict with the `llvm::copy` suggestion above. Which one do you 
prefer?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1098-1099
+
+  if (D->hasAttr())
+D->dropAttr();
+

aaron.ballman wrote:
> Just making sure I understand the semantics you want: redeclarations do not 
> have to have matching lists of builtins, but instead the definition will use 
> a merged list? e.g.,
> ```
> [[clang::no_builtin("memset")]] void whatever();
> [[clang::no_builtin("memcpy")]] void whatever();
> 
> [[clang::no_builtin("memmove")]] void whatever() {
>  // Will not use memset, memcpy, or memmove builtins.
> }
> ```
> That seems a bit strange, to me. In fact, being able to apply this attribute 
> to a declaration seems a bit like a mistake -- this only impacts the 
> definition of the function, and I can't imagine good things coming from 
> hypothetical code like:
> ```
> [[clang::no_builtin("memset")]] void whatever();
> #include "whatever.h" // Provides a library declaration of whatever() with no 
> restrictions on it
> ```
> WDYT about restricting this attribute to only appear on definitions?
That's a very good point. Thx for noticing.
Indeed I think it only makes sense to have the attribute on the function 
definition.

I've tried to to use `FunctionDecl->hasBody()` during attribute handling in the 
Sema phase but it seems like the `FunctionDecl` is not complete at this point.
All calls to `hasBody()` return `false`, if I repeat the operation in `CGCall` 
then `hasBody` returns `true` and I can see the `CompoundStatement`.

Do you have any recommendations on where to perform the check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68028



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


[PATCH] D68268: [Alignment][NFC] Remove StoreInst::setAlignment(unsigned)

2019-10-01 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet created this revision.
gchatelet added a reviewer: courbet.
Herald added a reviewer: bollu.
Herald added subscribers: llvm-commits, cfe-commits, asbirlea, hiraditya.
Herald added a reviewer: jdoerfert.
Herald added projects: clang, LLVM.

This is patch is part of a series to introduce an Alignment type.
See this thread for context: 
http://lists.llvm.org/pipermail/llvm-dev/2019-July/133851.html
See this patch for the introduction of the type: https://reviews.llvm.org/D64790


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68268

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCleanup.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  llvm/include/llvm/IR/IRBuilder.h
  llvm/include/llvm/IR/Instructions.h
  llvm/lib/CodeGen/AtomicExpandPass.cpp
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/lib/Transforms/InstCombine/InstCombineAtomicRMW.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
  llvm/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp
  llvm/lib/Transforms/Scalar/GVNHoist.cpp
  llvm/lib/Transforms/Scalar/LICM.cpp
  llvm/lib/Transforms/Scalar/SROA.cpp
  llvm/lib/Transforms/Utils/SimplifyCFG.cpp
  llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
  polly/lib/CodeGen/BlockGenerators.cpp

Index: polly/lib/CodeGen/BlockGenerators.cpp
===
--- polly/lib/CodeGen/BlockGenerators.cpp
+++ polly/lib/CodeGen/BlockGenerators.cpp
@@ -1209,7 +1209,7 @@
 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
 
 if (!Aligned)
-  Store->setAlignment(8);
+  Store->setAlignment(Align(8));
   } else {
 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
   Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Index: llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
===
--- llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -4024,7 +4024,7 @@
   if (!Alignment)
 Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
 
-  ST->setAlignment(Alignment);
+  ST->setAlignment(Align(Alignment));
   Value *V = propagateMetadata(ST, E->Scalars);
   if (NeedToShuffleReuses) {
 V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
Index: llvm/lib/Transforms/Utils/SimplifyCFG.cpp
===
--- llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -3087,15 +3087,15 @@
   // store that doesn't execute.
   if (MinAlignment != 0) {
 // Choose the minimum of all non-zero alignments.
-SI->setAlignment(MinAlignment);
+SI->setAlignment(Align(MinAlignment));
   } else if (MaxAlignment != 0) {
 // Choose the minimal alignment between the non-zero alignment and the ABI
 // default alignment for the type of the stored value.
-SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
+SI->setAlignment(Align(std::min(MaxAlignment, TypeAlignment)));
   } else {
 // If both alignments are zero, use ABI default alignment for the type of
 // the stored value.
-SI->setAlignment(TypeAlignment);
+SI->setAlignment(Align(TypeAlignment));
   }
 
   QStore->eraseFromParent();
Index: llvm/lib/Transforms/Scalar/SROA.cpp
===
--- llvm/lib/Transforms/Scalar/SROA.cpp
+++ llvm/lib/Transforms/Scalar/SROA.cpp
@@ -3127,7 +3127,7 @@
   Value *Op = SI->getOperand(0);
   StoreAlign = DL.getABITypeAlignment(Op->getType());
 }
-SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
+SI->setAlignment(MaybeAlign(std::min(StoreAlign, getSliceAlign(;
 continue;
   }
 
Index: llvm/lib/Transforms/Scalar/LICM.cpp
===
--- llvm/lib/Transforms/Scalar/LICM.cpp
+++ llvm/lib/Transforms/Scalar/LICM.cpp
@@ -1791,7 +1791,7 @@
   StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
   if (UnorderedAtomic)
 NewSI->setOrdering(AtomicOrdering::Unordered);
-  NewSI->setAlignment(Alignment);
+  NewSI->setAlignment(MaybeAlign(Alignment));
   NewSI->setDebugLoc(DL);
   if (AATags)
 NewSI->setAAMetadata(AATags);
Index: llvm/lib/Transforms/Scalar/GVNHoist.cpp
===
--- llvm/lib/Transforms/Scalar/GVNHoist.cpp
+++ llvm/lib/Transforms/Scalar/GVNHoist.cpp
@@ -894,8 +894,8 @@
   ++NumLoadsRemoved;
 } else if (auto *ReplacementStore = dyn_cast(Repl)) {
   ReplacementStore->setAlignment(
-  std::min(ReplacementStore->getAlignment(),
-   cast(I)->getAlignment()));
+  M

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

2019-10-01 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.

Many thanks! LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68143



___
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-01 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Sema/SemaDecl.cpp:17618
+
+  if (LangOpts.CUDA) {
+// When compiling for device, host functions are never emitted.  Similarly,

Are you going to handle `#pragma omp declare target device_type(nohost)` in 
Cuda mode correctly? Such functions should not be emitted on the host in OpenMP 
5.0.



Comment at: lib/Sema/SemaOpenMP.cpp:1569-1574
+static Sema::FunctionEmissionStatus isKnownDeviceEmitted(Sema &S,
+ FunctionDecl *FD) {
   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  "Expected OpenMP device compilation.");
-  // Templates are emitted when they're instantiated.
-  if (FD->isDependentContext())
-return FunctionEmissionStatus::Discarded;
-
-  Optional DevTy =
-  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
-  if (DevTy.hasValue())
-return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
-   ? FunctionEmissionStatus::Discarded
-   : FunctionEmissionStatus::Emitted;
-
-  // Otherwise, the function is known-emitted if it's in our set of
-  // known-emitted functions.
-  return (S.DeviceKnownEmittedFns.count(FD) > 0)
- ? FunctionEmissionStatus::Emitted
- : FunctionEmissionStatus::Unknown;
+  return S.getEmissionStatus(FD);
 }

You can remove the whole function and use `Sema::getEmissionStatus()` instead.



Comment at: lib/Sema/SemaOpenMP.cpp:1593
+  case FunctionEmissionStatus::OMPDiscarded:
+  case FunctionEmissionStatus::CUDADiscarded:
 Kind = DeviceDiagBuilder::K_Nop;

I think, `CUDADiscarded` case must be unreachable and it must be a case for 
`llvm_unreachable()` in case of the OpenMP device code.



Comment at: lib/Sema/SemaOpenMP.cpp:1602-1607
+static Sema::FunctionEmissionStatus isKnownHostEmitted(Sema &S,
+   FunctionDecl *FD) {
   assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
  "Expected OpenMP host compilation.");
-  // In OpenMP 4.5 all the functions are host functions.
-  if (S.LangOpts.OpenMP <= 45)
-return FunctionEmissionStatus::Emitted;
-
-  Optional DevTy =
-  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
-  if (DevTy.hasValue())
-return (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
-   ? FunctionEmissionStatus::Discarded
-   : FunctionEmissionStatus::Emitted;
-
-  // Otherwise, the function is known-emitted if it's in our set of
-  // known-emitted functions.
-  return (S.DeviceKnownEmittedFns.count(FD) > 0)
- ? FunctionEmissionStatus::Emitted
- : FunctionEmissionStatus::Unknown;
+  return S.getEmissionStatus(FD);
 }

You can remove the whole function and use `Sema::getEmissionStatus()` instead.



Comment at: lib/Sema/SemaOpenMP.cpp:1647-1648
 FunctionEmissionStatus::Unknown)) &&
   isKnownDeviceEmitted(*this, Callee) ==
-  FunctionEmissionStatus::Discarded) {
+  FunctionEmissionStatus::OMPDiscarded) {
 StringRef HostDevTy =

I would add an assert thet this function does not return `CUDADiscarded` value.



Comment at: lib/Sema/SemaOpenMP.cpp:1684-1685
   isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted &&
-  isKnownHostEmitted(*this, Callee) == FunctionEmissionStatus::Discarded) {
+  isKnownHostEmitted(*this, Callee) ==
+  FunctionEmissionStatus::OMPDiscarded) {
 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(

Also, it would be good to check that it cannot return `CUDADiscarded` here.


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] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked 3 inline comments as done.
balazske added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:109-110
 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
+  if (!Call.isGlobalCFunction())
+return false;
+

Szelethus wrote:
> Isn't this redundant with my other inline about parameter types?
Probably change to `isInSystemHeader` or use both?



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

Szelethus wrote:
> I'm not sure why we need this, is it true that *all* stream related functions 
> return a pointer or a numerical value? Are we actually checking whether this 
> really is a library function? If so, this looks pretty arbitrary.
This comes from code of CStringChecker:
```
  // Pro-actively check that argument types are safe to do arithmetic upon.
  // We do not want to crash if someone accidentally passes a structure
  // into, say, a C++ overload of any of these functions. We could not check
  // that for std::copy because they may have arguments of other types.
```
Still I am not sure that the checker works correct with code that contains 
similar named but "arbitrary" functions.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:156
+void StreamChecker::evalFread(const CallEvent &Call, CheckerContext &C) const {
+  (void)CheckNullStream(Call.getArgSVal(3), C);
 }

Szelethus wrote:
> Why the need for `(void)`? `CheckNullSteam` doesn't seem to have an 
> `LLVM_NODISCARD` attribute.
I wanted to be sure to get no buildbot compile errors (where -Werror is used).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

balazske wrote:
> Szelethus wrote:
> > I'm not sure why we need this, is it true that *all* stream related 
> > functions return a pointer or a numerical value? Are we actually checking 
> > whether this really is a library function? If so, this looks pretty 
> > arbitrary.
> This comes from code of CStringChecker:
> ```
>   // Pro-actively check that argument types are safe to do arithmetic upon.
>   // We do not want to crash if someone accidentally passes a structure
>   // into, say, a C++ overload of any of these functions. We could not check
>   // that for std::copy because they may have arguments of other types.
> ```
> Still I am not sure that the checker works correct with code that contains 
> similar named but "arbitrary" functions.
Oops, meant to write that ", is it true that *all* stream related functions 
have only pointer or a numerical parameters?".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


[PATCH] D66049: [analyzer] PR41729: Fix some false positives and improve strlcat and strlcpy modeling

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

The logic of the patch is fine in my eyes, but I dislike the formatting. Could 
you please make the code obey the LLVM coding style, and after that use 
clang-format-diff.py?
https://llvm.org/docs/CodingStandards.html
https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting




Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:31
 namespace {
+enum class appendKind { none = 0, strcat = 1, strlcat = 2 };
 class CStringChecker : public Checker< eval::Call,

Please capitalize these. Also, `ConcatFnKind` might be more descriptive? Ad 
absurdum, we might as well pass the `CallDescription` that is responsible for 
the concatenation. That maaay just be a little over engineered though.



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:133-134
   void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
-  void evalStrcpyCommon(CheckerContext &C,
-const CallExpr *CE,
-bool returnEnd,
-bool isBounded,
-bool isAppending,
+  void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
+bool isBounded, appendKind appendK,
 bool returnPtr = true) const;

CaPitALizeE :D



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1556
+
+  // Get the string length of the destination
+  SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);

Please terminate this sentence.



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1580
 
   // If the function is strncpy, strncat, etc... it is bounded.
   if (isBounded) {

Ah, okay, so the assumption is that bounded functions' third argument is always 
a numerical size parameter. Why isn't that enforced at all?



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1596
 
-  // Check if the max number to copy is less than the length of the src.
-  // If the bound is equal to the source length, strncpy won't null-
-  // terminate the result!
-  std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
-  svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
-  .castAs());
+  if (appendK == appendKind::none || appendK == appendKind::strcat) {
+ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;

Can we just do a switch-case? If someone were to add a new concat type, it 
would even give a warning in case it was left unhandled.



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1628
+  if (Optional freeSpaceNL = freeSpace.getAs()) {
+// Symbolic expression not too complex.
+

Please put comments like these before the branch. I like the following format 
better:

```lang=c++
// While unlikely, it is possible that the subtraction is too complexity
// to complex to compute, let's check whether it succeeded.
if (Optional freeSpaceNL = freeSpace.getAs())
```



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1630
+
+SVal haveEnoughSpace = svalBuilder.evalBinOpNN(
+state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);

`hasEnoughSpace`



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1637-1640
+if (TrueState && !FalseState) {
+  // srcStrLength <= size - dstStrLength -1
+  amountCopied = strLength;
+}

All of these too, and omit braces too:

```lang=c++
// srcStrLength <= size - dstStrLength -1
if (TrueState && !FalseState)
  amountCopied = strLength;
```



Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:1657
 if (lenValNL) {
-  if (isAppending) {
+  if (appendK == appendKind::strcat) {
 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)

Would prefer a switch case here too.


Repository:
  rC Clang

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

https://reviews.llvm.org/D66049



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


[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:109-110
 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
+  if (!Call.isGlobalCFunction())
+return false;
+

balazske wrote:
> Szelethus wrote:
> > Isn't this redundant with my other inline about parameter types?
> Probably change to `isInSystemHeader` or use both?
Actually, this looks fine. How about preserving this...



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

Szelethus wrote:
> balazske wrote:
> > Szelethus wrote:
> > > I'm not sure why we need this, is it true that *all* stream related 
> > > functions return a pointer or a numerical value? Are we actually checking 
> > > whether this really is a library function? If so, this looks pretty 
> > > arbitrary.
> > This comes from code of CStringChecker:
> > ```
> >   // Pro-actively check that argument types are safe to do arithmetic upon.
> >   // We do not want to crash if someone accidentally passes a structure
> >   // into, say, a C++ overload of any of these functions. We could not check
> >   // that for std::copy because they may have arguments of other types.
> > ```
> > Still I am not sure that the checker works correct with code that contains 
> > similar named but "arbitrary" functions.
> Oops, meant to write that ", is it true that *all* stream related functions 
> have only pointer or a numerical parameters?".
...and removing this one, or changing it to an assert?



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:156
+void StreamChecker::evalFread(const CallEvent &Call, CheckerContext &C) const {
+  (void)CheckNullStream(Call.getArgSVal(3), C);
 }

balazske wrote:
> Szelethus wrote:
> > Why the need for `(void)`? `CheckNullSteam` doesn't seem to have an 
> > `LLVM_NODISCARD` attribute.
> I wanted to be sure to get no buildbot compile errors (where -Werror is used).
They actually break on this?? Let me guess, is it the windows one? :D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


r373340 - [clang] Make handling of unnamed template params similar to function params

2019-10-01 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Tue Oct  1 07:08:51 2019
New Revision: 373340

URL: http://llvm.org/viewvc/llvm-project?rev=373340&view=rev
Log:
[clang] Make handling of unnamed template params similar to function params

Summary:
Clang uses the location identifier should be inserted for declarator
decls when a decl is unnamed. But for type template and template template
paramaters it uses the location of "typename/class" keyword, which makes it hard
for tooling to insert/change parameter names.

This change tries to unify these two cases by making template parameter
parsing and sourcerange operations similar to function params/declarator decls.

Reviewers: ilya-biryukov

Subscribers: arphaman, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/AST/DeclTemplate.cpp
cfe/trunk/lib/Parse/ParseTemplate.cpp
cfe/trunk/lib/Sema/SemaTemplate.cpp
cfe/trunk/test/AST/ast-dump-decl.cpp
cfe/trunk/test/AST/ast-dump-record-definition-data-json.cpp
cfe/trunk/test/AST/ast-dump-template-decls-json.cpp
cfe/trunk/test/AST/ast-dump-template-decls.cpp
cfe/trunk/test/ASTMerge/class-template/test.cpp
cfe/trunk/test/Index/index-templates.cpp

Modified: cfe/trunk/lib/AST/DeclTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/DeclTemplate.cpp?rev=373340&r1=373339&r2=373340&view=diff
==
--- cfe/trunk/lib/AST/DeclTemplate.cpp (original)
+++ cfe/trunk/lib/AST/DeclTemplate.cpp Tue Oct  1 07:08:51 2019
@@ -510,8 +510,12 @@ SourceRange TemplateTypeParmDecl::getSou
   if (hasDefaultArgument() && !defaultArgumentWasInherited())
 return SourceRange(getBeginLoc(),
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  // TypeDecl::getSourceRange returns a range containing name location, which 
is
+  // wrong for unnamed template parameters. e.g:
+  // it will return <[[typename>]] instead of <[[typename]]>
+  else if (getDeclName().isEmpty())
+return SourceRange(getBeginLoc());
+  return TypeDecl::getSourceRange();
 }
 
 unsigned TemplateTypeParmDecl::getDepth() const {

Modified: cfe/trunk/lib/Parse/ParseTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseTemplate.cpp?rev=373340&r1=373339&r2=373340&view=diff
==
--- cfe/trunk/lib/Parse/ParseTemplate.cpp (original)
+++ cfe/trunk/lib/Parse/ParseTemplate.cpp Tue Oct  1 07:08:51 2019
@@ -630,11 +630,11 @@ NamedDecl *Parser::ParseTypeParameter(un
   }
 
   // Grab the template parameter name (if given)
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;
   if (Tok.is(tok::identifier)) {
 ParamName = Tok.getIdentifierInfo();
-NameLoc = ConsumeToken();
+ConsumeToken();
   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  tok::greatergreater)) {
 // Unnamed template parameter. Don't have to do anything here, just
@@ -727,11 +727,11 @@ Parser::ParseTemplateTemplateParameter(u
: diag::ext_variadic_templates);
 
   // Get the identifier, if given.
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;
   if (Tok.is(tok::identifier)) {
 ParamName = Tok.getIdentifierInfo();
-NameLoc = ConsumeToken();
+ConsumeToken();
   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  tok::greatergreater)) {
 // Unnamed template parameter. Don't have to do anything here, just

Modified: cfe/trunk/lib/Sema/SemaTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplate.cpp?rev=373340&r1=373339&r2=373340&view=diff
==
--- cfe/trunk/lib/Sema/SemaTemplate.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplate.cpp Tue Oct  1 07:08:51 2019
@@ -1005,15 +1005,10 @@ NamedDecl *Sema::ActOnTypeParameter(Scop
   assert(S->isTemplateParamScope() &&
  "Template type parameter not in template parameter scope!");
 
-  SourceLocation Loc = ParamNameLoc;
-  if (!ParamName)
-Loc = KeyLoc;
-
   bool IsParameterPack = EllipsisLoc.isValid();
-  TemplateTypeParmDecl *Param
-= TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
-   KeyLoc, Loc, Depth, Position, ParamName,
-   Typename, IsParameterPack);
+  TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(
+  Context, Context.getTranslationUnitDecl(), KeyLoc, ParamNameLoc, Depth,
+  Position, ParamName, Typename, IsParameterPack);
   Param->setAccess(AS_public);
 
   if (Param->isParameterPack())
@@ -1044,7 +1039,7 @@ NamedDecl *Sema::ActOnTypeParameter(Scop
 assert(DefaultTInfo && "exp

[PATCH] D68143: [clang] Make handling of unnamed template params similar to function params

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373340: [clang] Make handling of unnamed template params 
similar to function params (authored by kadircet, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68143?vs=222581&id=222604#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68143

Files:
  cfe/trunk/lib/AST/DeclTemplate.cpp
  cfe/trunk/lib/Parse/ParseTemplate.cpp
  cfe/trunk/lib/Sema/SemaTemplate.cpp
  cfe/trunk/test/AST/ast-dump-decl.cpp
  cfe/trunk/test/AST/ast-dump-record-definition-data-json.cpp
  cfe/trunk/test/AST/ast-dump-template-decls-json.cpp
  cfe/trunk/test/AST/ast-dump-template-decls.cpp
  cfe/trunk/test/ASTMerge/class-template/test.cpp
  cfe/trunk/test/Index/index-templates.cpp

Index: cfe/trunk/lib/Parse/ParseTemplate.cpp
===
--- cfe/trunk/lib/Parse/ParseTemplate.cpp
+++ cfe/trunk/lib/Parse/ParseTemplate.cpp
@@ -630,11 +630,11 @@
   }
 
   // Grab the template parameter name (if given)
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;
   if (Tok.is(tok::identifier)) {
 ParamName = Tok.getIdentifierInfo();
-NameLoc = ConsumeToken();
+ConsumeToken();
   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  tok::greatergreater)) {
 // Unnamed template parameter. Don't have to do anything here, just
@@ -727,11 +727,11 @@
: diag::ext_variadic_templates);
 
   // Get the identifier, if given.
-  SourceLocation NameLoc;
+  SourceLocation NameLoc = Tok.getLocation();
   IdentifierInfo *ParamName = nullptr;
   if (Tok.is(tok::identifier)) {
 ParamName = Tok.getIdentifierInfo();
-NameLoc = ConsumeToken();
+ConsumeToken();
   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
  tok::greatergreater)) {
 // Unnamed template parameter. Don't have to do anything here, just
Index: cfe/trunk/lib/AST/DeclTemplate.cpp
===
--- cfe/trunk/lib/AST/DeclTemplate.cpp
+++ cfe/trunk/lib/AST/DeclTemplate.cpp
@@ -510,8 +510,12 @@
   if (hasDefaultArgument() && !defaultArgumentWasInherited())
 return SourceRange(getBeginLoc(),
getDefaultArgumentInfo()->getTypeLoc().getEndLoc());
-  else
-return TypeDecl::getSourceRange();
+  // TypeDecl::getSourceRange returns a range containing name location, which is
+  // wrong for unnamed template parameters. e.g:
+  // it will return <[[typename>]] instead of <[[typename]]>
+  else if (getDeclName().isEmpty())
+return SourceRange(getBeginLoc());
+  return TypeDecl::getSourceRange();
 }
 
 unsigned TemplateTypeParmDecl::getDepth() const {
Index: cfe/trunk/lib/Sema/SemaTemplate.cpp
===
--- cfe/trunk/lib/Sema/SemaTemplate.cpp
+++ cfe/trunk/lib/Sema/SemaTemplate.cpp
@@ -1005,15 +1005,10 @@
   assert(S->isTemplateParamScope() &&
  "Template type parameter not in template parameter scope!");
 
-  SourceLocation Loc = ParamNameLoc;
-  if (!ParamName)
-Loc = KeyLoc;
-
   bool IsParameterPack = EllipsisLoc.isValid();
-  TemplateTypeParmDecl *Param
-= TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
-   KeyLoc, Loc, Depth, Position, ParamName,
-   Typename, IsParameterPack);
+  TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(
+  Context, Context.getTranslationUnitDecl(), KeyLoc, ParamNameLoc, Depth,
+  Position, ParamName, Typename, IsParameterPack);
   Param->setAccess(AS_public);
 
   if (Param->isParameterPack())
@@ -1044,7 +1039,7 @@
 assert(DefaultTInfo && "expected source information for type");
 
 // Check for unexpanded parameter packs.
-if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
+if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
 UPPC_DefaultArgument))
   return Param;
 
Index: cfe/trunk/test/ASTMerge/class-template/test.cpp
===
--- cfe/trunk/test/ASTMerge/class-template/test.cpp
+++ cfe/trunk/test/ASTMerge/class-template/test.cpp
@@ -9,13 +9,13 @@
 // CHECK: class-template2.cpp:9:15: note: declared here with type 'long'
 
 // CHECK: class-template1.cpp:12:14: warning: template parameter has different kinds in different translation units
-// CHECK: class-template2.cpp:12:10: note: template parameter declared here
+// CHECK: class-template2.cpp:12:18: note: template parameter declared here
 
 // CHECK: class-template1.cpp:18:23: warning: non-type template parameter declared with incompatible types in different tran

[PATCH] D68162: [analyzer][MallocChecker][NFC] Communicate the allocation family information to auxiliary functions with template parameters

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

In D68162#1686810 , @NoQ wrote:

> Thank you, fantastic finding!
>
> > in fact we know it //compile time//
>
> Yeah, but is it accidental or is there a good reason behind always having 
> this information at compile time? 'Cause i don't want to restrict the code to 
> always provide this information at compile time if we're not sure it'll 
> always be able to provide it in compile time.


Definitely accidental. And now that I think about it, maybe it would be better 
to turn these into non-optional regular arguments. Though its far in the 
future, we could eventually add annotations that tell whether a function 
returns with `new`ed or `malloc()`ated memory.

The entire point of the patch was to get rid of `getAllocationFamily`, because 
there really isn't a need to get the allocation family of hardcoded functions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68162



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


Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Nico Weber via cfe-commits
Can we move this behind a Wenum-compare subgroup, say Wenum-compare-type?
Our codebase is (well, was) Wenum-compare clean, and this new warnings
fires pretty often and from a first quick glance the warning looks pretty
low-signal anyways (*). Maybe the subgroup shouldn't even be on by default
-- do you have any data on true / false positive rate of this?

(But for starters, just having a way to turn this off is enough.)

For example, we have a windows common control that's either a PGRP_DOWN or
a PGRP_UP page control and depending on which you store the control state
in the same int, then stuff like `return extra.inner_spin.spin_up ?
UPS_DISABLED : DNS_DISABLED;`.

On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: xbolva00
> Date: Mon Sep 30 12:55:50 2019
> New Revision: 373252
>
> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
> Log:
> [Diagnostics] Warn if enumeration type mismatch in conditional expression
>
> Summary:
> - Useful warning
> - GCC compatibility (GCC warns in C++ mode)
>
> Reviewers: rsmith, aaron.ballman
>
> Reviewed By: aaron.ballman
>
> Subscribers: cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D67919
>
> Added:
> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> Modified:
> cfe/trunk/lib/Sema/SemaChecking.cpp
>
> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373252&r1=373251&r2=373252&view=diff
>
> ==
> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Sep 30 12:55:50 2019
> @@ -11308,6 +11308,32 @@ static const IntegerLiteral *getIntegerL
>return IL;
>  }
>
> +static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
> +  Expr *LHS, Expr *RHS) {
> +  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
> +  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
> +
> +  const auto *LHSEnumType = LHSStrippedType->getAs();
> +  if (!LHSEnumType)
> +return;
> +  const auto *RHSEnumType = RHSStrippedType->getAs();
> +  if (!RHSEnumType)
> +return;
> +
> +  // Ignore anonymous enums.
> +  if (!LHSEnumType->getDecl()->hasNameForLinkage())
> +return;
> +  if (!RHSEnumType->getDecl()->hasNameForLinkage())
> +return;
> +
> +  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
> +return;
> +
> +  S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
> +  << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
> +  << RHS->getSourceRange();
> +}
> +
>  static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
>E = E->IgnoreParenImpCasts();
>SourceLocation ExprLoc = E->getExprLoc();
> @@ -11799,6 +11825,8 @@ static void CheckConditionalOperator(Sem
>bool Suspicious = false;
>CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
>CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
> +  CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
> +E->getFalseExpr());
>
>if (T->isBooleanType())
>  DiagnoseIntInBoolContext(S, E);
>
> Added: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373252&view=auto
>
> ==
> --- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (added)
> +++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Mon Sep 30
> 12:55:50 2019
> @@ -0,0 +1,39 @@
> +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
> +// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
> +
> +enum ro { A = 0x10 };
> +enum rw { B = 0xFF };
> +enum { C = 0x1A};
> +
> +enum {
> +  STATUS_SUCCESS,
> +  STATUS_FAILURE,
> +  MAX_BASE_STATUS_CODE
> +};
> +
> +enum ExtendedStatusCodes {
> +  STATUS_SOMETHING_INTERESTING = MAX_BASE_STATUS_CODE + 1000,
> +};
> +
> +
> +int get_flag(int cond) {
> +  return cond ? A : B;
> +  #ifdef __cplusplus
> +  // expected-warning@-2 {{enumeration type mismatch in conditional
> expression ('ro' and 'rw')}}
> +  #else
> +  // expected-no-diagnostics
> +  #endif
> +}
> +
> +// In the following cases we purposefully differ from GCC and dont warn
> because
> +// this code pattern is quite sensitive and we dont want to produce so
> many false positives.
> +
> +int get_flag_anon_enum(int cond) {
> +  return cond ? A : C;
> +}
> +
> +int foo(int c) {
> +  return c ? STATUS_SOMETHING_INTERESTING : STATUS_SUCCESS;
> +}
>
>
> ___
> cfe-commits mail

[PATCH] D68273: [clangd] Fix raciness in code completion tests

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68273

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -27,6 +27,8 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -1112,8 +1114,10 @@
   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);
+ReceivedRequest = true;
+ReceivedRequestCV.notify_one();
 return true;
   }
 
@@ -1132,7 +1136,9 @@
   size_t estimateMemoryUsage() const override { return 0; }
 
   const std::vector consumeRequests() const {
-std::lock_guard Lock(Mut);
+std::unique_lock Lock(Mut);
+ReceivedRequestCV.wait(Lock, [this]() { return ReceivedRequest; });
+ReceivedRequest = false;
 auto Reqs = std::move(Requests);
 Requests = {};
 return Reqs;
@@ -1140,7 +1146,9 @@
 
 private:
   // We need a mutex to handle async fuzzy find requests.
+  mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
+  mutable bool ReceivedRequest = false;
   mutable std::vector Requests;
 };
 
@@ -2098,9 +2106,6 @@
 
   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");


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -27,6 +27,8 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -1112,8 +1114,10 @@
   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);
+ReceivedRequest = true;
+ReceivedRequestCV.notify_one();
 return true;
   }
 
@@ -1132,7 +1136,9 @@
   size_t estimateMemoryUsage() const override { return 0; }
 
   const std::vector consumeRequests() const {
-std::lock_guard Lock(Mut);
+std::unique_lock Lock(Mut);
+ReceivedRequestCV.wait(Lock, [this]() { return ReceivedRequest; });
+ReceivedRequest = false;
 auto Reqs = std::move(Requests);
 Requests = {};
 return Reqs;
@@ -1140,7 +1146,9 @@
 
 private:
   // We need a mutex to handle async fuzzy find requests.
+  mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
+  mutable bool ReceivedRequest = false;
   mutable std::vector Requests;
 };
 
@@ -2098,9 +2106,6 @@
 
   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");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68273: [clangd] Fix raciness in code completion tests

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

This is still racy if there were > 1 request. I wonder if there a better way to 
address this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68273



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


[PATCH] D68274: [Alignment][Clang][NFC] Add CharUnits::getAsAlign

2019-10-01 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet created this revision.
gchatelet added a reviewer: courbet.
Herald added subscribers: cfe-commits, jholewinski.
Herald added a project: clang.

This is a prerequisite to removing `llvm::GlobalObject::setAlignment(unsigned)`.
This is patch is part of a series to introduce an Alignment type.
See this thread for context: 
http://lists.llvm.org/pipermail/llvm-dev/2019-July/133851.html
See this patch for the introduction of the type: https://reviews.llvm.org/D64790


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68274

Files:
  clang/include/clang/AST/CharUnits.h
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCleanup.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CGObjCGNU.cpp
  clang/lib/CodeGen/CGObjCMac.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/ConstantInitBuilder.cpp
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/CodeGen/MicrosoftCXXABI.cpp
  clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp

Index: clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
===
--- clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
+++ clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
@@ -279,7 +279,7 @@
 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
 "__clang_ast");
 // The on-disk hashtable needs to be aligned.
-ASTSym->setAlignment(8);
+ASTSym->setAlignment(llvm::Align(8));
 
 // Mach-O also needs a segment name.
 if (Triple.isOSBinFormatMachO())
Index: clang/lib/CodeGen/MicrosoftCXXABI.cpp
===
--- clang/lib/CodeGen/MicrosoftCXXABI.cpp
+++ clang/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -2355,7 +2355,7 @@
   /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
   /*Initializer=*/nullptr, VarName,
   /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
-  GV->setAlignment(Align.getQuantity());
+  GV->setAlignment(Align.getAsAlign());
   return ConstantAddress(GV, Align);
 }
 
@@ -2498,7 +2498,7 @@
  GV->getLinkage(), Zero, GuardName.str());
 GuardVar->setVisibility(GV->getVisibility());
 GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
-GuardVar->setAlignment(GuardAlign.getQuantity());
+GuardVar->setAlignment(GuardAlign.getAsAlign());
 if (GuardVar->isWeakForLinker())
   GuardVar->setComdat(
   CGM.getModule().getOrInsertComdat(GuardVar->getName()));
Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2194,7 +2194,7 @@
 guard->setVisibility(var->getVisibility());
 // If the variable is thread-local, so is its guard variable.
 guard->setThreadLocalMode(var->getThreadLocalMode());
-guard->setAlignment(guardAlignment.getQuantity());
+guard->setAlignment(guardAlignment.getAsAlign());
 
 // The ABI says: "It is suggested that it be emitted in the same COMDAT
 // group as the associated data object." In practice, this doesn't work for
@@ -2547,7 +2547,7 @@
 Guard->setThreadLocal(true);
 
 CharUnits GuardAlign = CharUnits::One();
-Guard->setAlignment(GuardAlign.getQuantity());
+Guard->setAlignment(GuardAlign.getAsAlign());
 
 CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
 InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
@@ -3479,7 +3479,7 @@
 
   CharUnits Align =
   CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
-  GV->setAlignment(Align.getQuantity());
+  GV->setAlignment(Align.getAsAlign());
 
   // The Itanium ABI specifies that type_info objects must be globally
   // unique, with one exception: if the type is an incomplete class
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -1442,7 +1442,7 @@
   CovDataVal, llvm::getCoverageMappingVarName());
 
   CovData->setSection(getCoverageSection(CGM));
-  CovData->setAlignment(8);
+  CovData->setAlignment(llvm::Align(8));
 
   // Make sure the data doesn't get deleted.
   CGM.addUsedGlobal(CovData);
Index: clang/lib/CodeGen/ConstantInitBuilder.cpp
===
--- clang/lib/CodeGen/ConstantInitBuilder.cpp
+++ clang/lib/CodeGen/ConstantInitBuilder.cpp
@@ -79,7 +79,7 @@
  /*insert before*/ nullptr,

[PATCH] D68273: [clangd] Fix raciness in code completion tests

2019-10-01 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 222618.
kadircet added a comment.

- As discussed offline, making `consumeRequests` take an argument for how many 
requests to receive before returning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68273

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -27,6 +27,8 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -1112,8 +1114,10 @@
   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);
+++NumRequestsReceived;
+ReceivedRequestCV.notify_one();
 return true;
   }
 
@@ -1131,8 +1135,11 @@
   // 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);
+ReceivedRequestCV.wait(Lock,
+   [this, Num] { return NumRequestsReceived == Num; });
+NumRequestsReceived = 0;
 auto Reqs = std::move(Requests);
 Requests = {};
 return Reqs;
@@ -1140,16 +1147,19 @@
 
 private:
   // We need a mutex to handle async fuzzy find requests.
+  mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
+  mutable size_t NumRequestsReceived = 0;
   mutable std::vector Requests;
 };
 
-std::vector captureIndexRequests(llvm::StringRef Code) {
+std::vector captureIndexRequests(llvm::StringRef Code,
+   size_t Num = 1) {
   clangd::CodeCompleteOptions Opts;
   IndexRequestCollector Requests;
   Opts.Index = &Requests;
   completions(Code, {}, Opts);
-  return Requests.consumeRequests();
+  return Requests.consumeRequests(Num);
 }
 
 TEST(CompletionTest, UnqualifiedIdQuery) {
@@ -2098,18 +2108,15 @@
 
   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 +2124,7 @@
   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);
 }
 


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -27,6 +27,8 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -1112,8 +1114,10 @@
   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);
+++NumRequestsReceived;
+ReceivedRequestCV.notify_one();
 return true;
   }
 
@@ -1131,8 +1135,11 @@
   // 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);
+ReceivedRequestCV.wait(Lock,
+   [this, Num] { return NumRequestsReceived == Num; });
+NumRequestsReceived = 0;
 auto Reqs = std::move(Requests);
 Requests = {};
 return Reqs;
@@ -1140,16 +1147,19 @@
 
 private:
   // We need a mutex to handle async fuzzy find requests.
+  mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
+  mutable size_t NumRequestsReceived = 0;
   mutable std::vector Requests;
 };
 
-std::vector captureIndexRequests(llvm::StringRef Code) {

[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked 2 inline comments as done.
balazske added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:109-110
 bool StreamChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
+  if (!Call.isGlobalCFunction())
+return false;
+

Szelethus wrote:
> balazske wrote:
> > Szelethus wrote:
> > > Isn't this redundant with my other inline about parameter types?
> > Probably change to `isInSystemHeader` or use both?
> Actually, this looks fine. How about preserving this...
Should be the "stream functions" always in system header? If no 
`isInSystemHeader` call is used any global function called "fopen" with 2 
arguments is recognized as stream opening function. If it returns a pointer and 
no "fclose" is called on that we will get a resource leak warning for that 
code. (But for this case the user will probably not enable the checker?).



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

Szelethus wrote:
> Szelethus wrote:
> > balazske wrote:
> > > Szelethus wrote:
> > > > I'm not sure why we need this, is it true that *all* stream related 
> > > > functions return a pointer or a numerical value? Are we actually 
> > > > checking whether this really is a library function? If so, this looks 
> > > > pretty arbitrary.
> > > This comes from code of CStringChecker:
> > > ```
> > >   // Pro-actively check that argument types are safe to do arithmetic 
> > > upon.
> > >   // We do not want to crash if someone accidentally passes a structure
> > >   // into, say, a C++ overload of any of these functions. We could not 
> > > check
> > >   // that for std::copy because they may have arguments of other types.
> > > ```
> > > Still I am not sure that the checker works correct with code that 
> > > contains similar named but "arbitrary" functions.
> > Oops, meant to write that ", is it true that *all* stream related functions 
> > have only pointer or a numerical parameters?".
> ...and removing this one, or changing it to an assert?
This can not be an assert because it is possible to have global functions with 
same name but different signature. The check can be kept to filter out such 
cases. The wanted stream functions have only integral or enum or pointer 
arguments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


[PATCH] D67901: [clangd] Improve semantic highlighting in dependent contexts (fixes #154)

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

In D67901#1687308 , @nridge wrote:

> I do feel strongly that types and non-types should be highlighted 
> differently, so the updated patch adds two new dependent highlightings, one 
> for types and one for variables/functions.


I see your point here, no objection.




Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:156
+  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+if (canHighlightName(E->getName())) {
+  addToken(E->getNameLoc(), HighlightingKind::DependentName);

nit: remove the `{}` and elsewhere, LLVM prefers not adding `{}` if the body 
only contains a single statement.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:163
+  bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
+if (canHighlightName(E->getMemberName())) {
+  addToken(E->getNameLoc(), HighlightingKind::DependentName);

I think we should use `E->getName()` since we are highlighting the `NameLoc` 
below.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:219
+  bool VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
+addToken(L.getNameLoc(), HighlightingKind::DependentType);
+return true;

nit: we have `kindForType` for hanlding all types, so I'd move the logic of 
detecting the dependent type there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67901



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


[PATCH] D14484: [clang-format] Formatting constructor initializer lists by putting them always on different lines

2019-10-01 Thread Pooya Daravi via Phabricator via cfe-commits
puya added a comment.

> Looking at this I'm wondering if this Isn't at least partially handled by the 
> BreakConstructorInitializersStyle in combination with 
> ConstructorInitializerAllOnOneLineOrOnePerLine style?

I’m fairly certain that’s only true when line is long enough to be broken. In 
which case second one ensures one per line (as opposed to different number of 
initializations per line) and the first one determines the style. They would 
not result in the requestes behavior if the line is not longer than max column. 
(I will double check when I am in front of a computer)


Repository:
  rL LLVM

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

https://reviews.llvm.org/D14484



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


r373345 - [Diagnostics] Move warning into the subgroup (-Wenum-compare-conditional)

2019-10-01 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Tue Oct  1 08:44:38 2019
New Revision: 373345

URL: http://llvm.org/viewvc/llvm-project?rev=373345&view=rev
Log:
[Diagnostics] Move warning into the subgroup (-Wenum-compare-conditional)


Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=373345&r1=373344&r2=373345&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Tue Oct  1 08:44:38 2019
@@ -563,8 +563,9 @@ def CoveredSwitchDefault : DiagGroup<"co
 def SwitchBool : DiagGroup<"switch-bool">;
 def SwitchEnum : DiagGroup<"switch-enum">;
 def Switch : DiagGroup<"switch">;
+def EnumCompareConditional : DiagGroup<"enum-compare-conditional">;
 def EnumCompareSwitch : DiagGroup<"enum-compare-switch">;
-def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareSwitch]>;
+def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareConditional, 
EnumCompareSwitch]>;
 def ImplicitFallthroughPerFunction :
   DiagGroup<"implicit-fallthrough-per-function">;
 def ImplicitFallthrough  : DiagGroup<"implicit-fallthrough",

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=373345&r1=373344&r2=373345&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Oct  1 08:44:38 
2019
@@ -6172,7 +6172,7 @@ def warn_comparison_of_mixed_enum_types
 def warn_conditional_mixed_enum_types : Warning<
   "enumeration type mismatch in conditional expression"
   "%diff{ ($ and $)|}0,1">,
-  InGroup;
+  InGroup;
 def warn_comparison_of_mixed_enum_types_switch : Warning<
   "comparison of two values with different enumeration types in switch 
statement"
   "%diff{ ($ and $)|}0,1">,

Modified: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373345&r1=373344&r2=373345&view=diff
==
--- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (original)
+++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Tue Oct  1 
08:44:38 2019
@@ -1,5 +1,7 @@
+// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare-conditional %s
 // RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
 // RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare-conditional %s
 // RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
 // RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
 


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


Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Dávid Bolvanský via cfe-commits
Yeah, I moved this warning into own subgroup in rL373345. Thanks.

ut 1. 10. 2019 o 16:24 Nico Weber  napísal(a):
>
> Can we move this behind a Wenum-compare subgroup, say Wenum-compare-type? Our 
> codebase is (well, was) Wenum-compare clean, and this new warnings fires 
> pretty often and from a first quick glance the warning looks pretty 
> low-signal anyways (*). Maybe the subgroup shouldn't even be on by default -- 
> do you have any data on true / false positive rate of this?
>
> (But for starters, just having a way to turn this off is enough.)
>
> For example, we have a windows common control that's either a PGRP_DOWN or a 
> PGRP_UP page control and depending on which you store the control state in 
> the same int, then stuff like `return extra.inner_spin.spin_up ? UPS_DISABLED 
> : DNS_DISABLED;`.
>
> On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits 
>  wrote:
>>
>> Author: xbolva00
>> Date: Mon Sep 30 12:55:50 2019
>> New Revision: 373252
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
>> Log:
>> [Diagnostics] Warn if enumeration type mismatch in conditional expression
>>
>> Summary:
>> - Useful warning
>> - GCC compatibility (GCC warns in C++ mode)
>>
>> Reviewers: rsmith, aaron.ballman
>>
>> Reviewed By: aaron.ballman
>>
>> Subscribers: cfe-commits
>>
>> Tags: #clang
>>
>> Differential Revision: https://reviews.llvm.org/D67919
>>
>> Added:
>> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
>> Modified:
>> cfe/trunk/lib/Sema/SemaChecking.cpp
>>
>> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373252&r1=373251&r2=373252&view=diff
>> ==
>> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Sep 30 12:55:50 2019
>> @@ -11308,6 +11308,32 @@ static const IntegerLiteral *getIntegerL
>>return IL;
>>  }
>>
>> +static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
>> +  Expr *LHS, Expr *RHS) {
>> +  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
>> +  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
>> +
>> +  const auto *LHSEnumType = LHSStrippedType->getAs();
>> +  if (!LHSEnumType)
>> +return;
>> +  const auto *RHSEnumType = RHSStrippedType->getAs();
>> +  if (!RHSEnumType)
>> +return;
>> +
>> +  // Ignore anonymous enums.
>> +  if (!LHSEnumType->getDecl()->hasNameForLinkage())
>> +return;
>> +  if (!RHSEnumType->getDecl()->hasNameForLinkage())
>> +return;
>> +
>> +  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
>> +return;
>> +
>> +  S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
>> +  << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
>> +  << RHS->getSourceRange();
>> +}
>> +
>>  static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
>>E = E->IgnoreParenImpCasts();
>>SourceLocation ExprLoc = E->getExprLoc();
>> @@ -11799,6 +11825,8 @@ static void CheckConditionalOperator(Sem
>>bool Suspicious = false;
>>CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
>>CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
>> +  CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
>> +E->getFalseExpr());
>>
>>if (T->isBooleanType())
>>  DiagnoseIntInBoolContext(S, E);
>>
>> Added: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373252&view=auto
>> ==
>> --- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (added)
>> +++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Mon Sep 30 
>> 12:55:50 2019
>> @@ -0,0 +1,39 @@
>> +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
>> +// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
>> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
>> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
>> +
>> +enum ro { A = 0x10 };
>> +enum rw { B = 0xFF };
>> +enum { C = 0x1A};
>> +
>> +enum {
>> +  STATUS_SUCCESS,
>> +  STATUS_FAILURE,
>> +  MAX_BASE_STATUS_CODE
>> +};
>> +
>> +enum ExtendedStatusCodes {
>> +  STATUS_SOMETHING_INTERESTING = MAX_BASE_STATUS_CODE + 1000,
>> +};
>> +
>> +
>> +int get_flag(int cond) {
>> +  return cond ? A : B;
>> +  #ifdef __cplusplus
>> +  // expected-warning@-2 {{enumeration type mismatch in conditional 
>> expression ('ro' and 'rw')}}
>> +  #else
>> +  // expected-no-diagnostics
>> +  #endif
>> +}
>> +
>> +// In the following cases we purposefully differ from GCC and dont warn 
>> because
>> +// this code pattern is quite sensitive and we dont want to produce so many 
>> false posi

Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Nico Weber via cfe-commits
Thanks!

Any thoughts on the true positive rate for this warning?

On Tue, Oct 1, 2019 at 11:43 AM Dávid Bolvanský 
wrote:

> Yeah, I moved this warning into own subgroup in rL373345. Thanks.
>
> ut 1. 10. 2019 o 16:24 Nico Weber  napísal(a):
> >
> > Can we move this behind a Wenum-compare subgroup, say
> Wenum-compare-type? Our codebase is (well, was) Wenum-compare clean, and
> this new warnings fires pretty often and from a first quick glance the
> warning looks pretty low-signal anyways (*). Maybe the subgroup shouldn't
> even be on by default -- do you have any data on true / false positive rate
> of this?
> >
> > (But for starters, just having a way to turn this off is enough.)
> >
> > For example, we have a windows common control that's either a PGRP_DOWN
> or a PGRP_UP page control and depending on which you store the control
> state in the same int, then stuff like `return extra.inner_spin.spin_up ?
> UPS_DISABLED : DNS_DISABLED;`.
> >
> > On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
> >>
> >> Author: xbolva00
> >> Date: Mon Sep 30 12:55:50 2019
> >> New Revision: 373252
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
> >> Log:
> >> [Diagnostics] Warn if enumeration type mismatch in conditional
> expression
> >>
> >> Summary:
> >> - Useful warning
> >> - GCC compatibility (GCC warns in C++ mode)
> >>
> >> Reviewers: rsmith, aaron.ballman
> >>
> >> Reviewed By: aaron.ballman
> >>
> >> Subscribers: cfe-commits
> >>
> >> Tags: #clang
> >>
> >> Differential Revision: https://reviews.llvm.org/D67919
> >>
> >> Added:
> >> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> >> Modified:
> >> cfe/trunk/lib/Sema/SemaChecking.cpp
> >>
> >> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> >> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373252&r1=373251&r2=373252&view=diff
> >>
> ==
> >> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
> >> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Sep 30 12:55:50 2019
> >> @@ -11308,6 +11308,32 @@ static const IntegerLiteral *getIntegerL
> >>return IL;
> >>  }
> >>
> >> +static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
> >> +  Expr *LHS, Expr *RHS) {
> >> +  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
> >> +  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
> >> +
> >> +  const auto *LHSEnumType = LHSStrippedType->getAs();
> >> +  if (!LHSEnumType)
> >> +return;
> >> +  const auto *RHSEnumType = RHSStrippedType->getAs();
> >> +  if (!RHSEnumType)
> >> +return;
> >> +
> >> +  // Ignore anonymous enums.
> >> +  if (!LHSEnumType->getDecl()->hasNameForLinkage())
> >> +return;
> >> +  if (!RHSEnumType->getDecl()->hasNameForLinkage())
> >> +return;
> >> +
> >> +  if (S.Context.hasSameUnqualifiedType(LHSStrippedType,
> RHSStrippedType))
> >> +return;
> >> +
> >> +  S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
> >> +  << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
> >> +  << RHS->getSourceRange();
> >> +}
> >> +
> >>  static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
> >>E = E->IgnoreParenImpCasts();
> >>SourceLocation ExprLoc = E->getExprLoc();
> >> @@ -11799,6 +11825,8 @@ static void CheckConditionalOperator(Sem
> >>bool Suspicious = false;
> >>CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
> >>CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
> >> +  CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
> >> +E->getFalseExpr());
> >>
> >>if (T->isBooleanType())
> >>  DiagnoseIntInBoolContext(S, E);
> >>
> >> Added: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> >> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373252&view=auto
> >>
> ==
> >> --- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (added)
> >> +++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Mon Sep
> 30 12:55:50 2019
> >> @@ -0,0 +1,39 @@
> >> +// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
> >> +// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
> >> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
> >> +// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
> >> +
> >> +enum ro { A = 0x10 };
> >> +enum rw { B = 0xFF };
> >> +enum { C = 0x1A};
> >> +
> >> +enum {
> >> +  STATUS_SUCCESS,
> >> +  STATUS_FAILURE,
> >> +  MAX_BASE_STATUS_CODE
> >> +};
> >> +
> >> +enum ExtendedStatusCodes {
> >> +  STATUS_SOMETHING_INTERESTING = MAX_BASE_STATUS_CODE + 1000,
> >> +};
> >> +
> >> +
> >> +int get_flag(int cond) {
> >> +  return cond ? A : B;
> >

[PATCH] D62686: [RISCV] Add support for save/restore of callee-saved registers via libcalls

2019-10-01 Thread Lewis Revill via Phabricator via cfe-commits
lewis-revill updated this revision to Diff 222612.
lewis-revill added a comment.

Rewrote logic to calculate stack sizes, frame indexes and frame pointer 
offsets. This was necessary to take into account the fact that the save/restore 
lib calls are essentially an opaque section of the stack that is inserted at 
the beginning of the frame, after positive offset objects such as fixed stack 
arguments, but before additional callee saved registers (IE FP registers) and 
negative offset (dynamic) objects. So calculations of the actual offsets of 
these objects must be adjusted accordingly for the stack to function correctly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D62686

Files:
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/test/Driver/riscv-features.c
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
  llvm/lib/Target/RISCV/RISCVFrameLowering.h
  llvm/lib/Target/RISCV/RISCVMachineFunctionInfo.h
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.h
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/saverestore.ll

Index: llvm/test/CodeGen/RISCV/saverestore.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/saverestore.ll
@@ -0,0 +1,640 @@
+; RUN: llc -mtriple=riscv32 < %s | FileCheck %s -check-prefix=RV32I
+; RUN: llc -mtriple=riscv64 < %s | FileCheck %s -check-prefix=RV64I
+; RUN: llc -mtriple=riscv32 -mattr=+save-restore < %s | FileCheck %s -check-prefix=RV32I-SR
+; RUN: llc -mtriple=riscv64 -mattr=+save-restore < %s | FileCheck %s -check-prefix=RV64I-SR
+; RUN: llc -mtriple=riscv32 -mattr=+f,+save-restore -target-abi=ilp32f < %s | FileCheck %s -check-prefix=RV32I-FP-SR
+; RUN: llc -mtriple=riscv64 -mattr=+f,+d,+save-restore -target-abi=lp64d < %s | FileCheck %s -check-prefix=RV64I-FP-SR
+
+; Check that the correct save/restore libcalls are generated.
+
+@var0 = global [18 x i32] zeroinitializer
+@var1 = global [24 x i32] zeroinitializer
+@var2 = global [30 x i32] zeroinitializer
+
+define void @callee_saved0() nounwind {
+; RV32I-LABEL: callee_saved0:
+; RV32I: addi sp, sp, -32
+; RV32I-NEXT:sw s0, 28(sp)
+; RV32I-NEXT:sw s1, 24(sp)
+; RV32I-NEXT:sw s2, 20(sp)
+; RV32I-NEXT:sw s3, 16(sp)
+; RV32I-NEXT:sw s4, 12(sp)
+; RV32I: lw s4, 12(sp)
+; RV32I-NEXT:lw s3, 16(sp)
+; RV32I-NEXT:lw s2, 20(sp)
+; RV32I-NEXT:lw s1, 24(sp)
+; RV32I-NEXT:lw s0, 28(sp)
+; RV32I-NEXT:addi sp, sp, 32
+; RV32I-NEXT:ret
+;
+; RV64I-LABEL: callee_saved0:
+; RV64I: addi sp, sp, -48
+; RV64I-NEXT:sd s0, 40(sp)
+; RV64I-NEXT:sd s1, 32(sp)
+; RV64I-NEXT:sd s2, 24(sp)
+; RV64I-NEXT:sd s3, 16(sp)
+; RV64I: ld s4, 8(sp)
+; RV64I-NEXT:ld s3, 16(sp)
+; RV64I-NEXT:ld s2, 24(sp)
+; RV64I-NEXT:ld s1, 32(sp)
+; RV64I-NEXT:ld s0, 40(sp)
+; RV64I-NEXT:addi sp, sp, 48
+; RV64I-NEXT:ret
+;
+; RV32I-SR-LABEL: callee_saved0:
+; RV32I-SR: call t0, __riscv_save_5
+; RV32I-SR: tail __riscv_restore_5
+;
+; RV64I-SR-LABEL: callee_saved0:
+; RV64I-SR: call t0, __riscv_save_5
+; RV64I-SR: tail __riscv_restore_5
+;
+; RV32I-FP-SR-LABEL: callee_saved0:
+; RV32I-FP-SR: call t0, __riscv_save_5
+; RV32I-FP-SR: tail __riscv_restore_5
+;
+; RV64I-FP-SR-LABEL: callee_saved0:
+; RV64I-FP-SR: call t0, __riscv_save_5
+; RV64I-FP-SR: tail __riscv_restore_5
+  %val = load [18 x i32], [18 x i32]* @var0
+  store volatile [18 x i32] %val, [18 x i32]* @var0
+  ret void
+}
+
+define void @callee_saved1() nounwind {
+; RV32I-LABEL: callee_saved1:
+; RV32I: addi sp, sp, -48
+; RV32I-NEXT:sw s0, 44(sp)
+; RV32I-NEXT:sw s1, 40(sp)
+; RV32I-NEXT:sw s2, 36(sp)
+; RV32I-NEXT:sw s3, 32(sp)
+; RV32I-NEXT:sw s4, 28(sp)
+; RV32I-NEXT:sw s5, 24(sp)
+; RV32I-NEXT:sw s6, 20(sp)
+; RV32I-NEXT:sw s7, 16(sp)
+; RV32I-NEXT:sw s8, 12(sp)
+; RV32I-NEXT:sw s9, 8(sp)
+; RV32I-NEXT:sw s10, 4(sp)
+; RV32I: lw s10, 4(sp)
+; RV32I-NEXT:lw s9, 8(sp)
+; RV32I-NEXT:lw s8, 12(sp)
+; RV32I-NEXT:lw s7, 16(sp)
+; RV32I-NEXT:lw s6, 20(sp)
+; RV32I-NEXT:lw s5, 24(sp)
+; RV32I-NEXT:lw s4, 28(sp)
+; RV32I-NEXT:lw s3, 32(sp)
+; RV32I-NEXT:lw s2, 36(sp)
+; RV32I-NEXT:lw s1, 40(sp)
+; RV32I-NEXT:lw s0, 44(sp)
+; RV32I-NEXT:addi sp, sp, 48
+; RV32I-NEXT:ret
+;
+; RV64I-LABEL: callee_saved1:
+; RV64I: addi sp, sp, -96
+; RV64I-NEXT:sd s0, 88(sp)
+; RV64I-NEXT:sd s1, 80(sp)
+; RV64I-NEXT:sd s2, 72(sp)
+; RV64I-NEXT:sd s3, 64(sp)
+; RV64I-NEXT:sd s4, 56(sp)
+; RV64I-NEXT:sd s5, 48(sp)
+; RV64I-NEXT:sd s6, 40(sp)
+; RV64I-NEXT:sd s7, 32(sp)
+; RV64I-NEXT:sd s8, 24(sp)
+; RV64I-NEXT:sd s9, 16(sp)
+; RV64I-NEXT:sd s10, 8(sp)
+; RV64I: ld s10,

r373348 - [OPENMP]Fix PR43516: Compiler crash with collapse(2) on non-rectangular

2019-10-01 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Oct  1 09:19:10 2019
New Revision: 373348

URL: http://llvm.org/viewvc/llvm-project?rev=373348&view=rev
Log:
[OPENMP]Fix PR43516: Compiler crash with collapse(2) on non-rectangular
loop.

Missed check if the condition is also dependent when building final
expressions for the collapsed loop directives.

Modified:
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/for_codegen.cpp

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=373348&r1=373347&r2=373348&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Tue Oct  1 09:19:10 2019
@@ -6247,13 +6247,21 @@ Expr *OpenMPIterationSpaceChecker::build
 Expr *OpenMPIterationSpaceChecker::buildPreCond(
 Scope *S, Expr *Cond,
 llvm::MapVector &Captures) const {
+  // Do not build a precondition when the condition/initialization is dependent
+  // to prevent pessimistic early loop exit.
+  // TODO: this can be improved by calculating min/max values but not sure that
+  // it will be very effective.
+  if (CondDependOnLC || InitDependOnLC)
+return SemaRef.PerformImplicitConversion(
+SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
+SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
+/*AllowExplicit=*/true).get();
+
   // Try to build LB  UB, where  is <, >, <=, or >=.
   Sema::TentativeAnalysisScope Trap(SemaRef);
 
-  ExprResult NewLB =
-  InitDependOnLC ? LB : tryBuildCapture(SemaRef, LB, Captures);
-  ExprResult NewUB =
-  CondDependOnLC ? UB : tryBuildCapture(SemaRef, UB, Captures);
+  ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
+  ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
   if (!NewLB.isUsable() || !NewUB.isUsable())
 return nullptr;
 
@@ -7425,7 +7433,7 @@ checkOpenMPLoop(OpenMPDirectiveKind DKin
   Built.DependentCounters[Cnt] = nullptr;
   Built.DependentInits[Cnt] = nullptr;
   Built.FinalsConditions[Cnt] = nullptr;
-  if (IS.IsNonRectangularLB) {
+  if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
 Built.DependentCounters[Cnt] =
 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
 Built.DependentInits[Cnt] =

Modified: cfe/trunk/test/OpenMP/for_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/for_codegen.cpp?rev=373348&r1=373347&r2=373348&view=diff
==
--- cfe/trunk/test/OpenMP/for_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/for_codegen.cpp Tue Oct  1 09:19:10 2019
@@ -89,23 +89,6 @@ void loop_with_counter_collapse() {
   // CHECK: [[NUM_ITERS_VAL:%.+]] = sub nsw i64 [[MUL]], 1
   // CHECK: store i64 [[NUM_ITERS_VAL]], i64* [[NUM_ITERS:%.+]],
 
-  // Initialization
-  // CHECK: store i32 0, i32* [[I:%.+]],
-  // CHECK: [[I_INIT:%.+]] = load i32, i32* [[I]],
-  // CHECK: store i32 [[I_INIT]], i32* [[J:%.+]],
-
-  // LIFETIME: call void @llvm.lifetime.end
-  // LIFETIME: call void @llvm.lifetime.end
-
-  // Precondition for j counter
-  // CHECK: store i32 0, i32* [[TMP_I:%.+]],
-  // CHECK: [[J_LB_VAL:%.+]] = load i32, i32* [[TMP_I]],
-  // CHECK: [[I_VAL:%.+]] = load i32, i32* [[TMP_I]],
-  // CHECK: [[J_UB_VAL:%.+]] = add nsw i32 4, [[I_VAL]]
-  // CHECK: [[CMP:%.+]] = icmp slt i32 [[J_LB_VAL]], [[J_UB_VAL]]
-  // CHECK: br i1 [[CMP]], label %[[THEN:[^,]+]], label %[[ELSE:[^,]+]]
-
-  // CHECK: [[THEN]]:
   // CHECK: store i64 0, i64* [[LB:%.+]],
   // CHECK: [[NUM_ITERS_VAL:%.+]] = load i64, i64* [[NUM_ITERS]],
   // CHECK: store i64 [[NUM_ITERS_VAL]], i64* [[UB:%.+]],
@@ -633,6 +616,22 @@ void for_with_references() {
 k = cnt;
 }
 
+// CHECK-LABEL: for_with_references_dep_cond
+void for_with_references_dep_cond() {
+// CHECK: [[I:%.+]] = alloca i8,
+// CHECK: [[CNT:%.+]] = alloca i8*,
+// CHECK: [[CNT_PRIV:%.+]] = alloca i8,
+// CHECK: call void @__kmpc_for_static_init_8(
+// CHECK-NOT: load i8, i8* [[CNT]],
+// CHECK: call void @__kmpc_for_static_fini(
+  char i = 0;
+  char &cnt = i;
+#pragma omp for collapse(2)
+  for (cnt = 0; cnt < 2; ++cnt)
+for (int j = 0; j < 4 + cnt; j++)
+k = cnt;
+}
+
 struct Bool {
   Bool(bool b) : b(b) {}
   operator bool() const { return b; }


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


[PATCH] D68029: [ThinLTO] Enable index-only WPD from clang

2019-10-01 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.
Herald added a subscriber: hiraditya.

Ping


Repository:
  rC Clang

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

https://reviews.llvm.org/D68029



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


[PATCH] D68029: [ThinLTO] Enable index-only WPD from clang

2019-10-01 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


Repository:
  rC Clang

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

https://reviews.llvm.org/D68029



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


Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Dávid Bolvanský via cfe-commits
Sorry, answered on phone, missed it. I looked at your buildbots for
chromium and yeah, so many warnings. I will make it off by default.

ut 1. 10. 2019 o 19:58 Dávid Bolvanský  napísal(a):
>
> (Not sure if you intentionally didn't reply-all.)
>
> Sorry, answered on phone, missed it. I looked at your buildbots for
> chromium and yeah, so many warnings. I will make it off by default.
>
> ut 1. 10. 2019 o 19:17 Nico Weber  napísal(a):
>
> >
> > (Not sure if you intentionally didn't reply-all.)
> >
> > We should probably write it down, but clang's warning philosophy is that 
> > warnings should be very high-signal. The usual way to prove this is to 
> > build some large open-source codebase with the warning and counting true 
> > and false positives.
> >
> > Just "gcc has it" isn't sufficient motivation – gcc has lots of not so good 
> > warnings :)
> >
> > ps: To be clear, I appreciate all your work to add warnings a lot! It's 
> > very useful. It's also possible that this warning is useful, but it's not 
> > immediately clear, so there should be some data to back it up.
> >
> > On Tue, Oct 1, 2019 at 12:12 PM Dávid Bolvanský  
> > wrote:
> >>
> >> I hit this bug myself, GCC warned me with -Wenum-compare, Clang was 
> >> silent. Clang “supports” this flag, but failed to catch it. Either Clang 
> >> should not pretend that it supports this flag (and all related 
> >> functionality) or should support it fully. Basically, new warnings will 
> >> show up only for Clang-only environments.
> >>
> >> I think the own subgroup is a good compromise for now.  We can still make 
> >> it off by default before next release if we decide so.
> >>
> >> Dňa 1. 10. 2019 o 17:56 užívateľ Nico Weber  napísal:
> >>
> >> 
> >> Thanks!
> >>
> >> Any thoughts on the true positive rate for this warning?
> >>
> >> On Tue, Oct 1, 2019 at 11:43 AM Dávid Bolvanský 
> >>  wrote:
> >>>
> >>> Yeah, I moved this warning into own subgroup in rL373345. Thanks.
> >>>
> >>> ut 1. 10. 2019 o 16:24 Nico Weber  napísal(a):
> >>> >
> >>> > Can we move this behind a Wenum-compare subgroup, say 
> >>> > Wenum-compare-type? Our codebase is (well, was) Wenum-compare clean, 
> >>> > and this new warnings fires pretty often and from a first quick glance 
> >>> > the warning looks pretty low-signal anyways (*). Maybe the subgroup 
> >>> > shouldn't even be on by default -- do you have any data on true / false 
> >>> > positive rate of this?
> >>> >
> >>> > (But for starters, just having a way to turn this off is enough.)
> >>> >
> >>> > For example, we have a windows common control that's either a PGRP_DOWN 
> >>> > or a PGRP_UP page control and depending on which you store the control 
> >>> > state in the same int, then stuff like `return extra.inner_spin.spin_up 
> >>> > ? UPS_DISABLED : DNS_DISABLED;`.
> >>> >
> >>> > On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits 
> >>> >  wrote:
> >>> >>
> >>> >> Author: xbolva00
> >>> >> Date: Mon Sep 30 12:55:50 2019
> >>> >> New Revision: 373252
> >>> >>
> >>> >> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
> >>> >> Log:
> >>> >> [Diagnostics] Warn if enumeration type mismatch in conditional 
> >>> >> expression
> >>> >>
> >>> >> Summary:
> >>> >> - Useful warning
> >>> >> - GCC compatibility (GCC warns in C++ mode)
> >>> >>
> >>> >> Reviewers: rsmith, aaron.ballman
> >>> >>
> >>> >> Reviewed By: aaron.ballman
> >>> >>
> >>> >> Subscribers: cfe-commits
> >>> >>
> >>> >> Tags: #clang
> >>> >>
> >>> >> Differential Revision: https://reviews.llvm.org/D67919
> >>> >>
> >>> >> Added:
> >>> >> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> >>> >> Modified:
> >>> >> cfe/trunk/lib/Sema/SemaChecking.cpp
> >>> >>
> >>> >> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> >>> >> URL: 
> >>> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373252&r1=373251&r2=373252&view=diff
> >>> >> ==
> >>> >> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
> >>> >> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Sep 30 12:55:50 2019
> >>> >> @@ -11308,6 +11308,32 @@ static const IntegerLiteral *getIntegerL
> >>> >>return IL;
> >>> >>  }
> >>> >>
> >>> >> +static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
> >>> >> +  Expr *LHS, Expr *RHS) {
> >>> >> +  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
> >>> >> +  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
> >>> >> +
> >>> >> +  const auto *LHSEnumType = LHSStrippedType->getAs();
> >>> >> +  if (!LHSEnumType)
> >>> >> +return;
> >>> >> +  const auto *RHSEnumType = RHSStrippedType->getAs();
> >>> >> +  if (!RHSEnumType)
> >>> >> +return;
> >>> >> +
> >>> >> +  // Ignore anonymous enums.
> >>> >> +  if (!LHSEnumType->getDecl()->hasNameForLinkage())
> >>> >> +return;
> >>> >> +  if (!RHSEnumType->getDecl()->hasNameForLinkage

r373370 - [ThinLTO] Enable index-only WPD from clang

2019-10-01 Thread Teresa Johnson via cfe-commits
Author: tejohnson
Date: Tue Oct  1 11:08:29 2019
New Revision: 373370

URL: http://llvm.org/viewvc/llvm-project?rev=373370&view=rev
Log:
[ThinLTO] Enable index-only WPD from clang

Summary:
To trigger the index-only Whole Program Devirt support added to LLVM, we
need to be able to specify -fno-split-lto-unit in conjunction with
-fwhole-program-vtables. Keep the default for -fwhole-program-vtables as
-fsplit-lto-unit, but don't error on that option combination.

Reviewers: pcc

Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, arphaman, 
cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/test/Driver/split-lto-unit.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=373370&r1=373369&r2=373370&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Tue Oct  1 11:08:29 2019
@@ -5456,14 +5456,13 @@ void Clang::ConstructJob(Compilation &C,
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
-  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
+  bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
-   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
-  if (RequiresSplitLTOUnit && !SplitLTOUnit)
-D.Diag(diag::err_drv_argument_not_allowed_with)
-<< "-fno-split-lto-unit"
-<< (WholeProgramVTables ? "-fwhole-program-vtables" : 
"-fsanitize=cfi");
+   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
+  if (Sanitize.needsLTO() && !SplitLTOUnit)
+D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
+<< "-fsanitize=cfi";
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 

Modified: cfe/trunk/test/Driver/split-lto-unit.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/split-lto-unit.c?rev=373370&r1=373369&r2=373370&view=diff
==
--- cfe/trunk/test/Driver/split-lto-unit.c (original)
+++ cfe/trunk/test/Driver/split-lto-unit.c Tue Oct  1 11:08:29 2019
@@ -6,5 +6,5 @@
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
-// ERROR1: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fwhole-program-vtables'
+// ERROR1-NOT: error: invalid argument
 // ERROR2: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fsanitize=cfi'


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


[PATCH] D64671: [clang-tidy] New check: misc-init-local-variables

2019-10-01 Thread Jussi Pakkanen via Phabricator via cfe-commits
jpakkane added a comment.

In D64671#1688626 , @aaron.ballman 
wrote:

> Do you need someone to commit this on your behalf (sorry for not asking that 
> question sooner)?


Yes, please. I have no rights of any kind, this is in fact my first ever pull 
request to LLVM.


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

https://reviews.llvm.org/D64671



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


[PATCH] D68029: [ThinLTO] Enable index-only WPD from clang

2019-10-01 Thread Teresa Johnson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373370: [ThinLTO] Enable index-only WPD from clang (authored 
by tejohnson, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68029

Files:
  cfe/trunk/lib/Driver/ToolChains/Clang.cpp
  cfe/trunk/test/Driver/split-lto-unit.c


Index: cfe/trunk/test/Driver/split-lto-unit.c
===
--- cfe/trunk/test/Driver/split-lto-unit.c
+++ cfe/trunk/test/Driver/split-lto-unit.c
@@ -6,5 +6,5 @@
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
-// ERROR1: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fwhole-program-vtables'
+// ERROR1-NOT: error: invalid argument
 // ERROR2: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fsanitize=cfi'
Index: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp
@@ -5456,14 +5456,13 @@
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
-  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
+  bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
-   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
-  if (RequiresSplitLTOUnit && !SplitLTOUnit)
-D.Diag(diag::err_drv_argument_not_allowed_with)
-<< "-fno-split-lto-unit"
-<< (WholeProgramVTables ? "-fwhole-program-vtables" : 
"-fsanitize=cfi");
+   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
+  if (Sanitize.needsLTO() && !SplitLTOUnit)
+D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
+<< "-fsanitize=cfi";
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 


Index: cfe/trunk/test/Driver/split-lto-unit.c
===
--- cfe/trunk/test/Driver/split-lto-unit.c
+++ cfe/trunk/test/Driver/split-lto-unit.c
@@ -6,5 +6,5 @@
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
-// ERROR1: error: invalid argument '-fno-split-lto-unit' not allowed with '-fwhole-program-vtables'
+// ERROR1-NOT: error: invalid argument
 // ERROR2: error: invalid argument '-fno-split-lto-unit' not allowed with '-fsanitize=cfi'
Index: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp
@@ -5456,14 +5456,13 @@
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
-  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
+  bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
-   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
-  if (RequiresSplitLTOUnit && !SplitLTOUnit)
-D.Diag(diag::err_drv_argument_not_allowed_with)
-<< "-fno-split-lto-unit"
-<< (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
+   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
+  if (Sanitize.needsLTO() && !SplitLTOUnit)
+D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
+<< "-fsanitize=cfi";
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Dávid Bolvanský via cfe-commits
Done. rL373371.

ut 1. 10. 2019 o 19:58 Dávid Bolvanský  napísal(a):
>
> Sorry, answered on phone, missed it. I looked at your buildbots for
> chromium and yeah, so many warnings. I will make it off by default.
>
> ut 1. 10. 2019 o 19:58 Dávid Bolvanský  napísal(a):
> >
> > (Not sure if you intentionally didn't reply-all.)
> >
> > Sorry, answered on phone, missed it. I looked at your buildbots for
> > chromium and yeah, so many warnings. I will make it off by default.
> >
> > ut 1. 10. 2019 o 19:17 Nico Weber  napísal(a):
> >
> > >
> > > (Not sure if you intentionally didn't reply-all.)
> > >
> > > We should probably write it down, but clang's warning philosophy is that 
> > > warnings should be very high-signal. The usual way to prove this is to 
> > > build some large open-source codebase with the warning and counting true 
> > > and false positives.
> > >
> > > Just "gcc has it" isn't sufficient motivation – gcc has lots of not so 
> > > good warnings :)
> > >
> > > ps: To be clear, I appreciate all your work to add warnings a lot! It's 
> > > very useful. It's also possible that this warning is useful, but it's not 
> > > immediately clear, so there should be some data to back it up.
> > >
> > > On Tue, Oct 1, 2019 at 12:12 PM Dávid Bolvanský 
> > >  wrote:
> > >>
> > >> I hit this bug myself, GCC warned me with -Wenum-compare, Clang was 
> > >> silent. Clang “supports” this flag, but failed to catch it. Either Clang 
> > >> should not pretend that it supports this flag (and all related 
> > >> functionality) or should support it fully. Basically, new warnings will 
> > >> show up only for Clang-only environments.
> > >>
> > >> I think the own subgroup is a good compromise for now.  We can still 
> > >> make it off by default before next release if we decide so.
> > >>
> > >> Dňa 1. 10. 2019 o 17:56 užívateľ Nico Weber  
> > >> napísal:
> > >>
> > >> 
> > >> Thanks!
> > >>
> > >> Any thoughts on the true positive rate for this warning?
> > >>
> > >> On Tue, Oct 1, 2019 at 11:43 AM Dávid Bolvanský 
> > >>  wrote:
> > >>>
> > >>> Yeah, I moved this warning into own subgroup in rL373345. Thanks.
> > >>>
> > >>> ut 1. 10. 2019 o 16:24 Nico Weber  napísal(a):
> > >>> >
> > >>> > Can we move this behind a Wenum-compare subgroup, say 
> > >>> > Wenum-compare-type? Our codebase is (well, was) Wenum-compare clean, 
> > >>> > and this new warnings fires pretty often and from a first quick 
> > >>> > glance the warning looks pretty low-signal anyways (*). Maybe the 
> > >>> > subgroup shouldn't even be on by default -- do you have any data on 
> > >>> > true / false positive rate of this?
> > >>> >
> > >>> > (But for starters, just having a way to turn this off is enough.)
> > >>> >
> > >>> > For example, we have a windows common control that's either a 
> > >>> > PGRP_DOWN or a PGRP_UP page control and depending on which you store 
> > >>> > the control state in the same int, then stuff like `return 
> > >>> > extra.inner_spin.spin_up ? UPS_DISABLED : DNS_DISABLED;`.
> > >>> >
> > >>> > On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits 
> > >>> >  wrote:
> > >>> >>
> > >>> >> Author: xbolva00
> > >>> >> Date: Mon Sep 30 12:55:50 2019
> > >>> >> New Revision: 373252
> > >>> >>
> > >>> >> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
> > >>> >> Log:
> > >>> >> [Diagnostics] Warn if enumeration type mismatch in conditional 
> > >>> >> expression
> > >>> >>
> > >>> >> Summary:
> > >>> >> - Useful warning
> > >>> >> - GCC compatibility (GCC warns in C++ mode)
> > >>> >>
> > >>> >> Reviewers: rsmith, aaron.ballman
> > >>> >>
> > >>> >> Reviewed By: aaron.ballman
> > >>> >>
> > >>> >> Subscribers: cfe-commits
> > >>> >>
> > >>> >> Tags: #clang
> > >>> >>
> > >>> >> Differential Revision: https://reviews.llvm.org/D67919
> > >>> >>
> > >>> >> Added:
> > >>> >> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> > >>> >> Modified:
> > >>> >> cfe/trunk/lib/Sema/SemaChecking.cpp
> > >>> >>
> > >>> >> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> > >>> >> URL: 
> > >>> >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=373252&r1=373251&r2=373252&view=diff
> > >>> >> ==
> > >>> >> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
> > >>> >> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Sep 30 12:55:50 2019
> > >>> >> @@ -11308,6 +11308,32 @@ static const IntegerLiteral *getIntegerL
> > >>> >>return IL;
> > >>> >>  }
> > >>> >>
> > >>> >> +static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation 
> > >>> >> Loc,
> > >>> >> +  Expr *LHS, Expr *RHS) {
> > >>> >> +  QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
> > >>> >> +  QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
> > >>> >> +
> > >>> >> +  const auto *LHSEnumType = LHSStrippedType->getAs();
> > >>> >> +  if (!LHSEnumType)
> > >>> >>

r373371 - [Diagnostics] Make -Wenum-compare-conditional off by default

2019-10-01 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Tue Oct  1 11:12:13 2019
New Revision: 373371

URL: http://llvm.org/viewvc/llvm-project?rev=373371&view=rev
Log:
[Diagnostics] Make -Wenum-compare-conditional off by default

Too many false positives, eg. in Chromium.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=373371&r1=373370&r2=373371&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Tue Oct  1 11:12:13 2019
@@ -565,7 +565,7 @@ def SwitchEnum : DiagGroup<"switch-e
 def Switch : DiagGroup<"switch">;
 def EnumCompareConditional : DiagGroup<"enum-compare-conditional">;
 def EnumCompareSwitch : DiagGroup<"enum-compare-switch">;
-def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareConditional, 
EnumCompareSwitch]>;
+def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareSwitch]>;
 def ImplicitFallthroughPerFunction :
   DiagGroup<"implicit-fallthrough-per-function">;
 def ImplicitFallthrough  : DiagGroup<"implicit-fallthrough",

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=373371&r1=373370&r2=373371&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Oct  1 11:12:13 
2019
@@ -6172,7 +6172,7 @@ def warn_comparison_of_mixed_enum_types
 def warn_conditional_mixed_enum_types : Warning<
   "enumeration type mismatch in conditional expression"
   "%diff{ ($ and $)|}0,1">,
-  InGroup;
+  InGroup, DefaultIgnore;
 def warn_comparison_of_mixed_enum_types_switch : Warning<
   "comparison of two values with different enumeration types in switch 
statement"
   "%diff{ ($ and $)|}0,1">,

Modified: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373371&r1=373370&r2=373371&view=diff
==
--- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (original)
+++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Tue Oct  1 
11:12:13 2019
@@ -1,9 +1,5 @@
 // RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare-conditional %s
-// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
-// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
 // RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare-conditional %s
-// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
-// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
 
 enum ro { A = 0x10 };
 enum rw { B = 0xFF };


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


Re: r373252 - [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-10-01 Thread Nico Weber via cfe-commits
Chromium shouldn't be a factor for determining is a warning is on or off by
default. We can easily turn warnings off, and I had done so in
http://crrev.com/http://crrev.com/701604 (as long as warnings have a
dedicated flag -- but that's needed for every large codebase adopting a new
clang). So that's not super relevant -- the bots would've cycled green
anyways.

We should probably write it down, but clang's warning philosophy is that
warnings should be very high-signal. The usual way to prove this is to
build some large open-source codebase with the warning and counting true
and false positives.

Another thing we sometimes say that a warning should be so good that it
should be possible to turn it on by default, and if a warning doesn't meet
that bar, then maybe we shouldn't have it. (There are exceptions.)

ps: To be clear, I appreciate all your work to add warnings a lot! It's
very useful. It's also possible that this warning is useful, but it's not
immediately clear, so there should be some data to back it up.

On Tue, Oct 1, 2019 at 1:59 PM Dávid Bolvanský 
wrote:

> Sorry, answered on phone, missed it. I looked at your buildbots for
> chromium and yeah, so many warnings. I will make it off by default.
>
> ut 1. 10. 2019 o 19:58 Dávid Bolvanský 
> napísal(a):
> >
> > (Not sure if you intentionally didn't reply-all.)
> >
> > Sorry, answered on phone, missed it. I looked at your buildbots for
> > chromium and yeah, so many warnings. I will make it off by default.
> >
> > ut 1. 10. 2019 o 19:17 Nico Weber  napísal(a):
> >
> > >
> > > (Not sure if you intentionally didn't reply-all.)
> > >
> > > We should probably write it down, but clang's warning philosophy is
> that warnings should be very high-signal. The usual way to prove this is to
> build some large open-source codebase with the warning and counting true
> and false positives.
> > >
> > > Just "gcc has it" isn't sufficient motivation – gcc has lots of not so
> good warnings :)
> > >
> > > ps: To be clear, I appreciate all your work to add warnings a lot!
> It's very useful. It's also possible that this warning is useful, but it's
> not immediately clear, so there should be some data to back it up.
> > >
> > > On Tue, Oct 1, 2019 at 12:12 PM Dávid Bolvanský <
> david.bolvan...@gmail.com> wrote:
> > >>
> > >> I hit this bug myself, GCC warned me with -Wenum-compare, Clang was
> silent. Clang “supports” this flag, but failed to catch it. Either Clang
> should not pretend that it supports this flag (and all related
> functionality) or should support it fully. Basically, new warnings will
> show up only for Clang-only environments.
> > >>
> > >> I think the own subgroup is a good compromise for now.  We can still
> make it off by default before next release if we decide so.
> > >>
> > >> Dňa 1. 10. 2019 o 17:56 užívateľ Nico Weber 
> napísal:
> > >>
> > >> 
> > >> Thanks!
> > >>
> > >> Any thoughts on the true positive rate for this warning?
> > >>
> > >> On Tue, Oct 1, 2019 at 11:43 AM Dávid Bolvanský <
> david.bolvan...@gmail.com> wrote:
> > >>>
> > >>> Yeah, I moved this warning into own subgroup in rL373345. Thanks.
> > >>>
> > >>> ut 1. 10. 2019 o 16:24 Nico Weber  napísal(a):
> > >>> >
> > >>> > Can we move this behind a Wenum-compare subgroup, say
> Wenum-compare-type? Our codebase is (well, was) Wenum-compare clean, and
> this new warnings fires pretty often and from a first quick glance the
> warning looks pretty low-signal anyways (*). Maybe the subgroup shouldn't
> even be on by default -- do you have any data on true / false positive rate
> of this?
> > >>> >
> > >>> > (But for starters, just having a way to turn this off is enough.)
> > >>> >
> > >>> > For example, we have a windows common control that's either a
> PGRP_DOWN or a PGRP_UP page control and depending on which you store the
> control state in the same int, then stuff like `return
> extra.inner_spin.spin_up ? UPS_DISABLED : DNS_DISABLED;`.
> > >>> >
> > >>> > On Mon, Sep 30, 2019 at 3:53 PM David Bolvansky via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
> > >>> >>
> > >>> >> Author: xbolva00
> > >>> >> Date: Mon Sep 30 12:55:50 2019
> > >>> >> New Revision: 373252
> > >>> >>
> > >>> >> URL: http://llvm.org/viewvc/llvm-project?rev=373252&view=rev
> > >>> >> Log:
> > >>> >> [Diagnostics] Warn if enumeration type mismatch in conditional
> expression
> > >>> >>
> > >>> >> Summary:
> > >>> >> - Useful warning
> > >>> >> - GCC compatibility (GCC warns in C++ mode)
> > >>> >>
> > >>> >> Reviewers: rsmith, aaron.ballman
> > >>> >>
> > >>> >> Reviewed By: aaron.ballman
> > >>> >>
> > >>> >> Subscribers: cfe-commits
> > >>> >>
> > >>> >> Tags: #clang
> > >>> >>
> > >>> >> Differential Revision: https://reviews.llvm.org/D67919
> > >>> >>
> > >>> >> Added:
> > >>> >> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> > >>> >> Modified:
> > >>> >> cfe/trunk/lib/Sema/SemaChecking.cpp
> > >>> >>
> > >>> >> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
> > >>> >> URL:
>

r373374 - [OPENMP]Fix PR43330: OpenMP target: Mapping of partial arrays fails.

2019-10-01 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Oct  1 11:18:03 2019
New Revision: 373374

URL: http://llvm.org/viewvc/llvm-project?rev=373374&view=rev
Log:
[OPENMP]Fix PR43330: OpenMP target: Mapping of partial arrays fails.

Fixed calculation the size of the array sections.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/test/OpenMP/target_map_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=373374&r1=373373&r2=373374&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Tue Oct  1 11:18:03 2019
@@ -7249,9 +7249,11 @@ private:
 OAE->getBase()->IgnoreParenImpCasts())
 .getCanonicalType();
 
-  // If there is no length associated with the expression, that means we
-  // are using the whole length of the base.
-  if (!OAE->getLength() && OAE->getColonLoc().isValid())
+  // If there is no length associated with the expression and lower bound 
is
+  // not specified too, that means we are using the whole length of the
+  // base.
+  if (!OAE->getLength() && OAE->getColonLoc().isValid() &&
+  !OAE->getLowerBound())
 return CGF.getTypeSize(BaseTy);
 
   llvm::Value *ElemSize;
@@ -7265,13 +7267,30 @@ private:
 
   // If we don't have a length at this point, that is because we have an
   // array section with a single element.
-  if (!OAE->getLength())
+  if (!OAE->getLength() && OAE->getColonLoc().isInvalid())
 return ElemSize;
 
-  llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
-  LengthVal =
-  CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
-  return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
+  if (const Expr *LenExpr = OAE->getLength()) {
+llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
+LengthVal = CGF.EmitScalarConversion(
+LengthVal, OAE->getLength()->getType(),
+CGF.getContext().getSizeType(), OAE->getLength()->getExprLoc());
+return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
+  }
+  assert(!OAE->getLength() && OAE->getColonLoc().isValid() &&
+ OAE->getLowerBound() && "expected array_section[lb:].");
+  // Size = sizetype - lb * elemtype;
+  llvm::Value *LengthVal = CGF.getTypeSize(BaseTy);
+  llvm::Value *LBVal = CGF.EmitScalarExpr(OAE->getLowerBound());
+  LBVal = CGF.EmitScalarConversion(LBVal, OAE->getLowerBound()->getType(),
+   CGF.getContext().getSizeType(),
+   OAE->getLowerBound()->getExprLoc());
+  LBVal = CGF.Builder.CreateNUWMul(LBVal, ElemSize);
+  llvm::Value *Cmp = CGF.Builder.CreateICmpUGT(LengthVal, LBVal);
+  llvm::Value *TrueVal = CGF.Builder.CreateNUWSub(LengthVal, LBVal);
+  LengthVal = CGF.Builder.CreateSelect(
+  Cmp, TrueVal, llvm::ConstantInt::get(CGF.SizeTy, 0));
+  return LengthVal;
 }
 return CGF.getTypeSize(ExprTy);
   }

Modified: cfe/trunk/test/OpenMP/target_map_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/target_map_codegen.cpp?rev=373374&r1=373373&r2=373374&view=diff
==
--- cfe/trunk/test/OpenMP/target_map_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/target_map_codegen.cpp Tue Oct  1 11:18:03 2019
@@ -1323,172 +1323,176 @@ void implicit_maps_template_type_capture
 // SIMD-ONLY18-NOT: {{__kmpc|__tgt}}
 #ifdef CK19
 
-// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1510.region_id = weak 
constant i8 0
+// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1514.region_id = weak 
constant i8 0
 // CK19: [[SIZE00:@.+]] = private {{.*}}constant [1 x i64] [i64 4]
 // CK19: [[MTYPE00:@.+]] = private {{.*}}constant [1 x i64] [i64 32]
 
-// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1531.region_id = weak 
constant i8 0
+// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1535.region_id = weak 
constant i8 0
 // CK19: [[SIZE00n:@.+]] = private {{.*}}constant [1 x i64] [i64 4]
 // CK19: [[MTYPE00n:@.+]] = private {{.*}}constant [1 x i64] [i64 32]
 
-// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1553.region_id = weak 
constant i8 0
+// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1557.region_id = weak 
constant i8 0
 // CK19: [[SIZE01:@.+]] = private {{.*}}constant [1 x i64] [i64 400]
 // CK19: [[MTYPE01:@.+]] = private {{.*}}constant [1 x i64] [i64 33]
 
-// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single{{.*}}_l1572.region_id = weak 
constant i8 0
+// CK19-LABEL: 
@.__omp_offloading_{{.*}}explicit_maps_single

r373375 - [NFC] Updated tests after rL373371

2019-10-01 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Tue Oct  1 11:18:45 2019
New Revision: 373375

URL: http://llvm.org/viewvc/llvm-project?rev=373375&view=rev
Log:
[NFC] Updated tests after rL373371

Forgot to run check-clang-semacxx.

Modified:
cfe/trunk/test/SemaCXX/warn-sign-conversion.cpp

Modified: cfe/trunk/test/SemaCXX/warn-sign-conversion.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-sign-conversion.cpp?rev=373375&r1=373374&r2=373375&view=diff
==
--- cfe/trunk/test/SemaCXX/warn-sign-conversion.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-sign-conversion.cpp Tue Oct  1 11:18:45 2019
@@ -70,15 +70,11 @@ namespace test2 {
 int d1 = 1 ? i : Foo::D; // expected-warning {{operand of ? changes 
signedness: 'test2::Foo::Named4' to 'int'}}
 int d2 = 1 ? Foo::D : i; // expected-warning {{operand of ? changes 
signedness: 'test2::Foo::Named4' to 'int'}}
 int d3 = 1 ? B : Foo::D; // expected-warning {{operand of ? changes 
signedness: 'test2::Foo::Named4' to 'int'}}
-// expected-warning@-1 {{enumeration type mismatch in conditional 
expression ('test2::Named2' and 'test2::Foo::Named4')}}
 int d4 = 1 ? Foo::D : B; // expected-warning {{operand of ? changes 
signedness: 'test2::Foo::Named4' to 'int'}}
-// expected-warning@-1 {{enumeration type mismatch in conditional 
expression ('test2::Foo::Named4' and 'test2::Named2')}}
 
 int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 
'test2::Named5' to 'int'}}
 int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 
'test2::Named5' to 'int'}}
 int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 
'test2::Named5' to 'int'}}
-// expected-warning@-1 {{enumeration type mismatch in conditional 
expression ('test2::Named5' and 'test2::Named2')}}
 int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 
'test2::Named5' to 'int'}}
-// expected-warning@-1 {{enumeration type mismatch in conditional 
expression ('test2::Named2' and 'test2::Named5')}}
   }
 }


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


[PATCH] D68284: [HIP] Support -emit-llvm for device compilation

2019-10-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.

Sometimes it is useful to compile HIP device code to LLVM BC. It is not 
convenient to use clang -cc1 since
there are lots of options needed.

This patch allows clang driver to compile HIP device code to LLVM BC with 
-emit-llvm -c.


https://reviews.llvm.org/D68284

Files:
  lib/Driver/Driver.cpp
  test/Driver/hip-toolchain-emit-llvm.hip


Index: test/Driver/hip-toolchain-emit-llvm.hip
===
--- /dev/null
+++ test/Driver/hip-toolchain-emit-llvm.hip
@@ -0,0 +1,26 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang -c -emit-llvm --cuda-device-only -### -target x86_64-linux-gnu \
+// RUN:   -o a.bc -x hip --cuda-gpu-arch=gfx900 \
+// RUN:   --hip-device-lib=lib1.bc \
+// RUN:   --hip-device-lib-path=%S/Inputs/hip_multiple_inputs/lib1 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN: 2>&1 | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: {{".*clang.*"}} "-cc1" "-triple" "amdgcn-amd-amdhsa"
+// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
+// CHECK-SAME: "-emit-llvm-bc"
+// CHECK-SAME: "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx900"
+// CHECK-SAME: "-fcuda-is-device"
+// CHECK-SAME: {{".*lib1.bc"}}
+// CHECK-SAME: "-o" "a.bc"
+// CHECK-SAME: {{".*a.cu"}}
+
+// CHECK-NOT: {{"*.llvm-link"}}
+// CHECK-NOT: {{".*opt"}}
+// CHECK-NOT: {{".*llc"}}
+// CHECK-NOT: {{".*lld"}}
+// CHECK-NOT: {{".*clang-offload-bundler"}}
+// CHECK-NOT: {{".*ld.*"}}
Index: lib/Driver/Driver.cpp
===
--- lib/Driver/Driver.cpp
+++ lib/Driver/Driver.cpp
@@ -2314,6 +2314,7 @@
 /// compilation.
 bool CompileHostOnly = false;
 bool CompileDeviceOnly = false;
+bool EmitLLVM = false;
 
 /// List of GPU architectures to use in this compilation.
 SmallVector GpuArchList;
@@ -2480,6 +2481,8 @@
   CompileDeviceOnly = PartialCompilationArg &&
   PartialCompilationArg->getOption().matches(
   options::OPT_cuda_device_only);
+  EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
+
 
   // Collect all cuda_gpu_arch parameters, removing duplicates.
   std::set GpuArchs;
@@ -2660,6 +2663,11 @@
   CurPhase == phases::Assemble)
 return ABRT_Success;
 
+  if (EmitLLVM &&
+  (CurPhase == phases::Backend || CurPhase == phases::Assemble ||
+   CurPhase == phases::Link))
+return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
+
   assert(((CurPhase == phases::Link && Relocatable) ||
   CudaDeviceActions.size() == GpuArchList.size()) &&
  "Expecting one action per GPU architecture.");


Index: test/Driver/hip-toolchain-emit-llvm.hip
===
--- /dev/null
+++ test/Driver/hip-toolchain-emit-llvm.hip
@@ -0,0 +1,26 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang -c -emit-llvm --cuda-device-only -### -target x86_64-linux-gnu \
+// RUN:   -o a.bc -x hip --cuda-gpu-arch=gfx900 \
+// RUN:   --hip-device-lib=lib1.bc \
+// RUN:   --hip-device-lib-path=%S/Inputs/hip_multiple_inputs/lib1 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN: 2>&1 | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: {{".*clang.*"}} "-cc1" "-triple" "amdgcn-amd-amdhsa"
+// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
+// CHECK-SAME: "-emit-llvm-bc"
+// CHECK-SAME: "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx900"
+// CHECK-SAME: "-fcuda-is-device"
+// CHECK-SAME: {{".*lib1.bc"}}
+// CHECK-SAME: "-o" "a.bc"
+// CHECK-SAME: {{".*a.cu"}}
+
+// CHECK-NOT: {{"*.llvm-link"}}
+// CHECK-NOT: {{".*opt"}}
+// CHECK-NOT: {{".*llc"}}
+// CHECK-NOT: {{".*lld"}}
+// CHECK-NOT: {{".*clang-offload-bundler"}}
+// CHECK-NOT: {{".*ld.*"}}
Index: lib/Driver/Driver.cpp
===
--- lib/Driver/Driver.cpp
+++ lib/Driver/Driver.cpp
@@ -2314,6 +2314,7 @@
 /// compilation.
 bool CompileHostOnly = false;
 bool CompileDeviceOnly = false;
+bool EmitLLVM = false;
 
 /// List of GPU architectures to use in this compilation.
 SmallVector GpuArchList;
@@ -2480,6 +2481,8 @@
   CompileDeviceOnly = PartialCompilationArg &&
   PartialCompilationArg->getOption().matches(
   options::OPT_cuda_device_only);
+  EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
+
 
   // Collect all cuda_gpu_arch parameters, removing duplicates.
   std::set GpuArchs;
@@ -2660,6 +2663,11 @@
   CurPhase == phases::Assemble)
 return ABRT_Success;
 
+  if (EmitLLVM &&
+  (CurPhase == phases::Backend || CurPhase == phases::Assemble ||
+   CurPhase == phases::Link))
+return C

Re: r373371 - [Diagnostics] Make -Wenum-compare-conditional off by default

2019-10-01 Thread Nico Weber via cfe-commits
This breaks emaCXX/warn-sign-conversion.cpp -- but see other thread, maybe
just revert this for now until we know what we want to do here :)

On Tue, Oct 1, 2019 at 2:10 PM David Bolvansky via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: xbolva00
> Date: Tue Oct  1 11:12:13 2019
> New Revision: 373371
>
> URL: http://llvm.org/viewvc/llvm-project?rev=373371&view=rev
> Log:
> [Diagnostics] Make -Wenum-compare-conditional off by default
>
> Too many false positives, eg. in Chromium.
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticGroups.td
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=373371&r1=373370&r2=373371&view=diff
>
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Tue Oct  1 11:12:13
> 2019
> @@ -565,7 +565,7 @@ def SwitchEnum : DiagGroup<"switch-e
>  def Switch : DiagGroup<"switch">;
>  def EnumCompareConditional : DiagGroup<"enum-compare-conditional">;
>  def EnumCompareSwitch : DiagGroup<"enum-compare-switch">;
> -def EnumCompare   : DiagGroup<"enum-compare",
> [EnumCompareConditional, EnumCompareSwitch]>;
> +def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareSwitch]>;
>  def ImplicitFallthroughPerFunction :
>DiagGroup<"implicit-fallthrough-per-function">;
>  def ImplicitFallthrough  : DiagGroup<"implicit-fallthrough",
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=373371&r1=373370&r2=373371&view=diff
>
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Oct  1
> 11:12:13 2019
> @@ -6172,7 +6172,7 @@ def warn_comparison_of_mixed_enum_types
>  def warn_conditional_mixed_enum_types : Warning<
>"enumeration type mismatch in conditional expression"
>"%diff{ ($ and $)|}0,1">,
> -  InGroup;
> +  InGroup, DefaultIgnore;
>  def warn_comparison_of_mixed_enum_types_switch : Warning<
>"comparison of two values with different enumeration types in switch
> statement"
>"%diff{ ($ and $)|}0,1">,
>
> Modified: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373371&r1=373370&r2=373371&view=diff
>
> ==
> --- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (original)
> +++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Tue Oct  1
> 11:12:13 2019
> @@ -1,9 +1,5 @@
>  // RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare-conditional
> %s
> -// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
> -// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
>  // RUN: %clang_cc1 -x c++ -fsyntax-only -verify
> -Wenum-compare-conditional %s
> -// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
> -// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
>
>  enum ro { A = 0x10 };
>  enum rw { B = 0xFF };
>
>
> ___
> 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: r373371 - [Diagnostics] Make -Wenum-compare-conditional off by default

2019-10-01 Thread Dávid Bolvanský via cfe-commits
I fixed it, forgot to run clang semacxx check too.

I am not sure.. I checked github and found case:
https://github.com/ros-industrial-consortium/godel/issues/115

Seems like this is very rare, not worth to make it on..

ut 1. 10. 2019 o 20:19 Nico Weber  napísal(a):
>
> This breaks emaCXX/warn-sign-conversion.cpp -- but see other thread, maybe 
> just revert this for now until we know what we want to do here :)
>
> On Tue, Oct 1, 2019 at 2:10 PM David Bolvansky via cfe-commits 
>  wrote:
>>
>> Author: xbolva00
>> Date: Tue Oct  1 11:12:13 2019
>> New Revision: 373371
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=373371&view=rev
>> Log:
>> [Diagnostics] Make -Wenum-compare-conditional off by default
>>
>> Too many false positives, eg. in Chromium.
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticGroups.td
>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=373371&r1=373370&r2=373371&view=diff
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Tue Oct  1 11:12:13 
>> 2019
>> @@ -565,7 +565,7 @@ def SwitchEnum : DiagGroup<"switch-e
>>  def Switch : DiagGroup<"switch">;
>>  def EnumCompareConditional : DiagGroup<"enum-compare-conditional">;
>>  def EnumCompareSwitch : DiagGroup<"enum-compare-switch">;
>> -def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareConditional, 
>> EnumCompareSwitch]>;
>> +def EnumCompare   : DiagGroup<"enum-compare", [EnumCompareSwitch]>;
>>  def ImplicitFallthroughPerFunction :
>>DiagGroup<"implicit-fallthrough-per-function">;
>>  def ImplicitFallthrough  : DiagGroup<"implicit-fallthrough",
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=373371&r1=373370&r2=373371&view=diff
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Oct  1 11:12:13 
>> 2019
>> @@ -6172,7 +6172,7 @@ def warn_comparison_of_mixed_enum_types
>>  def warn_conditional_mixed_enum_types : Warning<
>>"enumeration type mismatch in conditional expression"
>>"%diff{ ($ and $)|}0,1">,
>> -  InGroup;
>> +  InGroup, DefaultIgnore;
>>  def warn_comparison_of_mixed_enum_types_switch : Warning<
>>"comparison of two values with different enumeration types in switch 
>> statement"
>>"%diff{ ($ and $)|}0,1">,
>>
>> Modified: cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c?rev=373371&r1=373370&r2=373371&view=diff
>> ==
>> --- cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c (original)
>> +++ cfe/trunk/test/Sema/warn-conditional-emum-types-mismatch.c Tue Oct  1 
>> 11:12:13 2019
>> @@ -1,9 +1,5 @@
>>  // RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare-conditional %s
>> -// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare %s
>> -// RUN: %clang_cc1 -x c -fsyntax-only -verify  %s
>>  // RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare-conditional 
>> %s
>> -// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare %s
>> -// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
>>
>>  enum ro { A = 0x10 };
>>  enum rw { B = 0xFF };
>>
>>
>> ___
>> 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


[PATCH] D68252: [Stats] Add ALWAYS_ENABLED_STATISTIC enabled regardless of LLVM_ENABLE_STATS.

2019-10-01 Thread Daniel Sanders via Phabricator via cfe-commits
dsanders accepted this revision.
dsanders added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: llvm/include/llvm/ADT/Statistic.h:47
 
-class Statistic {
+class StatisticBase {
 public:

Do we actually need the common base class? I'm thinking that since 
NoopStatistic never registers (and can't because the interfaces to do so 
changed to TrackingStatistic*), then there's a good chance that nothing reads 
DebugType, Name, Desc, Value, Initialized and we might be able to save a little 
memory by eliminating them.


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

https://reviews.llvm.org/D68252



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


[PATCH] D67940: [BPF] Preserve and make bitfield access relocatable

2019-10-01 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song abandoned this revision.
yonghong-song added a comment.

We will take a different approach. So abandon this revision.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67940



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


[PATCH] D68227: [clang-format] [PR43372] - clang-format shows replacements in DOS files when no replacement is needed

2019-10-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 222665.
MyDeveloperDay set the repository for this revision to rC Clang.
MyDeveloperDay added a project: clang-tools-extra.

Repository:
  rC Clang

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

https://reviews.llvm.org/D68227

Files:
  clang/lib/Format/Format.cpp
  clang/unittests/Format/SortImportsTestJava.cpp
  clang/unittests/Format/SortIncludesTest.cpp


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -724,6 +724,14 @@
   EXPECT_EQ(Code, sort(Code, "input.h", 0));
 }
 
+TEST_F(SortIncludesTest,
+   DoNotOutputReplacementsForSortedBlocksWithRegroupingWindows) {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  std::string Code = "#include \"b.h\"\r\n"
+ "\r\n"
+ "#include \r\n";
+  EXPECT_EQ(Code, sort(Code, "input.h", 0));
+}
 
 TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
   FmtStyle = getGoogleStyle(FormatStyle::LK_ObjC);
Index: clang/unittests/Format/SortImportsTestJava.cpp
===
--- clang/unittests/Format/SortImportsTestJava.cpp
+++ clang/unittests/Format/SortImportsTestJava.cpp
@@ -285,6 +285,13 @@
   sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
 }
 
+TEST_F(SortImportsTestJava, NoReplacementsForValidImportsWindows) {
+  std::string Code = "import org.a;\r\n"
+ "import org.b;\r\n";
+  EXPECT_TRUE(
+  sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -1825,6 +1825,28 @@
   return std::make_pair(CursorIndex, OffsetToEOL);
 }
 
+// Replace all "\r\n" with "\n".
+std::string replaceCRLF(const std::string &Code) {
+  std::string NewCode;
+  size_t Pos = 0, LastPos = 0;
+
+  do {
+Pos = Code.find("\r\n", LastPos);
+if (Pos == LastPos) {
+  LastPos++;
+  continue;
+}
+if (Pos == std::string::npos) {
+  NewCode += Code.substr(LastPos);
+  break;
+}
+NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
+LastPos = Pos + 2;
+  } while (Pos != std::string::npos);
+
+  return NewCode;
+}
+
 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
 // source order.
@@ -1898,7 +1920,8 @@
 
   // If the #includes are out of order, we generate a single replacement fixing
   // the entire range of blocks. Otherwise, no replacement is generated.
-  if (result == Code.substr(IncludesBeginOffset, IncludesBlockSize))
+  if (replaceCRLF(result) ==
+  replaceCRLF(Code.substr(IncludesBeginOffset, IncludesBlockSize)))
 return;
 
   auto Err = Replaces.add(tooling::Replacement(
@@ -2066,7 +2089,8 @@
 
   // If the imports are out of order, we generate a single replacement fixing
   // the entire block. Otherwise, no replacement is generated.
-  if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
+  if (replaceCRLF(result) ==
+  replaceCRLF(Code.substr(Imports.front().Offset, ImportsBlockSize)))
 return;
 
   auto Err = Replaces.add(tooling::Replacement(FileName, 
Imports.front().Offset,
@@ -2356,7 +2380,7 @@
 
   auto Env =
   std::make_unique(Code, FileName, Ranges, FirstStartColumn,
- NextStartColumn, LastStartColumn);
+NextStartColumn, LastStartColumn);
   llvm::Optional CurrentCode = None;
   tooling::Replacements Fixes;
   unsigned Penalty = 0;


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -724,6 +724,14 @@
   EXPECT_EQ(Code, sort(Code, "input.h", 0));
 }
 
+TEST_F(SortIncludesTest,
+   DoNotOutputReplacementsForSortedBlocksWithRegroupingWindows) {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  std::string Code = "#include \"b.h\"\r\n"
+ "\r\n"
+ "#include \r\n";
+  EXPECT_EQ(Code, sort(Code, "input.h", 0));
+}
 
 TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
   FmtStyle = getGoogleStyle(FormatStyle::LK_ObjC);
Index: clang/unittests/Format/SortImportsTestJava.cpp
===
--- clang/unittests/Format/SortImportsTestJava.cpp
+++ clang/unittests/Format/SortImportsTestJava.cpp
@@ -285,6 +285,13 @@
   sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
 }
 
+TEST_F(SortImportsTestJava,

[PATCH] D68193: In openFileForRead don't cache erroneous entries if the error relates to them being directories. Add tests.

2019-10-01 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk updated this revision to Diff 222667.
kousikk marked an inline comment as done.
kousikk added a comment.

Address code-reorg comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68193

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -15,22 +15,19 @@
 using namespace tooling;
 using namespace dependencies;
 
+
 CachedFileSystemEntry CachedFileSystemEntry::createFileEntry(
-StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize) {
+llvm::vfs::Status &&Stat, llvm::vfs::FileSystem &FS, bool Minimize) {
   // Load the file and its content from the file system.
+  StringRef Filename = Stat.getName();
   llvm::ErrorOr> MaybeFile =
   FS.openFileForRead(Filename);
   if (!MaybeFile)
 return MaybeFile.getError();
-  llvm::ErrorOr Stat = (*MaybeFile)->status();
-  if (!Stat)
-return Stat.getError();
-  if (Stat->isDirectory())
-return std::make_error_code(std::errc::is_a_directory);
 
   llvm::vfs::File &F = **MaybeFile;
   llvm::ErrorOr> MaybeBuffer =
-  F.getBuffer(Stat->getName());
+  F.getBuffer(Filename);
   if (!MaybeBuffer)
 return MaybeBuffer.getError();
 
@@ -44,7 +41,7 @@
 // if the minimization failed.
 // FIXME: Propage the diagnostic if desired by the client.
 CachedFileSystemEntry Result;
-Result.MaybeStat = std::move(*Stat);
+Result.MaybeStat = Stat;
 Result.Contents.reserve(Buffer->getBufferSize() + 1);
 Result.Contents.append(Buffer->getBufferStart(), Buffer->getBufferEnd());
 // Implicitly null terminate the contents for Clang's lexer.
@@ -55,10 +52,10 @@
 
   CachedFileSystemEntry Result;
   size_t Size = MinimizedFileContents.size();
-  Result.MaybeStat = llvm::vfs::Status(Stat->getName(), Stat->getUniqueID(),
-   Stat->getLastModificationTime(),
-   Stat->getUser(), Stat->getGroup(), Size,
-   Stat->getType(), Stat->getPermissions());
+  Result.MaybeStat = llvm::vfs::Status(Stat.getName(), Stat.getUniqueID(),
+   Stat.getLastModificationTime(),
+   Stat.getUser(), Stat.getGroup(), Size,
+   Stat.getType(), Stat.getPermissions());
   // The contents produced by the minimizer must be null terminated.
   assert(MinimizedFileContents.data()[MinimizedFileContents.size()] == '\0' &&
  "not null terminated contents");
@@ -124,14 +121,11 @@
   return It.first->getValue();
 }
 
-llvm::ErrorOr
-DependencyScanningWorkerFilesystem::status(const Twine &Path) {
-  SmallString<256> OwnedFilename;
-  StringRef Filename = Path.toStringRef(OwnedFilename);
-
-  // Check the local cache first.
-  if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename))
-return Entry->getStatus();
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(const StringRef Filename) {
+  if (const CachedFileSystemEntry* Entry = getCachedEntry(Filename)) {
+return Entry;
+  }
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
@@ -139,7 +133,7 @@
   bool KeepOriginalSource = IgnoredFiles.count(Filename);
   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
   &SharedCacheEntry = SharedCache.get(Filename);
-  const CachedFileSystemEntry *Result;
+  CachedFileSystemEntry *Result;
   {
 std::unique_lock LockGuard(SharedCacheEntry.ValueLock);
 CachedFileSystemEntry &CacheEntry = SharedCacheEntry.Value;
@@ -154,7 +148,7 @@
 std::move(*MaybeStatus));
   else
 CacheEntry = CachedFileSystemEntry::createFileEntry(
-Filename, FS, !KeepOriginalSource);
+std::move(*MaybeStatus), FS, !KeepOriginalSource);
 }
 
 Result = &CacheEntry;
@@ -162,7 +156,17 @@
 
   // Store the result in the local cache.
   setCachedEntry(Filename, Result);
-  return Result->getStatus();
+  return Result;
+}
+
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::status(const Twine &Path) {
+  SmallString<256> OwnedFilename;
+  StringRef Filename = Path.toStringRef(OwnedFilename);
+  const llvm::ErrorOr Result = getOrCreateFileSystemEntry(Filename);
+  if (!Result)
+return Result.getError();
+  return (*Result)->getStatus();
 }
 
 namespace {
@@ -219,36 +223,8 @@
   SmallString<256> OwnedFilename;
   StringRef Filename = Path.toStringRef(OwnedFilename);
 
-  // Check the local cache first.
-  if (const CachedFileSystemEntry *Entry = getCachedEn

[PATCH] D68193: In openFileForRead don't cache erroneous entries if the error relates to them being directories. Add tests.

2019-10-01 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk added a comment.

In D68193#1688838 , @dexonsmith wrote:

> Sorry for bouncing you around, but I just had a look at the other user of 
> `createFileEntry` and I think the right thing to do is to somehow share the 
> code between `DependencyScanningWorkerFilesystem::status` and this.  I 
> suggest splitting a function out of `status` (called 
> `getOrCreateFileSystemEntry`?) that returns a `CachedFileSystemEntry` (or an 
> error).
>
> The fix I just asked you to make (to only call `stat` once) could be done on 
> `getOrCreateFileSystemEntry` as a follow-up, using 
> `std::unique_ptr` and changing `getFileEntry` to take that 
> instead of a filename.


IIUC, 
`DependencyScanningWorkerFilesystem::status()` and 
`DependencyScanningWorkerFilesystem::openFileForRead()` both inturn call into 
`CachedFileSystemEntry::createFileEntry()`.

Given that, I made `getOrCreateFileEntry()` a private-member of 
`DependencyScanningWorkerFilesystem` and made both these functions use it first.

In a subsequent step, I passed in `llvm::vfs::Status` object to 
`createFileEntry()` instead of `Filename`. I hope this aligns with the 
code-organization you are looking for. Let me know if this aligns with how you 
wanted the code to look (happy to re-write if not).

I also ran it against a canonical set of tests I'm maintaining internally and I 
didn't notice a difference in either performance and didn't get new crashes of 
the tool, so I think there should NOT be any regressions because of this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68193



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


[PATCH] D68227: [clang-format] [PR43372] - clang-format shows replacements in DOS files when no replacement is needed

2019-10-01 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir accepted this revision.
krasimir added a comment.
This revision is now accepted and ready to land.

Thank you!


Repository:
  rC Clang

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

https://reviews.llvm.org/D68227



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


[PATCH] D68193: In openFileForRead don't cache erroneous entries if the error relates to them being directories. Add tests.

2019-10-01 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk updated this revision to Diff 222669.
kousikk added a comment.

Add missed const


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68193

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -15,22 +15,19 @@
 using namespace tooling;
 using namespace dependencies;
 
+
 CachedFileSystemEntry CachedFileSystemEntry::createFileEntry(
-StringRef Filename, llvm::vfs::FileSystem &FS, bool Minimize) {
+llvm::vfs::Status &&Stat, llvm::vfs::FileSystem &FS, bool Minimize) {
   // Load the file and its content from the file system.
+  StringRef Filename = Stat.getName();
   llvm::ErrorOr> MaybeFile =
   FS.openFileForRead(Filename);
   if (!MaybeFile)
 return MaybeFile.getError();
-  llvm::ErrorOr Stat = (*MaybeFile)->status();
-  if (!Stat)
-return Stat.getError();
-  if (Stat->isDirectory())
-return std::make_error_code(std::errc::is_a_directory);
 
   llvm::vfs::File &F = **MaybeFile;
   llvm::ErrorOr> MaybeBuffer =
-  F.getBuffer(Stat->getName());
+  F.getBuffer(Filename);
   if (!MaybeBuffer)
 return MaybeBuffer.getError();
 
@@ -44,7 +41,7 @@
 // if the minimization failed.
 // FIXME: Propage the diagnostic if desired by the client.
 CachedFileSystemEntry Result;
-Result.MaybeStat = std::move(*Stat);
+Result.MaybeStat = Stat;
 Result.Contents.reserve(Buffer->getBufferSize() + 1);
 Result.Contents.append(Buffer->getBufferStart(), Buffer->getBufferEnd());
 // Implicitly null terminate the contents for Clang's lexer.
@@ -55,10 +52,10 @@
 
   CachedFileSystemEntry Result;
   size_t Size = MinimizedFileContents.size();
-  Result.MaybeStat = llvm::vfs::Status(Stat->getName(), Stat->getUniqueID(),
-   Stat->getLastModificationTime(),
-   Stat->getUser(), Stat->getGroup(), Size,
-   Stat->getType(), Stat->getPermissions());
+  Result.MaybeStat = llvm::vfs::Status(Stat.getName(), Stat.getUniqueID(),
+   Stat.getLastModificationTime(),
+   Stat.getUser(), Stat.getGroup(), Size,
+   Stat.getType(), Stat.getPermissions());
   // The contents produced by the minimizer must be null terminated.
   assert(MinimizedFileContents.data()[MinimizedFileContents.size()] == '\0' &&
  "not null terminated contents");
@@ -124,14 +121,11 @@
   return It.first->getValue();
 }
 
-llvm::ErrorOr
-DependencyScanningWorkerFilesystem::status(const Twine &Path) {
-  SmallString<256> OwnedFilename;
-  StringRef Filename = Path.toStringRef(OwnedFilename);
-
-  // Check the local cache first.
-  if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename))
-return Entry->getStatus();
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(const StringRef Filename) {
+  if (const CachedFileSystemEntry* Entry = getCachedEntry(Filename)) {
+return Entry;
+  }
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
@@ -154,7 +148,7 @@
 std::move(*MaybeStatus));
   else
 CacheEntry = CachedFileSystemEntry::createFileEntry(
-Filename, FS, !KeepOriginalSource);
+std::move(*MaybeStatus), FS, !KeepOriginalSource);
 }
 
 Result = &CacheEntry;
@@ -162,7 +156,17 @@
 
   // Store the result in the local cache.
   setCachedEntry(Filename, Result);
-  return Result->getStatus();
+  return Result;
+}
+
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::status(const Twine &Path) {
+  SmallString<256> OwnedFilename;
+  StringRef Filename = Path.toStringRef(OwnedFilename);
+  const llvm::ErrorOr Result = getOrCreateFileSystemEntry(Filename);
+  if (!Result)
+return Result.getError();
+  return (*Result)->getStatus();
 }
 
 namespace {
@@ -219,36 +223,8 @@
   SmallString<256> OwnedFilename;
   StringRef Filename = Path.toStringRef(OwnedFilename);
 
-  // Check the local cache first.
-  if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename))
-return createFile(Entry, PPSkipMappings);
-
-  // FIXME: Handle PCM/PCH files.
-  // FIXME: Handle module map files.
-
-  bool KeepOriginalSource = IgnoredFiles.count(Filename);
-  DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
-  &SharedCacheEntry = SharedCache.get(Filename);
-  const CachedFileSystemEntry *Result;
-  {
-std::unique_lock LockGuard(SharedCacheEntry.ValueLock);
-CachedFileSystemEntry &Cach

[PATCH] D67706: [clang][analyzer] Using CallDescription in StreamChecker.

2019-10-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:60-61
 private:
-  void Fopen(CheckerContext &C, const CallExpr *CE) const;
-  void Tmpfile(CheckerContext &C, const CallExpr *CE) const;
-  void Fclose(CheckerContext &C, const CallExpr *CE) const;
-  void Fread(CheckerContext &C, const CallExpr *CE) const;
-  void Fwrite(CheckerContext &C, const CallExpr *CE) const;
-  void Fseek(CheckerContext &C, const CallExpr *CE) const;
-  void Ftell(CheckerContext &C, const CallExpr *CE) const;
-  void Rewind(CheckerContext &C, const CallExpr *CE) const;
-  void Fgetpos(CheckerContext &C, const CallExpr *CE) const;
-  void Fsetpos(CheckerContext &C, const CallExpr *CE) const;
-  void Clearerr(CheckerContext &C, const CallExpr *CE) const;
-  void Feof(CheckerContext &C, const CallExpr *CE) const;
-  void Ferror(CheckerContext &C, const CallExpr *CE) const;
-  void Fileno(CheckerContext &C, const CallExpr *CE) const;
-
-  void OpenFileAux(CheckerContext &C, const CallExpr *CE) const;
-
-  ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state,
- CheckerContext &C) const;
-  ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef state,
- CheckerContext &C) const;
+  typedef void (StreamChecker::*FnCheck)(const CallEvent &,
+ CheckerContext &) const;
+

Szelethus wrote:
> Prefer using. When I wrote D68165, I spent about 10 minutes figuring out how 
> to do it... Ah, the joys of the C++ syntax.
> ```lang=c++
> using FnCheck = void (StreamChecker::*)(const CallEvent &,
> CheckerContext &) const;
> ```
It's actually very easy to remember, it's just an alien kiss smiley ::*)



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:127-131
+  for (auto P : Call.parameters()) {
+QualType T = P->getType();
+if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
+  return nullptr;
+  }

balazske wrote:
> Szelethus wrote:
> > Szelethus wrote:
> > > balazske wrote:
> > > > Szelethus wrote:
> > > > > I'm not sure why we need this, is it true that *all* stream related 
> > > > > functions return a pointer or a numerical value? Are we actually 
> > > > > checking whether this really is a library function? If so, this looks 
> > > > > pretty arbitrary.
> > > > This comes from code of CStringChecker:
> > > > ```
> > > >   // Pro-actively check that argument types are safe to do arithmetic 
> > > > upon.
> > > >   // We do not want to crash if someone accidentally passes a structure
> > > >   // into, say, a C++ overload of any of these functions. We could not 
> > > > check
> > > >   // that for std::copy because they may have arguments of other types.
> > > > ```
> > > > Still I am not sure that the checker works correct with code that 
> > > > contains similar named but "arbitrary" functions.
> > > Oops, meant to write that ", is it true that *all* stream related 
> > > functions have only pointer or a numerical parameters?".
> > ...and removing this one, or changing it to an assert?
> This can not be an assert because it is possible to have global functions 
> with same name but different signature. The check can be kept to filter out 
> such cases. The wanted stream functions have only integral or enum or pointer 
> arguments.
Clang shouldn't crash even when the library definition is incorrect.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:156
+void StreamChecker::evalFread(const CallEvent &Call, CheckerContext &C) const {
+  (void)CheckNullStream(Call.getArgSVal(3), C);
 }

Szelethus wrote:
> balazske wrote:
> > Szelethus wrote:
> > > Why the need for `(void)`? `CheckNullSteam` doesn't seem to have an 
> > > `LLVM_NODISCARD` attribute.
> > I wanted to be sure to get no buildbot compile errors (where -Werror is 
> > used).
> They actually break on this?? Let me guess, is it the windows one? :D
I'd rather not discard the return value, but allow callbacks indicate an error 
when something goes wrong, so that to allow them to abort `evalCall()`. 

But more importantly, note how `CheckNullStream` actually returns a 
`ProgramStateRef` that was meant to be transitioned into. Which means that the 
primary execution path actually gets cut off.

So even if buildbots didn't warn on this, i wish they did.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67706



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


[PATCH] D62686: [RISCV] Add support for save/restore of callee-saved registers via libcalls

2019-10-01 Thread Ana Pazos via Phabricator via cfe-commits
apazos added a comment.

Thanks for the patch update. I will launch some new correctness runs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D62686



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


r373387 - [OPENMP50]Initial codegen for declare variant implementation vendor.

2019-10-01 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Oct  1 13:18:32 2019
New Revision: 373387

URL: http://llvm.org/viewvc/llvm-project?rev=373387&view=rev
Log:
[OPENMP50]Initial codegen for declare variant implementation vendor.

Initial implementation of global aliases emission for the declare
variant pragma with implementation vendor context selector set.

Added:
cfe/trunk/test/OpenMP/declare_variant_implementation_vendor_codegen.cpp
Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
cfe/trunk/lib/CodeGen/CodeGenModule.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=373387&r1=373386&r2=373387&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Tue Oct  1 13:18:32 2019
@@ -1264,6 +1264,51 @@ CGOpenMPRuntime::CGOpenMPRuntime(CodeGen
   loadOffloadInfoMetadata();
 }
 
+static bool tryEmitAlias(CodeGenModule &CGM, const GlobalDecl &NewGD,
+ const GlobalDecl &OldGD, llvm::GlobalValue *OrigAddr,
+ bool IsForDefinition) {
+  // Emit at least a definition for the aliasee if the the address of the
+  // original function is requested.
+  if (IsForDefinition || OrigAddr)
+(void)CGM.GetAddrOfGlobal(NewGD);
+  StringRef NewMangledName = CGM.getMangledName(NewGD);
+  llvm::GlobalValue *Addr = CGM.GetGlobalValue(NewMangledName);
+  if (Addr && !Addr->isDeclaration()) {
+const auto *D = cast(OldGD.getDecl());
+const CGFunctionInfo &FI = CGM.getTypes().arrangeGlobalDeclaration(OldGD);
+llvm::Type *DeclTy = CGM.getTypes().GetFunctionType(FI);
+
+// Create a reference to the named value.  This ensures that it is emitted
+// if a deferred decl.
+llvm::GlobalValue::LinkageTypes LT = CGM.getFunctionLinkage(OldGD);
+
+// Create the new alias itself, but don't set a name yet.
+auto *GA =
+llvm::GlobalAlias::create(DeclTy, 0, LT, "", Addr, &CGM.getModule());
+
+if (OrigAddr) {
+  assert(OrigAddr->isDeclaration() && "Expected declaration");
+
+  GA->takeName(OrigAddr);
+  OrigAddr->replaceAllUsesWith(
+  llvm::ConstantExpr::getBitCast(GA, OrigAddr->getType()));
+  OrigAddr->eraseFromParent();
+} else {
+  GA->setName(CGM.getMangledName(OldGD));
+}
+
+// Set attributes which are particular to an alias; this is a
+// specialization of the attributes which may be set on a global function.
+if (D->hasAttr() || D->hasAttr() ||
+D->isWeakImported())
+  GA->setLinkage(llvm::Function::WeakAnyLinkage);
+
+CGM.SetCommonAttributes(OldGD, GA);
+return true;
+  }
+  return false;
+}
+
 void CGOpenMPRuntime::clear() {
   InternalVars.clear();
   // Clean non-target variable declarations possibly used only in debug info.
@@ -1277,6 +1322,14 @@ void CGOpenMPRuntime::clear() {
   continue;
 GV->eraseFromParent();
   }
+  // Emit aliases for the deferred aliasees.
+  for (const auto &Pair : DeferredVariantFunction) {
+StringRef MangledName = CGM.getMangledName(Pair.second.second);
+llvm::GlobalValue *Addr = CGM.GetGlobalValue(MangledName);
+// If not able to emit alias, just emit original declaration.
+(void)tryEmitAlias(CGM, Pair.second.first, Pair.second.second, Addr,
+   /*IsForDefinition=*/false);
+  }
 }
 
 std::string CGOpenMPRuntime::getName(ArrayRef Parts) const {
@@ -11086,6 +11139,80 @@ Address CGOpenMPRuntime::getAddressOfLoc
   return Address(Addr, Align);
 }
 
+/// Checks current context and returns true if it matches the context selector.
+template 
+static bool checkContext(const OMPDeclareVariantAttr *A) {
+  assert(CtxSet != OMPDeclareVariantAttr::CtxSetUnknown &&
+ Ctx != OMPDeclareVariantAttr::CtxUnknown &&
+ "Unknown context selector or context selector set.");
+  return false;
+}
+
+/// Checks for implementation={vendor()} context selector.
+/// \returns true iff ="llvm", false otherwise.
+template <>
+bool checkContext(
+const OMPDeclareVariantAttr *A) {
+  return !A->getImplVendor().compare("llvm");
+}
+
+/// Finds the variant function that matches current context with its context
+/// selector.
+static const FunctionDecl *getDeclareVariantFunction(const FunctionDecl *FD) {
+  if (!FD->hasAttrs() || !FD->hasAttr())
+return FD;
+  // Iterate through all DeclareVariant attributes and check context selectors.
+  SmallVector MatchingAttributes;
+  for (const auto * A : FD->specific_attrs()) {
+switch (A->getCtxSelectorSet()) {
+case OMPDeclareVariantAttr::CtxSetImplementation:
+  switch (A->getCtxSelector()) {
+  case OMPDeclareVariantAttr::CtxVendor:
+if (checkContext(A))
+  MatchingAttributes.push_back(A);
+break;
+  case OMPDeclareVariantAttr::CtxUnknown:
+llvm_unreachable(
+   

r373388 - [clang-format] [PR43372] - clang-format shows replacements in DOS files when no replacement is needed

2019-10-01 Thread Paul Hoad via cfe-commits
Author: paulhoad
Date: Tue Oct  1 13:20:22 2019
New Revision: 373388

URL: http://llvm.org/viewvc/llvm-project?rev=373388&view=rev
Log:
[clang-format] [PR43372] - clang-format shows replacements in DOS files when no 
replacement is needed

Summary:
This is a patch to fix PR43372 (https://bugs.llvm.org/show_bug.cgi?id=43372) - 
clang-format can't format file with includes, ( which really keep providing 
replacements for already sorted headers.)

A similar issue was addressed by @krasimir in {D60199}, however, this seemingly 
only prevented the issue when the files being formatted did not contain windows 
line endings (\r\n)

It's possible this is related to 
https://twitter.com/StephanTLavavej/status/1176722938243895296 given who 
@STL_MSFT  works for!

As people often used the existence of replacements to determine if a file needs 
clang-formatting, this is probably pretty important for windows users

There may be a better way of comparing 2 strings and ignoring \r (which appear 
in both Results and Code), I couldn't choose between this idiom or the copy_if 
approach, but I'm happy to change it to whatever people consider more 
performant.

Reviewers: krasimir, klimek, owenpan, ioeric

Reviewed By: krasimir

Subscribers: cfe-commits, STL_MSFT, krasimir

Tags: #clang-format, #clang, #clang-tools-extra

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

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/SortImportsTestJava.cpp
cfe/trunk/unittests/Format/SortIncludesTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=373388&r1=373387&r2=373388&view=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Oct  1 13:20:22 2019
@@ -1825,6 +1825,28 @@ FindCursorIndex(const SmallVectorImpl(Code, FileName, Ranges, FirstStartColumn,
- NextStartColumn, LastStartColumn);
+NextStartColumn, LastStartColumn);
   llvm::Optional CurrentCode = None;
   tooling::Replacements Fixes;
   unsigned Penalty = 0;

Modified: cfe/trunk/unittests/Format/SortImportsTestJava.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortImportsTestJava.cpp?rev=373388&r1=373387&r2=373388&view=diff
==
--- cfe/trunk/unittests/Format/SortImportsTestJava.cpp (original)
+++ cfe/trunk/unittests/Format/SortImportsTestJava.cpp Tue Oct  1 13:20:22 2019
@@ -285,6 +285,13 @@ TEST_F(SortImportsTestJava, NoReplacemen
   sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
 }
 
+TEST_F(SortImportsTestJava, NoReplacementsForValidImportsWindows) {
+  std::string Code = "import org.a;\r\n"
+ "import org.b;\r\n";
+  EXPECT_TRUE(
+  sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang

Modified: cfe/trunk/unittests/Format/SortIncludesTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortIncludesTest.cpp?rev=373388&r1=373387&r2=373388&view=diff
==
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp (original)
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp Tue Oct  1 13:20:22 2019
@@ -724,6 +724,14 @@ TEST_F(SortIncludesTest, DoNotOutputRepl
   EXPECT_EQ(Code, sort(Code, "input.h", 0));
 }
 
+TEST_F(SortIncludesTest,
+   DoNotOutputReplacementsForSortedBlocksWithRegroupingWindows) {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  std::string Code = "#include \"b.h\"\r\n"
+ "\r\n"
+ "#include \r\n";
+  EXPECT_EQ(Code, sort(Code, "input.h", 0));
+}
 
 TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
   FmtStyle = getGoogleStyle(FormatStyle::LK_ObjC);


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


[PATCH] D68227: [clang-format] [PR43372] - clang-format shows replacements in DOS files when no replacement is needed

2019-10-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL373388: [clang-format] [PR43372] - clang-format shows 
replacements in DOS files when no… (authored by paulhoad, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68227?vs=222665&id=222683#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68227

Files:
  cfe/trunk/lib/Format/Format.cpp
  cfe/trunk/unittests/Format/SortImportsTestJava.cpp
  cfe/trunk/unittests/Format/SortIncludesTest.cpp


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1825,6 +1825,28 @@
   return std::make_pair(CursorIndex, OffsetToEOL);
 }
 
+// Replace all "\r\n" with "\n".
+std::string replaceCRLF(const std::string &Code) {
+  std::string NewCode;
+  size_t Pos = 0, LastPos = 0;
+
+  do {
+Pos = Code.find("\r\n", LastPos);
+if (Pos == LastPos) {
+  LastPos++;
+  continue;
+}
+if (Pos == std::string::npos) {
+  NewCode += Code.substr(LastPos);
+  break;
+}
+NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
+LastPos = Pos + 2;
+  } while (Pos != std::string::npos);
+
+  return NewCode;
+}
+
 // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
 // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
 // source order.
@@ -1898,7 +1920,8 @@
 
   // If the #includes are out of order, we generate a single replacement fixing
   // the entire range of blocks. Otherwise, no replacement is generated.
-  if (result == Code.substr(IncludesBeginOffset, IncludesBlockSize))
+  if (replaceCRLF(result) ==
+  replaceCRLF(Code.substr(IncludesBeginOffset, IncludesBlockSize)))
 return;
 
   auto Err = Replaces.add(tooling::Replacement(
@@ -2066,7 +2089,8 @@
 
   // If the imports are out of order, we generate a single replacement fixing
   // the entire block. Otherwise, no replacement is generated.
-  if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
+  if (replaceCRLF(result) ==
+  replaceCRLF(Code.substr(Imports.front().Offset, ImportsBlockSize)))
 return;
 
   auto Err = Replaces.add(tooling::Replacement(FileName, 
Imports.front().Offset,
@@ -2356,7 +2380,7 @@
 
   auto Env =
   std::make_unique(Code, FileName, Ranges, FirstStartColumn,
- NextStartColumn, LastStartColumn);
+NextStartColumn, LastStartColumn);
   llvm::Optional CurrentCode = None;
   tooling::Replacements Fixes;
   unsigned Penalty = 0;
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp
@@ -724,6 +724,14 @@
   EXPECT_EQ(Code, sort(Code, "input.h", 0));
 }
 
+TEST_F(SortIncludesTest,
+   DoNotOutputReplacementsForSortedBlocksWithRegroupingWindows) {
+  Style.IncludeBlocks = Style.IBS_Regroup;
+  std::string Code = "#include \"b.h\"\r\n"
+ "\r\n"
+ "#include \r\n";
+  EXPECT_EQ(Code, sort(Code, "input.h", 0));
+}
 
 TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
   FmtStyle = getGoogleStyle(FormatStyle::LK_ObjC);
Index: cfe/trunk/unittests/Format/SortImportsTestJava.cpp
===
--- cfe/trunk/unittests/Format/SortImportsTestJava.cpp
+++ cfe/trunk/unittests/Format/SortImportsTestJava.cpp
@@ -285,6 +285,13 @@
   sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
 }
 
+TEST_F(SortImportsTestJava, NoReplacementsForValidImportsWindows) {
+  std::string Code = "import org.a;\r\n"
+ "import org.b;\r\n";
+  EXPECT_TRUE(
+  sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1825,6 +1825,28 @@
   return std::make_pair(CursorIndex, OffsetToEOL);
 }
 
+// Replace all "\r\n" with "\n".
+std::string replaceCRLF(const std::string &Code) {
+  std::string NewCode;
+  size_t Pos = 0, LastPos = 0;
+
+  do {
+Pos = Code.find("\r\n", LastPos);
+if (Pos == LastPos) {
+  LastPos++;
+  continue;
+}
+if (Pos == std::string::npos) {
+  NewCode += Code.substr(LastPos);
+  break;
+}
+NewCode += Code.substr(LastPos, Pos - LastPos) + "\n";
+LastPos = Pos + 2;
+  } while (Pos != std::string::npos);
+
+  return NewCode;
+}
+
 // Sorts and deduplicate a block of includes 

[PATCH] D67079: [analyzer] CastValueChecker: Model inheritance

2019-10-01 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 222685.
Charusso marked an inline comment as done.
Charusso added a comment.

- Use the TU's Decls instead of the gathered casts' Decls.
- The math is still missing.


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

https://reviews.llvm.org/D67079

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
  clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/DynamicType.cpp
  clang/test/Analysis/cast-value-hierarchy-failures-set.cpp
  clang/test/Analysis/cast-value-hierarchy-succeeds.cpp
  clang/test/Analysis/cast-value-hierarchy.cpp
  clang/test/Analysis/cast-value-notes.cpp
  clang/test/Analysis/cast-value-state-dump.cpp
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -38,8 +38,8 @@
 // CHECK-NEXT: { "symbol": "reg_$0", "range": "{ [-2147483648, 13] }" }
 // CHECK-NEXT:   ],
 // CHECK-NEXT:   "dynamic_types": null,
-// CHECK-NEXT:   "dynamic_casts": null,
+// CHECK-NEXT:   "succeeded_casts": null,
+// CHECK-NEXT:   "failed_casts": null,
 // CHECK-NEXT:   "constructing_objects": null,
 // CHECK-NEXT:   "checker_messages": null
 // CHECK-NEXT: }
-
Index: clang/test/Analysis/cast-value-state-dump.cpp
===
--- clang/test/Analysis/cast-value-state-dump.cpp
+++ clang/test/Analysis/cast-value-state-dump.cpp
@@ -8,22 +8,27 @@
 
 namespace clang {
 struct Shape {};
-class Triangle : public Shape {};
-class Circle : public Shape {};
-class Square : public Shape {};
+struct Circle : Shape {};
+struct Square : Shape {};
+struct Octagram : Shape {};
 } // namespace clang
 
 using namespace llvm;
 using namespace clang;
 
 void evalNonNullParamNonNullReturn(const Shape *S) {
+  if (isa(S)) {
+// expected-note@-1 {{Assuming 'S' is not a 'Octagram'}}
+// expected-note@-2 {{Taking false branch}}
+return;
+  }
+
   const auto *C = dyn_cast_or_null(S);
   // expected-note@-1 {{Assuming 'S' is a 'Circle'}}
   // expected-note@-2 {{'C' initialized here}}
 
-  // FIXME: We assumed that 'S' is a 'Circle' therefore it is not a 'Square'.
   if (dyn_cast_or_null(S)) {
-// expected-note@-1 {{Assuming 'S' is not a 'Square'}}
+// expected-note@-1 {{'S' is not a 'Square'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
@@ -31,13 +36,18 @@
   clang_analyzer_printState();
 
   // CHECK:  "dynamic_types": [
-  // CHECK-NEXT:   { "region": "SymRegion{reg_$0}", "dyn_type": "const class clang::Circle", "sub_classable": true }
+  // CHECK-NEXT:   { "region": "SymRegion{reg_$0}", "dyn_type": "const struct clang::Circle", "sub_classable": true }
   // CHECK-NEXT: ],
-  // CHECK-NEXT: "dynamic_casts": [
-  // CHECK:{ "region": "SymRegion{reg_$0}", "casts": [
-  // CHECK-NEXT: { "from": "const struct clang::Shape *", "to": "const class clang::Circle *", "kind": "success" },
-  // CHECK-NEXT: { "from": "const struct clang::Shape *", "to": "const class clang::Square *", "kind": "fail" }
+  // CHECK-NEXT: "succeeded_casts": [
+  // CHECK-NEXT:   { "region": "SymRegion{reg_$0}", "casts": [
+  // CHECK-NEXT: "const struct clang::Circle *"
   // CHECK-NEXT:   ]}
+  // CHECK-NEXT: ],
+  // CHECK-NEXT: "failed_casts": [
+  // CHECK-NEXT:   { "region": "SymRegion{reg_$0}", "casts": [
+  // CHECK-NEXT: "const struct clang::Square *", "struct clang::Octagram *"
+  // CHECK-NEXT:   ]}
+  // CHECK-NEXT: ],
 
   (void)(1 / !C);
   // expected-note@-1 {{'C' is non-null}}
Index: clang/test/Analysis/cast-value-notes.cpp
===
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -12,8 +12,8 @@
   template 
   const T *getAs() const;
 };
-class Triangle : public Shape {};
-class Circle : public Shape {};
+struct Triangle : Shape {};
+struct Circle : Shape {};
 } // namespace clang
 
 using namespace llvm;
@@ -37,12 +37,6 @@
 return;
   }
 
-  if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Triangle'}}
-// expected-note@-2 {{Taking false branch}}
-return;
-  }
-
   if (isa(C)) {
 // expected-note@-1 {{'C' is not a 'Triangle'}}
 // expected-note@-2 {{Taking false branch}}
@@ -65,14 +59,8 @@
   // expected-note@-1 {{'S' is a 'Circle'}}
   // expected-note@-2 {{'C' initialized here}}
 
-  if (!isa(C)) {
-

[PATCH] D68296: clang-format: Add ability to wrap braces after multi-line control statements

2019-10-01 Thread Mitchell via Phabricator via cfe-commits
mitchell-stellar created this revision.
mitchell-stellar added reviewers: sammccall, owenpan, reuk.
mitchell-stellar added a project: clang-format.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Change the BraceWrappingFlags' AfterControlStatement from a bool to an enum 
with three values:

- "Never": This is the default, and does not do any brace wrapping after 
control statements.
- "OnlyMultiLine": This only wraps braces after multi-line control statements 
(this really only happens when a ColumnLimit is specified).
- "Always": This always wraps braces after control statements.

The first and last options are backwards-compatible with "false" and "true", 
respectively.

The new "OnlyMultiLine" option is useful for when a wrapped control statement's 
indentation matches the subsequent block's indentation. It makes it easier to 
see at a glance where the control statement ends and where the block's code 
begins. For example:

  if (
foo
&& bar )
  {
baz();
  }

vs.

  if (
foo
&& bar ) {
baz();
  }


Repository:
  rC Clang

https://reviews.llvm.org/D68296

Files:
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestObjC.cpp

Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -207,7 +207,7 @@
"  f();\n"
"}\n");
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
-  Style.BraceWrapping.AfterControlStatement = true;
+  Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
   verifyFormat("@autoreleasepool\n"
"{\n"
"  f();\n"
@@ -237,7 +237,7 @@
"  f();\n"
"}\n");
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
-  Style.BraceWrapping.AfterControlStatement = true;
+  Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
   verifyFormat("@synchronized(self)\n"
"{\n"
"  f();\n"
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -644,7 +644,8 @@
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
   FormatStyle::SIS_WithoutElse;
   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
-  AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = true;
+  AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
+  FormatStyle::BWACS_Always;
 
   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
@@ -1168,7 +1169,7 @@
   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterCaseLabel = true;
-  Style.BraceWrapping.AfterControlStatement = true;
+  Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
   EXPECT_EQ("switch (n)\n"
 "{\n"
 "  case 0:\n"
@@ -1370,7 +1371,7 @@
   Style.AllowShortCaseLabelsOnASingleLine = true;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterCaseLabel = true;
-  Style.BraceWrapping.AfterControlStatement = true;
+  Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
   EXPECT_EQ("switch (n)\n"
 "{\n"
 "  case 0:\n"
@@ -1441,6 +1442,126 @@
"}");
 }
 
+TEST_F(FormatTest, MultiLineControlStatements) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
+  Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_OnlyMultiLine;
+  Style.ColumnLimit = 20;
+  // Short lines should keep opening brace on same line.
+  EXPECT_EQ("if (foo) {\n"
+"  bar();\n"
+"}",
+format("if(foo){bar();}", Style));
+  EXPECT_EQ("if (foo) {\n"
+"  bar();\n"
+"} else {\n"
+"  baz();\n"
+"}",
+format("if(foo){bar();}else{baz();}", Style));
+  EXPECT_EQ("if (foo && bar) {\n"
+"  baz();\n"
+"}",
+format("if(foo&&bar){baz();}", Style));
+  EXPECT_EQ("if (foo) {\n"
+"  bar();\n"
+"} else if (baz) {\n"
+"  quux();\n"
+"}",
+format("if(foo){bar();}else if(baz){quux();}", Style));
+  EXPECT_EQ(
+  "if (foo) {\n"
+  "  bar();\n"
+  "} else if (baz) {\n"
+  "  quux();\n"
+  "} else {\n"
+  "  foobar();\n"
+  "}",
+  format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
+  EXPECT_EQ("for (

[PATCH] D53768: Add VerboseOutputStream to CompilerInstance

2019-10-01 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] D68117: [DWARF-5] Support for C++11 defaulted, deleted member functions.

2019-10-01 Thread Sourabh Singh Tomar via Phabricator via cfe-commits
SouraVX updated this revision to Diff 222701.
SouraVX added a comment.

Added test cases for debug info Clang frontend.


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

https://reviews.llvm.org/D68117

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/dbg-info-all-calls-described.cpp
  clang/test/CodeGenCXX/debug-info-defaulted-in-class.cpp
  clang/test/CodeGenCXX/debug-info-defaulted-out-of-class.cpp
  clang/test/CodeGenCXX/debug-info-deleted.cpp
  clang/test/CodeGenCXX/debug-info-not-defaulted.cpp
  llvm/include/llvm/BinaryFormat/Dwarf.h
  llvm/include/llvm/IR/DebugInfoFlags.def
  llvm/include/llvm/IR/DebugInfoMetadata.h
  llvm/lib/BinaryFormat/Dwarf.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp

Index: llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
+++ llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
@@ -1296,6 +1296,19 @@
 addFlag(SPDie, dwarf::DW_AT_elemental);
   if (SP->isRecursive())
 addFlag(SPDie, dwarf::DW_AT_recursive);
+  if (DD->getDwarfVersion() >= 5) {
+if (SP->isDefaultedInClass())
+  addUInt(SPDie, dwarf::DW_AT_defaulted, dwarf::DW_FORM_data1,
+  dwarf::DW_DEFAULTED_in_class);
+if (SP->isDefaultedOutOfClass())
+  addUInt(SPDie, dwarf::DW_AT_defaulted, dwarf::DW_FORM_data1,
+  dwarf::DW_DEFAULTED_out_of_class);
+if (SP->isNotDefaulted())
+  addUInt(SPDie, dwarf::DW_AT_defaulted, dwarf::DW_FORM_data1,
+  dwarf::DW_DEFAULTED_no);
+if (SP->isDeleted())
+  addFlag(SPDie, dwarf::DW_AT_deleted);
+  }
 }
 
 void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
Index: llvm/lib/BinaryFormat/Dwarf.cpp
===
--- llvm/lib/BinaryFormat/Dwarf.cpp
+++ llvm/lib/BinaryFormat/Dwarf.cpp
@@ -271,6 +271,19 @@
   return StringRef();
 }
 
+StringRef llvm::dwarf::DefaultedMemberString(unsigned DefaultedEncodings) {
+  switch (DefaultedEncodings) {
+  // Defaulted Member Encodings codes
+  case DW_DEFAULTED_no:
+return "DW_DEFAULTED_no";
+  case DW_DEFAULTED_in_class:
+return "DW_DEFAULTED_in_class";
+  case DW_DEFAULTED_out_of_class:
+return "DW_DEFAULTED_out_of_class";
+  }
+  return StringRef();
+}
+
 StringRef llvm::dwarf::VisibilityString(unsigned Visibility) {
   switch (Visibility) {
   case DW_VIS_local:
@@ -601,6 +614,8 @@
 return ArrayOrderString(Val);
   case DW_AT_APPLE_runtime_class:
 return LanguageString(Val);
+  case DW_AT_defaulted:
+return DefaultedMemberString(Val);
   }
 
   return StringRef();
Index: llvm/include/llvm/IR/DebugInfoMetadata.h
===
--- llvm/include/llvm/IR/DebugInfoMetadata.h
+++ llvm/include/llvm/IR/DebugInfoMetadata.h
@@ -1758,6 +1758,14 @@
   bool isPure() const { return getSPFlags() & SPFlagPure; }
   bool isElemental() const { return getSPFlags() & SPFlagElemental; }
   bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
+  bool isDefaultedInClass() const {
+return getSPFlags() & SPFlagDefaultedInClass;
+  }
+  bool isDefaultedOutOfClass() const {
+return getSPFlags() & SPFlagDefaultedOutOfClass;
+  }
+  bool isNotDefaulted() const { return getSPFlags() & SPFlagNotDefaulted; }
+  bool isDeleted() const { return getSPFlags() & SPFlagDeleted; }
 
   /// Check if this is reference-qualified.
   ///
Index: llvm/include/llvm/IR/DebugInfoFlags.def
===
--- llvm/include/llvm/IR/DebugInfoFlags.def
+++ llvm/include/llvm/IR/DebugInfoFlags.def
@@ -88,11 +88,15 @@
 HANDLE_DISP_FLAG((1u << 6), Elemental)
 HANDLE_DISP_FLAG((1u << 7), Recursive)
 HANDLE_DISP_FLAG((1u << 8), MainSubprogram)
+HANDLE_DISP_FLAG((1u << 9), NotDefaulted)
+HANDLE_DISP_FLAG((1u << 10), DefaultedInClass)
+HANDLE_DISP_FLAG((1u << 11), DefaultedOutOfClass)
+HANDLE_DISP_FLAG((1u << 12), Deleted)
 
 #ifdef DISP_FLAG_LARGEST_NEEDED
 // Intended to be used with ADT/BitmaskEnum.h.
 // NOTE: Always must be equal to largest flag, check this when adding new flags.
-HANDLE_DISP_FLAG((1 << 8), Largest)
+HANDLE_DISP_FLAG((1 << 12), Largest)
 #undef DISP_FLAG_LARGEST_NEEDED
 #endif
 
Index: llvm/include/llvm/BinaryFormat/Dwarf.h
===
--- llvm/include/llvm/BinaryFormat/Dwarf.h
+++ llvm/include/llvm/BinaryFormat/Dwarf.h
@@ -411,6 +411,7 @@
 StringRef DecimalSignString(unsigned Sign);
 StringRef EndianityString(unsigned Endian);
 StringRef AccessibilityString(unsigned Access);
+StringRef DefaultedMemberString(unsigned DefaultedEncodings);
 StringRef VisibilityString(unsigned Visibility);
 StringRef VirtualityString(unsigned Virtuality);
 StringRef LanguageString(unsigned Language);
Index: clang/test/CodeGenCXX/debug-info-not-defaulted.cpp
===
---

  1   2   >