[PATCH] D47111: : Implement monotonic_buffer_resource.

2018-11-26 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF accepted this revision.
EricWF added a comment.
This revision is now accepted and ready to land.

LGTM. The tests might need some XFAIL'ing, but otherwise I think this looks 
good.

Sorry for the wait.


Repository:
  rCXX libc++

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

https://reviews.llvm.org/D47111



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


[PATCH] D54872: [clangd] Add ability to not use -resource-dir at all

2018-11-26 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle planned changes to this revision.
malaperle added a comment.

In D54872#1307775 , @ilya-biryukov 
wrote:

> We have to point clangd into the resource dir, corresponding to the version 
> of the headers it was built with. It's important we pick the exact version of 
> the built-in headers that clangd was built for.


Can you clarity/confirm "headers it was built with"? For example, if I build 
Clangd using Xcode's Clang, then running this Clangd, I would have to point to 
Xcode's Clang headers? This is what I have observed when using Clangd on 
Clangd's code. What if I compile Clangd with another non-Clang compiler?

> Note that resource-dir should **only** be used for the built-in headers, any 
> compiler-specific libraries should be found using other flags. Could you 
> provide an example clang-cl commands that it breaks with?

The problematic case is a bit different than I originally thought. The CDB 
contains an include path to the built-in headers of the Clang (windows 
installer) used to build the project, let's call the compiler Clang1. I also 
built Clang+Clangd separately from this Clang1, using CL, let's call it Clang2. 
When running that custom Clangd, the fallback resource-dir is the one from 
Clang2. I haven't looked deeply to confirm this, but having an include path to 
Clang1 (windows installer) and resource-dir to Clang2 (custom build) seems like 
would likely not work. In fact, when running Clangd from Clang2 and setting 
resource-dir to Clang1, it works properly. Now, I don't know if it's the CDB 
that's wrongly including the headers of Clang1 or if the CDB should include 
-resource-dir to Clang1. In any case, I'll spend a bit more time clarifying 
this.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54872



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


[PATCH] D54878: [clangd] NFC: Prefer `isa<>` to `dyn_cast<>` to do the checking.

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE347635: [clangd] NFC: Prefer `isa` to 
`dyn_cast` to do the checking. (authored by henrywong, committed by ).

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54878

Files:
  clangd/AST.cpp


Index: clangd/AST.cpp
===
--- clangd/AST.cpp
+++ clangd/AST.cpp
@@ -95,11 +95,11 @@
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast())
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }


Index: clangd/AST.cpp
===
--- clangd/AST.cpp
+++ clangd/AST.cpp
@@ -95,11 +95,11 @@
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast())
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347635 - [clangd] NFC: Prefer `isa<>` to `dyn_cast<>` to do the checking.

2018-11-26 Thread Henry Wong via cfe-commits
Author: henrywong
Date: Mon Nov 26 20:27:00 2018
New Revision: 347635

URL: http://llvm.org/viewvc/llvm-project?rev=347635=rev
Log:
[clangd] NFC: Prefer `isa<>` to `dyn_cast<>` to do the checking.

Summary: Prefer `isa<>` to `dyn_cast<>` when there only need a checking.

Reviewers: ilya-biryukov, MaskRay

Reviewed By: ilya-biryukov, MaskRay

Subscribers: ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits, MTC

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

Modified:
clang-tools-extra/trunk/clangd/AST.cpp

Modified: clang-tools-extra/trunk/clangd/AST.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/AST.cpp?rev=347635=347634=347635=diff
==
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Mon Nov 26 20:27:00 2018
@@ -95,11 +95,11 @@ std::string printName(const ASTContext &
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast())
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (llvm::dyn_cast())
+  if (isa(ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }


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


Re: r338941 - [constexpr] Support for constant evaluation of __builtin_memcpy and

2018-11-26 Thread Richard Smith via cfe-commits
Glad I could help you diagnose the issue at least :)

On Mon, 26 Nov 2018 at 18:03, Shoaib Meenai via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Uhh, we have our own build that uses the release branch, but somehow we
> didn’t have that commit in there. Not sure how that happened, but sorry for
> the noise.
>
>
>
> *From: *cfe-commits  on behalf of
> Richard Smith via cfe-commits 
> *Reply-To: *Richard Smith 
> *Date: *Monday, November 26, 2018 at 12:01 PM
> *To: *Shoaib Meenai 
> *Cc: *cfe-commits , Tom Stellard <
> tstel...@redhat.com>
> *Subject: *Re: r338941 - [constexpr] Support for constant evaluation of
> __builtin_memcpy and
>
>
>
> On Mon, 26 Nov 2018, 11:50 Richard Smith 
> On Wed, 21 Nov 2018, 15:32 Shoaib Meenai via cfe-commits <
> cfe-commits@lists.llvm.org wrote:
>
> If it's not too late, could we have this as part of 7.0.1? (You'll also
> need to cherry-pick the initial reversion in r338602.)
>
>
>
> The revert was cherrypicked onto the branch in r338674. Was that not in
> time for 7.0?
>
>
>
> Looks like the revert was in fact the very first thing cherrypicked into
> clang's release_70 branch after the branch was cut, so it should certainly
> have been in time for 7.0. Are you sure your clang binary is really the 7.0
> release?
>
>
>
> I don't think we should take this as a new feature for 7.0.1.
>
>
>
> 7.0 hits assertion failures for pretty basic memcpy cases on windows-msvc
> targets, and this patch fixes that.
>
>
>
> % cat /tmp/reduced.c
>
> void *memcpy(void *, const void *, __SIZE_TYPE__);
> void f(int i) {
>   struct { int i } s;
>   memcpy((char *), , sizeof(i));
> }
>
>
>
> % clang -cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility -o
> /dev/null /tmp/reduced.c
>
> llvm::SmallVectorTemplateCommon::const_reference
> llvm::SmallVectorTemplateCommon void>::back() const [T = clang::APValue::LValuePathEntry]: Assertion
> `!empty()' failed.
>
>
>
> On Fri, Aug 3, 2018 at 5:57 PM Richard Smith via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
> Author: rsmith
> Date: Fri Aug  3 17:57:17 2018
> New Revision: 338941
>
> URL: http://llvm.org/viewvc/llvm-project?rev=338941=rev
> 
> Log:
> [constexpr] Support for constant evaluation of __builtin_memcpy and
> __builtin_memmove (in non-type-punning cases).
>
> This is intended to permit libc++ to make std::copy etc constexpr
> without sacrificing the optimization that uses memcpy on
> trivially-copyable types.
>
> __builtin_strcpy and __builtin_wcscpy are not handled by this change.
> They'd be straightforward to add, but we haven't encountered a need for
> them just yet.
>
> This reinstates r338455, reverted in r338602, with a fix to avoid trying
> to constant-evaluate a memcpy call if either pointer operand has an
> invalid designator.
>
> Modified:
> cfe/trunk/include/clang/Basic/Builtins.def
> cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
> cfe/trunk/lib/AST/ExprConstant.cpp
> cfe/trunk/test/CodeGen/builtin-memfns.c
> cfe/trunk/test/SemaCXX/constexpr-string.cpp
>
> Modified: cfe/trunk/include/clang/Basic/Builtins.def
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338941=338940=338941=diff
> 
>
> ==
> --- cfe/trunk/include/clang/Basic/Builtins.def (original)
> +++ cfe/trunk/include/clang/Basic/Builtins.def Fri Aug  3 17:57:17 2018
> @@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
>  BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
>  BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
>  BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
> +BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
> +BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
>  BUILTIN(__builtin_return_address, "v*IUi", "n")
>  BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
>  BUILTIN(__builtin_frame_address, "v*IUi", "n")
> @@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*", "f", "wc
>  LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>  LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)
>  LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
> +LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
> +LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>
>  // C99
>  // In some systems setjmp is a macro that expands to _setjmp. We undefine
>
> Modified: 

r347633 - [docs] UBSan and ASan are supported on Windows

2018-11-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Mon Nov 26 19:55:15 2018
New Revision: 347633

URL: http://llvm.org/viewvc/llvm-project?rev=347633=rev
Log:
[docs] UBSan and ASan are supported on Windows

Also fix a bullet list.

Fixes PR39775

Modified:
cfe/trunk/docs/AddressSanitizer.rst
cfe/trunk/docs/UndefinedBehaviorSanitizer.rst

Modified: cfe/trunk/docs/AddressSanitizer.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/AddressSanitizer.rst?rev=347633=347632=347633=diff
==
--- cfe/trunk/docs/AddressSanitizer.rst (original)
+++ cfe/trunk/docs/AddressSanitizer.rst Mon Nov 26 19:55:15 2018
@@ -278,6 +278,7 @@ AddressSanitizer is supported on:
 * Android ARM
 * NetBSD i386/x86\_64
 * FreeBSD i386/x86\_64 (tested on FreeBSD 11-current)
+* Windows 8.1+ (i386/x86\_64)
 
 Ports to various other platforms are in progress.
 
@@ -288,6 +289,9 @@ AddressSanitizer is fully functional on
 3.1. The test suite is integrated into CMake build and can be run with ``make
 check-asan`` command.
 
+The Windows port is functional and is used by Chrome and Firefox, but it is not
+as well supported as the other ports.
+
 More Information
 
 

Modified: cfe/trunk/docs/UndefinedBehaviorSanitizer.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/UndefinedBehaviorSanitizer.rst?rev=347633=347632=347633=diff
==
--- cfe/trunk/docs/UndefinedBehaviorSanitizer.rst (original)
+++ cfe/trunk/docs/UndefinedBehaviorSanitizer.rst Mon Nov 26 19:55:15 2018
@@ -288,7 +288,7 @@ There are several limitations:
 Supported Platforms
 ===
 
-UndefinedBehaviorSanitizer is supported on the following OS:
+UndefinedBehaviorSanitizer is supported on the following operating systems:
 
 * Android
 * Linux
@@ -296,6 +296,11 @@ UndefinedBehaviorSanitizer is supported
 * FreeBSD
 * OpenBSD
 * OS X 10.6 onwards
+* Windows
+
+The runtime library is relatively portable and platform independent. If the OS
+you need is not listed above, UndefinedBehaviorSanitizer may already work for
+it, or could be made to work with a minor porting effort.
 
 Current Status
 ==
@@ -318,6 +323,7 @@ Example
 ---
 
 For a file called ``/code/library/file.cpp``, here is what would be emitted:
+
 * Default (No flag, or ``-fsanitize-undefined-strip-path-components=0``): 
``/code/library/file.cpp``
 * ``-fsanitize-undefined-strip-path-components=1``: ``code/library/file.cpp``
 * ``-fsanitize-undefined-strip-path-components=2``: ``library/file.cpp``


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


[PATCH] D54781: [clangd] Add 'Switch header/source' command in clangd-vscode

2018-11-26 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle added a comment.

In D54781#1307755 , @hokein wrote:

> @malaperle, do you want a new release of `vscode-clangd` extension for this?


I don't plan on doing changes for a little while in vscode-clangd so it would 
be good indeed to have a new release. Unless you know of some upcoming change 
that could also piggy back a new release? Thanks!


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54781



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


[PATCH] D54799: [clangd][WIP] textDocument/SymbolInfo method

2018-11-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

LGTM, we can optimize later. It looks like you also moved `SymbolID` to a new 
file, this should be an NFC precommit.


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

https://reviews.llvm.org/D54799



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


r347630 - Revert r347627 "[MS] Push fewer DeclContexts for delayed template parsing"

2018-11-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Mon Nov 26 18:54:17 2018
New Revision: 347630

URL: http://llvm.org/viewvc/llvm-project?rev=347630=rev
Log:
Revert r347627 "[MS] Push fewer DeclContexts for delayed template parsing"

It broke the Windows self-host:
http://lab.llvm.org:8011/builders/clang-x64-windows-msvc/builds/1799/steps/stage%202%20build/logs/stdio

I can build
lib/CodeGen/CMakeFiles/LLVMCodeGen.dir/MachinePostDominators.cpp.obj to
repro.

Modified:
cfe/trunk/lib/Parse/ParseTemplate.cpp
cfe/trunk/test/Parser/DelayedTemplateParsing.cpp

Modified: cfe/trunk/lib/Parse/ParseTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseTemplate.cpp?rev=347630=347629=347630=diff
==
--- cfe/trunk/lib/Parse/ParseTemplate.cpp (original)
+++ cfe/trunk/lib/Parse/ParseTemplate.cpp Mon Nov 26 18:54:17 2018
@@ -1382,7 +1382,7 @@ void Parser::ParseLateTemplatedFuncDef(L
   SmallVector TemplateParamScopeStack;
 
   // Get the list of DeclContexts to reenter.
-  SmallVector DeclContextsToReenter;
+  SmallVector DeclContextsToReenter;
   DeclContext *DD = FunD;
   while (DD && !DD->isTranslationUnit()) {
 DeclContextsToReenter.push_back(DD);
@@ -1398,12 +1398,7 @@ void Parser::ParseLateTemplatedFuncDef(L
 unsigned NumParamLists =
   Actions.ActOnReenterTemplateScope(getCurScope(), cast(*II));
 CurTemplateDepthTracker.addDepth(NumParamLists);
-// If we find a class in a class, we need to push the context of the
-// outermost class to match up with how we would parse a regular C++ class
-// inline method.
-if (*II != FunD &&
-!(isa(*II) && isa(Actions.CurContext) &&
-  Actions.CurContext == (*II)->getLexicalParent())) {
+if (*II != FunD) {
   TemplateParamScopeStack.push_back(new ParseScope(this, 
Scope::DeclScope));
   Actions.PushDeclContext(Actions.getCurScope(), *II);
 }

Modified: cfe/trunk/test/Parser/DelayedTemplateParsing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/DelayedTemplateParsing.cpp?rev=347630=347629=347630=diff
==
--- cfe/trunk/test/Parser/DelayedTemplateParsing.cpp (original)
+++ cfe/trunk/test/Parser/DelayedTemplateParsing.cpp Mon Nov 26 18:54:17 2018
@@ -181,20 +181,3 @@ static void h() {
 }
 
 }
-
-struct PR38460 {
-  template 
-  struct T {
-static void foo() {
-  struct U {
-void dummy() {
-  use_delayed_identifier();
-}
-  };
-}
-  };
-};
-void use_delayed_identifier();
-void trigger_PR38460() {
-  PR38460::T::foo();
-}


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


[PATCH] D51866: [analyzer][UninitializedObjectChecker] New flag to ignore guarded uninitialized fields

2018-11-26 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

> @george.karpenkov Matching macros is a very non-trivial job, how would you 
> feel if we shipped this patch as-is, and maybe leave a TODO about adding 
> macro `assert`s down the line?

The only solution I saw in clang-tidy was to match binary expressions as a 
heuristic, and check whether they are inside a macro named assert. That is 
hacky at best, any objection against the current state of this patch?

I'm planning to evaluate the checker in a variety of projects after this one, 
see how things are looking, and push it out of alpha.


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

https://reviews.llvm.org/D51866



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


[PATCH] D54737: [clang-tidy] Add the abseil-duration-comparison check

2018-11-26 Thread Hyrum Wright via Phabricator via cfe-commits
hwright added a comment.

Sorry it's taken so long to get all the feedback addressed!




Comment at: clang-tidy/abseil/DurationComparisonCheck.cpp:25
+static llvm::Optional getScaleForInverse(llvm::StringRef Name) {
+  static const std::unordered_map ScaleMap(
+  {{"ToDoubleHours", DurationScale::Hours},

JonasToth wrote:
> I think this could be made a `DenseMap` with just the right amount of dense 
> entries. 12 elements seems not too much to me.
> Does the key-type need to be `std::string`, or could it be `StringRef`(or 
> `StringLiteral` making everything `constexpr` if possible)?
> Is there some strange stuff with dangling pointers or other issues going on?
Conceptually, this could easily be `constexpr`, but my compiler doesn't seem to 
want to build something which is called `static constexpr 
llvm::DenseMap`.  It's chief complaint is that 
such a type has a non-trivial destructor. Am I using this correctly?



Comment at: clang-tidy/abseil/DurationComparisonCheck.cpp:50
+  static const std::unordered_map>
+  InverseMap(

JonasToth wrote:
> This variable is a little hard to read. Could you make a little 
> wrapper-struct instead of the `tuple` to make clear which element represents 
> what?
> Otherwise, why not `std::pair`?
> 
> - same `DenseMap` argument
> - same `StringRef`/`StringLiteral` instead `string` consideration
`std::pair` works here.

I'll defer the `DenseMap` and `StringRef`/`StringLiteral` changes until we 
determine if they are actually possible.



Comment at: clang-tidy/abseil/DurationComparisonCheck.cpp:68
+
+  // We know our map contains all the Scale values, so we can skip the
+  // nonexistence check.

JonasToth wrote:
> The basis for this "we know" might change in the future if `abs::Duration` 
> does things differently. Is adding stuff allowed in the `absl::` space? (i am 
> not fluent with the guarantees that it gives). You could maybe `assert` that 
> the find is always correct, depending on `absl` guarantees.
`absl::` could add things.  In this case, I'm very confident they won't, but 
I've still added the assert.



Comment at: clang-tidy/abseil/DurationComparisonCheck.cpp:108
+
+  // TODO(hwright): Check for another condition:
+  //  1. duration-factory-scale

JonasToth wrote:
> in LLVM the TODO does not contain a name for the author.
I just removed the TODO (this isn't a required part of the check).



Comment at: clang-tidy/abseil/DurationComparisonCheck.cpp:125
+  hasAnyName(
+  "::absl::ToDoubleHours", "::absl::ToDoubleMinutes",
+  "::absl::ToDoubleSeconds", 
"::absl::ToDoubleMilliseconds",

JonasToth wrote:
> the list here is somewhat duplicated with the static members in the functions 
> at the top. it would be best to merge them.
> Not sure on how much `constexpr` is supported by the llvm-datastructures, but 
> a constexpr `DenseMap.keys()` would be nice. Did you try something along this 
> line?
I haven't tried that exact formulation, but given the above issue with 
`DenseMap`, I'm not sure it will work.  Happy to try once we get it ironed out.

Another thing I've thought about is factoring the `functionDecl` matcher into a 
separate function, because I expect it to be reused.  I haven't been able to 
deduce what type that function would return.


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

https://reviews.llvm.org/D54737



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


[PATCH] D54737: [clang-tidy] Add the abseil-duration-comparison check

2018-11-26 Thread Hyrum Wright via Phabricator via cfe-commits
hwright updated this revision to Diff 175379.
hwright marked 23 inline comments as done.

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

https://reviews.llvm.org/D54737

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/abseil/CMakeLists.txt
  clang-tidy/abseil/DurationComparisonCheck.cpp
  clang-tidy/abseil/DurationComparisonCheck.h
  clang-tidy/abseil/DurationDivisionCheck.h
  clang-tidy/abseil/DurationFactoryFloatCheck.cpp
  clang-tidy/abseil/DurationFactoryScaleCheck.cpp
  clang-tidy/abseil/DurationRewriter.cpp
  clang-tidy/abseil/DurationRewriter.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-duration-comparison.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/abseil-duration-comparison.cpp

Index: test/clang-tidy/abseil-duration-comparison.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-duration-comparison.cpp
@@ -0,0 +1,189 @@
+// RUN: %check_clang_tidy %s abseil-duration-comparison %t
+
+// Mimic the implementation of absl::Duration
+namespace absl {
+
+class Duration {};
+class Time{};
+
+Duration Nanoseconds(long long);
+Duration Microseconds(long long);
+Duration Milliseconds(long long);
+Duration Seconds(long long);
+Duration Minutes(long long);
+Duration Hours(long long);
+
+#define GENERATE_DURATION_FACTORY_OVERLOADS(NAME) \
+  Duration NAME(float n); \
+  Duration NAME(double n);\
+  template\
+  Duration NAME(T n);
+
+GENERATE_DURATION_FACTORY_OVERLOADS(Nanoseconds);
+GENERATE_DURATION_FACTORY_OVERLOADS(Microseconds);
+GENERATE_DURATION_FACTORY_OVERLOADS(Milliseconds);
+GENERATE_DURATION_FACTORY_OVERLOADS(Seconds);
+GENERATE_DURATION_FACTORY_OVERLOADS(Minutes);
+GENERATE_DURATION_FACTORY_OVERLOADS(Hours);
+#undef GENERATE_DURATION_FACTORY_OVERLOADS
+
+using int64_t = long long int;
+
+double ToDoubleHours(Duration d);
+double ToDoubleMinutes(Duration d);
+double ToDoubleSeconds(Duration d);
+double ToDoubleMilliseconds(Duration d);
+double ToDoubleMicroseconds(Duration d);
+double ToDoubleNanoseconds(Duration d);
+int64_t ToInt64Hours(Duration d);
+int64_t ToInt64Minutes(Duration d);
+int64_t ToInt64Seconds(Duration d);
+int64_t ToInt64Milliseconds(Duration d);
+int64_t ToInt64Microseconds(Duration d);
+int64_t ToInt64Nanoseconds(Duration d);
+
+// Relational Operators
+constexpr bool operator<(Duration lhs, Duration rhs);
+constexpr bool operator>(Duration lhs, Duration rhs);
+constexpr bool operator>=(Duration lhs, Duration rhs);
+constexpr bool operator<=(Duration lhs, Duration rhs);
+constexpr bool operator==(Duration lhs, Duration rhs);
+constexpr bool operator!=(Duration lhs, Duration rhs);
+
+// Additive Operators
+inline Time operator+(Time lhs, Duration rhs);
+inline Time operator+(Duration lhs, Time rhs);
+inline Time operator-(Time lhs, Duration rhs);
+inline Duration operator-(Time lhs, Time rhs);
+
+}  // namespace absl
+
+void f() {
+  double x;
+  absl::Duration d1, d2;
+  bool b;
+  absl::Time t1, t2;
+
+  // Check against the RHS
+  b = x > absl::ToDoubleSeconds(d1);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) > d1;
+  b = x >= absl::ToDoubleSeconds(d1);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) >= d1;
+  b = x == absl::ToDoubleSeconds(d1);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) == d1;
+  b = x <= absl::ToDoubleSeconds(d1);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) <= d1;
+  b = x < absl::ToDoubleSeconds(d1);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) < d1;
+  b = x == absl::ToDoubleSeconds(t1 - t2);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: absl::Seconds(x) == t1 - t2;
+  b = absl::ToDoubleSeconds(d1) > absl::ToDoubleSeconds(d2);
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: d1 > d2;
+
+  // Check against the LHS
+  b = absl::ToDoubleSeconds(d1) < x;
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: d1 < absl::Seconds(x);
+  b = absl::ToDoubleSeconds(d1) <= x;
+  // CHECK-MESSAGES: [[@LINE-1]]:7: warning: perform duration comparison in the duration domain [abseil-duration-comparison]
+  // CHECK-FIXES: d1 

r347628 - Revert "[clang][slh] add attribute for speculative load hardening"

2018-11-26 Thread Zola Bridges via cfe-commits
Author: zbrid
Date: Mon Nov 26 18:22:00 2018
New Revision: 347628

URL: http://llvm.org/viewvc/llvm-project?rev=347628=rev
Log:
Revert "[clang][slh] add attribute for speculative load hardening"

until I figure out why the build is failing or timing out

***

Summary:
The prior diff had to be reverted because there were two tests
that failed. I updated the two tests in this diff

clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/SemaCXX/attr-speculative-load-hardening.cpp

LLVM IR already has an attribute for speculative_load_hardening. Before
this commit, when a user passed the -mspeculative-load-hardening flag to
Clang, every function would have this attribute added to it. This Clang
attribute will allow users to opt into SLH on a function by function
basis.

This can be applied to functions and Objective C methods.

Reviewers: chandlerc, echristo, kristof.beyls, aaron.ballman

Subscribers: llvm-commits

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

This reverts commit a5b3c232d1e3613f23efbc3960f8e23ea70f2a79.
(r347617)

Removed:
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.m
cfe/trunk/test/SemaCXX/attr-speculative-load-hardening.cpp
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347628=347627=347628=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 18:22:00 2018
@@ -3091,9 +3091,3 @@ def AlwaysDestroy : InheritableAttr {
   let Subjects = SubjectList<[Var]>;
   let Documentation = [AlwaysDestroyDocs];
 }
-
-def SpeculativeLoadHardening : InheritableAttr {
-  let Spellings = [Clang<"speculative_load_hardening">];
-  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
-  let Documentation = [SpeculativeLoadHardeningDocs];
-}

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347628=347627=347628=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 18:22:00 2018
@@ -3629,27 +3629,3 @@ GNU inline semantics are the default beh
 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
   }];
 }
-
-def SpeculativeLoadHardeningDocs : Documentation {
-  let Category = DocCatFunction;
-  let Content = [{
-  This attribute can be applied to a function declaration in order to indicate
-  that `Speculative Load Hardening 
`_
-  should be enabled for the function body. This can also be applied to a method
-  in Objective C.
-
-  Speculative Load Hardening is a best-effort mitigation against
-  information leak attacks that make use of control flow
-  miss-speculation - specifically miss-speculation of whether a branch
-  is taken or not. Typically vulnerabilities enabling such attacks are
-  classified as "Spectre variant #1". Notably, this does not attempt to
-  mitigate against miss-speculation of branch target, classified as
-  "Spectre variant #2" vulnerabilities.
-
-  When inlining, the attribute is sticky. Inlining a function that
-  carries this attribute will cause the caller to gain the
-  attribute. This is intended to provide a maximally conservative model
-  where the code in a function annotated with this attribute will always
-  (even after inlining) end up hardened.
-  }];
-}

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=347628=347627=347628=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Nov 26 18:22:00 2018
@@ -1791,8 +1791,6 @@ void CodeGenModule::ConstructDefaultFnAt
 if (CodeGenOpts.Backchain)
   FuncAttrs.addAttribute("backchain");
 
-// FIXME: The interaction of this attribute with the SLH command line flag
-// has not been determined.
 if (CodeGenOpts.SpeculativeLoadHardening)
   FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
   }
@@ -1856,8 +1854,6 @@ void CodeGenModule::ConstructAttributeLi
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
-if (TargetDecl->hasAttr())
-  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
 
 if (const 

r347627 - [MS] Push fewer DeclContexts for delayed template parsing

2018-11-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Mon Nov 26 18:21:51 2018
New Revision: 347627

URL: http://llvm.org/viewvc/llvm-project?rev=347627=rev
Log:
[MS] Push fewer DeclContexts for delayed template parsing

Only push the outermost record as a DeclContext when parsing a function
body. See the comments in Sema::getContainingDC about the way the parser
pushes contexts. This is intended to match the behavior the parser
normally displays where it parses all method bodies from all nested
classes at the end of the outermost class, when all nested classes are
complete.

Fixes PR38460.

Modified:
cfe/trunk/lib/Parse/ParseTemplate.cpp
cfe/trunk/test/Parser/DelayedTemplateParsing.cpp

Modified: cfe/trunk/lib/Parse/ParseTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseTemplate.cpp?rev=347627=347626=347627=diff
==
--- cfe/trunk/lib/Parse/ParseTemplate.cpp (original)
+++ cfe/trunk/lib/Parse/ParseTemplate.cpp Mon Nov 26 18:21:51 2018
@@ -1382,7 +1382,7 @@ void Parser::ParseLateTemplatedFuncDef(L
   SmallVector TemplateParamScopeStack;
 
   // Get the list of DeclContexts to reenter.
-  SmallVector DeclContextsToReenter;
+  SmallVector DeclContextsToReenter;
   DeclContext *DD = FunD;
   while (DD && !DD->isTranslationUnit()) {
 DeclContextsToReenter.push_back(DD);
@@ -1398,7 +1398,12 @@ void Parser::ParseLateTemplatedFuncDef(L
 unsigned NumParamLists =
   Actions.ActOnReenterTemplateScope(getCurScope(), cast(*II));
 CurTemplateDepthTracker.addDepth(NumParamLists);
-if (*II != FunD) {
+// If we find a class in a class, we need to push the context of the
+// outermost class to match up with how we would parse a regular C++ class
+// inline method.
+if (*II != FunD &&
+!(isa(*II) && isa(Actions.CurContext) &&
+  Actions.CurContext == (*II)->getLexicalParent())) {
   TemplateParamScopeStack.push_back(new ParseScope(this, 
Scope::DeclScope));
   Actions.PushDeclContext(Actions.getCurScope(), *II);
 }

Modified: cfe/trunk/test/Parser/DelayedTemplateParsing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/DelayedTemplateParsing.cpp?rev=347627=347626=347627=diff
==
--- cfe/trunk/test/Parser/DelayedTemplateParsing.cpp (original)
+++ cfe/trunk/test/Parser/DelayedTemplateParsing.cpp Mon Nov 26 18:21:51 2018
@@ -181,3 +181,20 @@ static void h() {
 }
 
 }
+
+struct PR38460 {
+  template 
+  struct T {
+static void foo() {
+  struct U {
+void dummy() {
+  use_delayed_identifier();
+}
+  };
+}
+  };
+};
+void use_delayed_identifier();
+void trigger_PR38460() {
+  PR38460::T::foo();
+}


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


Re: r338941 - [constexpr] Support for constant evaluation of __builtin_memcpy and

2018-11-26 Thread Shoaib Meenai via cfe-commits
Uhh, we have our own build that uses the release branch, but somehow we didn’t 
have that commit in there. Not sure how that happened, but sorry for the noise.

From: cfe-commits  on behalf of Richard 
Smith via cfe-commits 
Reply-To: Richard Smith 
Date: Monday, November 26, 2018 at 12:01 PM
To: Shoaib Meenai 
Cc: cfe-commits , Tom Stellard 
Subject: Re: r338941 - [constexpr] Support for constant evaluation of 
__builtin_memcpy and

On Mon, 26 Nov 2018, 11:50 Richard Smith 
mailto:rich...@metafoo.co.uk> wrote:
On Wed, 21 Nov 2018, 15:32 Shoaib Meenai via cfe-commits 
mailto:cfe-commits@lists.llvm.org> wrote:
If it's not too late, could we have this as part of 7.0.1? (You'll also need to 
cherry-pick the initial reversion in r338602.)

The revert was cherrypicked onto the branch in r338674. Was that not in time 
for 7.0?

Looks like the revert was in fact the very first thing cherrypicked into 
clang's release_70 branch after the branch was cut, so it should certainly have 
been in time for 7.0. Are you sure your clang binary is really the 7.0 release?

I don't think we should take this as a new feature for 7.0.1.

7.0 hits assertion failures for pretty basic memcpy cases on windows-msvc 
targets, and this patch fixes that.

% cat /tmp/reduced.c
void *memcpy(void *, const void *, __SIZE_TYPE__);
void f(int i) {
  struct { int i } s;
  memcpy((char *), , sizeof(i));
}

% clang -cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility -o 
/dev/null /tmp/reduced.c
llvm::SmallVectorTemplateCommon::const_reference 
llvm::SmallVectorTemplateCommon::back() 
const [T = clang::APValue::LValuePathEntry]: Assertion `!empty()' failed.

On Fri, Aug 3, 2018 at 5:57 PM Richard Smith via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:
Author: rsmith
Date: Fri Aug  3 17:57:17 2018
New Revision: 338941

URL: 
http://llvm.org/viewvc/llvm-project?rev=338941=rev
Log:
[constexpr] Support for constant evaluation of __builtin_memcpy and
__builtin_memmove (in non-type-punning cases).

This is intended to permit libc++ to make std::copy etc constexpr
without sacrificing the optimization that uses memcpy on
trivially-copyable types.

__builtin_strcpy and __builtin_wcscpy are not handled by this change.
They'd be straightforward to add, but we haven't encountered a need for
them just yet.

This reinstates r338455, reverted in r338602, with a fix to avoid trying
to constant-evaluate a memcpy call if either pointer operand has an
invalid designator.

Modified:
cfe/trunk/include/clang/Basic/Builtins.def
cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
cfe/trunk/lib/AST/ExprConstant.cpp
cfe/trunk/test/CodeGen/builtin-memfns.c
cfe/trunk/test/SemaCXX/constexpr-string.cpp

Modified: cfe/trunk/include/clang/Basic/Builtins.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338941=338940=338941=diff
==
--- cfe/trunk/include/clang/Basic/Builtins.def (original)
+++ cfe/trunk/include/clang/Basic/Builtins.def Fri Aug  3 17:57:17 2018
@@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
 BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
 BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
 BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
+BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
+BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
 BUILTIN(__builtin_return_address, "v*IUi", "n")
 BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
 BUILTIN(__builtin_frame_address, "v*IUi", "n")
@@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*", "f", "wc
 LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
 LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)
 LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
+LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
+LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)

 // C99
 // In some systems setjmp is a macro that expands to _setjmp. We undefine

Modified: cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
URL: 

[PATCH] D54923: [Modules] Remove non-determinism while serializing DECL_CONTEXT_LEXICAL and DECL_RECORD

2018-11-26 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno created this revision.
bruno added reviewers: rsmith, v.g.vassilev.
Herald added subscribers: dexonsmith, mgrang, jkorous.

A module signature hashes out all relevant content in a module in order
to guarantee that in a dep chain, an inconsistent module never gets
imported. When using implicit modules, clang is capable of rebuilding a
module in case its signature doesn't match what's expected in the
importer. However, when using PCHs + implicit modules, clang cannot
rebuild a imported module with a signature mismatch, since it doesn't
know how to rebuild PCHs.

Non-determinism in the module content, can lead to changes to the
signature of a PCM across compiler invocations that are expected to
produce the same result, causing:

- Build time penalties: rebuilding modules can be expensive.
- Failures: when using PCHs, leads to hard errors one cannot recover

from.

This patch address non-determinism when serializing DECL_CONTEXT_LEXICAL
and DECL_RECORD by sorting the decls by ID (which is supposed to be
deterministic across multiple invocations) prior to writing out the
records. Another approach would be to fix all the places that trigger
adding a Decl to a DeclContext in non deterministic order, but I
couldn't spot any after an audit, but probably didn't look at everything
since the number of different sites and nested calls that do that is
pretty high. Also, by fixing it right before serialization, we enforce
that future changes also don't mess up with the order.

This isn't new, I consistently tracked this behavior in clang all the
way back to 2016, where my testcase stops working for other reasons.

I have no sensible and reduced testcases to add to this patch.

rdar://problem/43442957


https://reviews.llvm.org/D54923

Files:
  lib/Serialization/ASTCommon.h
  lib/Serialization/ASTWriter.cpp


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -3182,7 +3182,16 @@
 
   uint64_t Offset = Stream.GetCurrentBitNo();
   SmallVector KindDeclPairs;
-  for (const auto *D : DC->decls()) {
+
+  // Decls have deterministic IDs, but they might show up in different order in
+  // a DeclContext. Make sure serialization gets the same order everytime by
+  // sorting the decls by ID.
+  SmallVector SortedDecls(DC->decls());
+  llvm::sort(SortedDecls, [](const Decl *L, const Decl *R) {
+return L->getID() < R->getID();
+  });
+
+  for (const auto *D : SortedDecls) {
 KindDeclPairs.push_back(D->getKind());
 KindDeclPairs.push_back(GetDeclRef(D));
   }
Index: lib/Serialization/ASTCommon.h
===
--- lib/Serialization/ASTCommon.h
+++ lib/Serialization/ASTCommon.h
@@ -96,6 +96,7 @@
 template void numberAnonymousDeclsWithin(const DeclContext *DC,
   Fn Visit) {
   unsigned Index = 0;
+  SmallVector DeclsToVisit;
   for (Decl *LexicalD : DC->decls()) {
 // For a friend decl, we care about the declaration within it, if any.
 if (auto *FD = dyn_cast(LexicalD))
@@ -105,8 +106,17 @@
 if (!ND || !needsAnonymousDeclarationNumber(ND))
   continue;
 
-Visit(ND, Index++);
+DeclsToVisit.push_back(ND);
   }
+
+  // Decls have deterministic IDs, but they might show up in different order in
+  // a DeclContext. Make sure serialization gets the same order everytime by
+  // sorting the decls by ID.
+  llvm::sort(DeclsToVisit, [](const NamedDecl *L, const NamedDecl *R) {
+return L->getID() < R->getID();
+  });
+  for (auto *ND : DeclsToVisit)
+Visit(ND, Index++);
 }
 
 } // namespace serialization


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -3182,7 +3182,16 @@
 
   uint64_t Offset = Stream.GetCurrentBitNo();
   SmallVector KindDeclPairs;
-  for (const auto *D : DC->decls()) {
+
+  // Decls have deterministic IDs, but they might show up in different order in
+  // a DeclContext. Make sure serialization gets the same order everytime by
+  // sorting the decls by ID.
+  SmallVector SortedDecls(DC->decls());
+  llvm::sort(SortedDecls, [](const Decl *L, const Decl *R) {
+return L->getID() < R->getID();
+  });
+
+  for (const auto *D : SortedDecls) {
 KindDeclPairs.push_back(D->getKind());
 KindDeclPairs.push_back(GetDeclRef(D));
   }
Index: lib/Serialization/ASTCommon.h
===
--- lib/Serialization/ASTCommon.h
+++ lib/Serialization/ASTCommon.h
@@ -96,6 +96,7 @@
 template void numberAnonymousDeclsWithin(const DeclContext *DC,
   Fn Visit) {
   unsigned Index = 0;
+  SmallVector DeclsToVisit;
   for (Decl *LexicalD : DC->decls()) {
 // For a friend decl, we care about the declaration within it, if 

r347617 - [clang][slh] add attribute for speculative load hardening

2018-11-26 Thread Zola Bridges via cfe-commits
Author: zbrid
Date: Mon Nov 26 16:03:44 2018
New Revision: 347617

URL: http://llvm.org/viewvc/llvm-project?rev=347617=rev
Log:
[clang][slh] add attribute for speculative load hardening

Summary:
The prior diff had to be reverted because there were two tests
that failed. I updated the two tests in this diff

clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/SemaCXX/attr-speculative-load-hardening.cpp

- Summary from Previous Diff (Still Accurate) -

LLVM IR already has an attribute for speculative_load_hardening. Before
this commit, when a user passed the -mspeculative-load-hardening flag to
Clang, every function would have this attribute added to it. This Clang
attribute will allow users to opt into SLH on a function by function basis.

This can be applied to functions and Objective C methods.

Reviewers: chandlerc, echristo, kristof.beyls, aaron.ballman

Subscribers: llvm-commits

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

Added:
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.m
cfe/trunk/test/SemaCXX/attr-speculative-load-hardening.cpp
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347617=347616=347617=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 16:03:44 2018
@@ -3091,3 +3091,9 @@ def AlwaysDestroy : InheritableAttr {
   let Subjects = SubjectList<[Var]>;
   let Documentation = [AlwaysDestroyDocs];
 }
+
+def SpeculativeLoadHardening : InheritableAttr {
+  let Spellings = [Clang<"speculative_load_hardening">];
+  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
+  let Documentation = [SpeculativeLoadHardeningDocs];
+}

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347617=347616=347617=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 16:03:44 2018
@@ -3629,3 +3629,27 @@ GNU inline semantics are the default beh
 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
   }];
 }
+
+def SpeculativeLoadHardeningDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+  This attribute can be applied to a function declaration in order to indicate
+  that `Speculative Load Hardening 
`_
+  should be enabled for the function body. This can also be applied to a method
+  in Objective C.
+
+  Speculative Load Hardening is a best-effort mitigation against
+  information leak attacks that make use of control flow
+  miss-speculation - specifically miss-speculation of whether a branch
+  is taken or not. Typically vulnerabilities enabling such attacks are
+  classified as "Spectre variant #1". Notably, this does not attempt to
+  mitigate against miss-speculation of branch target, classified as
+  "Spectre variant #2" vulnerabilities.
+
+  When inlining, the attribute is sticky. Inlining a function that
+  carries this attribute will cause the caller to gain the
+  attribute. This is intended to provide a maximally conservative model
+  where the code in a function annotated with this attribute will always
+  (even after inlining) end up hardened.
+  }];
+}

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=347617=347616=347617=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Nov 26 16:03:44 2018
@@ -1791,6 +1791,8 @@ void CodeGenModule::ConstructDefaultFnAt
 if (CodeGenOpts.Backchain)
   FuncAttrs.addAttribute("backchain");
 
+// FIXME: The interaction of this attribute with the SLH command line flag
+// has not been determined.
 if (CodeGenOpts.SpeculativeLoadHardening)
   FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
   }
@@ -1854,6 +1856,8 @@ void CodeGenModule::ConstructAttributeLi
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
+if (TargetDecl->hasAttr())
+  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
 
 if (const FunctionDecl *Fn = dyn_cast(TargetDecl)) {
   AddAttributesFromFunctionProtoType(

Modified: 

[PATCH] D53280: [analyzer] Emit an error for invalid -analyzer-config inputs

2018-11-26 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

Polite ping. :) I'd be most comfortable landing D53692 
 together with this patch.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53280



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


[PATCH] D50119: Compiler support for P1144R0 "__is_trivially_relocatable(T)"

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In D50119#1305503 , @Quuxplusone wrote:

> In D50119#1303720 , @rjmccall wrote:
>
> > In D50119#1303662 , @Quuxplusone 
> > wrote:
> >
> > > >> I still believe it is impossible to implement `std::optional` with 
> > > >> only `[[maybe_trivially_relocatable]]`.
> > > > 
> > > > This might also need elaboration.
> > >
> > > Because `__optional_destruct_base` contains an anonymous union member, 
> > > and that union type is not destructible; therefore that union type is not 
> > > trivially relocatable; therefore `__optional_destruct_base` contains a 
> > > member of non-trivially-destructible type. However, I'm working on 
> > > changing my patch to make anonymous unions "see-through" in this respect, 
> > > so that that union's non-destructibility doesn't interfere with the 
> > > `[[maybe_trivially_relocatable]]`ity of its enclosing class type, as long 
> > > as all the members of the //union// are trivially relocatable. This might 
> > > fix `optional`. I'm not sure yet.
> >
> >
> > Ah, that makes sense.  And yeah, that seems like the right rule for unions. 
> >  I really appreciate you putting the effort into exploring this part of the 
> > design space.
>
>
> I think it's part of the right rule, but it's not enough, either. Consider:
>
>   struct [[clang::maybe_trivially_relocatable]] DestroyBase {
>   int i;
>   DestroyBase(DestroyBase&&) = delete;
>   ~DestroyBase();
>   };
>   struct [[clang::maybe_trivially_relocatable]] MoveBase : DestroyBase {
>   MoveBase(MoveBase&&);
>   };
>  
>   static_assert(not std::is_move_constructible_v); //, therefore
>   static_assert(not std::is_relocatable_v); //, therefore
>   static_assert(not std::is_trivially_relocatable_v); //; and 
> since MoveBase now has a base class of non-trivially-relocatable type,
>   static_assert(not std::is_trivially_relocatable_v);
>


Hmm.  I don't remember what we do in this case for `trivial_abi` (which does 
need to address it because it's possible to return types like `DestroyBase`).  
It looks like we currently make it non-trivial.  But trivial-ABI needs to 
consider copy constructors as well as move constructors, which would undermine 
my case that it should be a subset of trivially-relocatability, at least in the 
fantasy world where there are correct types which default their move 
constructors but not their copy constructors or vice-versa.

> So maybe you need a notion like "a class is BlahBlah if all of its direct 
> members are BlahBlah, //and// either it is annotated 
> `[[maybe_trivially_relocatable]]` or else it has no non-defaulted move or 
> destroy operations." And then "a move-constructible, destructible class is 
> trivially relocatable if it is BlahBlah, //or// if it is annotated 
> `[[trivially_relocatable]]`." And then a class like `DestroyBase` can be 
> "BlahBlah but not move-constructible," and if it's placed inside `MoveBase`, 
> and `MoveBase` is //both// annotated and move-constructible, then `MoveBase` 
> becomes trivially relocatable.

I'm completely comfortable with saying that `MoveBase` just isn't 
trivially-relocatable under `maybe_trivially_relocatable` attribute, and if 
you've somehow arranged for it to be, you need to use the stronger attribute.  
In practice types like this either won't exist or won't actually satisfy the 
requirements.  That should allow you to avoid distinguishing between `BlahBlah` 
and `trivially-relocatable`.  As long as the analysis jumps directly down to 
variant members instead of treating anonymous unions as formal subobjects, I 
don't think this will cause serious limitations or usability problems.  Variant 
members are important as a special case only because anonymous unions can't 
really be fixed otherwise, and it's consistent with basically every other 
language rule around construction and destruction.

> The benefit of my original "second-level" `[[trivially_relocatable]]` 
> attribute is that it puts all the responsibility in a single very high-level 
> place. `optional` is the thing that knows exactly when it's trivially 
> relocatable (or at least can make a conservative guess, which might boil down 
> to "I'm never trivially relocatable"), so `optional` is the thing that should 
> get the attribute.

Yes, it's definitely unambiguous what happens with your stronger attribute.

> If I get time today I'll try adding the boolean argument to the attribute, 
> and do the libc++ patches that way for comparison.

Okay.  Sorry for the delayed response, I had last week off.


Repository:
  rC Clang

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

https://reviews.llvm.org/D50119



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


Re: r345099 - [analyzer] Trust summaries for OSObject::retain and OSObject::release

2018-11-26 Thread George Karpenkov via cfe-commits
The error is indeed strange.
The body is declared as

  LazyDeclStmtPtr Body;

where

using LazyDeclStmtPtr =
LazyOffsetPtr;

where

template
struct LazyOffsetPtr {
  mutable uint64_t Ptr = 0;
(…)
  explicit operator bool() const { return Ptr != 0; }
(…)
}

so it does not seem like it can be uninitialized.
Sadly on macOS I don’t have either valgrind or msan,
so I can’t reproduce the failure.
Do you think you could debug further?
Is “Body” indeed uninitialized at use time? (e.g. if you print it..)
A stacktrace from a debug build should be helpful.

Thanks,
George

> On Nov 26, 2018, at 12:03 AM, Mikael Holmén  
> wrote:
> 
> Hi again,
> 
> Do you have any opinion about the below valgrind complaint that starts 
> appearing with this patch?
> 
> valgrind still complains on it on current trunk.
> 
> I see it when compiling with clang 3.6.0. I've also tried gcc 5.4.0 but 
> then I don't get it.
> 
> Regards,
> Mikael
> 
> On 11/21/18 8:33 AM, Mikael Holmén via cfe-commits wrote:
>> Hi George,
>> 
>> I noticed that valgrind started complaining in one case with this patch.
>> 
>> I've no idea if it's really due to something in the patch or if it's
>> something old that surfaced or if it's a false flag.
>> 
>> Anyway, with this patch the following
>> 
>>   valgrind clang-tidy -checks='-*,clang-analyzer-*' 'memcpy.c' -- -O0
>> 
>> gives me
>> 
>> ==18829== Memcheck, a memory error detector
>> ==18829== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
>> ==18829== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
>> ==18829== Command: build-all/bin/clang-tidy -checks=-*,clang-analyzer-*
>> memcpy.c -- -O0
>> ==18829==
>> ==18829== Conditional jump or move depends on uninitialised value(s)
>> ==18829==at 0xE580DF:
>> clang::ento::RetainSummaryManager::canEval(clang::CallExpr const*,
>> clang::FunctionDecl const*, bool&) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xD034AA:
>> clang::ento::retaincountchecker::RetainCountChecker::evalCall(clang::CallExpr
>> const*, clang::ento::CheckerContext&) const (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDCBCD7:
>> clang::ento::CheckerManager::runCheckersForEvalCall(clang::ento::ExplodedNodeSet&,
>> clang::ento::ExplodedNodeSet const&, clang::ento::CallEvent const&,
>> clang::ento::ExprEngine&) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xE033D5:
>> clang::ento::ExprEngine::evalCall(clang::ento::ExplodedNodeSet&,
>> clang::ento::ExplodedNode*, clang::ento::CallEvent const&) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xE03165:
>> clang::ento::ExprEngine::VisitCallExpr(clang::CallExpr const*,
>> clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDE3D9A: clang::ento::ExprEngine::Visit(clang::Stmt
>> const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDDEFD1:
>> clang::ento::ExprEngine::ProcessStmt(clang::Stmt const*,
>> clang::ento::ExplodedNode*) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDDEBBC:
>> clang::ento::ExprEngine::processCFGElement(clang::CFGElement,
>> clang::ento::ExplodedNode*, unsigned int,
>> clang::ento::NodeBuilderContext*) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDD3154:
>> clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*, unsigned
>> int, clang::ento::ExplodedNode*) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xDD24D3:
>> clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext const*,
>> unsigned int, llvm::IntrusiveRefCntPtr)
>> (in /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xB8E90E: (anonymous
>> namespace)::AnalysisConsumer::HandleCode(clang::Decl*, unsigned int,
>> clang::ento::ExprEngine::InliningModes, llvm::DenseSet> const*, llvm::DenseMapInfo >*) (in
>> /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==by 0xB89943: (anonymous
>> namespace)::AnalysisConsumer::HandleTranslationUnit(clang::ASTContext&)
>> (in /data/repo/llvm-patch/build-all/bin/clang-tidy)
>> ==18829==
>> 
>> The call to
>> 
>>  const FunctionDecl* FDD = FD->getDefinition();
>> 
>> in RetainSummaryManager::canEval eventually ends up in
>> 
>>bool isThisDeclarationADefinition() const {
>>  return isDeletedAsWritten() || isDefaulted() || Body ||
>> hasSkippedBody() ||
>> isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
>>}
>> 
>> And here it seems to be the access of "Body" that valgrind complains on.
>> If I simply comment out "Body" the complaint is gone.
>> 
>> I really have no clue about this code, but perhaps this makes some sense
>> to you? Or perhaps to someone else?
>> 
>> Regards,
>> Mikael
>> 
>> On 10/24/18 1:11 AM, George Karpenkov via cfe-commits 

[PATCH] D53076: [analyzer] Enhance ConditionBRVisitor to write out more information

2018-11-26 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso marked 2 inline comments as done.
Charusso added a comment.

@george.karpenkov thanks you for the comments!

In D53076#1308641 , @george.karpenkov 
wrote:

> What about just dropping the `Knowing` prefix?
>  Just having `arr is null, taking true branch` seems considerably more 
> readable.


I wanted to create something identical to the current reports. If we are about 
to change readability, I would change that two first:

- identical operator printing with `<, <=, >...`, so `equal to` is `=` and `not 
equal to` is `!=`.
- emphasize the value information with quotes, so `Assuming 'i' >= '2'`.




Comment at: test/Analysis/uninit-vals.m:324
   testObj->origin = makeIntPoint2D(1, 2);
-  if (testObj->size > 0) { ; } // expected-note{{Taking false branch}}
+  if (testObj->size > 0) { ; } // expected-note{{Assuming 'testObj->size' is 
<= 0}}
// expected-note@-1{{Taking false branch}}

george.karpenkov wrote:
> That does not seem right: from `calloc` the analyzer should know that the 
> `testObj->size` is actually zero.
That `Assuming...` piece is rely on the change between the last two diffs: I 
just print out more `VarDecls` in `patternMatch()`. I thought everything works 
fine, so I will check that problem if @NoQ will not be faster as he already 
found some problematic code piece in that test file.



Comment at: test/Analysis/virtualcall.cpp:170
+   // expected-note-re@-4 ^}}Assuming 'i' is <= 0}}
+   // expected-note-re@-5 ^}}Taking false branch}}
 #endif

george.karpenkov wrote:
> Could you describe what happens here?
> Why the `assuming` notes weren't there before?
We do not have range information in the *newly seen `Assuming...` pieces. 
Because the analyzer has not learnt new information - as there is no 
information - we have not entered to `VisitTrueTest()` to report these. A good 
reference for that new behaviour is in 
`test/Analysis/Inputs/expected-plists/cxx-for-range.cpp.plist`.

*I have added these with https://reviews.llvm.org/D53076?id=175177


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

https://reviews.llvm.org/D53076



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


[PATCH] D54918: Apply clang-format to GenericTaintChecker.cpp

2018-11-26 Thread Borsik Gábor via Phabricator via cfe-commits
boga95 created this revision.
boga95 added a reviewer: gerazo.
boga95 added a project: clang.
Herald added a subscriber: cfe-commits.

I would like to add some patch for this checker later and I found that it isn't 
well formatted.


Repository:
  rC Clang

https://reviews.llvm.org/D54918

Files:
  lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp

Index: lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -28,10 +28,13 @@
 using namespace ento;
 
 namespace {
-class GenericTaintChecker : public Checker< check::PostStmt,
-check::PreStmt > {
+class GenericTaintChecker
+: public Checker, check::PreStmt> {
 public:
-  static void *getTag() { static int Tag; return  }
+  static void *getTag() {
+static int Tag;
+return 
+  }
 
   void checkPostStmt(const CallExpr *CE, CheckerContext ) const;
 
@@ -69,8 +72,8 @@
   static Optional getPointedToSVal(CheckerContext , const Expr *Arg);
 
   /// Functions defining the attack surface.
-  typedef ProgramStateRef (GenericTaintChecker::*FnCheck)(const CallExpr *,
-   CheckerContext ) const;
+  typedef ProgramStateRef (GenericTaintChecker::*FnCheck)(
+  const CallExpr *, CheckerContext ) const;
   ProgramStateRef postScanf(const CallExpr *CE, CheckerContext ) const;
   ProgramStateRef postSocket(const CallExpr *CE, CheckerContext ) const;
   ProgramStateRef postRetTaint(const CallExpr *CE, CheckerContext ) const;
@@ -120,16 +123,15 @@
 
 TaintPropagationRule() {}
 
-TaintPropagationRule(unsigned SArg,
- unsigned DArg, bool TaintRet = false) {
+TaintPropagationRule(unsigned SArg, unsigned DArg, bool TaintRet = false) {
   SrcArgs.push_back(SArg);
   DstArgs.push_back(DArg);
   if (TaintRet)
 DstArgs.push_back(ReturnValueIndex);
 }
 
-TaintPropagationRule(unsigned SArg1, unsigned SArg2,
- unsigned DArg, bool TaintRet = false) {
+TaintPropagationRule(unsigned SArg1, unsigned SArg2, unsigned DArg,
+ bool TaintRet = false) {
   SrcArgs.push_back(SArg1);
   SrcArgs.push_back(SArg2);
   DstArgs.push_back(DArg);
@@ -139,18 +141,17 @@
 
 /// Get the propagation rule for a given function.
 static TaintPropagationRule
-  getTaintPropagationRule(const FunctionDecl *FDecl,
-  StringRef Name,
-  CheckerContext );
+getTaintPropagationRule(const FunctionDecl *FDecl, StringRef Name,
+CheckerContext );
 
 inline void addSrcArg(unsigned A) { SrcArgs.push_back(A); }
-inline void addDstArg(unsigned A)  { DstArgs.push_back(A); }
+inline void addDstArg(unsigned A) { DstArgs.push_back(A); }
 
 inline bool isNull() const { return SrcArgs.empty(); }
 
 inline bool isDestinationArgument(unsigned ArgNum) const {
-  return (std::find(DstArgs.begin(),
-DstArgs.end(), ArgNum) != DstArgs.end());
+  return (std::find(DstArgs.begin(), DstArgs.end(), ArgNum) !=
+  DstArgs.end());
 }
 
 static inline bool isTaintedOrPointsToTainted(const Expr *E,
@@ -169,7 +170,6 @@
 /// Pre-process a function which propagates taint according to the
 /// taint rule.
 ProgramStateRef process(const CallExpr *CE, CheckerContext ) const;
-
   };
 };
 
@@ -177,17 +177,18 @@
 const unsigned GenericTaintChecker::InvalidArgIndex;
 
 const char GenericTaintChecker::MsgUncontrolledFormatString[] =
-  "Untrusted data is used as a format string "
-  "(CWE-134: Uncontrolled Format String)";
+"Untrusted data is used as a format string "
+"(CWE-134: Uncontrolled Format String)";
 
 const char GenericTaintChecker::MsgSanitizeSystemArgs[] =
-  "Untrusted data is passed to a system call "
-  "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
+"Untrusted data is passed to a system call "
+"(CERT/STR02-C. Sanitize data passed to complex subsystems)";
 
 const char GenericTaintChecker::MsgTaintedBufferSize[] =
-  "Untrusted data is used to specify the buffer size "
-  "(CERT/STR31-C. Guarantee that storage for strings has sufficient space for "
-  "character data and the null terminator)";
+"Untrusted data is used to specify the buffer size "
+"(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
+"for "
+"character data and the null terminator)";
 
 } // end of anonymous namespace
 
@@ -199,33 +200,32 @@
 
 GenericTaintChecker::TaintPropagationRule
 GenericTaintChecker::TaintPropagationRule::getTaintPropagationRule(
- const FunctionDecl *FDecl,
- StringRef Name,
-  

[PATCH] D54437: [analyzer][NFC] Merge ClangCheckerRegistry to CheckerRegistry

2018-11-26 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

Polite ping :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D54437



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


[PATCH] D54630: Move detection of libc++ include dirs to Driver on MacOS

2018-11-26 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added 1 blocking reviewer(s): arphaman.
dexonsmith added a comment.

In D54630#1308605 , @arphaman wrote:

> Sounds convincing.
>  @dexonsmith What do you think?


Besides maintaining correct behaviour, I think the most important thing here is 
that the code organization is logical.  Header search is complicated and we 
should be trying to make/keep it simple.  I'm a little skeptical that splitting 
this logic between cc1 and the driver will simplify things, but I haven't 
looked in detail and I'll defer to your (collective) judgement.

> @ilya-biryukov I'm going to do some internal testing to see if we uncover any 
> issues.

I've added you as a blocking reviewer since I think we should work through any 
uncovered issues pre-commit.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54630



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


[PATCH] D53076: [analyzer] Enhance ConditionBRVisitor to write out more information

2018-11-26 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov requested changes to this revision.
george.karpenkov added inline comments.
This revision now requires changes to proceed.



Comment at: test/Analysis/uninit-vals.m:222
   testObj->origin = makeIntPoint(1, 2);
-  if (testObj->size > 0) { ; } // expected-note{{Taking false branch}}
+  if (testObj->size > 0) { ; } // expected-note{{Assuming 'testObj->size' is 
<= 0}}
// expected-note@-1{{Taking false branch}}

Same here: we should know that `testObj->size == 0`



Comment at: test/Analysis/uninit-vals.m:324
   testObj->origin = makeIntPoint2D(1, 2);
-  if (testObj->size > 0) { ; } // expected-note{{Taking false branch}}
+  if (testObj->size > 0) { ; } // expected-note{{Assuming 'testObj->size' is 
<= 0}}
// expected-note@-1{{Taking false branch}}

That does not seem right: from `calloc` the analyzer should know that the 
`testObj->size` is actually zero.



Comment at: test/Analysis/virtualcall.cpp:170
+   // expected-note-re@-4 ^}}Assuming 'i' is <= 0}}
+   // expected-note-re@-5 ^}}Taking false branch}}
 #endif

Could you describe what happens here?
Why the `assuming` notes weren't there before?


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

https://reviews.llvm.org/D53076



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


[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri marked an inline comment as not done.
lebedev.ri added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:198
+assume-aligned-like attributes), `object-size``, and ``vptr`` checks do not
+apply to pointers to types with the ``volatile`` qualifier
 

lebedev.ri wrote:
> rjmccall wrote:
> > lebedev.ri wrote:
> > > rjmccall wrote:
> > > > Is there a reason for this exception?
> > > Are you asking about the LHS of the diff, or about adding an exception to 
> > > that for this sanitizer?
> > > I'm adding an exception here because i don't know what should be done 
> > > here.
> > > Does it make sense to emit an assumptions for volatile pointers, but do 
> > > not sanitize these assumptions?
> > > Are you asking about the LHS of the diff, or about adding an exception to 
> > > that for this sanitizer?
> > 
> > I'm asking about adding a new exception for one portion of one sanitizer.
> > 
> > > I'm adding an exception here because i don't know what should be done 
> > > here.
> > 
> > Okay, that's not a good enough reason.
> > 
> > The overall rule for annotation-based language/tool designs is that 
> > explicit/specific/close wins over implicit/general/distant.  So the 
> > question is: how does that rule apply here?
> > 
> > You can't end up with a pointer to `volatile` completely implicitly — at 
> > some point, a programmer was explicit about requesting `volatile` 
> > semantics, and that has somehow propagated to this particular 
> > access/assumption site.  So that's a pretty strong piece of information, 
> > and if we have a general rule for the sanitizers that `volatile` bypasses 
> > the check, it's generally a good idea to be consistent with that.
> > 
> > On the other hand, these assumption annotations are themselves always 
> > explicit, right?  If you have to be explicit about putting `align_value` on 
> > a specific pointer variable, and that pointer just happens to be 
> > `volatile`-qualified, we probably *shouldn't* bypass the check: that's 
> > about an explicit, specific, and close as a programmer can get, just short 
> > of literally writing it on every access to the variable.  The only 
> > counter-argument is that maybe the pointer is only `volatile`-qualified 
> > because of template instantiation or something.
> > 
> > So I think it makes sense to enforce it for at least some of these 
> > annotations and/or builtin calls, but we should be clear about *why* it 
> > makes sense.  However, it's possible that I may be misunderstanding part of 
> > the motivation behind the general exception for `volatile`, so you should 
> > reach out for input from the UBSan etc. people.
> Tried with nullability attributes https://godbolt.org/z/rJUb9U
> They do not bypass this "ignore volatile".
> So i guess i will drop this exception.
Whoops, i meant `nullable` of course, showed the wrong snippet 
https://godbolt.org/z/DbzKK0


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


[PATCH] D53076: [analyzer] Enhance ConditionBRVisitor to write out more information

2018-11-26 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov added a comment.

This looks more reasonable, thanks!
What about just dropping the `Knowing` prefix?
Just having `arr is null, taking true branch` seems considerably more readable.


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

https://reviews.llvm.org/D53076



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


[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri marked an inline comment as done.
lebedev.ri added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:198
+assume-aligned-like attributes), `object-size``, and ``vptr`` checks do not
+apply to pointers to types with the ``volatile`` qualifier
 

rjmccall wrote:
> lebedev.ri wrote:
> > rjmccall wrote:
> > > Is there a reason for this exception?
> > Are you asking about the LHS of the diff, or about adding an exception to 
> > that for this sanitizer?
> > I'm adding an exception here because i don't know what should be done here.
> > Does it make sense to emit an assumptions for volatile pointers, but do not 
> > sanitize these assumptions?
> > Are you asking about the LHS of the diff, or about adding an exception to 
> > that for this sanitizer?
> 
> I'm asking about adding a new exception for one portion of one sanitizer.
> 
> > I'm adding an exception here because i don't know what should be done here.
> 
> Okay, that's not a good enough reason.
> 
> The overall rule for annotation-based language/tool designs is that 
> explicit/specific/close wins over implicit/general/distant.  So the question 
> is: how does that rule apply here?
> 
> You can't end up with a pointer to `volatile` completely implicitly — at some 
> point, a programmer was explicit about requesting `volatile` semantics, and 
> that has somehow propagated to this particular access/assumption site.  So 
> that's a pretty strong piece of information, and if we have a general rule 
> for the sanitizers that `volatile` bypasses the check, it's generally a good 
> idea to be consistent with that.
> 
> On the other hand, these assumption annotations are themselves always 
> explicit, right?  If you have to be explicit about putting `align_value` on a 
> specific pointer variable, and that pointer just happens to be 
> `volatile`-qualified, we probably *shouldn't* bypass the check: that's about 
> an explicit, specific, and close as a programmer can get, just short of 
> literally writing it on every access to the variable.  The only 
> counter-argument is that maybe the pointer is only `volatile`-qualified 
> because of template instantiation or something.
> 
> So I think it makes sense to enforce it for at least some of these 
> annotations and/or builtin calls, but we should be clear about *why* it makes 
> sense.  However, it's possible that I may be misunderstanding part of the 
> motivation behind the general exception for `volatile`, so you should reach 
> out for input from the UBSan etc. people.
Tried with nullability attributes https://godbolt.org/z/rJUb9U
They do not bypass this "ignore volatile".
So i guess i will drop this exception.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


[PATCH] D54900: [Sema] Avoid CallExpr::setNumArgs in Sema::BuildCallToObjectOfClassType

2018-11-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/Sema/SemaOverload.cpp:13260
 
+  // The number of arguments slots to allocate in the call.
+  // If we have default arguments we need to allocate space for them

arguments -> argument

Also, I think this comment can be re-flowed to condense it.



Comment at: lib/Sema/SemaOverload.cpp:13308
 
-TheCall->setArg(i + 1, Arg);
+MethodArgs[i+1] = Arg;
   }

Formatting is off here.



Comment at: lib/Sema/SemaOverload.cpp:13318
   IsError |= Arg.isInvalid();
-  TheCall->setArg(i + 1, Arg.get());
+  MethodArgs[i+1] = Arg.get();
 }

Here as well.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54900



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


[PATCH] D54630: Move detection of libc++ include dirs to Driver on MacOS

2018-11-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

In D54630#1302566 , @ilya-biryukov 
wrote:

> In D54630#1301283 , @arphaman wrote:
>
> > I don't think we want to move the logic to add a libc++ path to the driver. 
> > `-cc1` with `-resource-dir` and `-stdlib=libc++` should still work as 
> > before. In this case the previous patch is better, except it should not set 
> > `InstalledDir` except when needed (e.g. for tooling when working with a CDB 
> > that has an absolute path to the compiler), so when `InstalledDir` is empty 
> > it should fallback to the current logic in `InitHeaderSearch.cpp`. That 
> > should solve the issues we had.
>
>
> Why not?
>  @ldionne made a good point: there is value in keeping the frontend separate 
> from the logic to detect system libraries and other toolchain-specific things.
>
> This is how other toolchains do it (Linux, etc.). It's more straightforward 
> to the user (one can inspect the -cc1 args produced by the driver), this is 
> where the logic to detect linker dependencies is. It seems that was also the 
> plan of some developers looking in that area: the test I've edited suggests 
> this should be moved to the driver (`darwin-stdlib.cpp`, it says: If and 
> **when** we change to finding them in the driver ...), there's a bug 
> corresponding bug to do this: http://llvm.org/PR30548. 
>  I might not have full information, but my understanding is that 
> `-resource-dir` has a pretty well-defined semantics: it should be used to 
> find the `compiler resources`, i.e. only the buit-in headers and not the C++ 
> standard library.
>
> What are the reasons we need to keep the old behavior?


Sounds convincing.
@dexonsmith What do you think?

@ilya-biryukov I'm going to do some internal testing to see if we uncover any 
issues.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54630



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


[PATCH] D54902: [AST][Sema] Remove CallExpr::setNumArgs

2018-11-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: include/clang/AST/ExprCXX.h:168
 public:
-  CXXMemberCallExpr(ASTContext , Expr *fn, ArrayRef args,
-QualType t, ExprValueKind VK, SourceLocation RP)
-  : CallExpr(C, CXXMemberCallExprClass, fn, args, t, VK, RP) {}
+  CXXMemberCallExpr(ASTContext , Expr *fn, ArrayRef args, QualType t,
+ExprValueKind VK, SourceLocation RP,

Since you're already touching the line, can you correct the names `fn`, `args`, 
and `t` to match our naming conventions?



Comment at: include/clang/AST/ExprCXX.h:212
   CUDAKernelCallExpr(ASTContext , Expr *fn, CallExpr *Config,
- ArrayRef args, QualType t, ExprValueKind VK,
- SourceLocation RP)
-  : CallExpr(C, CUDAKernelCallExprClass, fn, Config, args, t, VK, RP) {}
+ ArrayRef args, QualType t, ExprValueKind VK,
+ SourceLocation RP, unsigned MinNumArgs = 0)

Same here.



Comment at: lib/AST/Expr.cpp:1272
ArrayRef preargs, ArrayRef args, QualType t,
-   ExprValueKind VK, SourceLocation rparenloc)
+   ExprValueKind VK, SourceLocation rparenloc,
+   unsigned MinNumArgs)

If you want to fix these up as well, feel free.



Comment at: lib/Sema/SemaExpr.cpp:5565
+  // Check for a valid function type, but only if it is not a builtin which
+  // requires custom typechecking. These will be handled by
+  // CheckBuiltinFunctionCall below just after creation of the call expression.

typechecking -> type checking



Comment at: lib/Sema/SemaExpr.cpp:5594
+
+  // Get the number of parameter in the function prototype, if any.
+  // We will allocate space for max(Args.size(), NumParams) arguments

parameter -> parameters



Comment at: lib/Sema/SemaExpr.cpp:5607
-  Fn = rewrite.get();
-  TheCall->setCallee(Fn);
-  goto retry;

Why did this go away?



Comment at: lib/Sema/SemaOverload.cpp:12990
   assert(Method && "Member call to something that isn't a method?");
+  const FunctionProtoType *Proto =
+Method->getType()->getAs();

You can use `const auto *` here.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54902



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


[PATCH] D53751: [ASTImporter] Added Import functions for transition to new API.

2018-11-26 Thread Aleksei Sidorin via Phabricator via cfe-commits
a_sidorin accepted this revision.
a_sidorin added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


Repository:
  rC Clang

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

https://reviews.llvm.org/D53751



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


[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:198
+assume-aligned-like attributes), `object-size``, and ``vptr`` checks do not
+apply to pointers to types with the ``volatile`` qualifier
 

lebedev.ri wrote:
> rjmccall wrote:
> > Is there a reason for this exception?
> Are you asking about the LHS of the diff, or about adding an exception to 
> that for this sanitizer?
> I'm adding an exception here because i don't know what should be done here.
> Does it make sense to emit an assumptions for volatile pointers, but do not 
> sanitize these assumptions?
> Are you asking about the LHS of the diff, or about adding an exception to 
> that for this sanitizer?

I'm asking about adding a new exception for one portion of one sanitizer.

> I'm adding an exception here because i don't know what should be done here.

Okay, that's not a good enough reason.

The overall rule for annotation-based language/tool designs is that 
explicit/specific/close wins over implicit/general/distant.  So the question 
is: how does that rule apply here?

You can't end up with a pointer to `volatile` completely implicitly — at some 
point, a programmer was explicit about requesting `volatile` semantics, and 
that has somehow propagated to this particular access/assumption site.  So 
that's a pretty strong piece of information, and if we have a general rule for 
the sanitizers that `volatile` bypasses the check, it's generally a good idea 
to be consistent with that.

On the other hand, these assumption annotations are themselves always explicit, 
right?  If you have to be explicit about putting `align_value` on a specific 
pointer variable, and that pointer just happens to be `volatile`-qualified, we 
probably *shouldn't* bypass the check: that's about an explicit, specific, and 
close as a programmer can get, just short of literally writing it on every 
access to the variable.  The only counter-argument is that maybe the pointer is 
only `volatile`-qualified because of template instantiation or something.

So I think it makes sense to enforce it for at least some of these annotations 
and/or builtin calls, but we should be clear about *why* it makes sense.  
However, it's possible that I may be misunderstanding part of the motivation 
behind the general exception for `volatile`, so you should reach out for input 
from the UBSan etc. people.



Comment at: lib/CodeGen/CodeGenFunction.cpp:2467
+llvm::Value *OffsetValue, llvm::Value *TheCheck,
+llvm::Instruction *Assumption) {
+  assert(Assumption && isa(Assumption) &&

lebedev.ri wrote:
> rjmccall wrote:
> > What's the deal with the two different source locations?
> The first one points to the source-location of this alignment assumption.
> The second one *may* point to the location where the alignment was specified.
> See e.g. 
> "test/ubsan/TestCases/Pointer/alignment-assumption-attribute-align_value-on-lvalue.cpp"
>  in https://reviews.llvm.org/D54590#change-jI44M13yrBNo
I see, so the runtime diagnostic can point to the second location if it's known.

The parameter names do not make that clear at all.  It should at least be 
documented, and you should probably change the variable names to be clearer.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


[PATCH] D54799: [clangd][WIP] textDocument/SymbolInfo method

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous updated this revision to Diff 175314.
jkorous marked an inline comment as done.
jkorous added a comment.

Adressed last comments + initial unit tests.


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

https://reviews.llvm.org/D54799

Files:
  CMakeLists.txt
  ClangdLSPServer.cpp
  ClangdLSPServer.h
  ClangdServer.cpp
  ClangdServer.h
  Protocol.cpp
  Protocol.h
  XRefs.cpp
  XRefs.h
  clangd/CMakeLists.txt
  clangd/SymbolInfoTests.cpp
  clangd/symbol-info.test
  index/Index.cpp
  index/Index.h
  index/SymbolID.cpp
  index/SymbolID.h

Index: clangd/SymbolInfoTests.cpp
===
--- /dev/null
+++ clangd/SymbolInfoTests.cpp
@@ -0,0 +1,166 @@
+//===-- SymbolInfoTests.cpp  ---*- C++ -*--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "Annotations.h"
+#include "ClangdUnit.h"
+#include "Compiler.h"
+#include "Matchers.h"
+#include "SyncAPI.h"
+#include "TestFS.h"
+#include "TestTU.h"
+#include "XRefs.h"
+#include "index/FileIndex.h"
+#include "index/SymbolCollector.h"
+#include "clang/Index/IndexingAction.h"
+#include "llvm/Support/Path.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+namespace clang {
+namespace clangd {
+namespace {
+
+using testing::ElementsAreArray;
+
+auto CreateExpectedSymbolDetails = [](const std::string ,
+  const std::string ,
+  const std::string ) {
+  return SymbolDetails{name, container, USR, SymbolID(USR)};
+};
+
+TEST(SymbolInfoTests, All) {
+  std::pair>
+  TestInputExpectedOutput[] = {
+  {
+R"cpp( // Simple function reference
+  void foo();
+  int bar() { 
+fo^o(); 
+  }
+)cpp",
+{CreateExpectedSymbolDetails("foo", "", "c:@F@foo#")}
+  },
+  {
+R"cpp( // Function in namespace reference 
+  namespace bar {
+void foo();
+int baz() { 
+  fo^o(); 
+}
+  }
+)cpp",
+{CreateExpectedSymbolDetails("foo", "bar::", "c:@N@bar@F@foo#")}
+  },
+  {
+R"cpp( // Function in different namespace reference
+  namespace bar {
+void foo();
+  }
+  namespace barbar {
+int baz() { 
+  bar::fo^o(); 
+}
+  }
+)cpp",
+{CreateExpectedSymbolDetails("foo", "bar::", "c:@N@bar@F@foo#")}
+  },
+  {
+R"cpp( // Function reference - ADL
+  namespace bar {
+struct BarType {};
+void foo(const BarType&);
+  }
+  namespace barbar {
+int baz() {
+  bar::BarType b;
+  fo^o(b); 
+}
+  }
+)cpp",
+{CreateExpectedSymbolDetails("foo", "bar::", "c:@N@bar@F@foo#&1$@N@bar@S@BarType#")}
+  },
+  {
+R"cpp( // Simple value reference
+  int value;
+  void foo(int) { }
+  void bar() { 
+foo(val^ue); 
+  }
+)cpp",
+{CreateExpectedSymbolDetails("value", "", "c:@value")}
+  },
+  {
+R"cpp( // Local value reference
+  void foo() { int aaa; int bbb = aa^a; }
+)cpp",
+{CreateExpectedSymbolDetails("aaa", "foo", "c:TestTU.cpp@49@F@foo#@aaa")}
+  },
+  {
+R"cpp( // Macro reference
+  #define MACRO 5\nint i = MAC^RO;
+)cpp",
+{CreateExpectedSymbolDetails("MACRO", "", "c:TestTU.cpp@55@macro@MACRO")}
+  },
+  {
+R"cpp( // Multiple symbols returned
+  void foo() {}
+  void foo(bool) {}
+  void foo(int) {}
+  namespace bar {
+using ::fo^o;
+  }
+)cpp",
+{
+  CreateExpectedSymbolDetails("foo", "", "c:@F@foo#"),
+  CreateExpectedSymbolDetails("foo", "", "c:@F@foo#b#"),
+  CreateExpectedSymbolDetails("foo", "", "c:@F@foo#I#")
+}
+  },
+  {
+R"cpp( // Multiple symbols returned
+  struct foo {};
+  struct bar {
+bar(const foo&) {}
+  };
+  void func_baz1(bar) {}
+  void func_baz2() {
+foo ff;
+func_baz1(f^f);
+  }
+)cpp",
+{
+  CreateExpectedSymbolDetails("ff", "func_baz2", "c:TestTU.cpp@196@F@func_baz2#@ff"),
+  CreateExpectedSymbolDetails("bar", "bar::", "c:@S@bar@F@bar#&1$@S@foo#"),
+}
+  },
+  {
+R"cpp( // Type definition
+  struct fo^o {};
+)cpp",
+{CreateExpectedSymbolDetails("foo", "", "c:@S@foo")}
+  },
+  };
+
+  for (const auto  : 

[PATCH] D54799: [clangd][WIP] textDocument/SymbolInfo method

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous marked 5 inline comments as done.
jkorous added inline comments.



Comment at: clangd/ClangdServer.cpp:529
+
+  WorkScheduler.runWithAST("CursorInfo", File, Bind(Action, std::move(CB)));
+}

sammccall wrote:
> sammccall wrote:
> > nit: SymbolInfo
> (This still says CursorInfo in the runWithAST call)
I sent my comments first and updated the diff a minute after. You are probably 
just too fast and saw the stale version :)



Comment at: clangd/XRefs.cpp:785
+}
+Results.emplace_back(std::move(NewSymbol));
+  }

sammccall wrote:
> jkorous wrote:
> > sammccall wrote:
> > > nit: push_back (and below)
> > Sure, no problem. I have to admit I thought these two are the same but I 
> > guess you pointed this out because there's a functional difference. I'd 
> > appreciate if you could advise where can I learn the details.
> Here the behavior is identical, so this is really a style thing.
> 
> `emplace_back` is a more powerful function, with semantics "make a new 
> element": it will forward *any* argument list to a constructor of Symbol, 
> selected by overload resolution.
> 
> `push_back` is a more constrained function, with semantics "insert this 
> element": it takes one Symbol and forwards it to the move constructor (or 
> copy constructor, as appropriate).
> 
> They're equivalent here because `emplace_back` can select the 
> move-constructor when passed a single `Symbol&&`. But it communicates intent 
> less clearly, so humans have a harder time (harder to understand the code) as 
> does the compiler (error messages are worse).
Thanks!


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

https://reviews.llvm.org/D54799



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


Re: r347588 - Revert "[clang][slh] add attribute for speculative load hardening"

2018-11-26 Thread Aaron Ballman via cfe-commits
On Mon, Nov 26, 2018 at 3:13 PM Zola Bridges via cfe-commits
 wrote:
>
> Author: zbrid
> Date: Mon Nov 26 12:11:18 2018
> New Revision: 347588
>
> URL: http://llvm.org/viewvc/llvm-project?rev=347588=rev
> Log:
> Revert "[clang][slh] add attribute for speculative load hardening"
>
> This reverts commit 801eaf91221ba6dd6996b29ff82659ad6359e885.

Next time you revert something, can you add an explanation as to why
it was reverted into the commit message? It helps when doing code
archaeology.

Thanks!

~Aaron

>
> Removed:
> cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
> cfe/trunk/test/CodeGen/attr-speculative-load-hardening.m
> cfe/trunk/test/SemaCXX/attr-speculative-load-hardening.cpp
> Modified:
> cfe/trunk/include/clang/Basic/Attr.td
> cfe/trunk/include/clang/Basic/AttrDocs.td
> cfe/trunk/lib/CodeGen/CGCall.cpp
> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
>
> Modified: cfe/trunk/include/clang/Basic/Attr.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347588=347587=347588=diff
> ==
> --- cfe/trunk/include/clang/Basic/Attr.td (original)
> +++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 12:11:18 2018
> @@ -3091,9 +3091,3 @@ def AlwaysDestroy : InheritableAttr {
>let Subjects = SubjectList<[Var]>;
>let Documentation = [AlwaysDestroyDocs];
>  }
> -
> -def SpeculativeLoadHardening : InheritableAttr {
> -  let Spellings = [Clang<"speculative_load_hardening">];
> -  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
> -  let Documentation = [SpeculativeLoadHardeningDocs];
> -}
>
> Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347588=347587=347588=diff
> ==
> --- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
> +++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 12:11:18 2018
> @@ -3629,27 +3629,3 @@ GNU inline semantics are the default beh
>  ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
>}];
>  }
> -
> -def SpeculativeLoadHardeningDocs : Documentation {
> -  let Category = DocCatFunction;
> -  let Content = [{
> -  This attribute can be applied to a function declaration in order to 
> indicate
> -  that `Speculative Load Hardening 
> `_
> -  should be enabled for the function body. This can also be applied to a 
> method
> -  in Objective C.
> -
> -  Speculative Load Hardening is a best-effort mitigation against
> -  information leak attacks that make use of control flow
> -  miss-speculation - specifically miss-speculation of whether a branch
> -  is taken or not. Typically vulnerabilities enabling such attacks are
> -  classified as "Spectre variant #1". Notably, this does not attempt to
> -  mitigate against miss-speculation of branch target, classified as
> -  "Spectre variant #2" vulnerabilities.
> -
> -  When inlining, the attribute is sticky. Inlining a function that
> -  carries this attribute will cause the caller to gain the
> -  attribute. This is intended to provide a maximally conservative model
> -  where the code in a function annotated with this attribute will always
> -  (even after inlining) end up hardened.
> -  }];
> -}
>
> Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=347588=347587=347588=diff
> ==
> --- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Nov 26 12:11:18 2018
> @@ -1791,8 +1791,6 @@ void CodeGenModule::ConstructDefaultFnAt
>  if (CodeGenOpts.Backchain)
>FuncAttrs.addAttribute("backchain");
>
> -// FIXME: The interaction of this attribute with the SLH command line 
> flag
> -// has not been determined.
>  if (CodeGenOpts.SpeculativeLoadHardening)
>FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
>}
> @@ -1856,8 +1854,6 @@ void CodeGenModule::ConstructAttributeLi
>FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
>  if (TargetDecl->hasAttr())
>FuncAttrs.addAttribute(llvm::Attribute::Convergent);
> -if (TargetDecl->hasAttr())
> -  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
>
>  if (const FunctionDecl *Fn = dyn_cast(TargetDecl)) {
>AddAttributesFromFunctionProtoType(
>
> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=347588=347587=347588=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Mon Nov 26 12:11:18 2018
> @@ -6373,9 +6373,6 @@ static 

[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:198
+assume-aligned-like attributes), `object-size``, and ``vptr`` checks do not
+apply to pointers to types with the ``volatile`` qualifier
 

rjmccall wrote:
> Is there a reason for this exception?
Are you asking about the LHS of the diff, or about adding an exception to that 
for this sanitizer?
I'm adding an exception here because i don't know what should be done here.
Does it make sense to emit an assumptions for volatile pointers, but do not 
sanitize these assumptions?



Comment at: lib/CodeGen/CGBuiltin.cpp:1895
 
-EmitAlignmentAssumption(PtrValue, Alignment, OffsetValue);
+EmitAlignmentAssumption(PtrValue, Ptr, {/*The expr loc is sufficient.*/},
+Alignment, OffsetValue);

rjmccall wrote:
> Is this `{}`-initializing a `SourceLocation`?  Please use `SourceLocation()` 
> instead and put the comment before it.
> Is this `{}`-initializing a `SourceLocation`?
Yes

Ok.



Comment at: lib/CodeGen/CodeGenFunction.cpp:2467
+llvm::Value *OffsetValue, llvm::Value *TheCheck,
+llvm::Instruction *Assumption) {
+  assert(Assumption && isa(Assumption) &&

rjmccall wrote:
> What's the deal with the two different source locations?
The first one points to the source-location of this alignment assumption.
The second one *may* point to the location where the alignment was specified.
See e.g. 
"test/ubsan/TestCases/Pointer/alignment-assumption-attribute-align_value-on-lvalue.cpp"
 in https://reviews.llvm.org/D54590#change-jI44M13yrBNo


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


r347588 - Revert "[clang][slh] add attribute for speculative load hardening"

2018-11-26 Thread Zola Bridges via cfe-commits
Author: zbrid
Date: Mon Nov 26 12:11:18 2018
New Revision: 347588

URL: http://llvm.org/viewvc/llvm-project?rev=347588=rev
Log:
Revert "[clang][slh] add attribute for speculative load hardening"

This reverts commit 801eaf91221ba6dd6996b29ff82659ad6359e885.

Removed:
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.m
cfe/trunk/test/SemaCXX/attr-speculative-load-hardening.cpp
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347588=347587=347588=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 12:11:18 2018
@@ -3091,9 +3091,3 @@ def AlwaysDestroy : InheritableAttr {
   let Subjects = SubjectList<[Var]>;
   let Documentation = [AlwaysDestroyDocs];
 }
-
-def SpeculativeLoadHardening : InheritableAttr {
-  let Spellings = [Clang<"speculative_load_hardening">];
-  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
-  let Documentation = [SpeculativeLoadHardeningDocs];
-}

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347588=347587=347588=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 12:11:18 2018
@@ -3629,27 +3629,3 @@ GNU inline semantics are the default beh
 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
   }];
 }
-
-def SpeculativeLoadHardeningDocs : Documentation {
-  let Category = DocCatFunction;
-  let Content = [{
-  This attribute can be applied to a function declaration in order to indicate
-  that `Speculative Load Hardening 
`_
-  should be enabled for the function body. This can also be applied to a method
-  in Objective C.
-
-  Speculative Load Hardening is a best-effort mitigation against
-  information leak attacks that make use of control flow
-  miss-speculation - specifically miss-speculation of whether a branch
-  is taken or not. Typically vulnerabilities enabling such attacks are
-  classified as "Spectre variant #1". Notably, this does not attempt to
-  mitigate against miss-speculation of branch target, classified as
-  "Spectre variant #2" vulnerabilities.
-
-  When inlining, the attribute is sticky. Inlining a function that
-  carries this attribute will cause the caller to gain the
-  attribute. This is intended to provide a maximally conservative model
-  where the code in a function annotated with this attribute will always
-  (even after inlining) end up hardened.
-  }];
-}

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=347588=347587=347588=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Nov 26 12:11:18 2018
@@ -1791,8 +1791,6 @@ void CodeGenModule::ConstructDefaultFnAt
 if (CodeGenOpts.Backchain)
   FuncAttrs.addAttribute("backchain");
 
-// FIXME: The interaction of this attribute with the SLH command line flag
-// has not been determined.
 if (CodeGenOpts.SpeculativeLoadHardening)
   FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
   }
@@ -1856,8 +1854,6 @@ void CodeGenModule::ConstructAttributeLi
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
-if (TargetDecl->hasAttr())
-  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
 
 if (const FunctionDecl *Fn = dyn_cast(TargetDecl)) {
   AddAttributesFromFunctionProtoType(

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=347588=347587=347588=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Mon Nov 26 12:11:18 2018
@@ -6373,9 +6373,6 @@ static void ProcessDeclAttribute(Sema 
   case ParsedAttr::AT_Section:
 handleSectionAttr(S, D, AL);
 break;
-  case ParsedAttr::AT_SpeculativeLoadHardening:
-handleSimpleAttribute(S, D, AL);
-break;
   case ParsedAttr::AT_CodeSeg:
 handleCodeSegAttr(S, D, AL);
 break;

Removed: cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
URL: 

[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:75
   -  ``-fsanitize=alignment``: Use of a misaligned pointer or creation
- of a misaligned reference.
+ of a misaligned reference. Also sanitizes assume-aligned-like attributes.
   -  ``-fsanitize=bool``: Load of a ``bool`` value which is neither

`assume_aligned`-like



Comment at: docs/UndefinedBehaviorSanitizer.rst:198
+assume-aligned-like attributes), `object-size``, and ``vptr`` checks do not
+apply to pointers to types with the ``volatile`` qualifier
 

Is there a reason for this exception?



Comment at: lib/CodeGen/CGBuiltin.cpp:1895
 
-EmitAlignmentAssumption(PtrValue, Alignment, OffsetValue);
+EmitAlignmentAssumption(PtrValue, Ptr, {/*The expr loc is sufficient.*/},
+Alignment, OffsetValue);

Is this `{}`-initializing a `SourceLocation`?  Please use `SourceLocation()` 
instead and put the comment before it.



Comment at: lib/CodeGen/CodeGenFunction.cpp:2467
+llvm::Value *OffsetValue, llvm::Value *TheCheck,
+llvm::Instruction *Assumption) {
+  assert(Assumption && isa(Assumption) &&

What's the deal with the two different source locations?



Comment at: lib/CodeGen/CodeGenFunction.h:2840
+if (isa(E))
+  E = cast(E)->getSubExprAsWritten();
+QualType Ty = E->getType();

`dyn_cast`, please.  And these two methods should really be defined out-of-line.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


Re: r338941 - [constexpr] Support for constant evaluation of __builtin_memcpy and

2018-11-26 Thread Richard Smith via cfe-commits
On Mon, 26 Nov 2018, 11:50 Richard Smith  On Wed, 21 Nov 2018, 15:32 Shoaib Meenai via cfe-commits <
> cfe-commits@lists.llvm.org wrote:
>
>> If it's not too late, could we have this as part of 7.0.1? (You'll also
>> need to cherry-pick the initial reversion in r338602.)
>>
>
> The revert was cherrypicked onto the branch in r338674. Was that not in
> time for 7.0?
>

Looks like the revert was in fact the very first thing cherrypicked into
clang's release_70 branch after the branch was cut, so it should certainly
have been in time for 7.0. Are you sure your clang binary is really the 7.0
release?

I don't think we should take this as a new feature for 7.0.1.
>
> 7.0 hits assertion failures for pretty basic memcpy cases on windows-msvc
>> targets, and this patch fixes that.
>>
>> % cat /tmp/reduced.c
>> void *memcpy(void *, const void *, __SIZE_TYPE__);
>> void f(int i) {
>>   struct { int i } s;
>>   memcpy((char *), , sizeof(i));
>> }
>>
>> % clang -cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility -o
>> /dev/null /tmp/reduced.c
>> llvm::SmallVectorTemplateCommon::const_reference
>> llvm::SmallVectorTemplateCommon> void>::back() const [T = clang::APValue::LValuePathEntry]: Assertion
>> `!empty()' failed.
>>
>> On Fri, Aug 3, 2018 at 5:57 PM Richard Smith via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> Author: rsmith
>>> Date: Fri Aug  3 17:57:17 2018
>>> New Revision: 338941
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=338941=rev
>>> Log:
>>> [constexpr] Support for constant evaluation of __builtin_memcpy and
>>> __builtin_memmove (in non-type-punning cases).
>>>
>>> This is intended to permit libc++ to make std::copy etc constexpr
>>> without sacrificing the optimization that uses memcpy on
>>> trivially-copyable types.
>>>
>>> __builtin_strcpy and __builtin_wcscpy are not handled by this change.
>>> They'd be straightforward to add, but we haven't encountered a need for
>>> them just yet.
>>>
>>> This reinstates r338455, reverted in r338602, with a fix to avoid trying
>>> to constant-evaluate a memcpy call if either pointer operand has an
>>> invalid designator.
>>>
>>> Modified:
>>> cfe/trunk/include/clang/Basic/Builtins.def
>>> cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
>>> cfe/trunk/lib/AST/ExprConstant.cpp
>>> cfe/trunk/test/CodeGen/builtin-memfns.c
>>> cfe/trunk/test/SemaCXX/constexpr-string.cpp
>>>
>>> Modified: cfe/trunk/include/clang/Basic/Builtins.def
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338941=338940=338941=diff
>>>
>>> ==
>>> --- cfe/trunk/include/clang/Basic/Builtins.def (original)
>>> +++ cfe/trunk/include/clang/Basic/Builtins.def Fri Aug  3 17:57:17 2018
>>> @@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
>>>  BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
>>>  BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
>>>  BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
>>> +BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
>>> +BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
>>>  BUILTIN(__builtin_return_address, "v*IUi", "n")
>>>  BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
>>>  BUILTIN(__builtin_frame_address, "v*IUi", "n")
>>> @@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*", "f", "wc
>>>  LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>>  LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)
>>>  LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>> +LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>> +LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>>
>>>  // C99
>>>  // In some systems setjmp is a macro that expands to _setjmp. We
>>> undefine
>>>
>>> Modified: cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td?rev=338941=338940=338941=diff
>>>
>>> ==
>>> --- cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td (original)
>>> +++ cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td Fri Aug  3
>>> 17:57:17 2018
>>> @@ -163,6 +163,20 @@ def note_constexpr_unsupported_unsized_a
>>>  def note_constexpr_unsized_array_indexed : Note<
>>>"indexing of array without known bound is not allowed "
>>>"in a constant expression">;
>>> +def note_constexpr_memcpy_type_pun : Note<
>>> +  "cannot constant evaluate '%select{memcpy|memmove}0' from object of "
>>> +  "type %1 to object of type %2">;
>>> +def note_constexpr_memcpy_nontrivial : Note<
>>> +  "cannot constant evaluate '%select{memcpy|memmove}0' between objects
>>> of "
>>> +  "non-trivially-copyable type %1">;
>>> +def note_constexpr_memcpy_overlap : Note<
>>> +  "'%select{memcpy|wmemcpy}0' between overlapping memory regions">;
>>> +def note_constexpr_memcpy_unsupported : Note<
>>> +  

Re: [cfe-dev] Dumping AST information to other formats

2018-11-26 Thread Aaron Ballman via cfe-commits
On Mon, Nov 26, 2018 at 2:27 PM Keane, Erich via cfe-commits
 wrote:
>
> I'd be tentative to commit to any stability guarantees, particularly as the 
> AST tends to change reasonably often.

Understood. This presupposes that there are stability guarantees to be
made surrounding the information provided by the AST, but I really
think those guarantees exist. We add new things to the AST, but we
rarely remove entire AST nodes or refactor AST nodes such that
critical information is no longer exposed. Most often, we reformulate
how information is exposed in the AST, modify enumerations, change
underlying data types, etc, but that should (ideally) not impact the
output of this feature.

>  That said, I can see the value of this.
>
> Additionally, it would be preferential I suspect if we could make the 
> standard ast-dump just another (albeit default) "format" in whatever plugin 
> architecture you plan.  I presume that would result in a lesser maintenance 
> burden (again, depending on the plugin architecture).

The syntax I was proposing is: -ast-dump, -ast-dump=format where
format can either be "default" or "json" (but maybe someday we decide
we need "xml" or "s-expr", etc). I wasn't envisioning a plugin for
this; I was proposing to modify the existing -ast-dump option to
optionally support specifying the format, then threading that format
information through to the action that dumps the AST out to a file in
order to pick the proper AST dumping interface.

~Aaron

>
> -Original Message-
> From: cfe-dev [mailto:cfe-dev-boun...@lists.llvm.org] On Behalf Of Aaron 
> Ballman via cfe-dev
> Sent: Monday, November 26, 2018 11:20 AM
> To: cfe-dev ; cfe-commits 
> Cc: Eric Schulte 
> Subject: [cfe-dev] Dumping AST information to other formats
>
> Clang currently supports various -cc1 options that allow displaying AST 
> information (-ast-dump, -ast-print, -ast-list, etc), but these options are 
> not convenient to consume by third-party tools. GrammaTech has ongoing 
> research efforts where we would like to output some information from the AST 
> to a more open machine-consumable format (such as JSON or s-expressions). We 
> propose adding an optional output format to the -ast-dump command allowing 
> the user to select from either the default or JSON formats. If the output 
> format is not explicitly specified, it will continue to default to the same 
> textual representation it uses today. e.g., clang -cc1 -ast-dump=json foo.c.
> This feature is intended to output a safe subset of AST information that is 
> considered crucial rather than an implementation detail (like the name of a 
> NamedDecl object and the SourceRange for the name), so the output is expected 
> to be mostly stable between releases.
>
> Once upon a time, there was -ast-print-xml. This -cc1 option was dropped 
> because it was frequently out of sync with the AST data. It is right to ask: 
> why would JSON, etc be any different? This is still an open question, but a 
> goal of this implementation will be to ensure it's easier to maintain as the 
> AST evolves. However, this feature is intended to output a safe subset of AST 
> information, so I don't think this feature will require any more burden to 
> support than -ast-dump already requires (which is extremely limited). If AST 
> information is found to be missing from the output, it seems reasonable to 
> have a discussion as to whether it is stable information or an implementation 
> detail, so missing information is to be expected rather than concerned by. 
> That said, GrammaTech is able to commit to maintaining this code for at least 
> the next 1-2 years and possibly beyond as it useful functionality for our 
> research efforts.
>
> I wanted to see if there were concerns or implementation ideas the community 
> wanted to share before beginning the implementation phase of this feature.
>
> ~Aaron
> ___
> cfe-dev mailing list
> cfe-...@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r338941 - [constexpr] Support for constant evaluation of __builtin_memcpy and

2018-11-26 Thread Richard Smith via cfe-commits
On Wed, 21 Nov 2018, 15:32 Shoaib Meenai via cfe-commits <
cfe-commits@lists.llvm.org wrote:

> If it's not too late, could we have this as part of 7.0.1? (You'll also
> need to cherry-pick the initial reversion in r338602.)
>

The revert was cherrypicked onto the branch in r338674. Was that not in
time for 7.0?

I don't think we should take this as a new feature for 7.0.1.

7.0 hits assertion failures for pretty basic memcpy cases on windows-msvc
> targets, and this patch fixes that.
>
> % cat /tmp/reduced.c
> void *memcpy(void *, const void *, __SIZE_TYPE__);
> void f(int i) {
>   struct { int i } s;
>   memcpy((char *), , sizeof(i));
> }
>
> % clang -cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility -o
> /dev/null /tmp/reduced.c
> llvm::SmallVectorTemplateCommon::const_reference
> llvm::SmallVectorTemplateCommon void>::back() const [T = clang::APValue::LValuePathEntry]: Assertion
> `!empty()' failed.
>
> On Fri, Aug 3, 2018 at 5:57 PM Richard Smith via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: rsmith
>> Date: Fri Aug  3 17:57:17 2018
>> New Revision: 338941
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=338941=rev
>> Log:
>> [constexpr] Support for constant evaluation of __builtin_memcpy and
>> __builtin_memmove (in non-type-punning cases).
>>
>> This is intended to permit libc++ to make std::copy etc constexpr
>> without sacrificing the optimization that uses memcpy on
>> trivially-copyable types.
>>
>> __builtin_strcpy and __builtin_wcscpy are not handled by this change.
>> They'd be straightforward to add, but we haven't encountered a need for
>> them just yet.
>>
>> This reinstates r338455, reverted in r338602, with a fix to avoid trying
>> to constant-evaluate a memcpy call if either pointer operand has an
>> invalid designator.
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/Builtins.def
>> cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
>> cfe/trunk/lib/AST/ExprConstant.cpp
>> cfe/trunk/test/CodeGen/builtin-memfns.c
>> cfe/trunk/test/SemaCXX/constexpr-string.cpp
>>
>> Modified: cfe/trunk/include/clang/Basic/Builtins.def
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338941=338940=338941=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/Builtins.def (original)
>> +++ cfe/trunk/include/clang/Basic/Builtins.def Fri Aug  3 17:57:17 2018
>> @@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
>>  BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
>>  BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
>>  BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
>> +BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
>> +BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
>>  BUILTIN(__builtin_return_address, "v*IUi", "n")
>>  BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
>>  BUILTIN(__builtin_frame_address, "v*IUi", "n")
>> @@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*", "f", "wc
>>  LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>  LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)
>>  LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>> +LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>> +LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>>
>>  // C99
>>  // In some systems setjmp is a macro that expands to _setjmp. We undefine
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td?rev=338941=338940=338941=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td Fri Aug  3
>> 17:57:17 2018
>> @@ -163,6 +163,20 @@ def note_constexpr_unsupported_unsized_a
>>  def note_constexpr_unsized_array_indexed : Note<
>>"indexing of array without known bound is not allowed "
>>"in a constant expression">;
>> +def note_constexpr_memcpy_type_pun : Note<
>> +  "cannot constant evaluate '%select{memcpy|memmove}0' from object of "
>> +  "type %1 to object of type %2">;
>> +def note_constexpr_memcpy_nontrivial : Note<
>> +  "cannot constant evaluate '%select{memcpy|memmove}0' between objects
>> of "
>> +  "non-trivially-copyable type %1">;
>> +def note_constexpr_memcpy_overlap : Note<
>> +  "'%select{memcpy|wmemcpy}0' between overlapping memory regions">;
>> +def note_constexpr_memcpy_unsupported : Note<
>> +  "'%select{%select{memcpy|wmemcpy}1|%select{memmove|wmemmove}1}0' "
>> +  "not supported: %select{"
>> +  "size to copy (%4) is not a multiple of size of element type %3 (%5)|"
>> +  "source is not a contiguous array of at least %4 elements of type %3|"
>> +  "destination is not a contiguous array of at least %4 elements of type
>> %3}2">;
>>
>>  def warn_integer_constant_overflow : Warning<
>>

[PATCH] D54555: [clang][slh] add attribute for speculative load hardening

2018-11-26 Thread Zola Bridges via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347586: [clang][slh] add attribute for speculative load 
hardening (authored by zbrid, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D54555?vs=175306=175308#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D54555

Files:
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  lib/CodeGen/CGCall.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/CodeGen/attr-speculative-load-hardening.cpp
  test/CodeGen/attr-speculative-load-hardening.m
  test/SemaCXX/attr-speculative-load-hardening.cpp

Index: lib/CodeGen/CGCall.cpp
===
--- lib/CodeGen/CGCall.cpp
+++ lib/CodeGen/CGCall.cpp
@@ -1791,6 +1791,8 @@
 if (CodeGenOpts.Backchain)
   FuncAttrs.addAttribute("backchain");
 
+// FIXME: The interaction of this attribute with the SLH command line flag
+// has not been determined.
 if (CodeGenOpts.SpeculativeLoadHardening)
   FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
   }
@@ -1854,6 +1856,8 @@
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
+if (TargetDecl->hasAttr())
+  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
 
 if (const FunctionDecl *Fn = dyn_cast(TargetDecl)) {
   AddAttributesFromFunctionProtoType(
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -6373,6 +6373,9 @@
   case ParsedAttr::AT_Section:
 handleSectionAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_SpeculativeLoadHardening:
+handleSimpleAttribute(S, D, AL);
+break;
   case ParsedAttr::AT_CodeSeg:
 handleCodeSegAttr(S, D, AL);
 break;
Index: include/clang/Basic/AttrDocs.td
===
--- include/clang/Basic/AttrDocs.td
+++ include/clang/Basic/AttrDocs.td
@@ -3629,3 +3629,27 @@
 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
   }];
 }
+
+def SpeculativeLoadHardeningDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+  This attribute can be applied to a function declaration in order to indicate
+  that `Speculative Load Hardening `_
+  should be enabled for the function body. This can also be applied to a method
+  in Objective C.
+
+  Speculative Load Hardening is a best-effort mitigation against
+  information leak attacks that make use of control flow
+  miss-speculation - specifically miss-speculation of whether a branch
+  is taken or not. Typically vulnerabilities enabling such attacks are
+  classified as "Spectre variant #1". Notably, this does not attempt to
+  mitigate against miss-speculation of branch target, classified as
+  "Spectre variant #2" vulnerabilities.
+
+  When inlining, the attribute is sticky. Inlining a function that
+  carries this attribute will cause the caller to gain the
+  attribute. This is intended to provide a maximally conservative model
+  where the code in a function annotated with this attribute will always
+  (even after inlining) end up hardened.
+  }];
+}
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -3091,3 +3091,9 @@
   let Subjects = SubjectList<[Var]>;
   let Documentation = [AlwaysDestroyDocs];
 }
+
+def SpeculativeLoadHardening : InheritableAttr {
+  let Spellings = [Clang<"speculative_load_hardening">];
+  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
+  let Documentation = [SpeculativeLoadHardeningDocs];
+}
Index: test/SemaCXX/attr-speculative-load-hardening.cpp
===
--- test/SemaCXX/attr-speculative-load-hardening.cpp
+++ test/SemaCXX/attr-speculative-load-hardening.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify %s
+
+int i __attribute__((speculative_load_hardening)); // expected-error {{'speculative_load_hardening' attribute only applies to functions}}
+
+void f1() __attribute__((speculative_load_hardening));
+void f2() __attribute__((speculative_load_hardening(1))); // expected-error {{'speculative_load_hardening' attribute takes no arguments}}
+
+template 
+void tf1() __attribute__((speculative_load_hardening));
+
+int f3(int __attribute__((speculative_load_hardening)), int); // expected-error {{'speculative_load_hardening' attribute only applies to functions}}
+
+struct A {
+  int f __attribute__((speculative_load_hardening));  // expected-error {{'speculative_load_hardening' attribute only applies to functions}}
+  void mf1() 

r347586 - [clang][slh] add attribute for speculative load hardening

2018-11-26 Thread Zola Bridges via cfe-commits
Author: zbrid
Date: Mon Nov 26 11:41:14 2018
New Revision: 347586

URL: http://llvm.org/viewvc/llvm-project?rev=347586=rev
Log:
[clang][slh] add attribute for speculative load hardening

Summary:
LLVM IR already has an attribute for speculative_load_hardening. Before
this commit, when a user passed the -mspeculative-load-hardening flag to
Clang, every function would have this attribute added to it. This Clang
attribute will allow users to opt into SLH on a function by function basis.

This can be applied to functions and Objective C methods.

Reviewers: chandlerc, echristo

Subscribers: llvm-commits

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

Added:
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.cpp
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.m
cfe/trunk/test/SemaCXX/attr-speculative-load-hardening.cpp
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347586=347585=347586=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 11:41:14 2018
@@ -3091,3 +3091,9 @@ def AlwaysDestroy : InheritableAttr {
   let Subjects = SubjectList<[Var]>;
   let Documentation = [AlwaysDestroyDocs];
 }
+
+def SpeculativeLoadHardening : InheritableAttr {
+  let Spellings = [Clang<"speculative_load_hardening">];
+  let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
+  let Documentation = [SpeculativeLoadHardeningDocs];
+}

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347586=347585=347586=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 11:41:14 2018
@@ -3629,3 +3629,27 @@ GNU inline semantics are the default beh
 ``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.
   }];
 }
+
+def SpeculativeLoadHardeningDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+  This attribute can be applied to a function declaration in order to indicate
+  that `Speculative Load Hardening 
`_
+  should be enabled for the function body. This can also be applied to a method
+  in Objective C.
+
+  Speculative Load Hardening is a best-effort mitigation against
+  information leak attacks that make use of control flow
+  miss-speculation - specifically miss-speculation of whether a branch
+  is taken or not. Typically vulnerabilities enabling such attacks are
+  classified as "Spectre variant #1". Notably, this does not attempt to
+  mitigate against miss-speculation of branch target, classified as
+  "Spectre variant #2" vulnerabilities.
+
+  When inlining, the attribute is sticky. Inlining a function that
+  carries this attribute will cause the caller to gain the
+  attribute. This is intended to provide a maximally conservative model
+  where the code in a function annotated with this attribute will always
+  (even after inlining) end up hardened.
+  }];
+}

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=347586=347585=347586=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Nov 26 11:41:14 2018
@@ -1791,6 +1791,8 @@ void CodeGenModule::ConstructDefaultFnAt
 if (CodeGenOpts.Backchain)
   FuncAttrs.addAttribute("backchain");
 
+// FIXME: The interaction of this attribute with the SLH command line flag
+// has not been determined.
 if (CodeGenOpts.SpeculativeLoadHardening)
   FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
   }
@@ -1854,6 +1856,8 @@ void CodeGenModule::ConstructAttributeLi
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
+if (TargetDecl->hasAttr())
+  FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
 
 if (const FunctionDecl *Fn = dyn_cast(TargetDecl)) {
   AddAttributesFromFunctionProtoType(

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=347586=347585=347586=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Mon Nov 26 11:41:14 2018
@@ -6373,6 +6373,9 @@ static void ProcessDeclAttribute(Sema 
   case 

[PATCH] D54195: Fix linker option for -fprofile-arcs -ftest-coverage

2018-11-26 Thread Jessica Han via Phabricator via cfe-commits
jessicah added a comment.

I don't have commit permission to Clang review, can somebody commit this for 
me? Thanks, Jessica


Repository:
  rC Clang

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

https://reviews.llvm.org/D54195



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


[PATCH] D41044: Implementation of -fextend-lifetimes and -fextend-this-ptr to aid with debugging of optimized code

2018-11-26 Thread Wolfgang Pieb via Phabricator via cfe-commits
wolfgangp updated this revision to Diff 175307.
wolfgangp added a comment.

Rebased on r347577 with some test cases.


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

https://reviews.llvm.org/D41044

Files:
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGCleanup.cpp
  lib/CodeGen/CGCleanup.h
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.h
  lib/CodeGen/EHScopeStack.h
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/fake-use-determinism.c
  test/CodeGen/fake-use-landingpad.c
  test/CodeGen/fake-use-noreturn.c
  test/CodeGen/fake-use-return-line.c
  test/CodeGen/fake-use-sanitizer.cpp
  test/CodeGen/fake-use-scalar.c
  test/CodeGen/fake-use-while.c
  test/CodeGen/fake-use.cpp
  test/CodeGen/no-fake-use-O0.cpp

Index: test/CodeGen/no-fake-use-O0.cpp
===
--- /dev/null
+++ test/CodeGen/no-fake-use-O0.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 %s -O0 -emit-llvm -fextend-this-ptr -o -  | FileCheck %s
+// RUN: %clang_cc1 %s -O0 -emit-llvm -fextend-lifetimes -o - | FileCheck %s
+// RUN: %clang_cc1 %s -O1 -emit-llvm -fextend-this-ptr -o -  | FileCheck -check-prefix=OPT %s
+// RUN: %clang_cc1 %s -O1 -emit-llvm -fextend-lifetimes -o - | FileCheck -check-prefix=OPT %s
+// RUN: %clang_cc1 %s -Os -emit-llvm -fextend-this-ptr -o -  | FileCheck -check-prefix=OPT %s
+// RUN: %clang_cc1 %s -Os -emit-llvm -fextend-lifetimes -o - | FileCheck -check-prefix=OPT %s
+// RUN: %clang_cc1 %s -Oz -emit-llvm -fextend-this-ptr -o -  | FileCheck -check-prefix=OPT %s
+// RUN: %clang_cc1 %s -Oz -emit-llvm -fextend-lifetimes -o - | FileCheck -check-prefix=OPT %s
+// Check that we do not generate a fake_use call when we are not optimizing. 
+
+extern void bar();
+
+class v
+{
+public:
+int x;
+int y;
+int z;
+int w;
+
+v(int a, int b, int c, int d) : x(a), y(b), z(c), w(d) {}
+};
+
+class w
+{
+public:
+v test(int, int, int, int, int, int, int, int, int, int);
+w(int in): a(in), b(1234) {}
+
+private:
+int a;
+int b;
+};
+
+v w::test(int q, int w, int e, int r, int t, int y, int u, int i, int o, int p)
+{
+// CHECK: define{{.*}}test
+int res = q*w + e - r*t + y*u*i*o*p;
+int res2 = (w + e + r + t + y + o)*(p*q);
+int res3 = res + res2;
+int res4 = q*e + t*y*i + p*e*w * 6 * 4 * 3;
+
+v V(res, res2, res3, res4);
+
+bar();
+// CHECK-NOT: call void (...) @llvm.fake.use
+// OPT:   call void (...) @llvm.fake.use
+return V;
+}
Index: test/CodeGen/fake-use.cpp
===
--- /dev/null
+++ test/CodeGen/fake-use.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 %s -O2 -emit-llvm -fextend-this-ptr -o - | FileCheck %s
+// Check that we generate a fake_use call with the 'this' pointer as argument.
+// The call should appear after the call to bar().
+
+extern void bar();
+
+class v
+{
+public:
+int x;
+int y;
+int z;
+int w;
+
+v(int a, int b, int c, int d) : x(a), y(b), z(c), w(d) {}
+};
+
+class w
+{
+public:
+v test(int, int, int, int, int, int, int, int, int, int);
+w(int in): a(in), b(1234) {}
+
+private:
+int a;
+int b;
+};
+
+v w::test(int q, int w, int e, int r, int t, int y, int u, int i, int o, int p)
+{
+// CHECK: define{{.*}}test
+int res = q*w + e - r*t + y*u*i*o*p;
+int res2 = (w + e + r + t + y + o)*(p*q);
+int res3 = res + res2;
+int res4 = q*e + t*y*i + p*e*w * 6 * 4 * 3;
+
+v V(res, res2, res3, res4);
+
+bar();
+// CHECK: call{{.*}}bar
+// CHECK: call void (...) @llvm.fake.use(%class.w* %this)
+return V;
+// CHECK: ret
+}
Index: test/CodeGen/fake-use-while.c
===
--- /dev/null
+++ test/CodeGen/fake-use-while.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -S -emit-llvm -fextend-lifetimes -o %t.ll
+//
+// Check we don't assert when there is no more code after a while statement
+// and the body of the while statement ends in a return, i.e. no insertion point
+// is available.
+
+// CHECK: define{{.*}}main
+// CHECK: call{{.*}}llvm.fake.use
+
+void foo() {
+  {
+while (1) {
+  int ret;
+  if (1)
+return;
+}
+  }
+}
Index: test/CodeGen/fake-use-scalar.c
===
--- /dev/null
+++ test/CodeGen/fake-use-scalar.c
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -O2 -emit-llvm -fextend-lifetimes -o - | FileCheck %s
+// Make sure we don't generate fake.use for non-scalar 
+// variables.
+
+struct A {
+  unsigned long t;
+  char c[1024];
+  unsigned char r[32];
+};
+
+
+int foo()
+{
+  struct A s;
+  struct A v[128];
+  char c[32];
+  return 0;
+}
+
+// CHECK-NOT:  fake.use
Index: test/CodeGen/fake-use-sanitizer.cpp
===
--- /dev/null
+++ 

RE: [cfe-dev] Dumping AST information to other formats

2018-11-26 Thread Keane, Erich via cfe-commits
I'd be tentative to commit to any stability guarantees, particularly as the AST 
tends to change reasonably often.  That said, I can see the value of this.

Additionally, it would be preferential I suspect if we could make the standard 
ast-dump just another (albeit default) "format" in whatever plugin architecture 
you plan.  I presume that would result in a lesser maintenance burden (again, 
depending on the plugin architecture).  

-Original Message-
From: cfe-dev [mailto:cfe-dev-boun...@lists.llvm.org] On Behalf Of Aaron 
Ballman via cfe-dev
Sent: Monday, November 26, 2018 11:20 AM
To: cfe-dev ; cfe-commits 
Cc: Eric Schulte 
Subject: [cfe-dev] Dumping AST information to other formats

Clang currently supports various -cc1 options that allow displaying AST 
information (-ast-dump, -ast-print, -ast-list, etc), but these options are not 
convenient to consume by third-party tools. GrammaTech has ongoing research 
efforts where we would like to output some information from the AST to a more 
open machine-consumable format (such as JSON or s-expressions). We propose 
adding an optional output format to the -ast-dump command allowing the user to 
select from either the default or JSON formats. If the output format is not 
explicitly specified, it will continue to default to the same textual 
representation it uses today. e.g., clang -cc1 -ast-dump=json foo.c.
This feature is intended to output a safe subset of AST information that is 
considered crucial rather than an implementation detail (like the name of a 
NamedDecl object and the SourceRange for the name), so the output is expected 
to be mostly stable between releases.

Once upon a time, there was -ast-print-xml. This -cc1 option was dropped 
because it was frequently out of sync with the AST data. It is right to ask: 
why would JSON, etc be any different? This is still an open question, but a 
goal of this implementation will be to ensure it's easier to maintain as the 
AST evolves. However, this feature is intended to output a safe subset of AST 
information, so I don't think this feature will require any more burden to 
support than -ast-dump already requires (which is extremely limited). If AST 
information is found to be missing from the output, it seems reasonable to have 
a discussion as to whether it is stable information or an implementation 
detail, so missing information is to be expected rather than concerned by. That 
said, GrammaTech is able to commit to maintaining this code for at least the 
next 1-2 years and possibly beyond as it useful functionality for our research 
efforts.

I wanted to see if there were concerns or implementation ideas the community 
wanted to share before beginning the implementation phase of this feature.

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


Dumping AST information to other formats

2018-11-26 Thread Aaron Ballman via cfe-commits
Clang currently supports various -cc1 options that allow displaying
AST information (-ast-dump, -ast-print, -ast-list, etc), but these
options are not convenient to consume by third-party tools. GrammaTech
has ongoing research efforts where we would like to output some
information from the AST to a more open machine-consumable format
(such as JSON or s-expressions). We propose adding an optional output
format to the -ast-dump command allowing the user to select from
either the default or JSON formats. If the output format is not
explicitly specified, it will continue to default to the same textual
representation it uses today. e.g., clang -cc1 -ast-dump=json foo.c.
This feature is intended to output a safe subset of AST information
that is considered crucial rather than an implementation detail (like
the name of a NamedDecl object and the SourceRange for the name), so
the output is expected to be mostly stable between releases.

Once upon a time, there was -ast-print-xml. This -cc1 option was
dropped because it was frequently out of sync with the AST data. It is
right to ask: why would JSON, etc be any different? This is still an
open question, but a goal of this implementation will be to ensure
it's easier to maintain as the AST evolves. However, this feature is
intended to output a safe subset of AST information, so I don't think
this feature will require any more burden to support than -ast-dump
already requires (which is extremely limited). If AST information is
found to be missing from the output, it seems reasonable to have a
discussion as to whether it is stable information or an implementation
detail, so missing information is to be expected rather than concerned
by. That said, GrammaTech is able to commit to maintaining this code
for at least the next 1-2 years and possibly beyond as it useful
functionality for our research efforts.

I wanted to see if there were concerns or implementation ideas the
community wanted to share before beginning the implementation phase of
this feature.

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


[PATCH] D54195: Fix linker option for -fprofile-arcs -ftest-coverage

2018-11-26 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

@jessicah Please ping this review if you need someone to commit this patch on 
your behalf.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54195



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


[PATCH] D54858: [OpenCL] Improve diagnostics for address spaces in template instantiation

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/Sema/TreeTransform.h:4241
+  if (SemaRef.getLangOpts().OpenCL && T.getType()->isTemplateTypeParmType())
+Quals.removeAddressSpace();
+

When do you actually add the qualifier back?

Also, I don't think this is specific to either OpenCL or direct references to 
template type parameters; it has to be any dependent type.


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

https://reviews.llvm.org/D54858



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


[PATCH] D28462: clang-format: Add new style option AlignConsecutiveMacros

2018-11-26 Thread Erik Nyquist via Phabricator via cfe-commits
enyquist added a comment.

@smilewithani @lassi.niemisto @mewmew feel free to take a stab at it


Repository:
  rL LLVM

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

https://reviews.llvm.org/D28462



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


[PATCH] D53100: clang: Add ARCTargetInfo

2018-11-26 Thread Tatyana Krasnukha via Phabricator via cfe-commits
tatyana-krasnukha updated this revision to Diff 175290.
tatyana-krasnukha added a comment.

Minor change: remove splitting big numeric arguments on 32-bit integers. 
Backend lowering code does this work.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53100

Files:
  lib/Basic/CMakeLists.txt
  lib/Basic/Targets.cpp
  lib/Basic/Targets/ARC.cpp
  lib/Basic/Targets/ARC.h
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/arc/arguments.c
  test/CodeGen/arc/struct-align.c
  test/CodeGen/target-data.c

Index: test/CodeGen/target-data.c
===
--- test/CodeGen/target-data.c
+++ test/CodeGen/target-data.c
@@ -179,6 +179,10 @@
 // RUN: %s | FileCheck %s -check-prefix=ARM-GNU
 // ARM-GNU: target datalayout = "e-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"
 
+// RUN: %clang_cc1 -triple arc-unknown-unknown -o - -emit-llvm %s | \
+// RUN: FileCheck %s -check-prefix=ARC
+// ARC: target datalayout = "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-f32:32:32-i64:32-f64:32-a:0:32-n32"
+
 // RUN: %clang_cc1 -triple hexagon-unknown -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=HEXAGON
 // HEXAGON: target datalayout = "e-m:e-p:32:32:32-a:0-n16:32-i64:64:64-i32:32:32-i16:16:16-i1:8:8-f32:32:32-f64:64:64-v32:32:32-v64:64:64-v512:512:512-v1024:1024:1024-v2048:2048:2048"
Index: test/CodeGen/arc/struct-align.c
===
--- test/CodeGen/arc/struct-align.c
+++ test/CodeGen/arc/struct-align.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple arc-unknown-unknown %s -emit-llvm -o - \
+// RUN:   | FileCheck %s
+
+// 64-bit fields need only be 32-bit aligned for arc.
+
+typedef struct {
+  int aa;
+  double bb;
+} s1;
+
+// CHECK: define i32 @f1
+// CHECK: ret i32 12
+int f1() {
+  return sizeof(s1);
+}
+
+typedef struct {
+  int aa;
+  long long bb;
+} s2;
+// CHECK: define i32 @f2
+// CHECK: ret i32 12
+int f2() {
+  return sizeof(s2);
+}
+
Index: test/CodeGen/arc/arguments.c
===
--- test/CodeGen/arc/arguments.c
+++ test/CodeGen/arc/arguments.c
@@ -0,0 +1,135 @@
+// RUN: %clang_cc1 -triple arc-unknown-unknown %s -emit-llvm -o - \
+// RUN:   | FileCheck %s
+
+// Basic argument tests for ARC.
+
+// CHECK: define void @f0(i32 inreg %i, i32 inreg %j, i64 inreg %k)
+void f0(int i, long j, long long k) {}
+
+typedef struct {
+  int aa;
+  int bb;
+} s1;
+// CHECK: define void @f1(i32 inreg %i.coerce0, i32 inreg %i.coerce1)
+void f1(s1 i) {}
+
+typedef struct {
+  char aa; char bb; char cc; char dd;
+} cs1;
+// CHECK: define void @cf1(i32 inreg %i.coerce)
+void cf1(cs1 i) {}
+
+typedef struct {
+  int cc;
+} s2;
+// CHECK: define void @f2(%struct.s2* noalias sret %agg.result)
+s2 f2() {
+  s2 foo;
+  return foo;
+}
+
+typedef struct {
+  int cc;
+  int dd;
+} s3;
+// CHECK: define void @f3(%struct.s3* noalias sret %agg.result)
+s3 f3() {
+  s3 foo;
+  return foo;
+}
+
+// CHECK: define void @f4(i64 inreg %i)
+void f4(long long i) {}
+
+// CHECK: define void @f5(i8 inreg signext %a, i16 inreg signext %b)
+void f5(signed char a, short b) {}
+
+// CHECK: define void @f6(i8 inreg zeroext %a, i16 inreg zeroext %b)
+void f6(unsigned char a, unsigned short b) {}
+
+enum my_enum {
+  ENUM1,
+  ENUM2,
+  ENUM3,
+};
+// Enums should be treated as the underlying i32.
+// CHECK: define void @f7(i32 inreg %a)
+void f7(enum my_enum a) {}
+
+enum my_big_enum {
+  ENUM4 = 0x,
+};
+// Big enums should be treated as the underlying i64.
+// CHECK: define void @f8(i64 inreg %a)
+void f8(enum my_big_enum a) {}
+
+union simple_union {
+  int a;
+  char b;
+};
+// Unions should be passed inreg.
+// CHECK: define void @f9(i32 inreg %s.coerce)
+void f9(union simple_union s) {}
+
+typedef struct {
+  int b4 : 4;
+  int b3 : 3;
+  int b8 : 8;
+} bitfield1;
+// Bitfields should be passed inreg.
+// CHECK: define void @f10(i32 inreg %bf1.coerce)
+void f10(bitfield1 bf1) {}
+
+// CHECK: define inreg { float, float } @cplx1(float inreg %r)
+_Complex float cplx1(float r) {
+  return r + 2.0fi;
+}
+
+// CHECK: define inreg { double, double } @cplx2(double inreg %r)
+_Complex double cplx2(double r) {
+  return r + 2.0i;
+}
+
+// CHECK: define inreg { i32, i32 } @cplx3(i32 inreg %r)
+_Complex int cplx3(int r) {
+  return r + 2i;
+}
+
+// CHECK: define inreg { i64, i64 } @cplx4(i64 inreg %r)
+_Complex long long cplx4(long long r) {
+  return r + 2i;
+}
+
+// CHECK: define inreg { i8, i8 } @cplx6(i8 inreg signext %r)
+_Complex signed char cplx6(signed char r) {
+  return r + 2i;
+}
+
+// CHECK: define inreg { i16, i16 } @cplx7(i16 inreg signext %r)
+_Complex short cplx7(short r) {
+  return r + 2i;
+}
+
+typedef struct {
+  int aa; int bb;
+} s8;
+
+typedef struct {
+  int aa; int bb; int cc; int dd;
+} s16;
+
+// Use 16-byte struct 2 times, gets 8 registers.
+void st2(s16 a, s16 b) {}
+// 

r347583 - [OPENMP][NVPTX]Emit default locations with the correct Exec|Runtime

2018-11-26 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Mon Nov 26 10:37:09 2018
New Revision: 347583

URL: http://llvm.org/viewvc/llvm-project?rev=347583=rev
Log:
[OPENMP][NVPTX]Emit default locations with the correct Exec|Runtime
modes.

If the region is inside target|teams|distribute region, we can emit the
locations with the correct info for execution mode and runtime mode.
Patch adds this ability to the NVPTX codegen to help the optimizer to
produce better code.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
cfe/trunk/test/OpenMP/nvptx_SPMD_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_printf_codegen.c

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=347583=347582=347583=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Mon Nov 26 10:37:09 2018
@@ -148,19 +148,35 @@ public:
 /// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
 /// to the target region and used by containing directives such as 'parallel'
 /// to emit optimized code.
-class ExecutionModeRAII {
+class ExecutionRuntimeModesRAII {
 private:
-  CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
-  CGOpenMPRuntimeNVPTX::ExecutionMode 
+  CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
+  CGOpenMPRuntimeNVPTX::EM_Unknown;
+  CGOpenMPRuntimeNVPTX::ExecutionMode 
+  bool SavedRuntimeMode = false;
+  bool *RuntimeMode = nullptr;
 
 public:
-  ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode , bool IsSPMD)
-  : Mode(Mode) {
-SavedMode = Mode;
-Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
-  : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
+  /// Constructor for Non-SPMD mode.
+  ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode )
+  : ExecMode(ExecMode) {
+SavedExecMode = ExecMode;
+ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
+  }
+  /// Constructor for SPMD mode.
+  ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode ,
+bool , bool FullRuntimeMode)
+  : ExecMode(ExecMode), RuntimeMode() {
+SavedExecMode = ExecMode;
+SavedRuntimeMode = RuntimeMode;
+ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
+RuntimeMode = FullRuntimeMode;
+  }
+  ~ExecutionRuntimeModesRAII() {
+ExecMode = SavedExecMode;
+if (RuntimeMode)
+  *RuntimeMode = SavedRuntimeMode;
   }
-  ~ExecutionModeRAII() { Mode = SavedMode; }
 };
 
 /// GPU Configuration:  This information can be derived from cuda registers,
@@ -1187,7 +1203,7 @@ void CGOpenMPRuntimeNVPTX::emitNonSPMDKe
  llvm::Constant *,
  bool IsOffloadEntry,
  const RegionCodeGenTy ) {
-  ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
+  ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
   EntryFunctionState EST;
   WorkerFunctionState WST(CGM, D.getBeginLoc());
   Work.clear();
@@ -1319,7 +1335,10 @@ void CGOpenMPRuntimeNVPTX::emitSPMDKerne
   llvm::Constant *,
   bool IsOffloadEntry,
   const RegionCodeGenTy ) {
-  ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
+  ExecutionRuntimeModesRAII ModeRAII(
+  CurrentExecutionMode, RequiresFullRuntime,
+  CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
+  !supportsLightweightRuntime(CGM.getContext(), D));
   EntryFunctionState EST;
 
   // Emit target region as a standalone region.
@@ -1370,9 +1389,6 @@ void CGOpenMPRuntimeNVPTX::emitSPMDEntry
   llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
   EST.ExitBB = CGF.createBasicBlock(".exit");
 
-  // Initialize the OMP state in the runtime; called by all active threads.
-  bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
- !supportsLightweightRuntime(CGF.getContext(), D);
   llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
  /*RequiresOMPRuntime=*/
  Bld.getInt16(RequiresFullRuntime ? 1 : 0),
@@ -1919,7 +1935,18 @@ static const ModeFlagsTy UndefinedMode =
 } // anonymous namespace
 
 unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
-  return UndefinedMode;
+  switch (getExecutionMode()) {
+  case EM_SPMD:
+if (requiresFullRuntime())
+  return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
+return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
+  case EM_NonSPMD:
+assert(requiresFullRuntime() && "Expected full runtime.");
+return (~KMP_IDENT_SPMD_MODE) & 

[PATCH] D53738: [Fixed Point Arithmetic] Fixed Point Addition

2018-11-26 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan marked an inline comment as done.
leonardchan added a comment.

> Generally I think it's good! One final note; I assume we could technically 
> reuse/rename the EmitFixedPointAdd function and use it to emit other binops 
> when those are added?

Yes, but I imagine if we choose to keep the call to `EmitFixedPointConversion` 
to cast both operands to a common type, this wouldn't be reused for division or 
multiplication since I believe those do not require for the operands to be 
converted to a common type.




Comment at: clang/test/Frontend/fixed_point_add.c:269
+  // UNSIGNED-NEXT: [[SUM:%[0-9]+]] = call i15 @llvm.uadd.sat.i15(i15 
[[USA_TRUNC]], i15 [[USA_SAT_TRUNC]])
+  // UNSIGNED-NEXT: [[SUM_EXT:%[a-z0-9]+]] = zext i15 [[SUM]] to i16
+  // UNSIGNED-NEXT: store i16 [[SUM_EXT]], i16* %usa_sat, align 2

ebevhan wrote:
> leonardchan wrote:
> > ebevhan wrote:
> > > This is probably a candidate for an isel optimization. This operation 
> > > also works as an `i16 ssat.add` with a negative-clamp-to-zero afterwards, 
> > > and if the target supports `i16 ssat.add` natively then it will likely be 
> > > a lot more efficient than whatever an `i15 uadd.sat` produces.
> > Do you think it would be more efficient for now then if instead we did SHL 
> > by 1, saturate, then [AL]SHR by 1? This way we could use `i16 ssat.add` 
> > instead of `i15 ssat.add`?
> We should probably just do it in isel or instcombine instead. We don't know 
> at this point which intrinsic is a better choice (though, I think 
> power-of-two-types are generally better).
Ok. Are you suggesting something should be changed here though? I imagine that 
during legalization, `i15 ssat.add` would be legalized into `i16 ssat.add` if 
that is what's natively supported.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53738



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


r347571 - [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread Sander de Smalen via cfe-commits
Author: s.desmalen
Date: Mon Nov 26 08:38:37 2018
New Revision: 347571

URL: http://llvm.org/viewvc/llvm-project?rev=347571=rev
Log:
[AArch64] Add aarch64_vector_pcs function attribute to Clang

This is the Clang patch to complement the following LLVM patches:
  https://reviews.llvm.org/D51477
  https://reviews.llvm.org/D51479

More information describing the vector ABI and procedure call standard
can be found here:

https://developer.arm.com/products/software-development-tools/\
  hpc/arm-compiler-for-hpc/vector-function-abi

Patch by Kerry McLaughlin.

Reviewed By: rjmccall

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

Added:
cfe/trunk/test/CodeGen/aarch64-vpcs.c
cfe/trunk/test/Sema/aarch64-vpcs.c
Modified:
cfe/trunk/include/clang-c/Index.h
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/Specifiers.h
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/Type.cpp
cfe/trunk/lib/AST/TypePrinter.cpp
cfe/trunk/lib/Basic/Targets/AArch64.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/test/Sema/callingconv.c
cfe/trunk/tools/libclang/CXType.cpp

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=347571=347570=347571=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Mon Nov 26 08:38:37 2018
@@ -3336,6 +3336,7 @@ enum CXCallingConv {
   CXCallingConv_Swift = 13,
   CXCallingConv_PreserveMost = 14,
   CXCallingConv_PreserveAll = 15,
+  CXCallingConv_AArch64VectorCall = 16,
 
   CXCallingConv_Invalid = 100,
   CXCallingConv_Unexposed = 200

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=347571=347570=347571=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Mon Nov 26 08:38:37 2018
@@ -1785,6 +1785,11 @@ def Pcs : DeclOrTypeAttr {
   let Documentation = [PcsDocs];
 }
 
+def AArch64VectorPcs: DeclOrTypeAttr {
+  let Spellings = [Clang<"aarch64_vector_pcs">];
+  let Documentation = [AArch64VectorPcsDocs];
+}
+
 def Pure : InheritableAttr {
   let Spellings = [GCC<"pure">];
   let Documentation = [Undocumented];

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=347571=347570=347571=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Mon Nov 26 08:38:37 2018
@@ -1742,6 +1742,31 @@ similar to ``stdcall`` on x86. Valid par
   }];
 }
 
+def AArch64VectorPcsDocs : Documentation {
+  let Category = DocCatCallingConvs;
+  let Content = [{
+On AArch64 targets, this attribute changes the calling convention of a
+function to preserve additional floating-point and Advanced SIMD registers
+relative to the default calling convention used for AArch64.
+
+This means it is more efficient to call such functions from code that performs
+extensive floating-point and vector calculations, because fewer live SIMD and 
FP
+registers need to be saved. This property makes it well-suited for e.g.
+floating-point or vector math library functions, which are typically leaf
+functions that require a small number of registers.
+
+However, using this attribute also means that it is more expensive to call
+a function that adheres to the default calling convention from within such
+a function. Therefore, it is recommended that this attribute is only used
+for leaf functions.
+
+For more information, see the documentation for `aarch64_vector_pcs`_ on
+the Arm Developer website.
+
+.. _`aarch64_vector_pcs`: 
https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi
+  }];
+}
+
 def RegparmDocs : Documentation {
   let Category = DocCatCallingConvs;
   let Content = [{

Modified: cfe/trunk/include/clang/Basic/Specifiers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Specifiers.h?rev=347571=347570=347571=diff
==
--- cfe/trunk/include/clang/Basic/Specifiers.h (original)
+++ cfe/trunk/include/clang/Basic/Specifiers.h Mon Nov 26 08:38:37 2018
@@ -251,6 +251,7 @@ namespace clang {
 CC_Swift,// __attribute__((swiftcall))
 CC_PreserveMost, // __attribute__((preserve_most))
 CC_PreserveAll,  // __attribute__((preserve_all))
+CC_AArch64VectorCall, // __attribute__((aarch64_vector_pcs))
   };
 
   /// Checks 

[PATCH] D54763: [clang][slh] Forward mSLH only to Clang CC1

2018-11-26 Thread Zola Bridges via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347582: [clang][slh] Forward mSLH only to Clang CC1 
(authored by zbrid, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D54763?vs=174813=175286#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D54763

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/CodeGen/attr-speculative-load-hardening.c


Index: test/CodeGen/attr-speculative-load-hardening.c
===
--- test/CodeGen/attr-speculative-load-hardening.c
+++ test/CodeGen/attr-speculative-load-hardening.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -mspeculative-load-hardening -disable-llvm-passes 
-emit-llvm %s -o - | FileCheck %s -check-prefix=SLH
+// RUN: %clang -mno-speculative-load-hardening -S -emit-llvm %s -o - | 
FileCheck %s -check-prefix=NOSLH
 //
 // Check that we set the attribute on each function.
 
@@ -8,3 +9,7 @@
 // SLH: @{{.*}}test1{{.*}}[[SLH:#[0-9]+]]
 
 // SLH: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
+
+// NOSLH: @{{.*}}test1{{.*}}[[NOSLH:#[0-9]+]]
+
+// NOSLH-NOT: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -4452,8 +4452,9 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_pthread);
 
-  Args.AddLastArg(CmdArgs, options::OPT_mspeculative_load_hardening,
-  options::OPT_mno_speculative_load_hardening);
+  if (Args.hasFlag(options::OPT_mspeculative_load_hardening, 
options::OPT_mno_speculative_load_hardening,
+   false))
+CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
 


Index: test/CodeGen/attr-speculative-load-hardening.c
===
--- test/CodeGen/attr-speculative-load-hardening.c
+++ test/CodeGen/attr-speculative-load-hardening.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -mspeculative-load-hardening -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s -check-prefix=SLH
+// RUN: %clang -mno-speculative-load-hardening -S -emit-llvm %s -o - | FileCheck %s -check-prefix=NOSLH
 //
 // Check that we set the attribute on each function.
 
@@ -8,3 +9,7 @@
 // SLH: @{{.*}}test1{{.*}}[[SLH:#[0-9]+]]
 
 // SLH: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
+
+// NOSLH: @{{.*}}test1{{.*}}[[NOSLH:#[0-9]+]]
+
+// NOSLH-NOT: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -4452,8 +4452,9 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_pthread);
 
-  Args.AddLastArg(CmdArgs, options::OPT_mspeculative_load_hardening,
-  options::OPT_mno_speculative_load_hardening);
+  if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
+   false))
+CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r347582 - [clang][slh] Forward mSLH only to Clang CC1

2018-11-26 Thread Zola Bridges via cfe-commits
Author: zbrid
Date: Mon Nov 26 10:13:31 2018
New Revision: 347582

URL: http://llvm.org/viewvc/llvm-project?rev=347582=rev
Log:
[clang][slh] Forward mSLH only to Clang CC1

Summary:
-mno-speculative-load-hardening isn't a cc1 option, therefore,
before this change:

clang -mno-speculative-load-hardening hello.cpp

would have the following error:

error: unknown argument: '-mno-speculative-load-hardening'

This change will only ever forward -mspeculative-load-hardening
which is a CC1 option based on which flag was passed to clang.

Also added a test that uses this option that fails if an error like the
above is ever thrown.

Thank you ericwf for help debugging and fixing this error.

Reviewers: chandlerc, EricWF

Subscribers: llvm-commits

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/test/CodeGen/attr-speculative-load-hardening.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=347582=347581=347582=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Nov 26 10:13:31 2018
@@ -4452,8 +4452,9 @@ void Clang::ConstructJob(Compilation ,
 
   Args.AddLastArg(CmdArgs, options::OPT_pthread);
 
-  Args.AddLastArg(CmdArgs, options::OPT_mspeculative_load_hardening,
-  options::OPT_mno_speculative_load_hardening);
+  if (Args.hasFlag(options::OPT_mspeculative_load_hardening, 
options::OPT_mno_speculative_load_hardening,
+   false))
+CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
 

Modified: cfe/trunk/test/CodeGen/attr-speculative-load-hardening.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-speculative-load-hardening.c?rev=347582=347581=347582=diff
==
--- cfe/trunk/test/CodeGen/attr-speculative-load-hardening.c (original)
+++ cfe/trunk/test/CodeGen/attr-speculative-load-hardening.c Mon Nov 26 
10:13:31 2018
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -mspeculative-load-hardening -disable-llvm-passes 
-emit-llvm %s -o - | FileCheck %s -check-prefix=SLH
+// RUN: %clang -mno-speculative-load-hardening -S -emit-llvm %s -o - | 
FileCheck %s -check-prefix=NOSLH
 //
 // Check that we set the attribute on each function.
 
@@ -8,3 +9,7 @@ int test1() {
 // SLH: @{{.*}}test1{{.*}}[[SLH:#[0-9]+]]
 
 // SLH: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }
+
+// NOSLH: @{{.*}}test1{{.*}}[[NOSLH:#[0-9]+]]
+
+// NOSLH-NOT: attributes [[SLH]] = { {{.*}}speculative_load_hardening{{.*}} }


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


[PATCH] D54845: [clangd] Canonicalize file path in URIForFile.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/Protocol.h:73
+
+  /// \p AbsPath is resolved to a canonical path corresponding to its URI.
+  URIForFile(llvm::StringRef AbsPath, llvm::StringRef HintPath = "");

We need to document the APIs and motivation, these are subtle.



Comment at: clangd/Protocol.h:74
+  /// \p AbsPath is resolved to a canonical path corresponding to its URI.
+  URIForFile(llvm::StringRef AbsPath, llvm::StringRef HintPath = "");
+

I think it's no longer sufficiently clear what this constructor does - it 
should be a named factory function, and the HintPath should be required.
(If it's easy to implicitly skip canonicalization, then there's no advantage of 
changing URIForFile vs just asking people to canonicalize the inputs)

e.g. `URIForFile URIForFile::canonicalize(StringRef AbsPath, StringRef 
HintPath)`



Comment at: clangd/Protocol.h:74
+  /// \p AbsPath is resolved to a canonical path corresponding to its URI.
+  URIForFile(llvm::StringRef AbsPath, llvm::StringRef HintPath = "");
+

sammccall wrote:
> I think it's no longer sufficiently clear what this constructor does - it 
> should be a named factory function, and the HintPath should be required.
> (If it's easy to implicitly skip canonicalization, then there's no advantage 
> of changing URIForFile vs just asking people to canonicalize the inputs)
> 
> e.g. `URIForFile URIForFile::canonicalize(StringRef AbsPath, StringRef 
> HintPath)`
As we're exposing HintPath in more far-flung places, its semantics are becoming 
less obvious.

I think we should make them more concrete, e.g. rename to `TUPath` and doc like
```
Files can be referred to by several paths (e.g. in the presence of links).
Which one we prefer may depend on where we're coming from.
TUPath is a hint, and should usually be the main entrypoint file we're 
processing.
```



Comment at: clangd/Protocol.h:98
 private:
+  explicit URIForFile(std::string &) : File(std::move(File)) {}
+

Are there really *no* cases where the caller doesn't need canonicalization?



Comment at: clangd/URI.cpp:235
+Expected URI::resolvePath(StringRef AbsPath, StringRef HintPath) {
+  auto U = create(AbsPath);
+  // "file" scheme doesn't do anything fancy; it would resolve to the same

this seems pretty indirect - including the call to create(), this function 
special-cases File 3 times.

Seems a little cleaner to me to remove "file" from the registry, and repeat the 
loop here. Up to you.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54845



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


r347577 - [NFC] Replace magic numbers with CodeGenOpt enums

2018-11-26 Thread Sam Parker via cfe-commits
Author: sam_parker
Date: Mon Nov 26 09:26:49 2018
New Revision: 347577

URL: http://llvm.org/viewvc/llvm-project?rev=347577=rev
Log:
[NFC] Replace magic numbers with CodeGenOpt enums

Use enum values from llvm/Support/CodeGen.h for the optimisation
levels in CompilerInvocation.

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

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=347577=347576=347577=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Mon Nov 26 09:26:49 2018
@@ -120,25 +120,25 @@ CompilerInvocationBase::~CompilerInvocat
 
 static unsigned getOptimizationLevel(ArgList , InputKind IK,
  DiagnosticsEngine ) {
-  unsigned DefaultOpt = 0;
+  unsigned DefaultOpt = llvm::CodeGenOpt::None;
   if (IK.getLanguage() == InputKind::OpenCL && 
!Args.hasArg(OPT_cl_opt_disable))
-DefaultOpt = 2;
+DefaultOpt = llvm::CodeGenOpt::Default;
 
   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
 if (A->getOption().matches(options::OPT_O0))
-  return 0;
+  return llvm::CodeGenOpt::None;
 
 if (A->getOption().matches(options::OPT_Ofast))
-  return 3;
+  return llvm::CodeGenOpt::Aggressive;
 
 assert(A->getOption().matches(options::OPT_O));
 
 StringRef S(A->getValue());
 if (S == "s" || S == "z" || S.empty())
-  return 2;
+  return llvm::CodeGenOpt::Default;
 
 if (S == "g")
-  return 1;
+  return llvm::CodeGenOpt::Less;
 
 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
   }


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


[PATCH] D54905: [AddressSanitizer] Add flag to disable linking with CXX runtime

2018-11-26 Thread Eugene Leviant via Phabricator via cfe-commits
evgeny777 created this revision.
evgeny777 added reviewers: kcc, samsonov.

This prevents link errors when operators new/delete are overridden by 
application.


https://reviews.llvm.org/D54905

Files:
  include/clang/Driver/Options.td
  lib/Driver/SanitizerArgs.cpp
  test/Driver/sanitizer-ld.c


Index: test/Driver/sanitizer-ld.c
===
--- test/Driver/sanitizer-ld.c
+++ test/Driver/sanitizer-ld.c
@@ -115,6 +115,12 @@
 // CHECK-ASAN-LINUX-CXX-STATIC: "--whole-archive" 
"{{.*}}libclang_rt.asan-i386.a" "--no-whole-archive"
 // CHECK-ASAN-LINUX-CXX-STATIC: stdc++
 
+// RUN: %clangxx -x c++ %s -### -o /dev/null -fsanitize=address 
-fno-sanitize-link-c++-runtime \
+// RUN: -target i386-unknown-linux -fuse-ld=ld 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-NO-LINK-CXX-RUNTIME %s
+//
+// CHECK-ASAN-NO-LINK-CXX-RUNTIME-NOT: asan_cxx
+
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-gnueabi -fuse-ld=ld -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
Index: lib/Driver/SanitizerArgs.cpp
===
--- lib/Driver/SanitizerArgs.cpp
+++ lib/Driver/SanitizerArgs.cpp
@@ -743,7 +743,8 @@
 
   // Parse -link-cxx-sanitizer flag.
   LinkCXXRuntimes =
-  Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
+  Args.hasFlag(options::OPT_fsanitize_link_cxx_runtime,
+   options::OPT_fno_sanitize_link_cxx_runtime, D.CCCIsCXX());
 
   // Finally, initialize the set of available and recoverable sanitizers.
   Sanitizers.Mask |= Kinds;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1015,6 +1015,8 @@
 Group;
 def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
  Group;
+def fno_sanitize_link_cxx_runtime : Flag<["-"], 
"fno-sanitize-link-c++-runtime">,
+ Group;
 def fsanitize_cfi_cross_dso : Flag<["-"], "fsanitize-cfi-cross-dso">,
   Group,
   HelpText<"Enable control flow integrity (CFI) 
checks for cross-DSO calls.">;


Index: test/Driver/sanitizer-ld.c
===
--- test/Driver/sanitizer-ld.c
+++ test/Driver/sanitizer-ld.c
@@ -115,6 +115,12 @@
 // CHECK-ASAN-LINUX-CXX-STATIC: "--whole-archive" "{{.*}}libclang_rt.asan-i386.a" "--no-whole-archive"
 // CHECK-ASAN-LINUX-CXX-STATIC: stdc++
 
+// RUN: %clangxx -x c++ %s -### -o /dev/null -fsanitize=address -fno-sanitize-link-c++-runtime \
+// RUN: -target i386-unknown-linux -fuse-ld=ld 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-NO-LINK-CXX-RUNTIME %s
+//
+// CHECK-ASAN-NO-LINK-CXX-RUNTIME-NOT: asan_cxx
+
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-gnueabi -fuse-ld=ld -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
Index: lib/Driver/SanitizerArgs.cpp
===
--- lib/Driver/SanitizerArgs.cpp
+++ lib/Driver/SanitizerArgs.cpp
@@ -743,7 +743,8 @@
 
   // Parse -link-cxx-sanitizer flag.
   LinkCXXRuntimes =
-  Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
+  Args.hasFlag(options::OPT_fsanitize_link_cxx_runtime,
+   options::OPT_fno_sanitize_link_cxx_runtime, D.CCCIsCXX());
 
   // Finally, initialize the set of available and recoverable sanitizers.
   Sanitizers.Mask |= Kinds;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1015,6 +1015,8 @@
 Group;
 def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
  Group;
+def fno_sanitize_link_cxx_runtime : Flag<["-"], "fno-sanitize-link-c++-runtime">,
+ Group;
 def fsanitize_cfi_cross_dso : Flag<["-"], "fsanitize-cfi-cross-dso">,
   Group,
   HelpText<"Enable control flow integrity (CFI) checks for cross-DSO calls.">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347574 - [clangd] Do not drop diagnostics from macros

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 09:05:13 2018
New Revision: 347574

URL: http://llvm.org/viewvc/llvm-project?rev=347574=rev
Log:
[clangd] Do not drop diagnostics from macros

if they still end up being in the main file.

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

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=347574=347573=347574=diff
==
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Mon Nov 26 09:05:13 2018
@@ -79,7 +79,7 @@ Range diagnosticRange(const clang::Diagn
 }
 
 bool isInsideMainFile(const SourceLocation Loc, const SourceManager ) {
-  return Loc.isValid() && M.isWrittenInMainFile(Loc);
+  return Loc.isValid() && M.isWrittenInMainFile(M.getFileLoc(Loc));
 }
 
 bool isInsideMainFile(const clang::Diagnostic ) {

Modified: clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp?rev=347574=347573=347574=diff
==
--- clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp Mon Nov 26 
09:05:13 2018
@@ -159,7 +159,9 @@ TEST(DiagnosticsTest, ClangTidy) {
"macro expansion [bugprone-macro-repeated-side-effects]"),
   WithNote(Diag(Test.range("macrodef"),
 "macro 'SQUARE' defined here "
-"[bugprone-macro-repeated-side-effects]");
+"[bugprone-macro-repeated-side-effects]"))),
+  Diag(Test.range("macroarg"),
+   "multiple unsequenced modifications to 'y'")));
 }
 
 TEST(DiagnosticsTest, Preprocessor) {
@@ -181,6 +183,27 @@ TEST(DiagnosticsTest, Preprocessor) {
   ElementsAre(Diag(Test.range(), "use of undeclared identifier 'b'")));
 }
 
+TEST(DiagnosticsTest, InsideMacros) {
+  Annotations Test(R"cpp(
+#define TEN 10
+#define RET(x) return x + 10
+
+int* foo() {
+  RET($foo[[0]]);
+}
+int* bar() {
+  return $bar[[TEN]];
+}
+)cpp");
+  EXPECT_THAT(TestTU::withCode(Test.code()).build().getDiagnostics(),
+  ElementsAre(Diag(Test.range("foo"),
+   "cannot initialize return object of type "
+   "'int *' with an rvalue of type 'int'"),
+  Diag(Test.range("bar"),
+   "cannot initialize return object of type "
+   "'int *' with an rvalue of type 'int'")));
+}
+
 TEST(DiagnosticsTest, ToLSP) {
   clangd::Diag D;
   D.Message = "something terrible happened";


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


[PATCH] D54796: [clangd] C++ API for emitting file status

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

> It would be reasonable to be consistent with diagnostics: stop emitting the 
> statuses when ASTWorker was put into shutdown mode.

Thanks, sounds fair.




Comment at: clangd/ClangdServer.h:39
 
+// FIXME: find a better name.
 class DiagnosticsConsumer {

jkorous wrote:
> It would be unfortunate to have this name clashing with 
> `clang::DiagnosticsConsumer` indeed.
> How about something like `FileEventConsumer`?
yeah, I plan to rename it later (when the patch gets stable enough). 
`FileEventConsumer` is a candidate.



Comment at: clangd/TUScheduler.cpp:367
   IdleASTs.take(this);
+  FStatus.messages.push_back("fail to build CompilerInvocation;");
+  Callbacks.onFileUpdated(FStatus);

jkorous wrote:
> Wouldn't some different failure status like `FileStatusKind::FailedBuild` be 
> appropriate here?
The failure status is grouped into `FileStatus::messages`. I think `messages` 
provide enough information to users (if there are something wrong when building 
the file).


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54796



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


[PATCH] D54796: [clangd] C++ API for emitting file status

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 175277.
hokein marked 2 inline comments as done.
hokein added a comment.
Herald added a subscriber: jfb.

stop emitting file status when ASTworker is shutting down.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54796

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -44,6 +44,8 @@
 
 namespace {
 
+MATCHER_P(FileState, State, "") { return arg.kind == State; }
+
 bool diagsContainErrors(const std::vector ) {
   for (auto D : Diagnostics) {
 if (D.Severity == DiagnosticsEngine::Error ||
@@ -154,6 +156,64 @@
   }
 };
 
+TEST_F(ClangdVFSTest, FileStatus) {
+  class CaptureFileStatus : public DiagnosticsConsumer {
+  public:
+void onDiagnosticsReady(PathRef File,
+std::vector Diagnostics) override {}
+
+void onFileUpdated(const FileStatus ) override {
+  std::lock_guard Lock(Mutex);
+  AllStatus.push_back(FStatus);
+}
+
+std::vector AllStatus;
+
+  private:
+std::mutex Mutex;
+  } CaptureFStatus;
+  MockFSProvider FS;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, CaptureFStatus, ClangdServer::optsForTest());
+  Server.addDocument(testPath("foo.cpp"), "int main() {}",
+ WantDiagnostics::Yes);
+  ASSERT_TRUE(Server.blockUntilIdleForTest());
+
+  EXPECT_THAT(CaptureFStatus.AllStatus,
+  ElementsAre(FileState(FileStatusKind::Queued),
+  FileState(FileStatusKind::BuildingPreamble),
+  FileState(FileStatusKind::BuildingFile),
+  FileState(FileStatusKind::Ready)));
+}
+
+TEST_F(ClangdVFSTest, NoFileStatusEmittedForRemovedFile) {
+  class CaptureFileStatus : public DiagnosticsConsumer {
+  public:
+void onDiagnosticsReady(PathRef File,
+std::vector Diagnostics) override {}
+
+void onFileUpdated(const FileStatus ) override {
+  ASSERT_TRUE(FirstRequest)
+  << "Expected to see exacly one file status updated.";
+  if (FirstRequest) {
+ASSERT_TRUE(FStatus.kind == FileStatusKind::Queued);
+FirstRequest = false;
+// We wait long enough that the document gets removed.
+std::this_thread::sleep_for(std::chrono::milliseconds(50));
+  }
+}
+std::atomic FirstRequest = {true};
+  } CaptureFStatus;
+  MockFSProvider FS;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, CaptureFStatus, ClangdServer::optsForTest());
+  Server.addDocument(testPath("foo.cpp"), "int main() {}",
+ WantDiagnostics::Yes);
+  Server.removeDocument(testPath("foo.cpp"));
+  ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for finishing";
+  ASSERT_TRUE(!CaptureFStatus.FirstRequest);
+}
+
 TEST_F(ClangdVFSTest, Parse) {
   // FIXME: figure out a stable format for AST dumps, so that we can check the
   // output of the dump itself is equal to the expected one, not just that it's
Index: clangd/TUScheduler.h
===
--- clangd/TUScheduler.h
+++ clangd/TUScheduler.h
@@ -75,6 +75,9 @@
 
   /// Called whenever the diagnostics for \p File are produced.
   virtual void onDiagnostics(PathRef File, std::vector Diags) {}
+
+  /// Called whenever the file status is updated.
+  virtual void onFileUpdated(const FileStatus ) {}
 };
 
 /// Handles running tasks for ClangdServer and managing the resources (e.g.,
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -251,13 +251,18 @@
   bool Done;/* GUARDED_BY(Mutex) */
   std::deque Requests; /* GUARDED_BY(Mutex) */
   mutable std::condition_variable RequestsCV;
-  /// Guards a critical section for running the diagnostics callbacks. 
+  /// Guards a critical section for running the diagnostics callbacks.
   std::mutex DiagsMu;
   // Used to prevent remove document + leading to out-of-order diagnostics:
   // The lifetime of the old/new ASTWorkers will overlap, but their handles
   // don't. When the old handle is destroyed, the old worker will stop reporting
   // diagnostics.
   bool ReportDiagnostics = true; /* GUARDED_BY(DiagMu) */
+  /// Guards a critical section for running the file status callbacks.
+  std::mutex FileStatusMu;
+  // Similar to ReportDiagnostics, used to prevent remove document + emitting
+  // out-of-order file status.
+  bool ReportFileStatus = true; /* GUARDED_BY(FileStatusMu) */
 };
 
 /// A smart-pointer-like class that 

[PATCH] D54425: [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347571: [AArch64] Add aarch64_vector_pcs function attribute 
to Clang (authored by s.desmalen, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D54425

Files:
  include/clang-c/Index.h
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/Specifiers.h
  lib/AST/ItaniumMangle.cpp
  lib/AST/Type.cpp
  lib/AST/TypePrinter.cpp
  lib/Basic/Targets/AArch64.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGDebugInfo.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaType.cpp
  test/CodeGen/aarch64-vpcs.c
  test/Sema/aarch64-vpcs.c
  test/Sema/callingconv.c
  tools/libclang/CXType.cpp

Index: lib/CodeGen/CGCall.cpp
===
--- lib/CodeGen/CGCall.cpp
+++ lib/CodeGen/CGCall.cpp
@@ -59,6 +59,7 @@
   case CC_X86Pascal: return llvm::CallingConv::C;
   // TODO: Add support for __vectorcall to LLVM.
   case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
+  case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
   case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
   case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
   case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
@@ -214,6 +215,9 @@
   if (PcsAttr *PCS = D->getAttr())
 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
 
+  if (D->hasAttr())
+return CC_AArch64VectorCall;
+
   if (D->hasAttr())
 return CC_IntelOclBicc;
 
Index: lib/CodeGen/CGDebugInfo.cpp
===
--- lib/CodeGen/CGDebugInfo.cpp
+++ lib/CodeGen/CGDebugInfo.cpp
@@ -1102,6 +1102,7 @@
   case CC_X86_64SysV:
 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
   case CC_AAPCS:
+  case CC_AArch64VectorCall:
 return llvm::dwarf::DW_CC_LLVM_AAPCS;
   case CC_AAPCS_VFP:
 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Index: lib/AST/TypePrinter.cpp
===
--- lib/AST/TypePrinter.cpp
+++ lib/AST/TypePrinter.cpp
@@ -861,6 +861,9 @@
 case CC_AAPCS_VFP:
   OS << " __attribute__((pcs(\"aapcs-vfp\")))";
   break;
+case CC_AArch64VectorCall:
+  OS << "__attribute__((aarch64_vector_pcs))";
+  break;
 case CC_IntelOclBicc:
   OS << " __attribute__((intel_ocl_bicc))";
   break;
@@ -1492,7 +1495,7 @@
OS << ')';
break;
   }
-
+  case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
   case attr::IntelOclBicc: OS << "inteloclbicc"; break;
   case attr::PreserveMost:
 OS << "preserve_most";
Index: lib/AST/Type.cpp
===
--- lib/AST/Type.cpp
+++ lib/AST/Type.cpp
@@ -2824,6 +2824,7 @@
   case CC_X86RegCall : return "regcall";
   case CC_AAPCS: return "aapcs";
   case CC_AAPCS_VFP: return "aapcs-vfp";
+  case CC_AArch64VectorCall: return "aarch64_vector_pcs";
   case CC_IntelOclBicc: return "intel_ocl_bicc";
   case CC_SpirFunction: return "spir_function";
   case CC_OpenCLKernel: return "opencl_kernel";
@@ -3216,6 +3217,7 @@
   case attr::RegCall:
   case attr::SwiftCall:
   case attr::VectorCall:
+  case attr::AArch64VectorPcs:
   case attr::Pascal:
   case attr::MSABI:
   case attr::SysVABI:
Index: lib/AST/ItaniumMangle.cpp
===
--- lib/AST/ItaniumMangle.cpp
+++ lib/AST/ItaniumMangle.cpp
@@ -2659,6 +2659,7 @@
   case CC_X86RegCall:
   case CC_AAPCS:
   case CC_AAPCS_VFP:
+  case CC_AArch64VectorCall:
   case CC_IntelOclBicc:
   case CC_SpirFunction:
   case CC_OpenCLKernel:
Index: lib/Sema/SemaType.cpp
===
--- lib/Sema/SemaType.cpp
+++ lib/Sema/SemaType.cpp
@@ -116,6 +116,7 @@
   case ParsedAttr::AT_Pascal:  \
   case ParsedAttr::AT_SwiftCall:   \
   case ParsedAttr::AT_VectorCall:  \
+  case ParsedAttr::AT_AArch64VectorPcs:\
   case ParsedAttr::AT_MSABI:   \
   case ParsedAttr::AT_SysVABI: \
   case ParsedAttr::AT_Pcs: \
@@ -6653,6 +6654,8 @@
 return createSimpleAttr(Ctx, Attr);
   case ParsedAttr::AT_VectorCall:
 return createSimpleAttr(Ctx, Attr);
+  case ParsedAttr::AT_AArch64VectorPcs:
+return createSimpleAttr(Ctx, Attr);
   case ParsedAttr::AT_Pcs: {
 // The attribute may have had a fixit applied where we treated an
 // identifier as a string literal.  The contents of the string are valid,
Index: lib/Sema/SemaDeclAttr.cpp

[PATCH] D54903: [WIP][Sema] Improve static_assert diagnostics.

2018-11-26 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
Herald added a subscriber: cfe-commits.

`static_assert(std::is_same::value, "message")` now prints the
value of U and V.


Repository:
  rC Clang

https://reviews.llvm.org/D54903

Files:
  lib/Sema/SemaTemplate.cpp
  test/SemaCXX/static-assert.cpp


Index: test/SemaCXX/static-assert.cpp
===
--- test/SemaCXX/static-assert.cpp
+++ test/SemaCXX/static-assert.cpp
@@ -68,3 +68,27 @@
 };
 
 static_assert(first_trait::value && second_trait::value, "message"); // 
expected-error{{static_assert failed due to requirement 
'second_trait::value' "message"}}
+
+namespace std {
+
+template 
+struct is_same {
+  static const bool value = false;
+};
+
+template 
+struct is_same {
+  static const bool value = true;
+};
+
+} // namespace std
+
+struct ExampleTypes {
+  using T = int;
+  using U = float;
+};
+
+template 
+class StaticAssertIsSame {
+  static_assert(std::is_same::value, 
"message"); // expected-error{{static_assert failed due to requirement 'int and 
float are the same type' "message"}}
+};
Index: lib/Sema/SemaTemplate.cpp
===
--- lib/Sema/SemaTemplate.cpp
+++ lib/Sema/SemaTemplate.cpp
@@ -3052,6 +3052,48 @@
   return Cond;
 }
 
+// Pretty prints std::is_same as 'U and V are the same types'.
+static void
+prettyPrintFailedIsSameCondition(llvm::raw_string_ostream ,
+ const RecordDecl *Decl,
+ const PrintingPolicy ) {
+  const auto *const TmplDecl = dyn_cast(Decl);
+  assert(TmplDecl &&
+ "std::is_same should be a ClassTemplateSpecializationDecl");
+  const auto  = TmplDecl->getTemplateArgs();
+  assert(Args.size() == 2 && "std::is_same should have 2 template parameters");
+  Args.get(0).getAsType().print(OS, PrintPolicy);
+  OS << " and ";
+  Args.get(1).getAsType().print(OS, PrintPolicy);
+  OS << " are the same type";
+}
+
+// Print a diagnostic for the failing static_assert expression. Defaults to
+// pretty-printing the expression.
+static void
+prettyPrintFailedBooleanCondition(llvm::raw_string_ostream ,
+  const Expr *const FailedCond,
+  const PrintingPolicy ) {
+  if (const auto *const DR = dyn_cast(FailedCond)) {
+const auto *const Var = dyn_cast(DR->getDecl());
+if (Var && Var->isStaticDataMember() && Var->getName() == "value") {
+  const NestedNameSpecifier *const Qualifier = Var->getQualifier();
+  // This might be an std type trait.
+  const auto *const Record = Qualifier->getAsRecordDecl();
+  const auto *const Parent = Qualifier->getPrefix();
+  if (Parent && Parent->getPrefix() &&
+  Parent->getPrefix()->getKind() == NestedNameSpecifier::Global &&
+  Parent->getAsNamespace() &&
+  Parent->getAsNamespace()->getName() == "std" &&
+  Record->getName() == "is_same") {
+prettyPrintFailedIsSameCondition(OS, Record, PrintPolicy);
+return;
+  }
+}
+  }
+  FailedCond->printPretty(OS, nullptr, PrintPolicy);
+}
+
 std::pair
 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
   Cond = lookThroughRangesV3Condition(PP, Cond);
@@ -3093,7 +3135,7 @@
   std::string Description;
   {
 llvm::raw_string_ostream Out(Description);
-FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
+prettyPrintFailedBooleanCondition(Out, FailedCond, getPrintingPolicy());
   }
   return { FailedCond, Description };
 }


Index: test/SemaCXX/static-assert.cpp
===
--- test/SemaCXX/static-assert.cpp
+++ test/SemaCXX/static-assert.cpp
@@ -68,3 +68,27 @@
 };
 
 static_assert(first_trait::value && second_trait::value, "message"); // expected-error{{static_assert failed due to requirement 'second_trait::value' "message"}}
+
+namespace std {
+
+template 
+struct is_same {
+  static const bool value = false;
+};
+
+template 
+struct is_same {
+  static const bool value = true;
+};
+
+} // namespace std
+
+struct ExampleTypes {
+  using T = int;
+  using U = float;
+};
+
+template 
+class StaticAssertIsSame {
+  static_assert(std::is_same::value, "message"); // expected-error{{static_assert failed due to requirement 'int and float are the same type' "message"}}
+};
Index: lib/Sema/SemaTemplate.cpp
===
--- lib/Sema/SemaTemplate.cpp
+++ lib/Sema/SemaTemplate.cpp
@@ -3052,6 +3052,48 @@
   return Cond;
 }
 
+// Pretty prints std::is_same as 'U and V are the same types'.
+static void
+prettyPrintFailedIsSameCondition(llvm::raw_string_ostream ,
+ const RecordDecl *Decl,
+ const PrintingPolicy ) {
+  const auto *const TmplDecl = dyn_cast(Decl);
+  assert(TmplDecl &&
+ "std::is_same should be a ClassTemplateSpecializationDecl");
+  const 

[clang-tools-extra] r347570 - [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via cfe-commits
Author: gchatelet
Date: Mon Nov 26 08:25:55 2018
New Revision: 347570

URL: http://llvm.org/viewvc/llvm-project?rev=347570=rev
Log:
[clang-tidy] Improving narrowing conversions

Summary:
Newly flagged narrowing conversions:
 - integer to narrower signed integer (this is compiler implementation defined),
 - integer - floating point narrowing conversions,
 - floating point - integer narrowing conversions,
 - constants with narrowing conversions (even in ternary operator).

Reviewers: hokein, alexfh, aaron.ballman, JonasToth

Reviewed By: aaron.ballman, JonasToth

Subscribers: lebedev.ri, courbet, nemanjai, xazax.hun, kbarton, cfe-commits

Tags: #clang-tools-extra

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

Added:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-pedanticmode-option.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp
Modified:

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp

clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
clang-tools-extra/trunk/docs/ReleaseNotes.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp?rev=347570=347569=347570=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
 (original)
+++ 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
 Mon Nov 26 08:25:55 2018
@@ -9,7 +9,13 @@
 
 #include "NarrowingConversionsCheck.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/APSInt.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+
+#include 
 
 using namespace clang::ast_matchers;
 
@@ -17,52 +23,423 @@ namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
 
-// FIXME: Check double -> float truncation. Pay attention to casts:
+NarrowingConversionsCheck::NarrowingConversionsCheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  WarnOnFloatingPointNarrowingConversion(
+  Options.get("WarnOnFloatingPointNarrowingConversion", 1)),
+  PedanticMode(Options.get("PedanticMode", 0)) {}
+
 void NarrowingConversionsCheck::registerMatchers(MatchFinder *Finder) {
   // ceil() and floor() are guaranteed to return integers, even though the type
   // is not integral.
-  const auto IsCeilFloorCall = callExpr(callee(functionDecl(
-  hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor";
-
-  const auto IsFloatExpr =
-  expr(hasType(realFloatingPointType()), unless(IsCeilFloorCall));
+  const auto IsCeilFloorCallExpr = expr(callExpr(callee(functionDecl(
+  hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor");
 
-  // casts:
+  // Casts:
   //   i = 0.5;
   //   void f(int); f(0.5);
-  Finder->addMatcher(implicitCastExpr(hasImplicitDestinationType(isInteger()),
-  hasSourceExpression(IsFloatExpr),
-  unless(hasParent(castExpr())),
-  unless(isInTemplateInstantiation()))
- .bind("cast"),
- this);
+  Finder->addMatcher(
+  implicitCastExpr(hasImplicitDestinationType(builtinType()),
+   hasSourceExpression(hasType(builtinType())),
+   unless(hasSourceExpression(IsCeilFloorCallExpr)),
+   unless(hasParent(castExpr())),
+   unless(isInTemplateInstantiation()))
+  .bind("cast"),
+  this);
 
   // Binary operators:
   //   i += 0.5;
-  Finder->addMatcher(
-  binaryOperator(isAssignmentOperator(),
- // The `=` case generates an implicit cast which is 
covered
- // by the previous matcher.
- unless(hasOperatorName("=")),
- hasLHS(hasType(isInteger())), hasRHS(IsFloatExpr),
- unless(isInTemplateInstantiation()))
-  .bind("op"),
-  this);
+  Finder->addMatcher(binaryOperator(isAssignmentOperator(),
+hasLHS(expr(hasType(builtinType(,
+   

[PATCH] D54862: [OpenCL] Add generic AS to 'this' pointer

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGCall.cpp:80
+// used with the same version of generated operators.
+RecTy = Context.getAddrSpaceQualType(RecTy, LangAS::opencl_generic);
+

Anastasia wrote:
> rjmccall wrote:
> > I would suggest taking this opportunity to set up the AST to support 
> > declaring methods in an arbitrary address space, so that you can just ask a 
> > `CXXMethodDecl` what address space it's in.  You don't have to actually add 
> > language support for that — OpenCL C++ would simply change the it to the 
> > generic address space instead of the default — but I think that's the right 
> > technical approach for implementing this, as opposed to adding a bunch of 
> > OpenCL C++ -specific logic all over the compiler that just hardcodes a 
> > different address space.
> I quite like this idea. Apart from providing more clean implementation, it 
> opens opportunities for solving several problems that I am trying to 
> understand how to address. Specifically I am trying to find a way to 
> 'overload' methods based on the address space of the object.
> 
> For example, if an object is created in the address space 1 then programmers 
> should be able to provide a method to be used for objects in such address 
> space for efficiency or even correctness issue.
> 
> The reasons I am looking at it is that currently C++ doesn't make much sense 
> for address spaces, because we are removing them to generate just one 
> implementation with generic/default address space. However,
> - Not all address spaces can be converted to generic/default address space. 
> Example in OpenCL is constant AS that can't be converted to any other.
> - Higher performance can be achieved on some HW when using specific address 
> spaces instead of default.
> 
> I was wondering if a method qualifier is a good language solution for this? 
> For example in OpenCL we could write something like:
> 
>   class foo
>   {
>   public:
> void bar() __private; // implies bar(__private foo*)
> void bar() __constant; // implies bar(__constant foo*)
>   };
> 
> I guess in C++ it can be done similarly:
> 
>   class foo
>   {
>   public:
> void bar() __attribute__((address_space(1)));
> void bar() __attribute__((address_space(2)));
>   };
> 
> I would quite like to solve this generically, not just for OpenCL. I think a 
> lot of implementation can be unified/reused then.
> 
> Without this address spaces seem pretty useless with C++ because they are 
> just cast away to generic/default and no specific address space ends up at 
> the AST level at all. This means implementation will have to rely on the 
> optimizers to recover/deduce address spaces. But I would quite like to 
> provide a way for the developers to manually tune the code for address 
> spaces, just as it was done for OpenCL C.
> 
> Let me know if you have any thought/suggestions.
> I was wondering if a method qualifier is a good language solution for this? 
> For example in OpenCL we could write something like:

Yes, I think that's a very natural extension of C++'s method-qualification 
rules for `const` and `volatile`.  Overloads would then be resolved based on 
which address space was the best match.

Now, to briefly take a holistic perspective on the language design, this 
feature would *strongly* benefit from a way to make a method templated over the 
address space of `this`.  Unfortunately, I don't think that's reasonable to 
solve in a language extension; it's really something that needs core language 
work.  That would be a pretty big leap in scope; that said, if you're 
interested in pursuing it, I'd be happy to share some thoughts on how it'd 
look, and I think there are several people in the Clang community who could 
help you with putting a proposal before the committee.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54862



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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347570: [clang-tidy] Improving narrowing conversions 
(authored by gchatelet, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D53488

Files:
  
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  clang-tools-extra/trunk/docs/ReleaseNotes.rst
  
clang-tools-extra/trunk/docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-pedanticmode-option.cpp
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
===
--- clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
+++ clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
@@ -24,10 +24,76 @@
 /// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.html
 class NarrowingConversionsCheck : public ClangTidyCheck {
 public:
-  NarrowingConversionsCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  NarrowingConversionsCheck(StringRef Name, ClangTidyContext *Context);
+
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+
+private:
+  void diagNarrowType(SourceLocation SourceLoc, const Expr ,
+  const Expr );
+
+  void diagNarrowTypeToSignedInt(SourceLocation SourceLoc, const Expr ,
+ const Expr );
+
+  void diagNarrowIntegerConstant(SourceLocation SourceLoc, const Expr ,
+ const Expr , const llvm::APSInt );
+
+  void diagNarrowIntegerConstantToSignedInt(SourceLocation SourceLoc,
+const Expr , const Expr ,
+const llvm::APSInt ,
+const uint64_t HexBits);
+
+  void diagNarrowConstant(SourceLocation SourceLoc, const Expr ,
+  const Expr );
+
+  void diagConstantCast(SourceLocation SourceLoc, const Expr ,
+const Expr );
+
+  void diagNarrowTypeOrConstant(const ASTContext ,
+SourceLocation SourceLoc, const Expr ,
+const Expr );
+
+  void handleIntegralCast(const ASTContext , SourceLocation SourceLoc,
+  const Expr , const Expr );
+
+  void handleIntegralToBoolean(const ASTContext ,
+   SourceLocation SourceLoc, const Expr ,
+   const Expr );
+
+  void handleIntegralToFloating(const ASTContext ,
+SourceLocation SourceLoc, const Expr ,
+const Expr );
+
+  void handleFloatingToIntegral(const ASTContext ,
+SourceLocation SourceLoc, const Expr ,
+const Expr );
+
+  void handleFloatingToBoolean(const ASTContext ,
+   SourceLocation SourceLoc, const Expr ,
+   const Expr );
+
+  void handleBooleanToSignedIntegral(const ASTContext ,
+ SourceLocation SourceLoc, const Expr ,
+ const Expr );
+
+  void handleFloatingCast(const ASTContext , SourceLocation SourceLoc,
+  const Expr , const Expr );
+
+  void handleBinaryOperator(const ASTContext , SourceLocation SourceLoc,
+const Expr , const Expr );
+
+  bool handleConditionalOperator(const ASTContext , const Expr ,
+ const Expr );
+
+  void handleImplicitCast(const ASTContext ,
+  const ImplicitCastExpr );
+
+  void handleBinaryOperator(const ASTContext ,
+const BinaryOperator );
+
+  const bool WarnOnFloatingPointNarrowingConversion;
+  const bool PedanticMode;
 };
 
 } // namespace cppcoreguidelines
Index: clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
===
--- 

Re: r338941 - [constexpr] Support for constant evaluation of __builtin_memcpy and

2018-11-26 Thread Tom Stellard via cfe-commits
On 11/21/2018 03:32 PM, Shoaib Meenai wrote:
> If it's not too late, could we have this as part of 7.0.1? (You'll also need 
> to cherry-pick the initial reversion in r338602.) 7.0 hits assertion failures 
> for pretty basic memcpy cases on windows-msvc targets, and this patch fixes 
> that.
> 

I've created a bug to track this request: PR39791.

-Tom
> % cat /tmp/reduced.c
> void *memcpy(void *, const void *, __SIZE_TYPE__);
> void f(int i) {
>   struct { int i } s;
>   memcpy((char *), , sizeof(i));
> }
> 
> % clang -cc1 -triple x86_64-windows-msvc -emit-llvm -fms-compatibility -o 
> /dev/null /tmp/reduced.c
> llvm::SmallVectorTemplateCommon::const_reference 
> llvm::SmallVectorTemplateCommon void>::back() const [T = clang::APValue::LValuePathEntry]: Assertion 
> `!empty()' failed.
> 
> On Fri, Aug 3, 2018 at 5:57 PM Richard Smith via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
> 
> Author: rsmith
> Date: Fri Aug  3 17:57:17 2018
> New Revision: 338941
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=338941=rev
> Log:
> [constexpr] Support for constant evaluation of __builtin_memcpy and
> __builtin_memmove (in non-type-punning cases).
> 
> This is intended to permit libc++ to make std::copy etc constexpr
> without sacrificing the optimization that uses memcpy on
> trivially-copyable types.
> 
> __builtin_strcpy and __builtin_wcscpy are not handled by this change.
> They'd be straightforward to add, but we haven't encountered a need for
> them just yet.
> 
> This reinstates r338455, reverted in r338602, with a fix to avoid trying
> to constant-evaluate a memcpy call if either pointer operand has an
> invalid designator.
> 
> Modified:
> cfe/trunk/include/clang/Basic/Builtins.def
> cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
> cfe/trunk/lib/AST/ExprConstant.cpp
> cfe/trunk/test/CodeGen/builtin-memfns.c
> cfe/trunk/test/SemaCXX/constexpr-string.cpp
> 
> Modified: cfe/trunk/include/clang/Basic/Builtins.def
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Builtins.def?rev=338941=338940=338941=diff
> 
> ==
> --- cfe/trunk/include/clang/Basic/Builtins.def (original)
> +++ cfe/trunk/include/clang/Basic/Builtins.def Fri Aug  3 17:57:17 2018
> @@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
>  BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
>  BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
>  BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
> +BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
> +BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
>  BUILTIN(__builtin_return_address, "v*IUi", "n")
>  BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
>  BUILTIN(__builtin_frame_address, "v*IUi", "n")
> @@ -908,6 +910,8 @@ LIBBUILTIN(wcslen,  "zwC*", "f", "wc
>  LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
>  LIBBUILTIN(wmemchr, "w*wC*wz",  "f", "wchar.h", ALL_LANGUAGES)
>  LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
> +LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
> +LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
> 
>  // C99
>  // In some systems setjmp is a macro that expands to _setjmp. We undefine
> 
> Modified: cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td?rev=338941=338940=338941=diff
> 
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticASTKinds.td Fri Aug  3 
> 17:57:17 2018
> @@ -163,6 +163,20 @@ def note_constexpr_unsupported_unsized_a
>  def note_constexpr_unsized_array_indexed : Note<
>"indexing of array without known bound is not allowed "
>"in a constant expression">;
> +def note_constexpr_memcpy_type_pun : Note<
> +  "cannot constant evaluate '%select{memcpy|memmove}0' from object of "
> +  "type %1 to object of type %2">;
> +def note_constexpr_memcpy_nontrivial : Note<
> +  "cannot constant evaluate '%select{memcpy|memmove}0' between objects 
> of "
> +  "non-trivially-copyable type %1">;
> +def note_constexpr_memcpy_overlap : Note<
> +  "'%select{memcpy|wmemcpy}0' between overlapping memory regions">;
> +def note_constexpr_memcpy_unsupported : Note<
> +  "'%select{%select{memcpy|wmemcpy}1|%select{memmove|wmemmove}1}0' "
> +  "not supported: %select{"
> +  "size to copy (%4) is not a multiple of size of element type %3 (%5)|"
> +  "source is not a contiguous array of at least %4 elements of type %3|"
> +  "destination is not a contiguous array of at least %4 elements of type 

[PATCH] D54902: [AST][Sema] Remove CallExpr::setNumArgs

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added reviewers: rsmith, aaron.ballman.
riccibruno added a project: clang.
Herald added subscribers: cfe-commits, dexonsmith, mehdi_amini.

`CallExpr::setNumArgs` is the only thing that prevents storing the arguments
in a trailing array. There is only 3 places in `Sema` where `setNumArgs` is 
called.
D54900  dealt with one of them.

This patch remove the other two calls to `setNumArgs` in 
`ConvertArgumentsForCall`.
To do this we do the following changes:

1.) Replace the first call to `setNumArgs` by an assertion since we are moving 
the responsability
to allocate enough space for the arguments from `Sema::ConvertArgumentsForCall`
to its callers. (which are `Sema::BuildCallToMemberFunction`, and 
`Sema::BuildResolvedCallExpr`)

2.) Add a new member function `CallExpr::shrinkNumArgs`, which can only be used
to drop arguments and then replace the second call to `setNumArgs` by 
`shrinkNumArgs`.

3.) Add a new defaulted parameter `MinNumArgs` to `CallExpr` and its derived 
classes,
which specifies a minimum number of argument slots to allocate. The actual 
number of
arguments slots allocated will be `max(number of args, MinNumArgs)`, with the 
extra
args nulled. Note that after the creation of the call expression all of the 
arguments will
be non-null. It is just during the creation of the call expression that some of 
the
last arguments can be temporarily null, until filled by default arguments.

4.) Update `Sema::BuildCallToMemberFunction` by passing the number of parameters
in the function prototype to the constructor of `CXXMemberCallExpr`.
Here the change is pretty straightforward.

5.) Update `Sema::BuildResolvedCallExpr`. Here the change is more complicated 
since
the type-checking for the function type was done after the creation of the call 
expression.
We need to move this before the creation of the call expression, and then pass 
the number
of parameters in the function prototype (if any) to the constructor of the call 
expression.

6.) Update the deserialization of `CallExpr` and its derived classes.


Repository:
  rC Clang

https://reviews.llvm.org/D54902

Files:
  include/clang/AST/Expr.h
  include/clang/AST/ExprCXX.h
  lib/AST/Expr.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaOverload.cpp
  lib/Serialization/ASTReaderStmt.cpp

Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -731,10 +731,11 @@
 
 void ASTStmtReader::VisitCallExpr(CallExpr *E) {
   VisitExpr(E);
-  E->setNumArgs(Record.getContext(), Record.readInt());
+  unsigned NumArgs = Record.readInt();
+  assert((NumArgs == E->getNumArgs()) && "Wrong NumArgs!");
   E->setRParenLoc(ReadSourceLocation());
   E->setCallee(Record.readSubExpr());
-  for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
+  for (unsigned I = 0; I != NumArgs; ++I)
 E->setArg(I, Record.readSubExpr());
 }
 
@@ -2494,7 +2495,9 @@
   break;
 
 case EXPR_CALL:
-  S = new (Context) CallExpr(Context, Stmt::CallExprClass, Empty);
+  S = new (Context) CallExpr(
+  Context, /* NumArgs=*/Record[ASTStmtReader::NumExprFields + 0],
+  Empty);
   break;
 
 case EXPR_MEMBER: {
@@ -3084,11 +3087,15 @@
 }
 
 case EXPR_CXX_OPERATOR_CALL:
-  S = new (Context) CXXOperatorCallExpr(Context, Empty);
+  S = new (Context) CXXOperatorCallExpr(
+  Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields + 0],
+  Empty);
   break;
 
 case EXPR_CXX_MEMBER_CALL:
-  S = new (Context) CXXMemberCallExpr(Context, Empty);
+  S = new (Context) CXXMemberCallExpr(
+  Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields + 0],
+  Empty);
   break;
 
 case EXPR_CXX_CONSTRUCT:
@@ -3128,7 +3135,8 @@
   break;
 
 case EXPR_USER_DEFINED_LITERAL:
-  S = new (Context) UserDefinedLiteral(Context, Empty);
+  S = new (Context) UserDefinedLiteral(
+  Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields + 0], Empty);
   break;
 
 case EXPR_CXX_STD_INITIALIZER_LIST:
@@ -3303,7 +3311,8 @@
   break;
 
 case EXPR_CUDA_KERNEL_CALL:
-  S = new (Context) CUDAKernelCallExpr(Context, Empty);
+  S = new (Context) CUDAKernelCallExpr(
+  Context, /*NumArgs=*/Record[ASTStmtReader::NumExprFields + 0], Empty);
   break;
 
 case EXPR_ASTYPE:
Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -12836,7 +12836,8 @@
 
 CXXMemberCallExpr *call
   = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
-resultType, valueKind, RParenLoc);
+resultType, valueKind, RParenLoc,
+

[PATCH] D54425: [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM.


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

https://reviews.llvm.org/D54425



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


[PATCH] D54862: [OpenCL] Add generic AS to 'this' pointer

2018-11-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: lib/CodeGen/CGCall.cpp:80
+// used with the same version of generated operators.
+RecTy = Context.getAddrSpaceQualType(RecTy, LangAS::opencl_generic);
+

rjmccall wrote:
> I would suggest taking this opportunity to set up the AST to support 
> declaring methods in an arbitrary address space, so that you can just ask a 
> `CXXMethodDecl` what address space it's in.  You don't have to actually add 
> language support for that — OpenCL C++ would simply change the it to the 
> generic address space instead of the default — but I think that's the right 
> technical approach for implementing this, as opposed to adding a bunch of 
> OpenCL C++ -specific logic all over the compiler that just hardcodes a 
> different address space.
I quite like this idea. Apart from providing more clean implementation, it 
opens opportunities for solving several problems that I am trying to understand 
how to address. Specifically I am trying to find a way to 'overload' methods 
based on the address space of the object.

For example, if an object is created in the address space 1 then programmers 
should be able to provide a method to be used for objects in such address space 
for efficiency or even correctness issue.

The reasons I am looking at it is that currently C++ doesn't make much sense 
for address spaces, because we are removing them to generate just one 
implementation with generic/default address space. However,
- Not all address spaces can be converted to generic/default address space. 
Example in OpenCL is constant AS that can't be converted to any other.
- Higher performance can be achieved on some HW when using specific address 
spaces instead of default.

I was wondering if a method qualifier is a good language solution for this? For 
example in OpenCL we could write something like:

  class foo
  {
  public:
void bar() __private; // implies bar(__private foo*)
void bar() __constant; // implies bar(__constant foo*)
  };

I guess in C++ it can be done similarly:

  class foo
  {
  public:
void bar() __attribute__((address_space(1)));
void bar() __attribute__((address_space(2)));
  };

I would quite like to solve this generically, not just for OpenCL. I think a 
lot of implementation can be unified/reused then.

Without this address spaces seem pretty useless with C++ because they are just 
cast away to generic/default and no specific address space ends up at the AST 
level at all. This means implementation will have to rely on the optimizers to 
recover/deduce address spaces. But I would quite like to provide a way for the 
developers to manually tune the code for address spaces, just as it was done 
for OpenCL C.

Let me know if you have any thought/suggestions.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54862



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


[PATCH] D54898: Set MustBuildLookupTable on PrimaryContext in ExternalASTMerger

2018-11-26 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM. Thank you!


Repository:
  rC Clang

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

https://reviews.llvm.org/D54898



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347567: [clangd] Enable auto-index behind a flag. (authored 
by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D54894

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/ClangdLSPServer.h
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.h
  clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/trunk/clangd/index/Background.cpp
  clang-tools-extra/trunk/clangd/index/Background.h
  clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
  clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
  
clang-tools-extra/trunk/test/clangd/Inputs/background-index/compile_commands.json
  clang-tools-extra/trunk/test/clangd/Inputs/background-index/definition.jsonrpc
  clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.cpp
  clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.h
  clang-tools-extra/trunk/test/clangd/background-index.test
  clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
@@ -90,7 +90,7 @@
   Cmd.CommandLine = {"clang++", "-DA=1", testPath("root/A.cc")};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   EXPECT_THAT(
   runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -100,7 +100,7 @@
   Cmd.CommandLine = {"clang++", Cmd.Filename};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   // B_CC is dropped as we don't collect symbols from A.h in this compilation.
   EXPECT_THAT(runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -141,7 +141,7 @@
 BackgroundIndex Idx(Context::empty(), "", FS, CDB,
 [&](llvm::StringRef) { return  });
 CDB.setCompileCommand(testPath("root"), Cmd);
-Idx.blockUntilIdleForTest();
+ASSERT_TRUE(Idx.blockUntilIdleForTest());
   }
   EXPECT_EQ(CacheHits, 0U);
   EXPECT_EQ(Storage.size(), 2U);
Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -337,6 +337,17 @@
   Reply(nullptr);
 }
 
+// sync is a clangd extension: it blocks until all background work completes.
+// It blocks the calling thread, so no messages are processed until it returns!
+void ClangdLSPServer::onSync(const NoParams ,
+ Callback Reply) {
+  if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
+Reply(nullptr);
+  else
+Reply(createStringError(llvm::inconvertibleErrorCode(),
+"Not idle after a minute"));
+}
+
 void ClangdLSPServer::onDocumentDidOpen(
 const DidOpenTextDocumentParams ) {
   PathRef File = Params.textDocument.uri.file();
@@ -701,6 +712,7 @@
   // clang-format off
   MsgHandler->bind("initialize", ::onInitialize);
   MsgHandler->bind("shutdown", ::onShutdown);
+  MsgHandler->bind("sync", ::onSync);
   MsgHandler->bind("textDocument/rangeFormatting", ::onDocumentRangeFormatting);
   MsgHandler->bind("textDocument/onTypeFormatting", ::onDocumentOnTypeFormatting);
   MsgHandler->bind("textDocument/formatting", ::onDocumentFormatting);
Index: clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
@@ -164,6 +164,12 @@
 "eventually. Don't rely on it."),
 cl::init(""), cl::Hidden);
 
+static cl::opt EnableBackgroundIndex(
+"background-index",
+cl::desc("Index project code in the background and persist index on disk. "
+ "Experimental"),
+cl::init(false), cl::Hidden);
+
 enum CompileArgsFrom { LSPCompileArgs, FilesystemCompileArgs };
 static cl::opt CompileArgsFrom(
 "compile_args_from", cl::desc("The source of compile commands"),
@@ -344,6 +350,7 @@
 Opts.ResourceDir = ResourceDir;
   Opts.BuildDynamicSymbolIndex = EnableIndex;
   Opts.HeavyweightDynamicSymbolIndex = UseDex;
+  Opts.BackgroundIndex = EnableBackgroundIndex;
   std::unique_ptr StaticIdx;
   std::future AsyncIndexLoad; // Block exit while loading the index.
   if (EnableIndex && !IndexFile.empty()) {
Index: 

[PATCH] D53696: [Haiku] Support __float128 for Haiku x86 and x86_64

2018-11-26 Thread Alexander von Gluck IV via Phabricator via cfe-commits
kallisti5 added a comment.

I don't have permission to update this request, so I created 
https://reviews.llvm.org/D54901 with the updates recommended.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53696



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


[PATCH] D54450: Get the correct range of tokens for preprocessor conditions

2018-11-26 Thread Miklos Vajna via Phabricator via cfe-commits
vmiklos added a comment.

Could you please review this at some stage? As mentioned previously, this is a 
dependency for D54349 . Thanks!


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

https://reviews.llvm.org/D54450



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


[clang-tools-extra] r347567 - [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Nov 26 08:00:11 2018
New Revision: 347567

URL: http://llvm.org/viewvc/llvm-project?rev=347567=rev
Log:
[clangd] Enable auto-index behind a flag.

Summary:
Ownership and configuration:
The auto-index (background index) is maintained by ClangdServer, like Dynamic.
(This means ClangdServer will be able to enqueue preamble indexing in future).
For now it's enabled by a simple boolean flag in ClangdServer::Options, but
we probably want to eventually allow injecting the storage strategy.

New 'sync' command:
In order to meaningfully test the integration (not just unit-test components)
we need a way for tests to ensure the asynchronous index reads/writes occur
before a certain point.
Because these tests and assertions are few, I think exposing an explicit "sync"
command for use in tests is simpler than allowing threading to be completely
disabled in the background index (as we do for TUScheduler).

Bugs:
I fixed a couple of trivial bugs I found while testing, but there's one I can't.
JSONCompilationDatabase::getAllFiles() may return relative paths, and currently
we trigger an assertion that assumes they are absolute.
There's no efficient way to resolve them (you have to retrieve the corresponding
command and then resolve against its directory property). In general I think
this behavior is broken and we should fix it in JSONCompilationDatabase and
require CompilationDatabase::getAllFiles() to be absolute.

Reviewers: kadircet

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

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

Added:
clang-tools-extra/trunk/test/clangd/Inputs/background-index/

clang-tools-extra/trunk/test/clangd/Inputs/background-index/compile_commands.json

clang-tools-extra/trunk/test/clangd/Inputs/background-index/definition.jsonrpc
clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.cpp
clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.h
clang-tools-extra/trunk/test/clangd/background-index.test
Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/Background.h
clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=347567=347566=347567=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Nov 26 08:00:11 2018
@@ -337,6 +337,17 @@ void ClangdLSPServer::onShutdown(const S
   Reply(nullptr);
 }
 
+// sync is a clangd extension: it blocks until all background work completes.
+// It blocks the calling thread, so no messages are processed until it returns!
+void ClangdLSPServer::onSync(const NoParams ,
+ Callback Reply) {
+  if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
+Reply(nullptr);
+  else
+Reply(createStringError(llvm::inconvertibleErrorCode(),
+"Not idle after a minute"));
+}
+
 void ClangdLSPServer::onDocumentDidOpen(
 const DidOpenTextDocumentParams ) {
   PathRef File = Params.textDocument.uri.file();
@@ -701,6 +712,7 @@ ClangdLSPServer::ClangdLSPServer(class T
   // clang-format off
   MsgHandler->bind("initialize", ::onInitialize);
   MsgHandler->bind("shutdown", ::onShutdown);
+  MsgHandler->bind("sync", ::onSync);
   MsgHandler->bind("textDocument/rangeFormatting", 
::onDocumentRangeFormatting);
   MsgHandler->bind("textDocument/onTypeFormatting", 
::onDocumentOnTypeFormatting);
   MsgHandler->bind("textDocument/formatting", 
::onDocumentFormatting);

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=347567=347566=347567=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Mon Nov 26 08:00:11 2018
@@ -57,6 +57,7 @@ private:
   // Calls have signature void(const Params&, Callback).
   void onInitialize(const InitializeParams &, Callback);
   void onShutdown(const ShutdownParams &, Callback);
+  void onSync(const NoParams &, Callback);
   void onDocumentDidOpen(const DidOpenTextDocumentParams &);
   void onDocumentDidChange(const DidChangeTextDocumentParams &);
   void 

[PATCH] D54901: [Haiku] Support __float128 for Haiku x86 and x86_64

2018-11-26 Thread Alexander von Gluck IV via Phabricator via cfe-commits
kallisti5 created this revision.
kallisti5 added reviewers: chandlerc, joerg, compnerd, kristina, js.
kallisti5 added a project: clang.
Herald added a subscriber: cfe-commits.

A revision on https://reviews.llvm.org/D53696 from another user.


Repository:
  rC Clang

https://reviews.llvm.org/D54901

Files:
  lib/Basic/Targets/OSTargets.h
  test/CodeGenCXX/float128-declarations.cpp


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,9 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+}
   }
 
 public:
@@ -267,6 +270,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,9 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+}
   }
 
 public:
@@ -267,6 +270,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347566 - [clangd] Fix compilation of IndexBenchmark

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:58:29 2018
New Revision: 347566

URL: http://llvm.org/viewvc/llvm-project?rev=347566=rev
Log:
[clangd] Fix compilation of IndexBenchmark

Modified:
clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp

Modified: clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp?rev=347566=347565=347566=diff
==
--- clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp (original)
+++ clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp Mon Nov 26 
07:58:29 2018
@@ -27,11 +27,11 @@ namespace clangd {
 namespace {
 
 std::unique_ptr buildMem() {
-  return loadIndex(IndexFilename, {}, false);
+  return loadIndex(IndexFilename, /*UseDex=*/false);
 }
 
 std::unique_ptr buildDex() {
-  return loadIndex(IndexFilename, {}, true);
+  return loadIndex(IndexFilename, /*UseDex=*/true);
 }
 
 // Reads JSON array of serialized FuzzyFindRequest's from user-provided file.


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


[PATCH] D53697: [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347564: [ASTImporter][Structural Eq] Check for 
isBeingDefined (authored by martong, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D53697

Files:
  cfe/trunk/lib/AST/ASTImporter.cpp
  cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
  cfe/trunk/unittests/AST/ASTImporterTest.cpp


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -1740,8 +1740,9 @@
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData  = ToCXX->data();
 struct CXXRecordDecl::DefinitionData  = FromCXX->data();
Index: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
===
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&
Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp
===
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp
@@ -3725,6 +3725,45 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -1740,8 +1740,9 @@
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData  = ToCXX->data();
 struct CXXRecordDecl::DefinitionData  = FromCXX->data();
Index: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
===
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that 

r347564 - [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Nov 26 07:54:08 2018
New Revision: 347564

URL: http://llvm.org/viewvc/llvm-project?rev=347564=rev
Log:
[ASTImporter][Structural Eq] Check for isBeingDefined

Summary:
If one definition is currently being defined, we do not compare for
equality and we assume that the decls are equal.

Reviewers: a_sidorin, a.sidorin, shafik

Reviewed By: a_sidorin

Subscribers: gamesh411, shafik, rnkovacs, dkrupp, Szelethus, cfe-commits

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

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

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=347564=347563=347564=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Nov 26 07:54:08 2018
@@ -1740,8 +1740,9 @@ Error ASTNodeImporter::ImportDefinition(
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData  = ToCXX->data();
 struct CXXRecordDecl::DefinitionData  = FromCXX->data();

Modified: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp?rev=347564=347563=347564=diff
==
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp (original)
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp Mon Nov 26 07:54:08 2018
@@ -1016,7 +1016,8 @@ static bool IsStructurallyEquivalent(Str
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@ static bool IsStructurallyEquivalent(Str
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=347564=347563=347564=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Nov 26 07:54:08 2018
@@ -3725,6 +3725,45 @@ TEST_P(ImportFunctionTemplateSpecializat
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 


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


[clang-tools-extra] r347563 - [clangd] Fix use-after-free with expected types in indexing

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:52:16 2018
New Revision: 347563

URL: http://llvm.org/viewvc/llvm-project?rev=347563=rev
Log:
[clangd] Fix use-after-free with expected types in indexing

Modified:
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=347563=347562=347563=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Nov 26 
07:52:16 2018
@@ -587,9 +587,11 @@ const Symbol *SymbolCollector::addDeclar
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  llvm::Optional TypeStorage;
   if (S.Flags & Symbol::IndexedForCodeCompletion) {
-if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
-  S.Type = T->raw();
+TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
+if (TypeStorage)
+  S.Type = TypeStorage->raw();
   }
 
   S.Origin = Opts.Origin;


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


[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE347562: [clangd] Add type boosting in code completion 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52276?vs=175258=175260#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  clangd/index/Index.h

Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult );
   void merge(const Symbol );
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto  = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+  if (auto CompletionType = OpaqueType::fromCompletionResult(
+  Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
+Relevance.HadSymbolType |= true;
+if (PreferredType == CompletionType)
+  Relevance.TypeMatchesPreferred = true;
+  }
+}
 Origin |= SymbolOrigin::AST;
   }
 }
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+

[clang-tools-extra] r347562 - [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:38:01 2018
New Revision: 347562

URL: http://llvm.org/viewvc/llvm-project?rev=347562=rev
Log:
[clangd] Add type boosting in code completion

Reviewers: sammccall, ioeric

Reviewed By: sammccall

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

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/Quality.cpp
clang-tools-extra/trunk/clangd/Quality.h
clang-tools-extra/trunk/clangd/index/Index.h

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=347562=347561=347562=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Mon Nov 26 07:38:01 2018
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@ class CodeCompleteFlow {
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@ public:
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), 
"
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@ private:
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@ private:
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto  = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@ private:
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+  if (auto CompletionType = OpaqueType::fromCompletionResult(
+  Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
+Relevance.HadSymbolType |= true;
+if (PreferredType == CompletionType)
+  Relevance.TypeMatchesPreferred = true;
+  }
+}
 Origin |= SymbolOrigin::AST;
   }
 }

Modified: clang-tools-extra/trunk/clangd/Quality.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Quality.cpp?rev=347562=347561=347562=diff
==
--- clang-tools-extra/trunk/clangd/Quality.cpp (original)
+++ clang-tools-extra/trunk/clangd/Quality.cpp Mon Nov 26 07:38:01 2018
@@ -369,6 +369,9 @@ float SymbolRelevanceSignals::evaluate()
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@ raw_ostream <<(raw_ostream ,
 OS << formatv("\tIndex 

[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175258.
ilya-biryukov added a comment.

- Add a FIXME to FuzzyFindRequest


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  clangd/index/Index.h

Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -494,6 +494,8 @@
   /// Paths should be absolute.
   std::vector ProximityPaths;
 
+  // FIXME(ibiryukov): add expected type to the request.
+
   bool operator==(const FuzzyFindRequest ) const {
 return std::tie(Query, Scopes, Limit, RestrictForCodeCompletion,
 ProximityPaths) ==
Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult );
   void merge(const Symbol );
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@
 OS << formatv("\tIndex scope boost: {0}\n",
   scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
+  OS << formatv(
+  "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
+  S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
+
   return OS;
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto  = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 

[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: test/clangd/background-index.test:16
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+

kadircet wrote:
> kadircet wrote:
> > and this
> also I suppose we might wanna delete this file after test ends(if the temp 
> directory is not already deleted at exit)
Convention is that tests are responsible for cleaning up the temp directory 
*before* they run, but not after.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D54900: [Sema] Avoid CallExpr::setNumArgs in Sema::BuildCallToObjectOfClassType

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added reviewers: rsmith, aaron.ballman.
riccibruno added a project: clang.
Herald added subscribers: cfe-commits, dexonsmith, inglorion, mehdi_amini.

`CallExpr::setNumArgs` is the only thing that prevents storing the arguments
of a call expression in a trailing array since it might resize the argument 
array.
`setNumArgs` is only called in 3 places in `Sema`, and for all of them it is
possible to avoid it.

This deals with the call to `setNumArgs` in `BuildCallToObjectOfClassType`.
Instead of constructing the `CXXOperatorCallExpr` first and later calling
`setNumArgs` if we have default arguments, we first construct a large
enough `SmallVector`, do the promotion/check of the arguments, and
then construct the `CXXOperatorCallExpr`.

Incidentally this also avoid reallocating the arguments when the
call operator has default arguments but this is not the primary goal.


Repository:
  rC Clang

https://reviews.llvm.org/D54900

Files:
  lib/Sema/SemaOverload.cpp


Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -13257,29 +13257,14 @@
   if (NewFn.isInvalid())
 return true;
 
+  // The number of arguments slots to allocate in the call.
+  // If we have default arguments we need to allocate space for them
+  // as well. We additionally need one more slot for the object parameter.
+  unsigned NumArgsSlots = 1 + std::max(Args.size(), NumParams);
+
   // Build the full argument list for the method call (the implicit object
   // parameter is placed at the beginning of the list).
-  SmallVector MethodArgs(Args.size() + 1);
-  MethodArgs[0] = Object.get();
-  std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
-
-  // Once we've built TheCall, all of the expressions are properly
-  // owned.
-  QualType ResultTy = Method->getReturnType();
-  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
-  ResultTy = ResultTy.getNonLValueExprType(Context);
-
-  CXXOperatorCallExpr *TheCall = new (Context)
-  CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
-  VK, RParenLoc, FPOptions());
-
-  if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
-return true;
-
-  // We may have default arguments. If so, we need to allocate more
-  // slots in the call for them.
-  if (Args.size() < NumParams)
-TheCall->setNumArgs(Context, NumParams + 1);
+  SmallVector MethodArgs(NumArgsSlots);
 
   bool IsError = false;
 
@@ -13291,7 +13276,7 @@
 IsError = true;
   else
 Object = ObjRes;
-  TheCall->setArg(0, Object.get());
+  MethodArgs[0] = Object.get();
 
   // Check the argument types.
   for (unsigned i = 0; i != NumParams; i++) {
@@ -13320,7 +13305,7 @@
   Arg = DefArg.getAs();
 }
 
-TheCall->setArg(i + 1, Arg);
+MethodArgs[i+1] = Arg;
   }
 
   // If this is a variadic call, handle args passed through "...".
@@ -13330,14 +13315,27 @@
   ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], 
VariadicMethod,
 nullptr);
   IsError |= Arg.isInvalid();
-  TheCall->setArg(i + 1, Arg.get());
+  MethodArgs[i+1] = Arg.get();
 }
   }
 
-  if (IsError) return true;
+  if (IsError)
+return true;
 
   DiagnoseSentinelCalls(Method, LParenLoc, Args);
 
+  // Once we've built TheCall, all of the expressions are properly owned.
+  QualType ResultTy = Method->getReturnType();
+  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
+  ResultTy = ResultTy.getNonLValueExprType(Context);
+
+  CXXOperatorCallExpr *TheCall = new (Context)
+  CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
+  VK, RParenLoc, FPOptions());
+
+  if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
+return true;
+
   if (CheckFunctionCall(Method, TheCall, Proto))
 return true;
 


Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -13257,29 +13257,14 @@
   if (NewFn.isInvalid())
 return true;
 
+  // The number of arguments slots to allocate in the call.
+  // If we have default arguments we need to allocate space for them
+  // as well. We additionally need one more slot for the object parameter.
+  unsigned NumArgsSlots = 1 + std::max(Args.size(), NumParams);
+
   // Build the full argument list for the method call (the implicit object
   // parameter is placed at the beginning of the list).
-  SmallVector MethodArgs(Args.size() + 1);
-  MethodArgs[0] = Object.get();
-  std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
-
-  // Once we've built TheCall, all of the expressions are properly
-  // owned.
-  QualType ResultTy = Method->getReturnType();
-  ExprValueKind VK = 

[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175257.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Address comments


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h

Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult );
   void merge(const Symbol );
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@
 OS << formatv("\tIndex scope boost: {0}\n",
   scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
+  OS << formatv(
+  "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
+  S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
+
   return OS;
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto  = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+

[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347560: [clangd] Collect and store expected types in the 
index (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D52274

Files:
  clang-tools-extra/trunk/clangd/index/Index.h
  clang-tools-extra/trunk/clangd/index/Serialization.cpp
  clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
  clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp


Index: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clang-tools-extra/trunk/clangd/index/Serialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences ) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto  : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clang-tools-extra/trunk/clangd/index/Index.h
===
--- clang-tools-extra/trunk/clangd/index/Index.h
+++ clang-tools-extra/trunk/clangd/index/Index.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [](const char *) {
 llvm::StringRef S(P);
 CB(S);
Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;


Index: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clang-tools-extra/trunk/clangd/index/Serialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp
@@ -264,6 +264,7 

[clang-tools-extra] r347560 - [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:29:14 2018
New Revision: 347560

URL: http://llvm.org/viewvc/llvm-project?rev=347560=rev
Log:
[clangd] Collect and store expected types in the index

Summary:
And add a hidden option to control whether the types are collected.
For experiments, will be removed when expected types implementation
is stabilized.

The index size is almost unchanged, e.g. the YAML index for all clangd
sources increased from 53MB to 54MB.

Reviewers: ioeric, sammccall

Reviewed By: sammccall

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

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

Modified:
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=347560=347559=347560=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Mon Nov 26 07:29:14 2018
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@ struct Symbol {
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@ template  void visitS
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [](const char *) {
 llvm::StringRef S(P);
 CB(S);

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=347560=347559=347560=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Mon Nov 26 07:29:14 
2018
@@ -264,6 +264,7 @@ void writeSymbol(const Symbol , cons
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences ) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@ Symbol readSymbol(Reader , ArrayRef
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto  : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@ std::pair> re
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=347560=347559=347560=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Nov 26 
07:29:14 2018
@@ -587,6 +587,11 @@ const Symbol *SymbolCollector::addDeclar
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;

Modified: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp?rev=347560=347559=347560=diff
==
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp Mon Nov 26 
07:29:14 

[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175254.
ilya-biryukov added a comment.

- Remove unused #include


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52274

Files:
  clangd/index/Index.h
  clangd/index/Serialization.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/YAMLSerialization.cpp


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences ) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto  : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [](const char *) {
 llvm::StringRef S(P);
 CB(S);


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   

[PATCH] D54898: Set MustBuildLookupTable on PrimaryContext in ExternalASTMerger

2018-11-26 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor created this revision.
teemperor added reviewers: martong, a.sidorin.
teemperor added a project: LLDB.
Herald added subscribers: cfe-commits, rnkovacs.

`MustBuildLookupTable` must always be called on a primary context as we 
otherwise
trigger an assert, but we don't ensure that this will always happen in our code 
right now.

This patch explicitly requests the primary context when doing this call as this 
shouldn't break
anything (as calling `getPrimaryContext` on a context which is its own primary 
context is a no-op) 
but will catch these rare cases where we somehow operate on a declaration 
context that is
not its own primary context.

See also D54863 .


Repository:
  rC Clang

https://reviews.llvm.org/D54898

Files:
  lib/AST/ExternalASTMerger.cpp


Index: lib/AST/ExternalASTMerger.cpp
===
--- lib/AST/ExternalASTMerger.cpp
+++ lib/AST/ExternalASTMerger.cpp
@@ -144,14 +144,14 @@
 }
 if (auto *ToTag = dyn_cast(To)) {
   ToTag->setHasExternalLexicalStorage();
-  ToTag->setMustBuildLookupTable();
+  ToTag->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToTag));
 } else if (auto *ToNamespace = dyn_cast(To)) {
   ToNamespace->setHasExternalVisibleStorage();
   assert(Parent.CanComplete(ToNamespace));
 } else if (auto *ToContainer = dyn_cast(To)) {
   ToContainer->setHasExternalLexicalStorage();
-  ToContainer->setMustBuildLookupTable();
+  ToContainer->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToContainer));
 }
 return To;


Index: lib/AST/ExternalASTMerger.cpp
===
--- lib/AST/ExternalASTMerger.cpp
+++ lib/AST/ExternalASTMerger.cpp
@@ -144,14 +144,14 @@
 }
 if (auto *ToTag = dyn_cast(To)) {
   ToTag->setHasExternalLexicalStorage();
-  ToTag->setMustBuildLookupTable();
+  ToTag->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToTag));
 } else if (auto *ToNamespace = dyn_cast(To)) {
   ToNamespace->setHasExternalVisibleStorage();
   assert(Parent.CanComplete(ToNamespace));
 } else if (auto *ToContainer = dyn_cast(To)) {
   ToContainer->setHasExternalLexicalStorage();
-  ToContainer->setMustBuildLookupTable();
+  ToContainer->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToContainer));
 }
 return To;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52273: [clangd] Initial implementation of expected types

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347559: [clangd] Initial implementation of expected types 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D52273

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
  clang-tools-extra/trunk/clangd/ExpectedTypes.h
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
  clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp

Index: clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
+++ clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
@@ -0,0 +1,157 @@
+//===-- ExpectedTypeTest.cpp  ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ClangdUnit.h"
+#include "ExpectedTypes.h"
+#include "TestTU.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/StringRef.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using ::testing::Field;
+using ::testing::Matcher;
+using ::testing::SizeIs;
+using ::testing::UnorderedElementsAreArray;
+
+class ExpectedTypeConversionTest : public ::testing::Test {
+protected:
+  void build(StringRef Code) {
+assert(!AST && "AST built twice");
+AST = TestTU::withCode(Code).build();
+  }
+
+  const ValueDecl *decl(StringRef Name) {
+return (findDecl(*AST, Name));
+  }
+
+  QualType typeOf(StringRef Name) {
+return decl(Name)->getType().getCanonicalType();
+  }
+
+  /// An overload for convenience.
+  Optional fromCompletionResult(const ValueDecl *D) {
+return OpaqueType::fromCompletionResult(
+ASTCtx(), CodeCompletionResult(D, CCP_Declaration));
+  }
+
+  /// A set of DeclNames whose type match each other computed by
+  /// OpaqueType::fromCompletionResult.
+  using EquivClass = std::set;
+
+  Matcher>
+  ClassesAre(ArrayRef Classes) {
+using MapEntry = std::map::value_type;
+
+std::vector> Elements;
+Elements.reserve(Classes.size());
+for (auto  : Classes)
+  Elements.push_back(Field(::second, Cls));
+return UnorderedElementsAreArray(Elements);
+  }
+
+  // Groups \p Decls into equivalence classes based on the result of
+  // 'OpaqueType::fromCompletionResult'.
+  std::map
+  buildEquivClasses(ArrayRef DeclNames) {
+std::map Classes;
+for (StringRef Name : DeclNames) {
+  auto Type = OpaqueType::fromType(ASTCtx(), typeOf(Name));
+  Classes[Type->raw()].insert(Name);
+}
+return Classes;
+  }
+
+  ASTContext () { return AST->getASTContext(); }
+
+private:
+  // Set after calling build().
+  Optional AST;
+};
+
+TEST_F(ExpectedTypeConversionTest, BasicTypes) {
+  build(R"cpp(
+// ints.
+bool b;
+int i;
+unsigned int ui;
+long long ll;
+
+// floats.
+float f;
+double d;
+
+// pointers
+int* iptr;
+bool* bptr;
+
+// user-defined types.
+struct X {};
+X user_type;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"b", "i", "ui", "ll", "f", "d", "iptr", "bptr",
+ "user_type"}),
+  ClassesAre({{"b"},
+  {"i", "ui", "ll"},
+  {"f", "d"},
+  {"iptr"},
+  {"bptr"},
+  {"user_type"}}));
+}
+
+TEST_F(ExpectedTypeConversionTest, ReferencesDontMatter) {
+  build(R"cpp(
+int noref;
+int & ref = noref;
+const int & const_ref = noref;
+int && rv_ref = 10;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"noref", "ref", "const_ref", "rv_ref"}),
+  SizeIs(1));
+}
+
+TEST_F(ExpectedTypeConversionTest, ArraysDecay) {
+  build(R"cpp(
+ int arr[2];
+ int (_ref)[2] = arr;
+ int *ptr;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"arr", "arr_ref", "ptr"}), SizeIs(1));
+}
+
+TEST_F(ExpectedTypeConversionTest, FunctionReturns) {
+  build(R"cpp(
+ int returns_int();
+ int* returns_ptr();
+
+ int int_;
+ int* int_ptr;
+  )cpp");
+
+  OpaqueType IntTy = *OpaqueType::fromType(ASTCtx(), typeOf("int_"));
+  EXPECT_EQ(fromCompletionResult(decl("returns_int")), IntTy);
+
+  OpaqueType IntPtrTy = *OpaqueType::fromType(ASTCtx(), typeOf("int_ptr"));
+  EXPECT_EQ(fromCompletionResult(decl("returns_ptr")), IntPtrTy);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: 

[clang-tools-extra] r347559 - [clangd] Initial implementation of expected types

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:25:20 2018
New Revision: 347559

URL: http://llvm.org/viewvc/llvm-project?rev=347559=rev
Log:
[clangd] Initial implementation of expected types

Summary:
Provides facilities to model the C++ conversion rules without the AST.
The introduced representation can be stored in the index and used to
implement type-based ranking improvements for index-based completions.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: malaperle, mgorny, MaskRay, jkorous, arphaman, kadircet, 
cfe-commits

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

Added:
clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
clang-tools-extra/trunk/clangd/ExpectedTypes.h
clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=347559=347558=347559=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Mon Nov 26 07:25:20 2018
@@ -19,6 +19,7 @@ add_clang_library(clangDaemon
   Context.cpp
   Diagnostics.cpp
   DraftStore.cpp
+  ExpectedTypes.cpp
   FindSymbols.cpp
   FileDistance.cpp
   FS.cpp

Added: clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ExpectedTypes.cpp?rev=347559=auto
==
--- clang-tools-extra/trunk/clangd/ExpectedTypes.cpp (added)
+++ clang-tools-extra/trunk/clangd/ExpectedTypes.cpp Mon Nov 26 07:25:20 2018
@@ -0,0 +1,80 @@
+#include "ExpectedTypes.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
+#include "clang/Index/USRGeneration.h"
+#include "clang/Sema/CodeCompleteConsumer.h"
+#include "llvm/ADT/STLExtras.h"
+
+using namespace llvm;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+static const Type *toEquivClass(ASTContext , QualType T) {
+  if (T.isNull() || T->isDependentType())
+return nullptr;
+  // Drop references, we do not handle reference inits properly anyway.
+  T = T.getCanonicalType().getNonReferenceType();
+  // Numeric types are the simplest case.
+  if (T->isBooleanType())
+return Ctx.BoolTy.getTypePtr();
+  if (T->isIntegerType() && !T->isEnumeralType())
+return Ctx.IntTy.getTypePtr(); // All integers are equivalent.
+  if (T->isFloatingType() && !T->isComplexType())
+return Ctx.FloatTy.getTypePtr(); // All floats are equivalent.
+
+  // Do some simple transformations.
+  if (T->isArrayType()) // Decay arrays to pointers.
+return Ctx.getPointerType(QualType(T->getArrayElementTypeNoTypeQual(), 0))
+.getTypePtr();
+  // Drop the qualifiers and return the resulting type.
+  // FIXME: also drop qualifiers from pointer types, e.g. 'const T* => T*'
+  return T.getTypePtr();
+}
+
+static Optional typeOfCompletion(const CodeCompletionResult ) {
+  auto *VD = dyn_cast_or_null(R.Declaration);
+  if (!VD)
+return None; // We handle only variables and functions below.
+  auto T = VD->getType();
+  if (auto FuncT = T->getAs()) {
+// Functions are a special case. They are completed as 'foo()' and we want
+// to match their return type rather than the function type itself.
+// FIXME(ibiryukov): in some cases, we might want to avoid completing `()`
+// after the function name, e.g. `std::cout << std::endl`.
+return FuncT->getReturnType();
+  }
+  return T;
+}
+} // namespace
+
+Optional OpaqueType::encode(ASTContext , QualType T) {
+  if (T.isNull())
+return None;
+  const Type *C = toEquivClass(Ctx, T);
+  if (!C)
+return None;
+  SmallString<128> Encoded;
+  if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded))
+return None;
+  return OpaqueType(Encoded.str());
+}
+
+OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}
+
+Optional OpaqueType::fromType(ASTContext , QualType Type) {
+  return encode(Ctx, Type);
+}
+
+Optional
+OpaqueType::fromCompletionResult(ASTContext ,
+ const CodeCompletionResult ) {
+  auto T = typeOfCompletion(R);
+  if (!T)
+return None;
+  return encode(Ctx, *T);
+}
+
+} // namespace clangd
+} // namespace clang

Added: clang-tools-extra/trunk/clangd/ExpectedTypes.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ExpectedTypes.h?rev=347559=auto
==
--- clang-tools-extra/trunk/clangd/ExpectedTypes.h (added)
+++ clang-tools-extra/trunk/clangd/ExpectedTypes.h Mon Nov 26 07:25:20 2018
@@ -0,0 +1,65 @@
+//===--- ExpectedTypes.h - Simplified C++ types -*- 
C++-*--===//
+//
+// The LLVM Compiler 

[PATCH] D52275: [Index] Expose USR generation for types

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347558: [Index] Expose USR generation for types (authored by 
ibiryukov, committed by ).
Herald added a subscriber: arphaman.

Changed prior to commit:
  https://reviews.llvm.org/D52275?vs=166167=175252#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D52275

Files:
  include/clang/Index/USRGeneration.h
  lib/Index/USRGeneration.cpp


Index: lib/Index/USRGeneration.cpp
===
--- lib/Index/USRGeneration.cpp
+++ lib/Index/USRGeneration.cpp
@@ -1105,6 +1105,17 @@
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext ,
+  SmallVectorImpl ) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream ) {
   if (!Mod->Parent)
Index: include/clang/Index/USRGeneration.h
===
--- include/clang/Index/USRGeneration.h
+++ include/clang/Index/USRGeneration.h
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager , SmallVectorImpl );
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext , SmallVectorImpl 
);
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream );
@@ -87,6 +94,7 @@
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream );
 
+
 } // namespace index
 } // namespace clang
 


Index: lib/Index/USRGeneration.cpp
===
--- lib/Index/USRGeneration.cpp
+++ lib/Index/USRGeneration.cpp
@@ -1105,6 +1105,17 @@
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext ,
+  SmallVectorImpl ) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream ) {
   if (!Mod->Parent)
Index: include/clang/Index/USRGeneration.h
===
--- include/clang/Index/USRGeneration.h
+++ include/clang/Index/USRGeneration.h
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager , SmallVectorImpl );
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext , SmallVectorImpl );
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream );
@@ -87,6 +94,7 @@
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream );
 
+
 } // namespace index
 } // namespace clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r347558 - [Index] Expose USR generation for types

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:24:48 2018
New Revision: 347558

URL: http://llvm.org/viewvc/llvm-project?rev=347558=rev
Log:
[Index] Expose USR generation for types

Summary: Used in clangd.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: kadircet, cfe-commits

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

Modified:
cfe/trunk/include/clang/Index/USRGeneration.h
cfe/trunk/lib/Index/USRGeneration.cpp

Modified: cfe/trunk/include/clang/Index/USRGeneration.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/USRGeneration.h?rev=347558=347557=347558=diff
==
--- cfe/trunk/include/clang/Index/USRGeneration.h (original)
+++ cfe/trunk/include/clang/Index/USRGeneration.h Mon Nov 26 07:24:48 2018
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@ bool generateUSRForMacro(const MacroDefi
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager , SmallVectorImpl );
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext , SmallVectorImpl 
);
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream );
@@ -87,6 +94,7 @@ bool generateUSRFragmentForModule(const
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream );
 
+
 } // namespace index
 } // namespace clang
 

Modified: cfe/trunk/lib/Index/USRGeneration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/USRGeneration.cpp?rev=347558=347557=347558=diff
==
--- cfe/trunk/lib/Index/USRGeneration.cpp (original)
+++ cfe/trunk/lib/Index/USRGeneration.cpp Mon Nov 26 07:24:48 2018
@@ -1105,6 +1105,17 @@ bool clang::index::generateUSRForMacro(S
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext ,
+  SmallVectorImpl ) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream ) {
   if (!Mod->Parent)


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


[PATCH] D45478: [clangd] Merge symbols in global-sym-builder on the go

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov abandoned this revision.
ilya-biryukov added a comment.
Herald added subscribers: kadircet, arphaman.

This landed as a different change.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D45478



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


[PATCH] D40988: Clang-format: add finer-grained options for putting all arguments on one line

2018-11-26 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!  Thanks again for your consideration


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

https://reviews.llvm.org/D40988



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 175249.
sammccall marked an inline comment as done.
sammccall added a comment.

Make blockUntilIdleForTest() accept a timeout, update comment.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/index/BackgroundIndexStorage.cpp
  clangd/tool/ClangdMain.cpp
  test/clangd/Inputs/background-index/compile_commands.json
  test/clangd/Inputs/background-index/definition.jsonrpc
  test/clangd/Inputs/background-index/foo.cpp
  test/clangd/Inputs/background-index/foo.h
  test/clangd/background-index.test
  unittests/clangd/BackgroundIndexTests.cpp

Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -90,7 +90,7 @@
   Cmd.CommandLine = {"clang++", "-DA=1", testPath("root/A.cc")};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   EXPECT_THAT(
   runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -100,7 +100,7 @@
   Cmd.CommandLine = {"clang++", Cmd.Filename};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   // B_CC is dropped as we don't collect symbols from A.h in this compilation.
   EXPECT_THAT(runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -141,7 +141,7 @@
 BackgroundIndex Idx(Context::empty(), "", FS, CDB,
 [&](llvm::StringRef) { return  });
 CDB.setCompileCommand(testPath("root"), Cmd);
-Idx.blockUntilIdleForTest();
+ASSERT_TRUE(Idx.blockUntilIdleForTest());
   }
   EXPECT_EQ(CacheHits, 0U);
   EXPECT_EQ(Storage.size(), 2U);
Index: test/clangd/background-index.test
===
--- /dev/null
+++ test/clangd/background-index.test
@@ -0,0 +1,21 @@
+# We need to splice paths into file:// URIs for this test.
+# UNSUPPORTED: win32
+
+# Use a copy of inputs, as we'll mutate it (as will the background index).
+# RUN: rm -rf %t
+# RUN: cp -r %S/Inputs/background-index %t
+# Need to embed the correct temp path in the actual JSON-RPC requests.
+# RUN: sed -i -e "s|DIRECTORY|%t|" %t/*
+
+# We're editing bar.cpp, which includes foo.h.
+# foo() is declared in foo.h and defined in foo.cpp.
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck %t/definition.jsonrpc
+
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+
+# Test the index is read from disk: delete code and restart clangd.
+# FIXME: This test currently fails as we don't read the index yet.
+# RUN: rm %t/foo.cpp
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | not FileCheck %t/definition.jsonrpc
Index: test/clangd/Inputs/background-index/foo.h
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.h
@@ -0,0 +1,4 @@
+#ifndef FOO_H
+#define FOO_H
+int foo();
+#endif
Index: test/clangd/Inputs/background-index/foo.cpp
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.cpp
@@ -0,0 +1,2 @@
+#include "foo.h"
+int foo() { return 42; }
Index: test/clangd/Inputs/background-index/definition.jsonrpc
===
--- /dev/null
+++ test/clangd/Inputs/background-index/definition.jsonrpc
@@ -0,0 +1,51 @@
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+"processId": 123,
+"rootPath": "clangd",
+"capabilities": {},
+"trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp",
+  "languageId": "cpp",
+  "version": 1,
+  "text": "#include \"foo.h\"\nint main(){\nreturn foo();\n}"
+}
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "method": "sync",
+  "params": null
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 2,
+  "method": "textDocument/definition",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp"
+},
+"position": {
+  "line": 2,
+  "character": 8
+}
+  }
+}
+# CHECK: "uri": "file://DIRECTORY/foo.cpp"
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: test/clangd/Inputs/background-index/compile_commands.json

[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: test/clangd/background-index.test:13
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc
+

kadircet wrote:
> shouldn't this one be running ?
Argh, sorry somehow I got confused and thought these were commented-out.. NVM


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


  1   2   >